SkPicture.h revision 8f831f262f5e57665587cb3033860eea39fe1621
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 330 // Note: If the picture version needs to be increased then please follow the 331 // steps to generate new SKPs in (only accessible to Googlers): http://goo.gl/qATVcw 332 333 // Only SKPs within the min/current picture version range (inclusive) can be read. 334 static const uint32_t MIN_PICTURE_VERSION = 19; 335 static const uint32_t CURRENT_PICTURE_VERSION = 25; 336 337 mutable uint32_t fUniqueID; 338 339 // fPlayback, fRecord, fWidth & fHeight are protected to allow derived classes to 340 // install their own SkPicturePlayback-derived players,SkPictureRecord-derived 341 // recorders and set the picture size 342 SkPicturePlayback* fPlayback; 343 SkPictureRecord* fRecord; 344 int fWidth, fHeight; 345 const AccelData* fAccelData; 346 347 void needsNewGenID() { fUniqueID = SK_InvalidGenID; } 348 349 // Create a new SkPicture from an existing SkPicturePlayback. Ref count of 350 // playback is unchanged. 351 SkPicture(SkPicturePlayback*, int width, int height); 352 353#ifdef SK_SUPPORT_LEGACY_DERIVED_PICTURE_CLASSES 354 // For testing. Derived classes may instantiate an alternate 355 // SkBBoxHierarchy implementation 356 virtual SkBBoxHierarchy* createBBoxHierarchy() const; 357#endif 358 359 SkCanvas* beginRecording(int width, int height, SkBBHFactory* factory, uint32_t recordFlags); 360 361private: 362 friend class SkPictureRecord; 363 friend class SkPictureTester; // for unit testing 364 365 SkAutoTUnref<SkPathHeap> fPathHeap; // reference counted 366 367 const SkPath& getPath(int index) const; 368 int addPathToHeap(const SkPath& path); 369 370 void flattenToBuffer(SkWriteBuffer& buffer) const; 371 bool parseBufferTag(SkReadBuffer& buffer, uint32_t tag, uint32_t size); 372 373 static void WriteTagSize(SkWriteBuffer& buffer, uint32_t tag, size_t size); 374 static void WriteTagSize(SkWStream* stream, uint32_t tag, size_t size); 375 376 void initForPlayback() const; 377 void dumpSize() const; 378 379 // An OperationList encapsulates a set of operation offsets into the picture byte 380 // stream along with the CTMs needed for those operation. 381 class OperationList : ::SkNoncopyable { 382 public: 383 virtual ~OperationList() {} 384 385 // If valid returns false then there is no optimization data 386 // present. All the draw operations need to be issued. 387 virtual bool valid() const { return false; } 388 389 // The following three entry points should only be accessed if 390 // 'valid' returns true. 391 virtual int numOps() const { SkASSERT(false); return 0; }; 392 // The offset in the picture of the operation to execute. 393 virtual uint32_t offset(int index) const { SkASSERT(false); return 0; }; 394 // The CTM that must be installed for the operation to behave correctly 395 virtual const SkMatrix& matrix(int index) const { SkASSERT(false); return SkMatrix::I(); } 396 397 static const OperationList& InvalidList(); 398 }; 399 400 /** PRIVATE / EXPERIMENTAL -- do not call 401 Return the operations required to render the content inside 'queryRect'. 402 */ 403 const OperationList& EXPERIMENTAL_getActiveOps(const SkIRect& queryRect); 404 405 /** PRIVATE / EXPERIMENTAL -- do not call 406 Return the ID of the operation currently being executed when playing 407 back. 0 indicates no call is active. 408 */ 409 size_t EXPERIMENTAL_curOpID() const; 410 411 void createHeader(SkPictInfo* info) const; 412 static bool IsValidPictInfo(const SkPictInfo& info); 413 414 friend class SkFlatPicture; 415 friend class SkPicturePlayback; 416 friend class SkPictureRecorder; 417 friend class SkGpuDevice; 418 friend class GrGatherDevice; 419 friend class SkDebugCanvas; 420 421 typedef SkRefCnt INHERITED; 422}; 423 424/** 425 * Subclasses of this can be passed to canvas.drawPicture. During the drawing 426 * of the picture, this callback will periodically be invoked. If its 427 * abortDrawing() returns true, then picture playback will be interrupted. 428 * 429 * The resulting drawing is undefined, as there is no guarantee how often the 430 * callback will be invoked. If the abort happens inside some level of nested 431 * calls to save(), restore will automatically be called to return the state 432 * to the same level it was before the drawPicture call was made. 433 */ 434class SK_API SkDrawPictureCallback { 435public: 436 SkDrawPictureCallback() {} 437 virtual ~SkDrawPictureCallback() {} 438 439 virtual bool abortDrawing() = 0; 440}; 441 442#ifdef SK_SUPPORT_LEGACY_DERIVED_PICTURE_CLASSES 443 444class SkPictureFactory : public SkRefCnt { 445public: 446 /** 447 * Allocate a new SkPicture. Return NULL on failure. 448 */ 449 virtual SkPicture* create(int width, int height) = 0; 450 451private: 452 typedef SkRefCnt INHERITED; 453}; 454 455#endif 456 457#ifdef SK_SUPPORT_LEGACY_PICTURE_HEADERS 458#include "SkPictureRecorder.h" 459#endif 460 461#endif 462