2 * Copyright (C) 2015 The Android Open Source Project
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 #include "RecordingCanvas.h"
19 #include "DeferredLayerUpdater.h"
20 #include "RecordedOp.h"
21 #include "RenderNode.h"
22 #include "VectorDrawable.h"
25 namespace uirenderer {
27 RecordingCanvas::RecordingCanvas(size_t width, size_t height)
29 , mResourceCache(ResourceCache::getInstance()) {
30 resetRecording(width, height);
33 RecordingCanvas::~RecordingCanvas() {
34 LOG_ALWAYS_FATAL_IF(mDisplayList,
35 "Destroyed a RecordingCanvas during a record!");
38 void RecordingCanvas::resetRecording(int width, int height) {
39 LOG_ALWAYS_FATAL_IF(mDisplayList,
40 "prepareDirty called a second time during a recording!");
41 mDisplayList = new DisplayList();
43 mState.initializeRecordingSaveStack(width, height);
45 mDeferredBarrierType = DeferredBarrierType::InOrder;
46 mState.setDirtyClip(false);
49 DisplayList* RecordingCanvas::finishRecording() {
54 DisplayList* displayList = mDisplayList;
55 mDisplayList = nullptr;
56 mSkiaCanvasProxy.reset(nullptr);
60 void RecordingCanvas::insertReorderBarrier(bool enableReorder) {
62 mDeferredBarrierType = DeferredBarrierType::OutOfOrder;
63 mDeferredBarrierClip = getRecordedClip();
65 mDeferredBarrierType = DeferredBarrierType::InOrder;
66 mDeferredBarrierClip = nullptr;
70 SkCanvas* RecordingCanvas::asSkCanvas() {
71 LOG_ALWAYS_FATAL_IF(!mDisplayList,
72 "attempting to get an SkCanvas when we are not recording!");
73 if (!mSkiaCanvasProxy) {
74 mSkiaCanvasProxy.reset(new SkiaCanvasProxy(this));
77 // SkCanvas instances default to identity transform, but should inherit
78 // the state of this Canvas; if this code was in the SkiaCanvasProxy
79 // constructor, we couldn't cache mSkiaCanvasProxy.
80 SkMatrix parentTransform;
81 getMatrix(&parentTransform);
82 mSkiaCanvasProxy.get()->setMatrix(parentTransform);
84 return mSkiaCanvasProxy.get();
87 // ----------------------------------------------------------------------------
88 // CanvasStateClient implementation
89 // ----------------------------------------------------------------------------
91 void RecordingCanvas::onViewportInitialized() {
94 void RecordingCanvas::onSnapshotRestored(const Snapshot& removed, const Snapshot& restored) {
95 if (removed.flags & Snapshot::kFlagIsFboLayer) {
96 addOp(alloc().create_trivial<EndLayerOp>());
97 } else if (removed.flags & Snapshot::kFlagIsLayer) {
98 addOp(alloc().create_trivial<EndUnclippedLayerOp>());
102 // ----------------------------------------------------------------------------
103 // android/graphics/Canvas state operations
104 // ----------------------------------------------------------------------------
106 int RecordingCanvas::save(SaveFlags::Flags flags) {
107 return mState.save((int) flags);
110 void RecordingCanvas::RecordingCanvas::restore() {
114 void RecordingCanvas::restoreToCount(int saveCount) {
115 mState.restoreToCount(saveCount);
118 int RecordingCanvas::saveLayer(float left, float top, float right, float bottom,
119 const SkPaint* paint, SaveFlags::Flags flags) {
120 // force matrix/clip isolation for layer
121 flags |= SaveFlags::MatrixClip;
122 bool clippedLayer = flags & SaveFlags::ClipToLayer;
124 const Snapshot& previous = *mState.currentSnapshot();
126 // initialize the snapshot as though it almost represents an FBO layer so deferred draw
127 // operations will be able to store and restore the current clip and transform info, and
128 // quick rejection will be correct (for display lists)
130 const Rect unmappedBounds(left, top, right, bottom);
132 // determine clipped bounds relative to previous viewport.
133 Rect visibleBounds = unmappedBounds;
134 previous.transform->mapRect(visibleBounds);
136 if (CC_UNLIKELY(!clippedLayer
137 && previous.transform->rectToRect()
138 && visibleBounds.contains(previous.getRenderTargetClip()))) {
139 // unlikely case where an unclipped savelayer is recorded with a clip it can use,
140 // as none of its unaffected/unclipped area is visible
142 flags |= SaveFlags::ClipToLayer;
145 visibleBounds.doIntersect(previous.getRenderTargetClip());
146 visibleBounds.snapToPixelBoundaries();
147 visibleBounds.doIntersect(Rect(previous.getViewportWidth(), previous.getViewportHeight()));
149 // Map visible bounds back to layer space, and intersect with parameter bounds
150 Rect layerBounds = visibleBounds;
152 inverse.loadInverse(*previous.transform);
153 inverse.mapRect(layerBounds);
154 layerBounds.doIntersect(unmappedBounds);
156 int saveValue = mState.save((int) flags);
157 Snapshot& snapshot = *mState.writableSnapshot();
159 // layerBounds is in original bounds space, but clipped by current recording clip
160 if (layerBounds.isEmpty() || unmappedBounds.isEmpty()) {
161 // Don't bother recording layer, since it's been rejected
162 if (CC_LIKELY(clippedLayer)) {
163 snapshot.resetClip(0, 0, 0, 0);
168 if (CC_LIKELY(clippedLayer)) {
169 auto previousClip = getRecordedClip(); // note: done before new snapshot's clip has changed
171 snapshot.flags |= Snapshot::kFlagIsLayer | Snapshot::kFlagIsFboLayer;
172 snapshot.initializeViewport(unmappedBounds.getWidth(), unmappedBounds.getHeight());
173 snapshot.transform->loadTranslate(-unmappedBounds.left, -unmappedBounds.top, 0.0f);
175 Rect clip = layerBounds;
176 clip.translate(-unmappedBounds.left, -unmappedBounds.top);
177 snapshot.resetClip(clip.left, clip.top, clip.right, clip.bottom);
178 snapshot.roundRectClipState = nullptr;
180 addOp(alloc().create_trivial<BeginLayerOp>(
182 *previous.transform, // transform to *draw* with
183 previousClip, // clip to *draw* with
186 snapshot.flags |= Snapshot::kFlagIsLayer;
188 addOp(alloc().create_trivial<BeginUnclippedLayerOp>(
190 *mState.currentSnapshot()->transform,
199 void RecordingCanvas::rotate(float degrees) {
200 if (degrees == 0) return;
202 mState.rotate(degrees);
205 void RecordingCanvas::scale(float sx, float sy) {
206 if (sx == 1 && sy == 1) return;
208 mState.scale(sx, sy);
211 void RecordingCanvas::skew(float sx, float sy) {
215 void RecordingCanvas::translate(float dx, float dy) {
216 if (dx == 0 && dy == 0) return;
218 mState.translate(dx, dy, 0);
222 bool RecordingCanvas::getClipBounds(SkRect* outRect) const {
223 *outRect = mState.getLocalClipBounds().toSkRect();
224 return !(outRect->isEmpty());
226 bool RecordingCanvas::quickRejectRect(float left, float top, float right, float bottom) const {
227 return mState.quickRejectConservative(left, top, right, bottom);
229 bool RecordingCanvas::quickRejectPath(const SkPath& path) const {
230 SkRect bounds = path.getBounds();
231 return mState.quickRejectConservative(bounds.fLeft, bounds.fTop, bounds.fRight, bounds.fBottom);
233 bool RecordingCanvas::clipRect(float left, float top, float right, float bottom, SkRegion::Op op) {
234 return mState.clipRect(left, top, right, bottom, op);
236 bool RecordingCanvas::clipPath(const SkPath* path, SkRegion::Op op) {
237 return mState.clipPath(path, op);
239 bool RecordingCanvas::clipRegion(const SkRegion* region, SkRegion::Op op) {
240 return mState.clipRegion(region, op);
243 // ----------------------------------------------------------------------------
244 // android/graphics/Canvas draw operations
245 // ----------------------------------------------------------------------------
246 void RecordingCanvas::drawColor(int color, SkXfermode::Mode mode) {
247 addOp(alloc().create_trivial<ColorOp>(
253 void RecordingCanvas::drawPaint(const SkPaint& paint) {
255 if (getClipBounds(&bounds)) {
256 drawRect(bounds.fLeft, bounds.fTop, bounds.fRight, bounds.fBottom, paint);
260 static Rect calcBoundsOfPoints(const float* points, int floatCount) {
261 Rect unmappedBounds(points[0], points[1], points[0], points[1]);
262 for (int i = 2; i < floatCount; i += 2) {
263 unmappedBounds.expandToCover(points[i], points[i + 1]);
265 return unmappedBounds;
269 void RecordingCanvas::drawPoints(const float* points, int floatCount, const SkPaint& paint) {
270 if (floatCount < 2) return;
271 floatCount &= ~0x1; // round down to nearest two
273 addOp(alloc().create_trivial<PointsOp>(
274 calcBoundsOfPoints(points, floatCount),
275 *mState.currentSnapshot()->transform,
277 refPaint(&paint), refBuffer<float>(points, floatCount), floatCount));
280 void RecordingCanvas::drawLines(const float* points, int floatCount, const SkPaint& paint) {
281 if (floatCount < 4) return;
282 floatCount &= ~0x3; // round down to nearest four
284 addOp(alloc().create_trivial<LinesOp>(
285 calcBoundsOfPoints(points, floatCount),
286 *mState.currentSnapshot()->transform,
288 refPaint(&paint), refBuffer<float>(points, floatCount), floatCount));
291 void RecordingCanvas::drawRect(float left, float top, float right, float bottom, const SkPaint& paint) {
292 addOp(alloc().create_trivial<RectOp>(
293 Rect(left, top, right, bottom),
294 *(mState.currentSnapshot()->transform),
299 void RecordingCanvas::drawSimpleRects(const float* rects, int vertexCount, const SkPaint* paint) {
300 if (rects == nullptr) return;
302 Vertex* rectData = (Vertex*) mDisplayList->allocator.create_trivial_array<Vertex>(vertexCount);
303 Vertex* vertex = rectData;
305 float left = FLT_MAX;
307 float right = FLT_MIN;
308 float bottom = FLT_MIN;
309 for (int index = 0; index < vertexCount; index += 4) {
310 float l = rects[index + 0];
311 float t = rects[index + 1];
312 float r = rects[index + 2];
313 float b = rects[index + 3];
315 Vertex::set(vertex++, l, t);
316 Vertex::set(vertex++, r, t);
317 Vertex::set(vertex++, l, b);
318 Vertex::set(vertex++, r, b);
320 left = std::min(left, l);
321 top = std::min(top, t);
322 right = std::max(right, r);
323 bottom = std::max(bottom, b);
325 addOp(alloc().create_trivial<SimpleRectsOp>(
326 Rect(left, top, right, bottom),
327 *(mState.currentSnapshot()->transform),
329 refPaint(paint), rectData, vertexCount));
332 void RecordingCanvas::drawRegion(const SkRegion& region, const SkPaint& paint) {
333 if (paint.getStyle() == SkPaint::kFill_Style
334 && (!paint.isAntiAlias() || mState.currentTransform()->isSimple())) {
337 SkRegion::Iterator it(region);
339 const SkIRect& r = it.rect();
342 rects.push(r.fRight);
343 rects.push(r.fBottom);
347 drawSimpleRects(rects.array(), count, &paint);
349 SkRegion::Iterator it(region);
351 const SkIRect& r = it.rect();
352 drawRect(r.fLeft, r.fTop, r.fRight, r.fBottom, paint);
357 void RecordingCanvas::drawRoundRect(float left, float top, float right, float bottom,
358 float rx, float ry, const SkPaint& paint) {
359 if (CC_LIKELY(MathUtils::isPositive(rx) || MathUtils::isPositive(ry))) {
360 addOp(alloc().create_trivial<RoundRectOp>(
361 Rect(left, top, right, bottom),
362 *(mState.currentSnapshot()->transform),
364 refPaint(&paint), rx, ry));
366 drawRect(left, top, right, bottom, paint);
370 void RecordingCanvas::drawRoundRect(
371 CanvasPropertyPrimitive* left, CanvasPropertyPrimitive* top,
372 CanvasPropertyPrimitive* right, CanvasPropertyPrimitive* bottom,
373 CanvasPropertyPrimitive* rx, CanvasPropertyPrimitive* ry,
374 CanvasPropertyPaint* paint) {
375 mDisplayList->ref(left);
376 mDisplayList->ref(top);
377 mDisplayList->ref(right);
378 mDisplayList->ref(bottom);
379 mDisplayList->ref(rx);
380 mDisplayList->ref(ry);
381 mDisplayList->ref(paint);
382 refBitmapsInShader(paint->value.getShader());
383 addOp(alloc().create_trivial<RoundRectPropsOp>(
384 *(mState.currentSnapshot()->transform),
387 &left->value, &top->value, &right->value, &bottom->value,
388 &rx->value, &ry->value));
391 void RecordingCanvas::drawCircle(float x, float y, float radius, const SkPaint& paint) {
392 // TODO: move to Canvas.h
393 if (radius <= 0) return;
394 drawOval(x - radius, y - radius, x + radius, y + radius, paint);
397 void RecordingCanvas::drawCircle(
398 CanvasPropertyPrimitive* x, CanvasPropertyPrimitive* y,
399 CanvasPropertyPrimitive* radius, CanvasPropertyPaint* paint) {
400 mDisplayList->ref(x);
401 mDisplayList->ref(y);
402 mDisplayList->ref(radius);
403 mDisplayList->ref(paint);
404 refBitmapsInShader(paint->value.getShader());
405 addOp(alloc().create_trivial<CirclePropsOp>(
406 *(mState.currentSnapshot()->transform),
409 &x->value, &y->value, &radius->value));
412 void RecordingCanvas::drawOval(float left, float top, float right, float bottom, const SkPaint& paint) {
413 addOp(alloc().create_trivial<OvalOp>(
414 Rect(left, top, right, bottom),
415 *(mState.currentSnapshot()->transform),
420 void RecordingCanvas::drawArc(float left, float top, float right, float bottom,
421 float startAngle, float sweepAngle, bool useCenter, const SkPaint& paint) {
422 if (fabs(sweepAngle) >= 360.0f) {
423 drawOval(left, top, right, bottom, paint);
425 addOp(alloc().create_trivial<ArcOp>(
426 Rect(left, top, right, bottom),
427 *(mState.currentSnapshot()->transform),
430 startAngle, sweepAngle, useCenter));
434 void RecordingCanvas::drawPath(const SkPath& path, const SkPaint& paint) {
435 addOp(alloc().create_trivial<PathOp>(
436 Rect(path.getBounds()),
437 *(mState.currentSnapshot()->transform),
439 refPaint(&paint), refPath(&path)));
442 void RecordingCanvas::drawVectorDrawable(VectorDrawableRoot* tree) {
443 mDisplayList->pushStagingFunctors.push_back(tree->getFunctor());
444 mDisplayList->ref(tree);
445 addOp(alloc().create_trivial<VectorDrawableOp>(
447 Rect(tree->stagingProperties()->getBounds()),
448 *(mState.currentSnapshot()->transform),
453 void RecordingCanvas::drawBitmap(const SkBitmap& bitmap, float left, float top, const SkPaint* paint) {
454 save(SaveFlags::Matrix);
455 translate(left, top);
456 drawBitmap(&bitmap, paint);
460 void RecordingCanvas::drawBitmap(const SkBitmap& bitmap, const SkMatrix& matrix,
461 const SkPaint* paint) {
462 if (matrix.isIdentity()) {
463 drawBitmap(&bitmap, paint);
464 } else if (!(matrix.getType() & ~(SkMatrix::kScale_Mask | SkMatrix::kTranslate_Mask))
465 && MathUtils::isPositive(matrix.getScaleX())
466 && MathUtils::isPositive(matrix.getScaleY())) {
467 // SkMatrix::isScaleTranslate() not available in L
470 bitmap.getBounds(&src);
471 matrix.mapRect(&dst, src);
472 drawBitmap(bitmap, src.fLeft, src.fTop, src.fRight, src.fBottom,
473 dst.fLeft, dst.fTop, dst.fRight, dst.fBottom, paint);
475 save(SaveFlags::Matrix);
477 drawBitmap(&bitmap, paint);
482 void RecordingCanvas::drawBitmap(const SkBitmap& bitmap, float srcLeft, float srcTop,
483 float srcRight, float srcBottom, float dstLeft, float dstTop,
484 float dstRight, float dstBottom, const SkPaint* paint) {
485 if (srcLeft == 0 && srcTop == 0
486 && srcRight == bitmap.width()
487 && srcBottom == bitmap.height()
488 && (srcBottom - srcTop == dstBottom - dstTop)
489 && (srcRight - srcLeft == dstRight - dstLeft)) {
490 // transform simple rect to rect drawing case into position bitmap ops, since they merge
491 save(SaveFlags::Matrix);
492 translate(dstLeft, dstTop);
493 drawBitmap(&bitmap, paint);
496 addOp(alloc().create_trivial<BitmapRectOp>(
497 Rect(dstLeft, dstTop, dstRight, dstBottom),
498 *(mState.currentSnapshot()->transform),
500 refPaint(paint), refBitmap(bitmap),
501 Rect(srcLeft, srcTop, srcRight, srcBottom)));
505 void RecordingCanvas::drawBitmapMesh(const SkBitmap& bitmap, int meshWidth, int meshHeight,
506 const float* vertices, const int* colors, const SkPaint* paint) {
507 int vertexCount = (meshWidth + 1) * (meshHeight + 1);
508 addOp(alloc().create_trivial<BitmapMeshOp>(
509 calcBoundsOfPoints(vertices, vertexCount * 2),
510 *(mState.currentSnapshot()->transform),
512 refPaint(paint), refBitmap(bitmap), meshWidth, meshHeight,
513 refBuffer<float>(vertices, vertexCount * 2), // 2 floats per vertex
514 refBuffer<int>(colors, vertexCount))); // 1 color per vertex
517 void RecordingCanvas::drawNinePatch(const SkBitmap& bitmap, const android::Res_png_9patch& patch,
518 float dstLeft, float dstTop, float dstRight, float dstBottom,
519 const SkPaint* paint) {
520 addOp(alloc().create_trivial<PatchOp>(
521 Rect(dstLeft, dstTop, dstRight, dstBottom),
522 *(mState.currentSnapshot()->transform),
524 refPaint(paint), refBitmap(bitmap), refPatch(&patch)));
528 void RecordingCanvas::drawGlyphs(const uint16_t* glyphs, const float* positions, int glyphCount,
529 const SkPaint& paint, float x, float y, float boundsLeft, float boundsTop,
530 float boundsRight, float boundsBottom, float totalAdvance) {
531 if (!glyphs || !positions || glyphCount <= 0 || PaintUtils::paintWillNotDrawText(paint)) return;
532 glyphs = refBuffer<glyph_t>(glyphs, glyphCount);
533 positions = refBuffer<float>(positions, glyphCount * 2);
535 // TODO: either must account for text shadow in bounds, or record separate ops for text shadows
536 addOp(alloc().create_trivial<TextOp>(
537 Rect(boundsLeft, boundsTop, boundsRight, boundsBottom),
538 *(mState.currentSnapshot()->transform),
540 refPaint(&paint), glyphs, positions, glyphCount, x, y));
541 drawTextDecorations(x, y, totalAdvance, paint);
544 void RecordingCanvas::drawGlyphsOnPath(const uint16_t* glyphs, int glyphCount, const SkPath& path,
545 float hOffset, float vOffset, const SkPaint& paint) {
546 if (!glyphs || glyphCount <= 0 || PaintUtils::paintWillNotDrawText(paint)) return;
547 glyphs = refBuffer<glyph_t>(glyphs, glyphCount);
548 addOp(alloc().create_trivial<TextOnPathOp>(
549 *(mState.currentSnapshot()->transform),
551 refPaint(&paint), glyphs, glyphCount, refPath(&path), hOffset, vOffset));
554 void RecordingCanvas::drawBitmap(const SkBitmap* bitmap, const SkPaint* paint) {
555 addOp(alloc().create_trivial<BitmapOp>(
556 Rect(bitmap->width(), bitmap->height()),
557 *(mState.currentSnapshot()->transform),
559 refPaint(paint), refBitmap(*bitmap)));
562 void RecordingCanvas::drawRenderNode(RenderNode* renderNode) {
563 auto&& stagingProps = renderNode->stagingProperties();
564 RenderNodeOp* op = alloc().create_trivial<RenderNodeOp>(
565 Rect(stagingProps.getWidth(), stagingProps.getHeight()),
566 *(mState.currentSnapshot()->transform),
569 int opIndex = addOp(op);
570 if (CC_LIKELY(opIndex >= 0)) {
571 int childIndex = mDisplayList->addChild(op);
573 // update the chunk's child indices
574 DisplayList::Chunk& chunk = mDisplayList->chunks.back();
575 chunk.endChildIndex = childIndex + 1;
577 if (renderNode->stagingProperties().isProjectionReceiver()) {
578 // use staging property, since recording on UI thread
579 mDisplayList->projectionReceiveIndex = opIndex;
584 void RecordingCanvas::drawLayer(DeferredLayerUpdater* layerHandle) {
585 // We ref the DeferredLayerUpdater due to its thread-safe ref-counting semantics.
586 mDisplayList->ref(layerHandle);
588 // Note that the backing layer has *not* yet been updated, so don't trust
589 // its width, height, transform, etc...!
590 addOp(alloc().create_trivial<TextureLayerOp>(
591 Rect(layerHandle->getWidth(), layerHandle->getHeight()),
592 *(mState.currentSnapshot()->transform),
594 layerHandle->backingLayer()));
597 void RecordingCanvas::callDrawGLFunction(Functor* functor,
598 GlFunctorLifecycleListener* listener) {
599 mDisplayList->functors.push_back({functor, listener});
600 mDisplayList->ref(listener);
601 addOp(alloc().create_trivial<FunctorOp>(
602 *(mState.currentSnapshot()->transform),
607 size_t RecordingCanvas::addOp(RecordedOp* op) {
608 // skip op with empty clip
609 if (op->localClip && op->localClip->rect.isEmpty()) {
610 // NOTE: this rejection happens after op construction/content ref-ing, so content ref'd
611 // and held by renderthread isn't affected by clip rejection.
612 // Could rewind alloc here if desired, but callers would have to not touch op afterwards.
616 int insertIndex = mDisplayList->ops.size();
617 mDisplayList->ops.push_back(op);
618 if (mDeferredBarrierType != DeferredBarrierType::None) {
619 // op is first in new chunk
620 mDisplayList->chunks.emplace_back();
621 DisplayList::Chunk& newChunk = mDisplayList->chunks.back();
622 newChunk.beginOpIndex = insertIndex;
623 newChunk.endOpIndex = insertIndex + 1;
624 newChunk.reorderChildren = (mDeferredBarrierType == DeferredBarrierType::OutOfOrder);
625 newChunk.reorderClip = mDeferredBarrierClip;
627 int nextChildIndex = mDisplayList->children.size();
628 newChunk.beginChildIndex = newChunk.endChildIndex = nextChildIndex;
629 mDeferredBarrierType = DeferredBarrierType::None;
631 // standard case - append to existing chunk
632 mDisplayList->chunks.back().endOpIndex = insertIndex + 1;
637 void RecordingCanvas::refBitmapsInShader(const SkShader* shader) {
640 // If this paint has an SkShader that has an SkBitmap add
641 // it to the bitmap pile
643 SkShader::TileMode xy[2];
644 if (shader->isABitmap(&bitmap, nullptr, xy)) {
648 SkShader::ComposeRec rec;
649 if (shader->asACompose(&rec)) {
650 refBitmapsInShader(rec.fShaderA);
651 refBitmapsInShader(rec.fShaderB);
656 }; // namespace uirenderer
657 }; // namespace android