SkPicture.h revision 4b8f8022550daa7458ed3de207d1300917d4a8cb
1
2/*
3 * Copyright 2007 The Android Open Source Project
4 *
5 * Use of this source code is governed by a BSD-style license that can be
6 * found in the LICENSE file.
7 */
8
9
10#ifndef SkPicture_DEFINED
11#define SkPicture_DEFINED
12
13#include "SkBitmap.h"
14#include "SkImageDecoder.h"
15#include "SkRefCnt.h"
16
17#if SK_SUPPORT_GPU
18class GrContext;
19#endif
20
21class SkBBHFactory;
22class SkBBoxHierarchy;
23class SkCanvas;
24class SkDrawPictureCallback;
25class SkData;
26class SkPathHeap;
27class SkPicturePlayback;
28class SkPictureRecord;
29class SkStream;
30class SkWStream;
31
32struct SkPictInfo;
33
34/** \class SkPicture
35
36    The SkPicture class records the drawing commands made to a canvas, to
37    be played back at a later time.
38*/
39class SK_API SkPicture : public SkRefCnt {
40public:
41    SK_DECLARE_INST_COUNT(SkPicture)
42
43    // AccelData provides a base class for device-specific acceleration
44    // data. It is added to the picture via a call to a device's optimize
45    // method.
46    class AccelData : public SkRefCnt {
47    public:
48        typedef uint8_t Domain;
49        typedef uint32_t Key;
50
51        AccelData(Key key) : fKey(key) { }
52
53        const Key& getKey() const { return fKey; }
54
55        // This entry point allows user's to get a unique domain prefix
56        // for their keys
57        static Domain GenerateDomain();
58    private:
59        Key fKey;
60
61        typedef SkRefCnt INHERITED;
62    };
63
64    SkPicture();
65    /** Make a copy of the contents of src. If src records more drawing after
66        this call, those elements will not appear in this picture.
67    */
68    SkPicture(const SkPicture& src);
69
70    /**  PRIVATE / EXPERIMENTAL -- do not call */
71    void EXPERIMENTAL_addAccelData(const AccelData* data) {
72        SkRefCnt_SafeAssign(fAccelData, data);
73    }
74    /**  PRIVATE / EXPERIMENTAL -- do not call */
75    const AccelData* EXPERIMENTAL_getAccelData(AccelData::Key key) const {
76        if (NULL != fAccelData && fAccelData->getKey() == key) {
77            return fAccelData;
78        }
79        return NULL;
80    }
81
82    /**
83     *  Function signature defining a function that sets up an SkBitmap from encoded data. On
84     *  success, the SkBitmap should have its Config, width, height, rowBytes and pixelref set.
85     *  If the installed pixelref has decoded the data into pixels, then the src buffer need not be
86     *  copied. If the pixelref defers the actual decode until its lockPixels() is called, then it
87     *  must make a copy of the src buffer.
88     *  @param src Encoded data.
89     *  @param length Size of the encoded data, in bytes.
90     *  @param dst SkBitmap to install the pixel ref on.
91     *  @param bool Whether or not a pixel ref was successfully installed.
92     */
93    typedef bool (*InstallPixelRefProc)(const void* src, size_t length, SkBitmap* dst);
94
95    /**
96     *  Recreate a picture that was serialized into a stream.
97     *  @param SkStream Serialized picture data.
98     *  @param proc Function pointer for installing pixelrefs on SkBitmaps representing the
99     *              encoded bitmap data from the stream.
100     *  @return A new SkPicture representing the serialized data, or NULL if the stream is
101     *          invalid.
102     */
103    static SkPicture* CreateFromStream(SkStream*,
104                                       InstallPixelRefProc proc = &SkImageDecoder::DecodeMemory);
105
106    /**
107     *  Recreate a picture that was serialized into a buffer. If the creation requires bitmap
108     *  decoding, the decoder must be set on the SkReadBuffer parameter by calling
109     *  SkReadBuffer::setBitmapDecoder() before calling SkPicture::CreateFromBuffer().
110     *  @param SkReadBuffer Serialized picture data.
111     *  @return A new SkPicture representing the serialized data, or NULL if the buffer is
112     *          invalid.
113     */
114    static SkPicture* CreateFromBuffer(SkReadBuffer&);
115
116    virtual ~SkPicture();
117
118    /**
119     *  Swap the contents of the two pictures. Guaranteed to succeed.
120     */
121    void swap(SkPicture& other);
122
123    /**
124     *  Creates a thread-safe clone of the picture that is ready for playback.
125     */
126    SkPicture* clone() const;
127
128    /**
129     * Creates multiple thread-safe clones of this picture that are ready for
130     * playback. The resulting clones are stored in the provided array of
131     * SkPictures.
132     */
133    void clone(SkPicture* pictures, int count) const;
134
135    enum RecordingFlags {
136        /*  This flag specifies that when clipPath() is called, the path will
137            be faithfully recorded, but the recording canvas' current clip will
138            only see the path's bounds. This speeds up the recording process
139            without compromising the fidelity of the playback. The only side-
140            effect for recording is that calling getTotalClip() or related
141            clip-query calls will reflect the path's bounds, not the actual
142            path.
143         */
144        kUsePathBoundsForClip_RecordingFlag = 0x01
145    };
146
147#ifndef SK_SUPPORT_DEPRECATED_RECORD_FLAGS
148    // TODO: once kOptimizeForClippedPlayback_RecordingFlag is hidden from
149    // all external consumers, SkPicture::createBBoxHierarchy can also be
150    // cleaned up.
151private:
152#endif
153    enum Deprecated_RecordingFlags {
154        /*  This flag causes the picture to compute bounding boxes and build
155            up a spatial hierarchy (currently an R-Tree), plus a tree of Canvas'
156            usually stack-based clip/etc state. This requires an increase in
157            recording time (often ~2x; likely more for very complex pictures),
158            but allows us to perform much faster culling at playback time, and
159            completely avoid some unnecessary clips and other operations. This
160            is ideal for tiled rendering, or any other situation where you're
161            drawing a fraction of a large scene into a smaller viewport.
162
163            In most cases the record cost is offset by the playback improvement
164            after a frame or two of tiled rendering (and complex pictures that
165            induce the worst record times will generally get the largest
166            speedups at playback time).
167
168            Note: Currently this is not serializable, the bounding data will be
169            discarded if you serialize into a stream and then deserialize.
170        */
171        kOptimizeForClippedPlayback_RecordingFlag = 0x02,
172    };
173#ifndef SK_SUPPORT_DEPRECATED_RECORD_FLAGS
174public:
175#endif
176
177#ifndef SK_SUPPORT_LEGACY_PICTURE_CAN_RECORD
178private:
179#endif
180
181#ifdef SK_SUPPORT_LEGACY_DERIVED_PICTURE_CLASSES
182
183    /** Returns the canvas that records the drawing commands.
184        @param width the base width for the picture, as if the recording
185                     canvas' bitmap had this width.
186        @param height the base width for the picture, as if the recording
187                     canvas' bitmap had this height.
188        @param recordFlags optional flags that control recording.
189        @return the picture canvas.
190    */
191    SkCanvas* beginRecording(int width, int height, uint32_t recordFlags = 0);
192#endif
193
194    /** Returns the recording canvas if one is active, or NULL if recording is
195        not active. This does not alter the refcnt on the canvas (if present).
196    */
197    SkCanvas* getRecordingCanvas() const;
198    /** Signal that the caller is done recording. This invalidates the canvas
199        returned by beginRecording/getRecordingCanvas, and prepares the picture
200        for drawing. Note: this happens implicitly the first time the picture
201        is drawn.
202    */
203    void endRecording();
204
205#ifndef SK_SUPPORT_LEGACY_PICTURE_CAN_RECORD
206public:
207#endif
208
209    /** Replays the drawing commands on the specified canvas. This internally
210        calls endRecording() if that has not already been called.
211        @param canvas the canvas receiving the drawing commands.
212    */
213    void draw(SkCanvas* canvas, SkDrawPictureCallback* = NULL);
214
215    /** Return the width of the picture's recording canvas. This
216        value reflects what was passed to setSize(), and does not necessarily
217        reflect the bounds of what has been recorded into the picture.
218        @return the width of the picture's recording canvas
219    */
220    int width() const { return fWidth; }
221
222    /** Return the height of the picture's recording canvas. This
223        value reflects what was passed to setSize(), and does not necessarily
224        reflect the bounds of what has been recorded into the picture.
225        @return the height of the picture's recording canvas
226    */
227    int height() const { return fHeight; }
228
229    /** Return a non-zero, unique value representing the picture. This call is
230        only valid when not recording. Between a beginRecording/endRecording
231        pair it will just return 0 (the invalid ID). Each beginRecording/
232        endRecording pair will cause a different generation ID to be returned.
233    */
234    uint32_t uniqueID() const;
235
236    /**
237     *  Function to encode an SkBitmap to an SkData. A function with this
238     *  signature can be passed to serialize() and SkWriteBuffer.
239     *  Returning NULL will tell the SkWriteBuffer to use
240     *  SkBitmap::flatten() to store the bitmap.
241     *
242     *  @param pixelRefOffset DEPRECATED -- caller assumes it will return 0.
243     *  @return SkData If non-NULL, holds encoded data representing the passed
244     *      in bitmap. The caller is responsible for calling unref().
245     */
246    typedef SkData* (*EncodeBitmap)(size_t* pixelRefOffset, const SkBitmap& bm);
247
248    /**
249     *  Serialize to a stream. If non NULL, encoder will be used to encode
250     *  any bitmaps in the picture.
251     *  encoder will never be called with a NULL pixelRefOffset.
252     */
253    void serialize(SkWStream*, EncodeBitmap encoder = NULL) const;
254
255    /**
256     *  Serialize to a buffer.
257     */
258    void flatten(SkWriteBuffer&) const;
259
260    /**
261     * Returns true if any bitmaps may be produced when this SkPicture
262     * is replayed.
263     * Returns false if called while still recording.
264     */
265    bool willPlayBackBitmaps() const;
266
267#ifdef SK_BUILD_FOR_ANDROID
268    /** Signals that the caller is prematurely done replaying the drawing
269        commands. This can be called from a canvas virtual while the picture
270        is drawing. Has no effect if the picture is not drawing.
271        @deprecated preserving for legacy purposes
272    */
273    void abortPlayback();
274#endif
275
276    /** Return true if the SkStream/Buffer represents a serialized picture, and
277        fills out SkPictInfo. After this function returns, the data source is not
278        rewound so it will have to be manually reset before passing to
279        CreateFromStream or CreateFromBuffer. Note, CreateFromStream and
280        CreateFromBuffer perform this check internally so these entry points are
281        intended for stand alone tools.
282        If false is returned, SkPictInfo is unmodified.
283    */
284    static bool InternalOnly_StreamIsSKP(SkStream*, SkPictInfo*);
285    static bool InternalOnly_BufferIsSKP(SkReadBuffer&, SkPictInfo*);
286
287    /** Enable/disable all the picture recording optimizations (i.e.,
288        those in SkPictureRecord). It is mainly intended for testing the
289        existing optimizations (i.e., to actually have the pattern
290        appear in an .skp we have to disable the optimization). Call right
291        after 'beginRecording'.
292    */
293    void internalOnly_EnableOpts(bool enableOpts);
294
295    /** Return true if the picture is suitable for rendering on the GPU.
296     */
297
298#if SK_SUPPORT_GPU
299    bool suitableForGpuRasterization(GrContext*) const;
300#endif
301
302protected:
303    // V2 : adds SkPixelRef's generation ID.
304    // V3 : PictInfo tag at beginning, and EOF tag at the end
305    // V4 : move SkPictInfo to be the header
306    // V5 : don't read/write FunctionPtr on cross-process (we can detect that)
307    // V6 : added serialization of SkPath's bounds (and packed its flags tighter)
308    // V7 : changed drawBitmapRect(IRect) to drawBitmapRectToRect(Rect)
309    // V8 : Add an option for encoding bitmaps
310    // V9 : Allow the reader and writer of an SKP disagree on whether to support
311    //      SK_SUPPORT_HINTING_SCALE_FACTOR
312    // V10: add drawRRect, drawOval, clipRRect
313    // V11: modify how readBitmap and writeBitmap store their info.
314    // V12: add conics to SkPath, use new SkPathRef flattening
315    // V13: add flag to drawBitmapRectToRect
316    //      parameterize blurs by sigma rather than radius
317    // V14: Add flags word to PathRef serialization
318    // V15: Remove A1 bitmap config (and renumber remaining configs)
319    // V16: Move SkPath's isOval flag to SkPathRef
320    // V17: SkPixelRef now writes SkImageInfo
321    // V18: SkBitmap now records x,y for its pixelref origin, instead of offset.
322    // V19: encode matrices and regions into the ops stream
323    // V20: added bool to SkPictureImageFilter's serialization (to allow SkPicture serialization)
324    // V21: add pushCull, popCull
325    // V22: SK_PICT_FACTORY_TAG's size is now the chunk size in bytes
326    // V23: SkPaint::FilterLevel became a real enum
327    // V24: SkTwoPointConicalGradient now has fFlipped flag for gradient flipping
328    // V25: SkDashPathEffect now only writes phase and interval array when flattening
329    // V26: Removed boolean from SkColorShader for inheriting color from SkPaint.
330    // V27: Remove SkUnitMapper from gradients (and skia).
331
332    // Note: If the picture version needs to be increased then please follow the
333    // steps to generate new SKPs in (only accessible to Googlers): http://goo.gl/qATVcw
334
335    // Only SKPs within the min/current picture version range (inclusive) can be read.
336    static const uint32_t MIN_PICTURE_VERSION = 19;
337    static const uint32_t CURRENT_PICTURE_VERSION = 27;
338
339    mutable uint32_t      fUniqueID;
340
341    // fPlayback, fRecord, fWidth & fHeight are protected to allow derived classes to
342    // install their own SkPicturePlayback-derived players,SkPictureRecord-derived
343    // recorders and set the picture size
344    SkPicturePlayback*    fPlayback;
345    SkPictureRecord*      fRecord;
346    int                   fWidth, fHeight;
347    const AccelData*      fAccelData;
348
349    void needsNewGenID() { fUniqueID = SK_InvalidGenID; }
350
351    // Create a new SkPicture from an existing SkPicturePlayback. Ref count of
352    // playback is unchanged.
353    SkPicture(SkPicturePlayback*, int width, int height);
354
355#ifdef SK_SUPPORT_LEGACY_DERIVED_PICTURE_CLASSES
356    // For testing. Derived classes may instantiate an alternate
357    // SkBBoxHierarchy implementation
358    virtual SkBBoxHierarchy* createBBoxHierarchy() const;
359#endif
360
361    SkCanvas* beginRecording(int width, int height, SkBBHFactory* factory, uint32_t recordFlags);
362
363private:
364    friend class SkPictureRecord;
365    friend class SkPictureTester;   // for unit testing
366
367    SkAutoTUnref<SkPathHeap> fPathHeap;  // reference counted
368
369    // ContentInfo is not serialized! It is intended solely for use
370    // with suitableForGpuRasterization.
371    class ContentInfo {
372    public:
373        ContentInfo() { this->reset(); }
374
375        ContentInfo(const ContentInfo& src) { this->set(src); }
376
377        void set(const ContentInfo& src) {
378            fNumPaintWithPathEffectUses = src.fNumPaintWithPathEffectUses;
379            fNumAAConcavePaths = src.fNumAAConcavePaths;
380            fNumAAHairlineConcavePaths = src.fNumAAHairlineConcavePaths;
381        }
382
383        void reset() {
384            fNumPaintWithPathEffectUses = 0;
385            fNumAAConcavePaths = 0;
386            fNumAAHairlineConcavePaths = 0;
387        }
388
389        void swap(ContentInfo* other) {
390            SkTSwap(fNumPaintWithPathEffectUses, other->fNumPaintWithPathEffectUses);
391            SkTSwap(fNumAAConcavePaths, other->fNumAAConcavePaths);
392            SkTSwap(fNumAAHairlineConcavePaths, other->fNumAAHairlineConcavePaths);
393        }
394
395        // This field is incremented every time a paint with a path effect is
396        // used (i.e., it is not a de-duplicated count)
397        int fNumPaintWithPathEffectUses;
398        // This field is incremented every time an anti-aliased drawPath call is
399        // issued with a concave path
400        int fNumAAConcavePaths;
401        // This field is incremented every time a drawPath call is
402        // issued for a hairline stroked concave path.
403        int fNumAAHairlineConcavePaths;
404    };
405
406    ContentInfo fContentInfo;
407
408    void incPaintWithPathEffectUses() {
409        ++fContentInfo.fNumPaintWithPathEffectUses;
410    }
411    int numPaintWithPathEffectUses() const {
412        return fContentInfo.fNumPaintWithPathEffectUses;
413    }
414
415    void incAAConcavePaths() {
416        ++fContentInfo.fNumAAConcavePaths;
417    }
418    int numAAConcavePaths() const {
419        return fContentInfo.fNumAAConcavePaths;
420    }
421
422    void incAAHairlineConcavePaths() {
423        ++fContentInfo.fNumAAHairlineConcavePaths;
424        SkASSERT(fContentInfo.fNumAAHairlineConcavePaths <= fContentInfo.fNumAAConcavePaths);
425    }
426    int numAAHairlineConcavePaths() const {
427        return fContentInfo.fNumAAHairlineConcavePaths;
428    }
429
430    const SkPath& getPath(int index) const;
431    int addPathToHeap(const SkPath& path);
432
433    void flattenToBuffer(SkWriteBuffer& buffer) const;
434    bool parseBufferTag(SkReadBuffer& buffer, uint32_t tag, uint32_t size);
435
436    static void WriteTagSize(SkWriteBuffer& buffer, uint32_t tag, size_t size);
437    static void WriteTagSize(SkWStream* stream, uint32_t tag, size_t size);
438
439    void initForPlayback() const;
440    void dumpSize() const;
441
442    // An OperationList encapsulates a set of operation offsets into the picture byte
443    // stream along with the CTMs needed for those operation.
444    class OperationList : ::SkNoncopyable {
445    public:
446        virtual ~OperationList() {}
447
448        // If valid returns false then there is no optimization data
449        // present. All the draw operations need to be issued.
450        virtual bool valid() const { return false; }
451
452        // The following three entry points should only be accessed if
453        // 'valid' returns true.
454        virtual int numOps() const { SkASSERT(false); return 0; };
455        // The offset in the picture of the operation to execute.
456        virtual uint32_t offset(int index) const { SkASSERT(false); return 0; };
457        // The CTM that must be installed for the operation to behave correctly
458        virtual const SkMatrix& matrix(int index) const { SkASSERT(false); return SkMatrix::I(); }
459
460        static const OperationList& InvalidList();
461    };
462
463    /** PRIVATE / EXPERIMENTAL -- do not call
464        Return the operations required to render the content inside 'queryRect'.
465    */
466    const OperationList& EXPERIMENTAL_getActiveOps(const SkIRect& queryRect);
467
468    /** PRIVATE / EXPERIMENTAL -- do not call
469        Return the ID of the operation currently being executed when playing
470        back. 0 indicates no call is active.
471    */
472    size_t EXPERIMENTAL_curOpID() const;
473
474    void createHeader(SkPictInfo* info) const;
475    static bool IsValidPictInfo(const SkPictInfo& info);
476    static SkPicturePlayback* FakeEndRecording(const SkPicture* resourceSrc,
477                                               const SkPictureRecord& record,
478                                               bool deepCopy);
479
480    friend class SkFlatPicture;
481    friend class SkPicturePlayback;
482    friend class SkPictureRecorder;
483    friend class SkGpuDevice;
484    friend class GrGatherCanvas;
485    friend class GrGatherDevice;
486    friend class SkDebugCanvas;
487
488    typedef SkRefCnt INHERITED;
489};
490
491/**
492 *  Subclasses of this can be passed to canvas.drawPicture. During the drawing
493 *  of the picture, this callback will periodically be invoked. If its
494 *  abortDrawing() returns true, then picture playback will be interrupted.
495 *
496 *  The resulting drawing is undefined, as there is no guarantee how often the
497 *  callback will be invoked. If the abort happens inside some level of nested
498 *  calls to save(), restore will automatically be called to return the state
499 *  to the same level it was before the drawPicture call was made.
500 */
501class SK_API SkDrawPictureCallback {
502public:
503    SkDrawPictureCallback() {}
504    virtual ~SkDrawPictureCallback() {}
505
506    virtual bool abortDrawing() = 0;
507};
508
509#ifdef SK_SUPPORT_LEGACY_DERIVED_PICTURE_CLASSES
510
511class SkPictureFactory : public SkRefCnt {
512public:
513    /**
514     *  Allocate a new SkPicture. Return NULL on failure.
515     */
516    virtual SkPicture* create(int width, int height) = 0;
517
518private:
519    typedef SkRefCnt INHERITED;
520};
521
522#endif
523
524#ifdef SK_SUPPORT_LEGACY_PICTURE_HEADERS
525#include "SkPictureRecorder.h"
526#endif
527
528#endif
529