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