Home | History | Annotate | Download | only in core
      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 class SkBBoxHierarchy;
     18 class SkCanvas;
     19 class SkDrawPictureCallback;
     20 class SkData;
     21 class SkPicturePlayback;
     22 class SkPictureRecord;
     23 class SkStream;
     24 class SkWStream;
     25 
     26 struct SkPictInfo;
     27 
     28 /** \class SkPicture
     29 
     30     The SkPicture class records the drawing commands made to a canvas, to
     31     be played back at a later time.
     32 */
     33 class SK_API SkPicture : public SkRefCnt {
     34 public:
     35     SK_DECLARE_INST_COUNT(SkPicture)
     36 
     37     /** The constructor prepares the picture to record.
     38         @param width the width of the virtual device the picture records.
     39         @param height the height of the virtual device the picture records.
     40     */
     41     SkPicture();
     42     /** Make a copy of the contents of src. If src records more drawing after
     43         this call, those elements will not appear in this picture.
     44     */
     45     SkPicture(const SkPicture& src);
     46 
     47     /**
     48      *  Function signature defining a function that sets up an SkBitmap from encoded data. On
     49      *  success, the SkBitmap should have its Config, width, height, rowBytes and pixelref set.
     50      *  If the installed pixelref has decoded the data into pixels, then the src buffer need not be
     51      *  copied. If the pixelref defers the actual decode until its lockPixels() is called, then it
     52      *  must make a copy of the src buffer.
     53      *  @param src Encoded data.
     54      *  @param length Size of the encoded data, in bytes.
     55      *  @param dst SkBitmap to install the pixel ref on.
     56      *  @param bool Whether or not a pixel ref was successfully installed.
     57      */
     58     typedef bool (*InstallPixelRefProc)(const void* src, size_t length, SkBitmap* dst);
     59 
     60     /**
     61      *  Recreate a picture that was serialized into a stream.
     62      *  @param SkStream Serialized picture data.
     63      *  @param proc Function pointer for installing pixelrefs on SkBitmaps representing the
     64      *              encoded bitmap data from the stream.
     65      *  @return A new SkPicture representing the serialized data, or NULL if the stream is
     66      *          invalid.
     67      */
     68     static SkPicture* CreateFromStream(SkStream*,
     69                                        InstallPixelRefProc proc = &SkImageDecoder::DecodeMemory);
     70 
     71     virtual ~SkPicture();
     72 
     73     /**
     74      *  Swap the contents of the two pictures. Guaranteed to succeed.
     75      */
     76     void swap(SkPicture& other);
     77 
     78     /**
     79      *  Creates a thread-safe clone of the picture that is ready for playback.
     80      */
     81     SkPicture* clone() const;
     82 
     83     /**
     84      * Creates multiple thread-safe clones of this picture that are ready for
     85      * playback. The resulting clones are stored in the provided array of
     86      * SkPictures.
     87      */
     88     void clone(SkPicture* pictures, int count) const;
     89 
     90     enum RecordingFlags {
     91         /*  This flag specifies that when clipPath() is called, the path will
     92             be faithfully recorded, but the recording canvas' current clip will
     93             only see the path's bounds. This speeds up the recording process
     94             without compromising the fidelity of the playback. The only side-
     95             effect for recording is that calling getTotalClip() or related
     96             clip-query calls will reflect the path's bounds, not the actual
     97             path.
     98          */
     99         kUsePathBoundsForClip_RecordingFlag = 0x01,
    100         /*  This flag causes the picture to compute bounding boxes and build
    101             up a spatial hierarchy (currently an R-Tree), plus a tree of Canvas'
    102             usually stack-based clip/etc state. This requires an increase in
    103             recording time (often ~2x; likely more for very complex pictures),
    104             but allows us to perform much faster culling at playback time, and
    105             completely avoid some unnecessary clips and other operations. This
    106             is ideal for tiled rendering, or any other situation where you're
    107             drawing a fraction of a large scene into a smaller viewport.
    108 
    109             In most cases the record cost is offset by the playback improvement
    110             after a frame or two of tiled rendering (and complex pictures that
    111             induce the worst record times will generally get the largest
    112             speedups at playback time).
    113 
    114             Note: Currently this is not serializable, the bounding data will be
    115             discarded if you serialize into a stream and then deserialize.
    116         */
    117         kOptimizeForClippedPlayback_RecordingFlag = 0x02,
    118         /*
    119             This flag disables all the picture recording optimizations (i.e.,
    120             those in SkPictureRecord). It is mainly intended for testing the
    121             existing optimizations (i.e., to actually have the pattern
    122             appear in an .skp we have to disable the optimization). This
    123             option doesn't affect the optimizations controlled by
    124             'kOptimizeForClippedPlayback_RecordingFlag'.
    125          */
    126         kDisableRecordOptimizations_RecordingFlag = 0x04
    127     };
    128 
    129     /** Returns the canvas that records the drawing commands.
    130         @param width the base width for the picture, as if the recording
    131                      canvas' bitmap had this width.
    132         @param height the base width for the picture, as if the recording
    133                      canvas' bitmap had this height.
    134         @param recordFlags optional flags that control recording.
    135         @return the picture canvas.
    136     */
    137     SkCanvas* beginRecording(int width, int height, uint32_t recordFlags = 0);
    138 
    139     /** Returns the recording canvas if one is active, or NULL if recording is
    140         not active. This does not alter the refcnt on the canvas (if present).
    141     */
    142     SkCanvas* getRecordingCanvas() const;
    143     /** Signal that the caller is done recording. This invalidates the canvas
    144         returned by beginRecording/getRecordingCanvas, and prepares the picture
    145         for drawing. Note: this happens implicitly the first time the picture
    146         is drawn.
    147     */
    148     void endRecording();
    149 
    150     /** Replays the drawing commands on the specified canvas. This internally
    151         calls endRecording() if that has not already been called.
    152         @param canvas the canvas receiving the drawing commands.
    153     */
    154     void draw(SkCanvas* canvas, SkDrawPictureCallback* = NULL);
    155 
    156     /** Return the width of the picture's recording canvas. This
    157         value reflects what was passed to setSize(), and does not necessarily
    158         reflect the bounds of what has been recorded into the picture.
    159         @return the width of the picture's recording canvas
    160     */
    161     int width() const { return fWidth; }
    162 
    163     /** Return the height of the picture's recording canvas. This
    164         value reflects what was passed to setSize(), and does not necessarily
    165         reflect the bounds of what has been recorded into the picture.
    166         @return the height of the picture's recording canvas
    167     */
    168     int height() const { return fHeight; }
    169 
    170     /**
    171      *  Function to encode an SkBitmap to an SkData. A function with this
    172      *  signature can be passed to serialize() and SkOrderedWriteBuffer.
    173      *  Returning NULL will tell the SkOrderedWriteBuffer to use
    174      *  SkBitmap::flatten() to store the bitmap.
    175      *  @param pixelRefOffset Output parameter, telling the deserializer what
    176      *      offset in the bm's pixelRef corresponds to the encoded data.
    177      *  @return SkData If non-NULL, holds encoded data representing the passed
    178      *      in bitmap. The caller is responsible for calling unref().
    179      */
    180     typedef SkData* (*EncodeBitmap)(size_t* pixelRefOffset, const SkBitmap& bm);
    181 
    182     /**
    183      *  Serialize to a stream. If non NULL, encoder will be used to encode
    184      *  any bitmaps in the picture.
    185      *  encoder will never be called with a NULL pixelRefOffset.
    186      */
    187     void serialize(SkWStream*, EncodeBitmap encoder = NULL) const;
    188 
    189 #ifdef SK_BUILD_FOR_ANDROID
    190     /** Signals that the caller is prematurely done replaying the drawing
    191         commands. This can be called from a canvas virtual while the picture
    192         is drawing. Has no effect if the picture is not drawing.
    193         @deprecated preserving for legacy purposes
    194     */
    195     void abortPlayback();
    196 #endif
    197 
    198 protected:
    199     // V2 : adds SkPixelRef's generation ID.
    200     // V3 : PictInfo tag at beginning, and EOF tag at the end
    201     // V4 : move SkPictInfo to be the header
    202     // V5 : don't read/write FunctionPtr on cross-process (we can detect that)
    203     // V6 : added serialization of SkPath's bounds (and packed its flags tighter)
    204     // V7 : changed drawBitmapRect(IRect) to drawBitmapRectToRect(Rect)
    205     // V8 : Add an option for encoding bitmaps
    206     // V9 : Allow the reader and writer of an SKP disagree on whether to support
    207     //      SK_SUPPORT_HINTING_SCALE_FACTOR
    208     // V10: add drawRRect, drawOval, clipRRect
    209     // V11: modify how readBitmap and writeBitmap store their info.
    210     // V12: add conics to SkPath, use new SkPathRef flattening
    211     static const uint32_t PICTURE_VERSION = 12;
    212 
    213     // fPlayback, fRecord, fWidth & fHeight are protected to allow derived classes to
    214     // install their own SkPicturePlayback-derived players,SkPictureRecord-derived
    215     // recorders and set the picture size
    216     SkPicturePlayback* fPlayback;
    217     SkPictureRecord* fRecord;
    218     int fWidth, fHeight;
    219 
    220     // Create a new SkPicture from an existing SkPicturePlayback. Ref count of
    221     // playback is unchanged.
    222     SkPicture(SkPicturePlayback*, int width, int height);
    223 
    224     // For testing. Derived classes may instantiate an alternate
    225     // SkBBoxHierarchy implementation
    226     virtual SkBBoxHierarchy* createBBoxHierarchy() const;
    227 
    228     // Return true if the SkStream represents a serialized picture, and fills out
    229     // SkPictInfo. After this function returns, the SkStream is not rewound; it
    230     // will be ready to be parsed to create an SkPicturePlayback.
    231     // If false is returned, SkPictInfo is unmodified.
    232     static bool StreamIsSKP(SkStream*, SkPictInfo*);
    233 private:
    234     friend class SkFlatPicture;
    235     friend class SkPicturePlayback;
    236 
    237     typedef SkRefCnt INHERITED;
    238 };
    239 
    240 class SkAutoPictureRecord : SkNoncopyable {
    241 public:
    242     SkAutoPictureRecord(SkPicture* pict, int width, int height,
    243                         uint32_t recordingFlags = 0) {
    244         fPicture = pict;
    245         fCanvas = pict->beginRecording(width, height, recordingFlags);
    246     }
    247     ~SkAutoPictureRecord() {
    248         fPicture->endRecording();
    249     }
    250 
    251     /** Return the canvas to draw into for recording into the picture.
    252     */
    253     SkCanvas* getRecordingCanvas() const { return fCanvas; }
    254 
    255 private:
    256     SkPicture*  fPicture;
    257     SkCanvas*   fCanvas;
    258 };
    259 
    260 /**
    261  *  Subclasses of this can be passed to canvas.drawPicture. During the drawing
    262  *  of the picture, this callback will periodically be invoked. If its
    263  *  abortDrawing() returns true, then picture playback will be interrupted.
    264  *
    265  *  The resulting drawing is undefined, as there is no guarantee how often the
    266  *  callback will be invoked. If the abort happens inside some level of nested
    267  *  calls to save(), restore will automatically be called to return the state
    268  *  to the same level it was before the drawPicture call was made.
    269  */
    270 class SK_API SkDrawPictureCallback {
    271 public:
    272     SkDrawPictureCallback() {}
    273     virtual ~SkDrawPictureCallback() {}
    274 
    275     virtual bool abortDrawing() = 0;
    276 };
    277 
    278 #endif
    279