SkRecorder.cpp revision cdeeb095a629b0db9f0ddff09516f2b78255c047
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 "SkData.h"
9#include "SkRecorder.h"
10#include "SkPatchUtils.h"
11#include "SkPicture.h"
12
13SkRecorder::SkRecorder(SkRecord* record, int width, int height)
14    : SkCanvas(SkIRect::MakeWH(width, height), SkCanvas::kConservativeRasterClip_InitFlag)
15    , fRecord(record)
16    , fSaveLayerCount(0) {}
17
18SkRecorder::SkRecorder(SkRecord* record, const SkRect& bounds)
19    : SkCanvas(bounds.roundOut(), SkCanvas::kConservativeRasterClip_InitFlag)
20    , fRecord(record)
21    , fSaveLayerCount(0) {}
22
23SkRecorder::~SkRecorder() {
24    fDrawableList.unrefAll();
25}
26
27void SkRecorder::forgetRecord() {
28    fDrawableList.unrefAll();
29    fDrawableList.reset();
30    fRecord = NULL;
31}
32
33// ReleaseProc for SkData, assuming the data was allocated via sk_malloc, and its contents are an
34// array of SkRefCnt* which need to be unref'd.
35//
36static void unref_all_malloc_releaseProc(const void* ptr, size_t length, void* context) {
37    SkASSERT(ptr == context);   // our context is our ptr, allocated via sk_malloc
38    int count = SkToInt(length / sizeof(SkRefCnt*));
39    SkASSERT(count * sizeof(SkRefCnt*) == length);  // our length is snug for the array
40
41    SkRefCnt* const* array = reinterpret_cast<SkRefCnt* const*>(ptr);
42    for (int i = 0; i < count; ++i) {
43        SkSafeUnref(array[i]);
44    }
45    sk_free(context);
46}
47
48// Return an uninitialized SkData sized for "count" SkRefCnt pointers. They will be unref'd when
49// the SkData is destroyed.
50//
51static SkData* new_uninitialized_refcnt_ptrs(int count) {
52    size_t length = count * sizeof(SkRefCnt*);
53    void* array = sk_malloc_throw(length);
54    void* context = array;
55    return SkData::NewWithProc(array, length, unref_all_malloc_releaseProc, context);
56}
57
58SkData* SkRecorder::newDrawableSnapshot(SkBBHFactory* factory, uint32_t recordFlags) {
59    const int count = fDrawableList.count();
60    if (0 == count) {
61        return NULL;
62    }
63    SkData* data = new_uninitialized_refcnt_ptrs(count);
64    SkPicture** pics = reinterpret_cast<SkPicture**>(data->writable_data());
65    for (int i = 0; i < count; ++i) {
66        pics[i] = fDrawableList[i]->newPictureSnapshot(factory, recordFlags);
67    }
68    return data;
69}
70
71// To make appending to fRecord a little less verbose.
72#define APPEND(T, ...) \
73        SkNEW_PLACEMENT_ARGS(fRecord->append<SkRecords::T>(), SkRecords::T, (__VA_ARGS__))
74
75// For methods which must call back into SkCanvas.
76#define INHERITED(method, ...) this->SkCanvas::method(__VA_ARGS__)
77
78// The structs we're creating all copy their constructor arguments.  Given the way the SkRecords
79// framework works, sometimes they happen to technically be copied twice, which is fine and elided
80// into a single copy unless the class has a non-trivial copy constructor.  For classes with
81// non-trivial copy constructors, we skip the first copy (and its destruction) by wrapping the value
82// with delay_copy(), forcing the argument to be passed by const&.
83//
84// This is used below for SkBitmap, SkPaint, SkPath, and SkRegion, which all have non-trivial copy
85// constructors and destructors.  You'll know you've got a good candidate T if you see ~T() show up
86// unexpectedly on a profile of record time.  Otherwise don't bother.
87template <typename T>
88class Reference {
89public:
90    Reference(const T& x) : fX(x) {}
91    operator const T&() const { return fX; }
92private:
93    const T& fX;
94};
95
96template <typename T>
97static Reference<T> delay_copy(const T& x) { return Reference<T>(x); }
98
99// Use copy() only for optional arguments, to be copied if present or skipped if not.
100// (For most types we just pass by value and let copy constructors do their thing.)
101template <typename T>
102T* SkRecorder::copy(const T* src) {
103    if (NULL == src) {
104        return NULL;
105    }
106    return SkNEW_PLACEMENT_ARGS(fRecord->alloc<T>(), T, (*src));
107}
108
109// This copy() is for arrays.
110// It will work with POD or non-POD, though currently we only use it for POD.
111template <typename T>
112T* SkRecorder::copy(const T src[], size_t count) {
113    if (NULL == src) {
114        return NULL;
115    }
116    T* dst = fRecord->alloc<T>(count);
117    for (size_t i = 0; i < count; i++) {
118        SkNEW_PLACEMENT_ARGS(dst + i, T, (src[i]));
119    }
120    return dst;
121}
122
123// Specialization for copying strings, using memcpy.
124// This measured around 2x faster for copying code points,
125// but I found no corresponding speedup for other arrays.
126template <>
127char* SkRecorder::copy(const char src[], size_t count) {
128    if (NULL == src) {
129        return NULL;
130    }
131    char* dst = fRecord->alloc<char>(count);
132    memcpy(dst, src, count);
133    return dst;
134}
135
136// As above, assuming and copying a terminating \0.
137template <>
138char* SkRecorder::copy(const char* src) {
139    return this->copy(src, strlen(src)+1);
140}
141
142
143void SkRecorder::clear(SkColor color) {
144    APPEND(Clear, color);
145}
146
147void SkRecorder::drawPaint(const SkPaint& paint) {
148    APPEND(DrawPaint, delay_copy(paint));
149}
150
151void SkRecorder::drawPoints(PointMode mode,
152                            size_t count,
153                            const SkPoint pts[],
154                            const SkPaint& paint) {
155    APPEND(DrawPoints, delay_copy(paint), mode, count, this->copy(pts, count));
156}
157
158void SkRecorder::drawRect(const SkRect& rect, const SkPaint& paint) {
159    APPEND(DrawRect, delay_copy(paint), rect);
160}
161
162void SkRecorder::drawOval(const SkRect& oval, const SkPaint& paint) {
163    APPEND(DrawOval, delay_copy(paint), oval);
164}
165
166void SkRecorder::drawRRect(const SkRRect& rrect, const SkPaint& paint) {
167    APPEND(DrawRRect, delay_copy(paint), rrect);
168}
169
170void SkRecorder::onDrawDRRect(const SkRRect& outer, const SkRRect& inner, const SkPaint& paint) {
171    APPEND(DrawDRRect, delay_copy(paint), outer, inner);
172}
173
174void SkRecorder::onDrawDrawable(SkCanvasDrawable* drawable) {
175    *fDrawableList.append() = SkRef(drawable);
176    APPEND(DrawDrawable, drawable->getBounds(), fDrawableList.count() - 1);
177}
178
179void SkRecorder::drawPath(const SkPath& path, const SkPaint& paint) {
180    APPEND(DrawPath, delay_copy(paint), delay_copy(path));
181}
182
183void SkRecorder::drawBitmap(const SkBitmap& bitmap,
184                            SkScalar left,
185                            SkScalar top,
186                            const SkPaint* paint) {
187    APPEND(DrawBitmap, this->copy(paint), delay_copy(bitmap), left, top);
188}
189
190void SkRecorder::drawBitmapRectToRect(const SkBitmap& bitmap,
191                                      const SkRect* src,
192                                      const SkRect& dst,
193                                      const SkPaint* paint,
194                                      DrawBitmapRectFlags flags) {
195    APPEND(DrawBitmapRectToRect,
196           this->copy(paint), delay_copy(bitmap), this->copy(src), dst, flags);
197}
198
199void SkRecorder::drawBitmapMatrix(const SkBitmap& bitmap,
200                                  const SkMatrix& matrix,
201                                  const SkPaint* paint) {
202    APPEND(DrawBitmapMatrix, this->copy(paint), delay_copy(bitmap), matrix);
203}
204
205void SkRecorder::drawBitmapNine(const SkBitmap& bitmap,
206                                const SkIRect& center,
207                                const SkRect& dst,
208                                const SkPaint* paint) {
209    APPEND(DrawBitmapNine, this->copy(paint), delay_copy(bitmap), center, dst);
210}
211
212void SkRecorder::drawImage(const SkImage* image, SkScalar left, SkScalar top,
213                           const SkPaint* paint) {
214    APPEND(DrawImage, this->copy(paint), image, left, top);
215}
216
217void SkRecorder::drawImageRect(const SkImage* image, const SkRect* src,
218                               const SkRect& dst,
219                               const SkPaint* paint) {
220    APPEND(DrawImageRect, this->copy(paint), image, this->copy(src), dst);
221}
222
223void SkRecorder::drawSprite(const SkBitmap& bitmap, int left, int top, const SkPaint* paint) {
224    APPEND(DrawSprite, this->copy(paint), delay_copy(bitmap), left, top);
225}
226
227void SkRecorder::onDrawText(const void* text, size_t byteLength,
228                            SkScalar x, SkScalar y, const SkPaint& paint) {
229    APPEND(DrawText,
230           delay_copy(paint), this->copy((const char*)text, byteLength), byteLength, x, y);
231}
232
233void SkRecorder::onDrawPosText(const void* text, size_t byteLength,
234                               const SkPoint pos[], const SkPaint& paint) {
235    const unsigned points = paint.countText(text, byteLength);
236    APPEND(DrawPosText,
237           delay_copy(paint),
238           this->copy((const char*)text, byteLength),
239           byteLength,
240           this->copy(pos, points));
241}
242
243void SkRecorder::onDrawPosTextH(const void* text, size_t byteLength,
244                                const SkScalar xpos[], SkScalar constY, const SkPaint& paint) {
245    const unsigned points = paint.countText(text, byteLength);
246    APPEND(DrawPosTextH,
247           delay_copy(paint),
248           this->copy((const char*)text, byteLength),
249           byteLength,
250           this->copy(xpos, points),
251           constY);
252}
253
254void SkRecorder::onDrawTextOnPath(const void* text, size_t byteLength, const SkPath& path,
255                                  const SkMatrix* matrix, const SkPaint& paint) {
256    APPEND(DrawTextOnPath,
257           delay_copy(paint),
258           this->copy((const char*)text, byteLength),
259           byteLength,
260           delay_copy(path),
261           this->copy(matrix));
262}
263
264void SkRecorder::onDrawTextBlob(const SkTextBlob* blob, SkScalar x, SkScalar y,
265                                const SkPaint& paint) {
266    APPEND(DrawTextBlob, delay_copy(paint), blob, x, y);
267}
268
269void SkRecorder::onDrawPicture(const SkPicture* pic, const SkMatrix* matrix, const SkPaint* paint) {
270    APPEND(DrawPicture, this->copy(paint), pic, this->copy(matrix));
271}
272
273void SkRecorder::drawVertices(VertexMode vmode,
274                              int vertexCount, const SkPoint vertices[],
275                              const SkPoint texs[], const SkColor colors[],
276                              SkXfermode* xmode,
277                              const uint16_t indices[], int indexCount, const SkPaint& paint) {
278    APPEND(DrawVertices, delay_copy(paint),
279                         vmode,
280                         vertexCount,
281                         this->copy(vertices, vertexCount),
282                         texs ? this->copy(texs, vertexCount) : NULL,
283                         colors ? this->copy(colors, vertexCount) : NULL,
284                         xmode,
285                         this->copy(indices, indexCount),
286                         indexCount);
287}
288
289void SkRecorder::onDrawPatch(const SkPoint cubics[12], const SkColor colors[4],
290                             const SkPoint texCoords[4], SkXfermode* xmode, const SkPaint& paint) {
291    APPEND(DrawPatch, delay_copy(paint),
292           cubics ? this->copy(cubics, SkPatchUtils::kNumCtrlPts) : NULL,
293           colors ? this->copy(colors, SkPatchUtils::kNumCorners) : NULL,
294           texCoords ? this->copy(texCoords, SkPatchUtils::kNumCorners) : NULL,
295           xmode);
296}
297
298void SkRecorder::willSave() {
299    fSaveIsSaveLayer.push(false);
300    APPEND(Save);
301}
302
303SkCanvas::SaveLayerStrategy SkRecorder::willSaveLayer(const SkRect* bounds,
304                                                      const SkPaint* paint,
305                                                      SkCanvas::SaveFlags flags) {
306    fSaveLayerCount++;
307    fSaveIsSaveLayer.push(true);
308    APPEND(SaveLayer, this->copy(bounds), this->copy(paint), flags);
309    return SkCanvas::kNoLayer_SaveLayerStrategy;
310}
311
312void SkRecorder::didRestore() {
313    SkBool8 saveLayer;
314    fSaveIsSaveLayer.pop(&saveLayer);
315    if (saveLayer) {
316        fSaveLayerCount--;
317    }
318    APPEND(Restore, this->devBounds(), this->getTotalMatrix());
319}
320
321void SkRecorder::onPushCull(const SkRect& rect) {
322    APPEND(PushCull, rect);
323}
324
325void SkRecorder::onPopCull() {
326    APPEND(PopCull);
327}
328
329void SkRecorder::didConcat(const SkMatrix& matrix) {
330    this->didSetMatrix(this->getTotalMatrix());
331}
332
333void SkRecorder::didSetMatrix(const SkMatrix& matrix) {
334    SkDEVCODE(if (matrix != this->getTotalMatrix()) {
335        matrix.dump();
336        this->getTotalMatrix().dump();
337        SkASSERT(matrix == this->getTotalMatrix());
338    })
339    APPEND(SetMatrix, matrix);
340}
341
342void SkRecorder::onClipRect(const SkRect& rect, SkRegion::Op op, ClipEdgeStyle edgeStyle) {
343    INHERITED(onClipRect, rect, op, edgeStyle);
344    SkRecords::RegionOpAndAA opAA(op, kSoft_ClipEdgeStyle == edgeStyle);
345    APPEND(ClipRect, this->devBounds(), rect, opAA);
346}
347
348void SkRecorder::onClipRRect(const SkRRect& rrect, SkRegion::Op op, ClipEdgeStyle edgeStyle) {
349    INHERITED(onClipRRect, rrect, op, edgeStyle);
350    SkRecords::RegionOpAndAA opAA(op, kSoft_ClipEdgeStyle == edgeStyle);
351    APPEND(ClipRRect, this->devBounds(), rrect, opAA);
352}
353
354void SkRecorder::onClipPath(const SkPath& path, SkRegion::Op op, ClipEdgeStyle edgeStyle) {
355    INHERITED(onClipPath, path, op, edgeStyle);
356    SkRecords::RegionOpAndAA opAA(op, kSoft_ClipEdgeStyle == edgeStyle);
357    APPEND(ClipPath, this->devBounds(), delay_copy(path), opAA);
358}
359
360void SkRecorder::onClipRegion(const SkRegion& deviceRgn, SkRegion::Op op) {
361    INHERITED(onClipRegion, deviceRgn, op);
362    APPEND(ClipRegion, this->devBounds(), delay_copy(deviceRgn), op);
363}
364
365void SkRecorder::beginCommentGroup(const char* description) {
366    APPEND(BeginCommentGroup, this->copy(description));
367}
368
369void SkRecorder::addComment(const char* key, const char* value) {
370    APPEND(AddComment, this->copy(key), this->copy(value));
371}
372
373void SkRecorder::endCommentGroup() {
374    APPEND(EndCommentGroup);
375}
376
377bool SkRecorder::isDrawingToLayer() const {
378    return fSaveLayerCount > 0;
379}
380
381void SkRecorder::drawData(const void* data, size_t length) {
382    APPEND(DrawData, copy((const char*)data), length);
383}
384