xref: /third_party/skia/src/core/SkRecordDraw.cpp (revision cb93a386)
1/*
2 * Copyright 2014 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8#include "include/core/SkBBHFactory.h"
9#include "include/core/SkImage.h"
10#include "src/core/SkCanvasPriv.h"
11#include "src/core/SkColorFilterBase.h"
12#include "src/core/SkImageFilter_Base.h"
13#include "src/core/SkRecordDraw.h"
14#include "src/utils/SkPatchUtils.h"
15
16void SkRecordDraw(const SkRecord& record,
17                  SkCanvas* canvas,
18                  SkPicture const* const drawablePicts[],
19                  SkDrawable* const drawables[],
20                  int drawableCount,
21                  const SkBBoxHierarchy* bbh,
22                  SkPicture::AbortCallback* callback) {
23    SkAutoCanvasRestore saveRestore(canvas, true /*save now, restore at exit*/);
24
25    if (bbh) {
26        // Draw only ops that affect pixels in the canvas's current clip.
27        // The SkRecord and BBH were recorded in identity space.  This canvas
28        // is not necessarily in that same space.  getLocalClipBounds() returns us
29        // this canvas' clip bounds transformed back into identity space, which
30        // lets us query the BBH.
31        SkRect query = canvas->getLocalClipBounds();
32
33        std::vector<int> ops;
34        bbh->search(query, &ops);
35
36        SkRecords::Draw draw(canvas, drawablePicts, drawables, drawableCount);
37        for (int i = 0; i < (int)ops.size(); i++) {
38            if (callback && callback->abort()) {
39                return;
40            }
41            // This visit call uses the SkRecords::Draw::operator() to call
42            // methods on the |canvas|, wrapped by methods defined with the
43            // DRAW() macro.
44            record.visit(ops[i], draw);
45        }
46    } else {
47        // Draw all ops.
48        SkRecords::Draw draw(canvas, drawablePicts, drawables, drawableCount);
49        for (int i = 0; i < record.count(); i++) {
50            if (callback && callback->abort()) {
51                return;
52            }
53            // This visit call uses the SkRecords::Draw::operator() to call
54            // methods on the |canvas|, wrapped by methods defined with the
55            // DRAW() macro.
56            record.visit(i, draw);
57        }
58    }
59}
60
61void SkRecordPartialDraw(const SkRecord& record, SkCanvas* canvas,
62                         SkPicture const* const drawablePicts[], int drawableCount,
63                         int start, int stop,
64                         const SkM44& initialCTM) {
65    SkAutoCanvasRestore saveRestore(canvas, true /*save now, restore at exit*/);
66
67    stop = std::min(stop, record.count());
68    SkRecords::Draw draw(canvas, drawablePicts, nullptr, drawableCount, &initialCTM);
69    for (int i = start; i < stop; i++) {
70        record.visit(i, draw);
71    }
72}
73
74namespace SkRecords {
75
76// NoOps draw nothing.
77template <> void Draw::draw(const NoOp&) {}
78
79#define DRAW(T, call) template <> void Draw::draw(const T& r) { fCanvas->call; }
80DRAW(Flush, flush());
81DRAW(Restore, restore());
82DRAW(Save, save());
83DRAW(SaveLayer, saveLayer(SkCanvasPriv::ScaledBackdropLayer(r.bounds,
84                                                            r.paint,
85                                                            r.backdrop.get(),
86                                                            r.backdropScale,
87                                                            r.saveLayerFlags)));
88
89template <> void Draw::draw(const SaveBehind& r) {
90    SkCanvasPriv::SaveBehind(fCanvas, r.subset);
91}
92
93template <> void Draw::draw(const DrawBehind& r) {
94    SkCanvasPriv::DrawBehind(fCanvas, r.paint);
95}
96
97DRAW(MarkCTM, markCTM(r.name.c_str()));
98DRAW(SetMatrix, setMatrix(fInitialCTM.asM33() * r.matrix));
99DRAW(SetM44, setMatrix(fInitialCTM * r.matrix));
100DRAW(Concat44, concat(r.matrix));
101DRAW(Concat, concat(r.matrix));
102DRAW(Translate, translate(r.dx, r.dy));
103DRAW(Scale, scale(r.sx, r.sy));
104
105DRAW(ClipPath, clipPath(r.path, r.opAA.op(), r.opAA.aa()));
106DRAW(ClipRRect, clipRRect(r.rrect, r.opAA.op(), r.opAA.aa()));
107DRAW(ClipRect, clipRect(r.rect, r.opAA.op(), r.opAA.aa()));
108DRAW(ClipRegion, clipRegion(r.region, r.op));
109DRAW(ClipShader, clipShader(r.shader, r.op));
110
111template <> void Draw::draw(const ResetClip& r) {
112    SkCanvasPriv::ResetClip(fCanvas);
113}
114
115DRAW(DrawArc, drawArc(r.oval, r.startAngle, r.sweepAngle, r.useCenter, r.paint));
116DRAW(DrawDRRect, drawDRRect(r.outer, r.inner, r.paint));
117DRAW(DrawImage, drawImage(r.image.get(), r.left, r.top, r.sampling, r.paint));
118
119template <> void Draw::draw(const DrawImageLattice& r) {
120    SkCanvas::Lattice lattice;
121    lattice.fXCount = r.xCount;
122    lattice.fXDivs = r.xDivs;
123    lattice.fYCount = r.yCount;
124    lattice.fYDivs = r.yDivs;
125    lattice.fRectTypes = (0 == r.flagCount) ? nullptr : r.flags;
126    lattice.fColors = (0 == r.flagCount) ? nullptr : r.colors;
127    lattice.fBounds = &r.src;
128    fCanvas->drawImageLattice(r.image.get(), lattice, r.dst, r.filter, r.paint);
129}
130
131DRAW(DrawImageRect, drawImageRect(r.image.get(), r.src, r.dst, r.sampling, r.paint, r.constraint));
132DRAW(DrawOval, drawOval(r.oval, r.paint));
133DRAW(DrawPaint, drawPaint(r.paint));
134DRAW(DrawPath, drawPath(r.path, r.paint));
135DRAW(DrawPatch, drawPatch(r.cubics, r.colors, r.texCoords, r.bmode, r.paint));
136DRAW(DrawPicture, drawPicture(r.picture.get(), &r.matrix, r.paint));
137DRAW(DrawPoints, drawPoints(r.mode, r.count, r.pts, r.paint));
138DRAW(DrawRRect, drawRRect(r.rrect, r.paint));
139DRAW(DrawRect, drawRect(r.rect, r.paint));
140DRAW(DrawRegion, drawRegion(r.region, r.paint));
141DRAW(DrawTextBlob, drawTextBlob(r.blob.get(), r.x, r.y, r.paint));
142DRAW(DrawAtlas, drawAtlas(r.atlas.get(), r.xforms, r.texs, r.colors, r.count, r.mode, r.sampling,
143                          r.cull, r.paint));
144DRAW(DrawVertices, drawVertices(r.vertices, r.bmode, r.paint));
145DRAW(DrawShadowRec, private_draw_shadow_rec(r.path, r.rec));
146DRAW(DrawAnnotation, drawAnnotation(r.rect, r.key.c_str(), r.value.get()));
147
148DRAW(DrawEdgeAAQuad, experimental_DrawEdgeAAQuad(
149        r.rect, r.clip, r.aa, r.color, r.mode));
150DRAW(DrawEdgeAAImageSet, experimental_DrawEdgeAAImageSet(
151        r.set.get(), r.count, r.dstClips, r.preViewMatrices, r.sampling, r.paint, r.constraint));
152
153#undef DRAW
154
155template <> void Draw::draw(const DrawDrawable& r) {
156    SkASSERT(r.index >= 0);
157    SkASSERT(r.index < fDrawableCount);
158    if (fDrawables) {
159        SkASSERT(nullptr == fDrawablePicts);
160        fCanvas->drawDrawable(fDrawables[r.index], r.matrix);
161    } else {
162        fCanvas->drawPicture(fDrawablePicts[r.index], r.matrix, nullptr);
163    }
164}
165
166// This is an SkRecord visitor that fills an SkBBoxHierarchy.
167//
168// The interesting part here is how to calculate bounds for ops which don't
169// have intrinsic bounds.  What is the bounds of a Save or a Translate?
170//
171// We answer this by thinking about a particular definition of bounds: if I
172// don't execute this op, pixels in this rectangle might draw incorrectly.  So
173// the bounds of a Save, a Translate, a Restore, etc. are the union of the
174// bounds of Draw* ops that they might have an effect on.  For any given
175// Save/Restore block, the bounds of the Save, the Restore, and any other
176// non-drawing ("control") ops inside are exactly the union of the bounds of
177// the drawing ops inside that block.
178//
179// To implement this, we keep a stack of active Save blocks.  As we consume ops
180// inside the Save/Restore block, drawing ops are unioned with the bounds of
181// the block, and control ops are stashed away for later.  When we finish the
182// block with a Restore, our bounds are complete, and we go back and fill them
183// in for all the control ops we stashed away.
184class FillBounds : SkNoncopyable {
185public:
186    FillBounds(const SkRect& cullRect, const SkRecord& record,
187               SkRect bounds[], SkBBoxHierarchy::Metadata meta[])
188        : fCullRect(cullRect)
189        , fBounds(bounds)
190        , fMeta(meta) {
191        fCTM = SkMatrix::I();
192
193        // We push an extra save block to track the bounds of any top-level control operations.
194        fSaveStack.push_back({ 0, Bounds::MakeEmpty(), nullptr, fCTM });
195    }
196
197    ~FillBounds() {
198        // If we have any lingering unpaired Saves, simulate restores to make
199        // sure all ops in those Save blocks have their bounds calculated.
200        while (!fSaveStack.isEmpty()) {
201            this->popSaveBlock();
202        }
203
204        // Any control ops not part of any Save/Restore block draw everywhere.
205        while (!fControlIndices.isEmpty()) {
206            this->popControl(fCullRect);
207        }
208    }
209
210    void setCurrentOp(int currentOp) { fCurrentOp = currentOp; }
211
212
213    template <typename T> void operator()(const T& op) {
214        this->updateCTM(op);
215        this->trackBounds(op);
216    }
217
218    // In this file, SkRect are in local coordinates, Bounds are translated back to identity space.
219    typedef SkRect Bounds;
220
221    // Adjust rect for all paints that may affect its geometry, then map it to identity space.
222    Bounds adjustAndMap(SkRect rect, const SkPaint* paint) const {
223        // Inverted rectangles really confuse our BBHs.
224        rect.sort();
225
226        // Adjust the rect for its own paint.
227        if (!AdjustForPaint(paint, &rect)) {
228            // The paint could do anything to our bounds.  The only safe answer is the cull.
229            return fCullRect;
230        }
231
232        // Adjust rect for all the paints from the SaveLayers we're inside.
233        if (!this->adjustForSaveLayerPaints(&rect)) {
234            // Same deal as above.
235            return fCullRect;
236        }
237
238        // Map the rect back to identity space.
239        fCTM.mapRect(&rect);
240
241        // Nothing can draw outside the cull rect.
242        if (!rect.intersect(fCullRect)) {
243            return Bounds::MakeEmpty();
244        }
245
246        return rect;
247    }
248
249private:
250    struct SaveBounds {
251        int controlOps;        // Number of control ops in this Save block, including the Save.
252        Bounds bounds;         // Bounds of everything in the block.
253        const SkPaint* paint;  // Unowned.  If set, adjusts the bounds of all ops in this block.
254        SkMatrix ctm;
255    };
256
257    // Only Restore, SetMatrix, Concat, and Translate change the CTM.
258    template <typename T> void updateCTM(const T&) {}
259    void updateCTM(const Restore& op)   { fCTM = op.matrix; }
260    void updateCTM(const SetMatrix& op) { fCTM = op.matrix; }
261    void updateCTM(const SetM44& op)    { fCTM = op.matrix.asM33(); }
262    void updateCTM(const Concat44& op)  { fCTM.preConcat(op.matrix.asM33()); }
263    void updateCTM(const Concat& op)    { fCTM.preConcat(op.matrix); }
264    void updateCTM(const Scale& op)     { fCTM.preScale(op.sx, op.sy); }
265    void updateCTM(const Translate& op) { fCTM.preTranslate(op.dx, op.dy); }
266
267    // The bounds of these ops must be calculated when we hit the Restore
268    // from the bounds of the ops in the same Save block.
269    void trackBounds(const Save&)          { this->pushSaveBlock(nullptr); }
270    void trackBounds(const SaveLayer& op)  { this->pushSaveBlock(op.paint); }
271    void trackBounds(const SaveBehind&)    { this->pushSaveBlock(nullptr); }
272    void trackBounds(const Restore&) {
273        const bool isSaveLayer = fSaveStack.top().paint != nullptr;
274        fBounds[fCurrentOp] = this->popSaveBlock();
275        fMeta  [fCurrentOp].isDraw = isSaveLayer;
276    }
277
278    void trackBounds(const MarkCTM&)           { this->pushControl(); }
279    void trackBounds(const SetMatrix&)         { this->pushControl(); }
280    void trackBounds(const SetM44&)            { this->pushControl(); }
281    void trackBounds(const Concat&)            { this->pushControl(); }
282    void trackBounds(const Concat44&)          { this->pushControl(); }
283    void trackBounds(const Scale&)             { this->pushControl(); }
284    void trackBounds(const Translate&)         { this->pushControl(); }
285    void trackBounds(const ClipRect&)          { this->pushControl(); }
286    void trackBounds(const ClipRRect&)         { this->pushControl(); }
287    void trackBounds(const ClipPath&)          { this->pushControl(); }
288    void trackBounds(const ClipRegion&)        { this->pushControl(); }
289    void trackBounds(const ClipShader&)        { this->pushControl(); }
290    void trackBounds(const ResetClip&)         { this->pushControl(); }
291
292
293    // For all other ops, we can calculate and store the bounds directly now.
294    template <typename T> void trackBounds(const T& op) {
295        fBounds[fCurrentOp] = this->bounds(op);
296        fMeta  [fCurrentOp].isDraw = true;
297        this->updateSaveBounds(fBounds[fCurrentOp]);
298    }
299
300    void pushSaveBlock(const SkPaint* paint) {
301        // Starting a new Save block.  Push a new entry to represent that.
302        SaveBounds sb;
303        sb.controlOps = 0;
304        // If the paint affects transparent black,
305        // the bound shouldn't be smaller than the cull.
306        sb.bounds =
307            PaintMayAffectTransparentBlack(paint) ? fCullRect : Bounds::MakeEmpty();
308        sb.paint = paint;
309        sb.ctm = this->fCTM;
310
311        fSaveStack.push_back(sb);
312        this->pushControl();
313    }
314
315    static bool PaintMayAffectTransparentBlack(const SkPaint* paint) {
316        if (paint) {
317            // FIXME: this is very conservative
318            if ((paint->getImageFilter() &&
319                 as_IFB(paint->getImageFilter())->affectsTransparentBlack()) ||
320                (paint->getColorFilter() &&
321                 as_CFB(paint->getColorFilter())->affectsTransparentBlack())) {
322                return true;
323            }
324            const auto bm = paint->asBlendMode();
325            if (!bm) {
326                return true;    // can we query other blenders for this?
327            }
328
329            // Unusual blendmodes require us to process a saved layer
330            // even with operations outisde the clip.
331            // For example, DstIn is used by masking layers.
332            // https://code.google.com/p/skia/issues/detail?id=1291
333            // https://crbug.com/401593
334            switch (bm.value()) {
335                // For each of the following transfer modes, if the source
336                // alpha is zero (our transparent black), the resulting
337                // blended alpha is not necessarily equal to the original
338                // destination alpha.
339                case SkBlendMode::kClear:
340                case SkBlendMode::kSrc:
341                case SkBlendMode::kSrcIn:
342                case SkBlendMode::kDstIn:
343                case SkBlendMode::kSrcOut:
344                case SkBlendMode::kDstATop:
345                case SkBlendMode::kModulate:
346                    return true;
347                    break;
348                default:
349                    break;
350            }
351        }
352        return false;
353    }
354
355    Bounds popSaveBlock() {
356        // We're done the Save block.  Apply the block's bounds to all control ops inside it.
357        SaveBounds sb;
358        fSaveStack.pop(&sb);
359
360        while (sb.controlOps --> 0) {
361            this->popControl(sb.bounds);
362        }
363
364        // This whole Save block may be part another Save block.
365        this->updateSaveBounds(sb.bounds);
366
367        // If called from a real Restore (not a phony one for balance), it'll need the bounds.
368        return sb.bounds;
369    }
370
371    void pushControl() {
372        fControlIndices.push_back(fCurrentOp);
373        if (!fSaveStack.isEmpty()) {
374            fSaveStack.top().controlOps++;
375        }
376    }
377
378    void popControl(const Bounds& bounds) {
379        fBounds[fControlIndices.top()] = bounds;
380        fMeta  [fControlIndices.top()].isDraw = false;
381        fControlIndices.pop();
382    }
383
384    void updateSaveBounds(const Bounds& bounds) {
385        // If we're in a Save block, expand its bounds to cover these bounds too.
386        if (!fSaveStack.isEmpty()) {
387            fSaveStack.top().bounds.join(bounds);
388        }
389    }
390
391    Bounds bounds(const Flush&) const { return fCullRect; }
392
393    Bounds bounds(const DrawPaint&) const { return fCullRect; }
394    Bounds bounds(const DrawBehind&) const { return fCullRect; }
395    Bounds bounds(const NoOp&)  const { return Bounds::MakeEmpty(); }    // NoOps don't draw.
396
397    Bounds bounds(const DrawRect& op) const { return this->adjustAndMap(op.rect, &op.paint); }
398    Bounds bounds(const DrawRegion& op) const {
399        SkRect rect = SkRect::Make(op.region.getBounds());
400        return this->adjustAndMap(rect, &op.paint);
401    }
402    Bounds bounds(const DrawOval& op) const { return this->adjustAndMap(op.oval, &op.paint); }
403    // Tighter arc bounds?
404    Bounds bounds(const DrawArc& op) const { return this->adjustAndMap(op.oval, &op.paint); }
405    Bounds bounds(const DrawRRect& op) const {
406        return this->adjustAndMap(op.rrect.rect(), &op.paint);
407    }
408    Bounds bounds(const DrawDRRect& op) const {
409        return this->adjustAndMap(op.outer.rect(), &op.paint);
410    }
411    Bounds bounds(const DrawImage& op) const {
412        const SkImage* image = op.image.get();
413        SkRect rect = SkRect::MakeXYWH(op.left, op.top, image->width(), image->height());
414
415        return this->adjustAndMap(rect, op.paint);
416    }
417    Bounds bounds(const DrawImageLattice& op) const {
418        return this->adjustAndMap(op.dst, op.paint);
419    }
420    Bounds bounds(const DrawImageRect& op) const {
421        return this->adjustAndMap(op.dst, op.paint);
422    }
423    Bounds bounds(const DrawPath& op) const {
424        return op.path.isInverseFillType() ? fCullRect
425                                           : this->adjustAndMap(op.path.getBounds(), &op.paint);
426    }
427    Bounds bounds(const DrawPoints& op) const {
428        SkRect dst;
429        dst.setBounds(op.pts, op.count);
430
431        // Pad the bounding box a little to make sure hairline points' bounds aren't empty.
432        SkScalar stroke = std::max(op.paint.getStrokeWidth(), 0.01f);
433        dst.outset(stroke/2, stroke/2);
434
435        return this->adjustAndMap(dst, &op.paint);
436    }
437    Bounds bounds(const DrawPatch& op) const {
438        SkRect dst;
439        dst.setBounds(op.cubics, SkPatchUtils::kNumCtrlPts);
440        return this->adjustAndMap(dst, &op.paint);
441    }
442    Bounds bounds(const DrawVertices& op) const {
443        return this->adjustAndMap(op.vertices->bounds(), &op.paint);
444    }
445
446    Bounds bounds(const DrawAtlas& op) const {
447        if (op.cull) {
448            // TODO: <reed> can we pass nullptr for the paint? Isn't cull already "correct"
449            // for the paint (by the caller)?
450            return this->adjustAndMap(*op.cull, op.paint);
451        } else {
452            return fCullRect;
453        }
454    }
455
456    Bounds bounds(const DrawShadowRec& op) const {
457        SkRect bounds;
458        SkDrawShadowMetrics::GetLocalBounds(op.path, op.rec, fCTM, &bounds);
459        return this->adjustAndMap(bounds, nullptr);
460    }
461
462    Bounds bounds(const DrawPicture& op) const {
463        SkRect dst = op.picture->cullRect();
464        op.matrix.mapRect(&dst);
465        return this->adjustAndMap(dst, op.paint);
466    }
467
468    Bounds bounds(const DrawTextBlob& op) const {
469        SkRect dst = op.blob->bounds();
470        dst.offset(op.x, op.y);
471        return this->adjustAndMap(dst, &op.paint);
472    }
473
474    Bounds bounds(const DrawDrawable& op) const {
475        return this->adjustAndMap(op.worstCaseBounds, nullptr);
476    }
477
478    Bounds bounds(const DrawAnnotation& op) const {
479        return this->adjustAndMap(op.rect, nullptr);
480    }
481    Bounds bounds(const DrawEdgeAAQuad& op) const {
482        SkRect bounds = op.rect;
483        if (op.clip) {
484            bounds.setBounds(op.clip, 4);
485        }
486        return this->adjustAndMap(bounds, nullptr);
487    }
488    Bounds bounds(const DrawEdgeAAImageSet& op) const {
489        SkRect rect = SkRect::MakeEmpty();
490        int clipIndex = 0;
491        for (int i = 0; i < op.count; ++i) {
492            SkRect entryBounds = op.set[i].fDstRect;
493            if (op.set[i].fHasClip) {
494                entryBounds.setBounds(op.dstClips + clipIndex, 4);
495                clipIndex += 4;
496            }
497            if (op.set[i].fMatrixIndex >= 0) {
498                op.preViewMatrices[op.set[i].fMatrixIndex].mapRect(&entryBounds);
499            }
500            rect.join(this->adjustAndMap(entryBounds, nullptr));
501        }
502        return rect;
503    }
504
505    // Returns true if rect was meaningfully adjusted for the effects of paint,
506    // false if the paint could affect the rect in unknown ways.
507    static bool AdjustForPaint(const SkPaint* paint, SkRect* rect) {
508        if (paint) {
509            if (paint->canComputeFastBounds()) {
510                *rect = paint->computeFastBounds(*rect, rect);
511                return true;
512            }
513            return false;
514        }
515        return true;
516    }
517
518    bool adjustForSaveLayerPaints(SkRect* rect, int savesToIgnore = 0) const {
519        for (int i = fSaveStack.count() - 1 - savesToIgnore; i >= 0; i--) {
520            SkMatrix inverse;
521            if (!fSaveStack[i].ctm.invert(&inverse)) {
522                return false;
523            }
524            inverse.mapRect(rect);
525            if (!AdjustForPaint(fSaveStack[i].paint, rect)) {
526                return false;
527            }
528            fSaveStack[i].ctm.mapRect(rect);
529        }
530        return true;
531    }
532
533    // We do not guarantee anything for operations outside of the cull rect
534    const SkRect fCullRect;
535
536    // Conservative identity-space bounds for each op in the SkRecord.
537    Bounds* fBounds;
538
539    // Parallel array to fBounds, holding metadata for each bounds rect.
540    SkBBoxHierarchy::Metadata* fMeta;
541
542    // We walk fCurrentOp through the SkRecord,
543    // as we go using updateCTM() to maintain the exact CTM (fCTM).
544    int fCurrentOp;
545    SkMatrix fCTM;
546
547    // Used to track the bounds of Save/Restore blocks and the control ops inside them.
548    SkTDArray<SaveBounds> fSaveStack;
549    SkTDArray<int>   fControlIndices;
550};
551
552}  // namespace SkRecords
553
554void SkRecordFillBounds(const SkRect& cullRect, const SkRecord& record,
555                        SkRect bounds[], SkBBoxHierarchy::Metadata meta[]) {
556    {
557        SkRecords::FillBounds visitor(cullRect, record, bounds, meta);
558        for (int i = 0; i < record.count(); i++) {
559            visitor.setCurrentOp(i);
560            record.visit(i, visitor);
561        }
562    }
563}
564