FrameBuilder.cpp revision a748c08241e43fc68c7c34767d819aef5183936e
1/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
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
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
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.
15 */
16
17#include "FrameBuilder.h"
18
19#include "Canvas.h"
20#include "LayerUpdateQueue.h"
21#include "RenderNode.h"
22#include "VectorDrawable.h"
23#include "renderstate/OffscreenBufferPool.h"
24#include "utils/FatVector.h"
25#include "utils/PaintUtils.h"
26#include "utils/TraceUtils.h"
27
28#include <SkPathOps.h>
29#include <utils/TypeHelpers.h>
30
31namespace android {
32namespace uirenderer {
33
34FrameBuilder::FrameBuilder(const LayerUpdateQueue& layers, const SkRect& clip,
35        uint32_t viewportWidth, uint32_t viewportHeight,
36        const std::vector< sp<RenderNode> >& nodes,
37        const LightGeometry& lightGeometry, const Rect &contentDrawBounds, Caches* caches)
38        : mCanvasState(*this)
39        , mCaches(caches)
40        , mLightRadius(lightGeometry.radius) {
41    ATRACE_NAME("prepare drawing commands");
42
43    mLayerBuilders.reserve(layers.entries().size());
44    mLayerStack.reserve(layers.entries().size());
45
46    // Prepare to defer Fbo0
47    auto fbo0 = mAllocator.create<LayerBuilder>(viewportWidth, viewportHeight, Rect(clip));
48    mLayerBuilders.push_back(fbo0);
49    mLayerStack.push_back(0);
50    mCanvasState.initializeSaveStack(viewportWidth, viewportHeight,
51            clip.fLeft, clip.fTop, clip.fRight, clip.fBottom,
52            lightGeometry.center);
53
54    // Render all layers to be updated, in order. Defer in reverse order, so that they'll be
55    // updated in the order they're passed in (mLayerBuilders are issued to Renderer in reverse)
56    for (int i = layers.entries().size() - 1; i >= 0; i--) {
57        RenderNode* layerNode = layers.entries()[i].renderNode;
58        // only schedule repaint if node still on layer - possible it may have been
59        // removed during a dropped frame, but layers may still remain scheduled so
60        // as not to lose info on what portion is damaged
61        if (CC_LIKELY(layerNode->getLayer() != nullptr)) {
62            const Rect& layerDamage = layers.entries()[i].damage;
63            layerNode->computeOrdering();
64
65            // map current light center into RenderNode's coordinate space
66            Vector3 lightCenter = mCanvasState.currentSnapshot()->getRelativeLightCenter();
67            layerNode->getLayer()->inverseTransformInWindow.mapPoint3d(lightCenter);
68
69            saveForLayer(layerNode->getWidth(), layerNode->getHeight(), 0, 0,
70                    layerDamage, lightCenter, nullptr, layerNode);
71
72            if (layerNode->getDisplayList()) {
73                deferNodeOps(*layerNode);
74            }
75            restoreForLayer();
76        }
77    }
78
79    // It there are multiple render nodes, they are laid out as follows:
80    // #0 - backdrop (content + caption)
81    // #1 - content (positioned at (0,0) and clipped to - its bounds mContentDrawBounds)
82    // #2 - additional overlay nodes
83    // Usually the backdrop cannot be seen since it will be entirely covered by the content. While
84    // resizing however it might become partially visible. The following render loop will crop the
85    // backdrop against the content and draw the remaining part of it. It will then draw the content
86    // cropped to the backdrop (since that indicates a shrinking of the window).
87    //
88    // Additional nodes will be drawn on top with no particular clipping semantics.
89
90    // The bounds of the backdrop against which the content should be clipped.
91    Rect backdropBounds = contentDrawBounds;
92    // Usually the contents bounds should be mContentDrawBounds - however - we will
93    // move it towards the fixed edge to give it a more stable appearance (for the moment).
94    // If there is no content bounds we ignore the layering as stated above and start with 2.
95    int layer = (contentDrawBounds.isEmpty() || nodes.size() == 1) ? 2 : 0;
96
97    for (const sp<RenderNode>& node : nodes) {
98        if (node->nothingToDraw()) continue;
99        node->computeOrdering();
100        int count = mCanvasState.save(SaveFlags::MatrixClip);
101
102        if (layer == 0) {
103            const RenderProperties& properties = node->properties();
104            Rect targetBounds(properties.getLeft(), properties.getTop(),
105                              properties.getRight(), properties.getBottom());
106            // Move the content bounds towards the fixed corner of the backdrop.
107            const int x = targetBounds.left;
108            const int y = targetBounds.top;
109            // Remember the intersection of the target bounds and the intersection bounds against
110            // which we have to crop the content.
111            backdropBounds.set(x, y, x + backdropBounds.getWidth(), y + backdropBounds.getHeight());
112            backdropBounds.doIntersect(targetBounds);
113        } else if (layer == 1) {
114            // We shift and clip the content to match its final location in the window.
115            const float left = contentDrawBounds.left;
116            const float top = contentDrawBounds.top;
117            const float dx = backdropBounds.left - left;
118            const float dy = backdropBounds.top - top;
119            const float width = backdropBounds.getWidth();
120            const float height = backdropBounds.getHeight();
121            mCanvasState.translate(dx, dy);
122            // It gets cropped against the bounds of the backdrop to stay inside.
123            mCanvasState.clipRect(left, top, left + width, top + height, SkRegion::kIntersect_Op);
124        }
125
126        deferNodePropsAndOps(*node);
127        mCanvasState.restoreToCount(count);
128        layer++;
129    }
130}
131
132void FrameBuilder::onViewportInitialized() {}
133
134void FrameBuilder::onSnapshotRestored(const Snapshot& removed, const Snapshot& restored) {}
135
136void FrameBuilder::deferNodePropsAndOps(RenderNode& node) {
137    const RenderProperties& properties = node.properties();
138    const Outline& outline = properties.getOutline();
139    if (properties.getAlpha() <= 0
140            || (outline.getShouldClip() && outline.isEmpty())
141            || properties.getScaleX() == 0
142            || properties.getScaleY() == 0) {
143        return; // rejected
144    }
145
146    if (properties.getLeft() != 0 || properties.getTop() != 0) {
147        mCanvasState.translate(properties.getLeft(), properties.getTop());
148    }
149    if (properties.getStaticMatrix()) {
150        mCanvasState.concatMatrix(*properties.getStaticMatrix());
151    } else if (properties.getAnimationMatrix()) {
152        mCanvasState.concatMatrix(*properties.getAnimationMatrix());
153    }
154    if (properties.hasTransformMatrix()) {
155        if (properties.isTransformTranslateOnly()) {
156            mCanvasState.translate(properties.getTranslationX(), properties.getTranslationY());
157        } else {
158            mCanvasState.concatMatrix(*properties.getTransformMatrix());
159        }
160    }
161
162    const int width = properties.getWidth();
163    const int height = properties.getHeight();
164
165    Rect saveLayerBounds; // will be set to non-empty if saveLayer needed
166    const bool isLayer = properties.effectiveLayerType() != LayerType::None;
167    int clipFlags = properties.getClippingFlags();
168    if (properties.getAlpha() < 1) {
169        if (isLayer) {
170            clipFlags &= ~CLIP_TO_BOUNDS; // bounds clipping done by layer
171        }
172        if (CC_LIKELY(isLayer || !properties.getHasOverlappingRendering())) {
173            // simply scale rendering content's alpha
174            mCanvasState.scaleAlpha(properties.getAlpha());
175        } else {
176            // schedule saveLayer by initializing saveLayerBounds
177            saveLayerBounds.set(0, 0, width, height);
178            if (clipFlags) {
179                properties.getClippingRectForFlags(clipFlags, &saveLayerBounds);
180                clipFlags = 0; // all clipping done by savelayer
181            }
182        }
183
184        if (CC_UNLIKELY(ATRACE_ENABLED() && properties.promotedToLayer())) {
185            // pretend alpha always causes savelayer to warn about
186            // performance problem affecting old versions
187            ATRACE_FORMAT("%s alpha caused saveLayer %dx%d", node.getName(), width, height);
188        }
189    }
190    if (clipFlags) {
191        Rect clipRect;
192        properties.getClippingRectForFlags(clipFlags, &clipRect);
193        mCanvasState.clipRect(clipRect.left, clipRect.top, clipRect.right, clipRect.bottom,
194                SkRegion::kIntersect_Op);
195    }
196
197    if (properties.getRevealClip().willClip()) {
198        Rect bounds;
199        properties.getRevealClip().getBounds(&bounds);
200        mCanvasState.setClippingRoundRect(mAllocator,
201                bounds, properties.getRevealClip().getRadius());
202    } else if (properties.getOutline().willClip()) {
203        mCanvasState.setClippingOutline(mAllocator, &(properties.getOutline()));
204    }
205
206    bool quickRejected = properties.getClipToBounds()
207            && mCanvasState.quickRejectConservative(0, 0, width, height);
208    if (!quickRejected) {
209        // not rejected, so defer render as either Layer, or direct (possibly wrapped in saveLayer)
210        if (node.getLayer()) {
211            // HW layer
212            LayerOp* drawLayerOp = mAllocator.create_trivial<LayerOp>(node);
213            BakedOpState* bakedOpState = tryBakeOpState(*drawLayerOp);
214            if (bakedOpState) {
215                // Node's layer already deferred, schedule it to render into parent layer
216                currentLayer().deferUnmergeableOp(mAllocator, bakedOpState, OpBatchType::Bitmap);
217            }
218        } else if (CC_UNLIKELY(!saveLayerBounds.isEmpty())) {
219            // draw DisplayList contents within temporary, since persisted layer could not be used.
220            // (temp layers are clipped to viewport, since they don't persist offscreen content)
221            SkPaint saveLayerPaint;
222            saveLayerPaint.setAlpha(properties.getAlpha());
223            deferBeginLayerOp(*mAllocator.create_trivial<BeginLayerOp>(
224                    saveLayerBounds,
225                    Matrix4::identity(),
226                    nullptr, // no record-time clip - need only respect defer-time one
227                    &saveLayerPaint));
228            deferNodeOps(node);
229            deferEndLayerOp(*mAllocator.create_trivial<EndLayerOp>());
230        } else {
231            deferNodeOps(node);
232        }
233    }
234}
235
236typedef key_value_pair_t<float, const RenderNodeOp*> ZRenderNodeOpPair;
237
238template <typename V>
239static void buildZSortedChildList(V* zTranslatedNodes,
240        const DisplayList& displayList, const DisplayList::Chunk& chunk) {
241    if (chunk.beginChildIndex == chunk.endChildIndex) return;
242
243    for (size_t i = chunk.beginChildIndex; i < chunk.endChildIndex; i++) {
244        RenderNodeOp* childOp = displayList.getChildren()[i];
245        RenderNode* child = childOp->renderNode;
246        float childZ = child->properties().getZ();
247
248        if (!MathUtils::isZero(childZ) && chunk.reorderChildren) {
249            zTranslatedNodes->push_back(ZRenderNodeOpPair(childZ, childOp));
250            childOp->skipInOrderDraw = true;
251        } else if (!child->properties().getProjectBackwards()) {
252            // regular, in order drawing DisplayList
253            childOp->skipInOrderDraw = false;
254        }
255    }
256
257    // Z sort any 3d children (stable-ness makes z compare fall back to standard drawing order)
258    std::stable_sort(zTranslatedNodes->begin(), zTranslatedNodes->end());
259}
260
261template <typename V>
262static size_t findNonNegativeIndex(const V& zTranslatedNodes) {
263    for (size_t i = 0; i < zTranslatedNodes.size(); i++) {
264        if (zTranslatedNodes[i].key >= 0.0f) return i;
265    }
266    return zTranslatedNodes.size();
267}
268
269template <typename V>
270void FrameBuilder::defer3dChildren(ChildrenSelectMode mode, const V& zTranslatedNodes) {
271    const int size = zTranslatedNodes.size();
272    if (size == 0
273            || (mode == ChildrenSelectMode::Negative&& zTranslatedNodes[0].key > 0.0f)
274            || (mode == ChildrenSelectMode::Positive && zTranslatedNodes[size - 1].key < 0.0f)) {
275        // no 3d children to draw
276        return;
277    }
278
279    /**
280     * Draw shadows and (potential) casters mostly in order, but allow the shadows of casters
281     * with very similar Z heights to draw together.
282     *
283     * This way, if Views A & B have the same Z height and are both casting shadows, the shadows are
284     * underneath both, and neither's shadow is drawn on top of the other.
285     */
286    const size_t nonNegativeIndex = findNonNegativeIndex(zTranslatedNodes);
287    size_t drawIndex, shadowIndex, endIndex;
288    if (mode == ChildrenSelectMode::Negative) {
289        drawIndex = 0;
290        endIndex = nonNegativeIndex;
291        shadowIndex = endIndex; // draw no shadows
292    } else {
293        drawIndex = nonNegativeIndex;
294        endIndex = size;
295        shadowIndex = drawIndex; // potentially draw shadow for each pos Z child
296    }
297
298    float lastCasterZ = 0.0f;
299    while (shadowIndex < endIndex || drawIndex < endIndex) {
300        if (shadowIndex < endIndex) {
301            const RenderNodeOp* casterNodeOp = zTranslatedNodes[shadowIndex].value;
302            const float casterZ = zTranslatedNodes[shadowIndex].key;
303            // attempt to render the shadow if the caster about to be drawn is its caster,
304            // OR if its caster's Z value is similar to the previous potential caster
305            if (shadowIndex == drawIndex || casterZ - lastCasterZ < 0.1f) {
306                deferShadow(*casterNodeOp);
307
308                lastCasterZ = casterZ; // must do this even if current caster not casting a shadow
309                shadowIndex++;
310                continue;
311            }
312        }
313
314        const RenderNodeOp* childOp = zTranslatedNodes[drawIndex].value;
315        deferRenderNodeOpImpl(*childOp);
316        drawIndex++;
317    }
318}
319
320void FrameBuilder::deferShadow(const RenderNodeOp& casterNodeOp) {
321    auto& node = *casterNodeOp.renderNode;
322    auto& properties = node.properties();
323
324    if (properties.getAlpha() <= 0.0f
325            || properties.getOutline().getAlpha() <= 0.0f
326            || !properties.getOutline().getPath()
327            || properties.getScaleX() == 0
328            || properties.getScaleY() == 0) {
329        // no shadow to draw
330        return;
331    }
332
333    const SkPath* casterOutlinePath = properties.getOutline().getPath();
334    const SkPath* revealClipPath = properties.getRevealClip().getPath();
335    if (revealClipPath && revealClipPath->isEmpty()) return;
336
337    float casterAlpha = properties.getAlpha() * properties.getOutline().getAlpha();
338
339    // holds temporary SkPath to store the result of intersections
340    SkPath* frameAllocatedPath = nullptr;
341    const SkPath* casterPath = casterOutlinePath;
342
343    // intersect the shadow-casting path with the reveal, if present
344    if (revealClipPath) {
345        frameAllocatedPath = createFrameAllocatedPath();
346
347        Op(*casterPath, *revealClipPath, kIntersect_SkPathOp, frameAllocatedPath);
348        casterPath = frameAllocatedPath;
349    }
350
351    // intersect the shadow-casting path with the clipBounds, if present
352    if (properties.getClippingFlags() & CLIP_TO_CLIP_BOUNDS) {
353        if (!frameAllocatedPath) {
354            frameAllocatedPath = createFrameAllocatedPath();
355        }
356        Rect clipBounds;
357        properties.getClippingRectForFlags(CLIP_TO_CLIP_BOUNDS, &clipBounds);
358        SkPath clipBoundsPath;
359        clipBoundsPath.addRect(clipBounds.left, clipBounds.top,
360                clipBounds.right, clipBounds.bottom);
361
362        Op(*casterPath, clipBoundsPath, kIntersect_SkPathOp, frameAllocatedPath);
363        casterPath = frameAllocatedPath;
364    }
365
366
367    if (CC_LIKELY(!mCanvasState.getRenderTargetClipBounds().isEmpty())) {
368        Matrix4 shadowMatrixXY(casterNodeOp.localMatrix);
369        Matrix4 shadowMatrixZ(casterNodeOp.localMatrix);
370        node.applyViewPropertyTransforms(shadowMatrixXY, false);
371        node.applyViewPropertyTransforms(shadowMatrixZ, true);
372
373        LOG_ALWAYS_FATAL_IF(!mCaches, "Caches needed for shadows");
374        sp<TessellationCache::ShadowTask> task = mCaches->tessellationCache.getShadowTask(
375                mCanvasState.currentTransform(),
376                mCanvasState.getLocalClipBounds(),
377                casterAlpha >= 1.0f,
378                casterPath,
379                &shadowMatrixXY, &shadowMatrixZ,
380                mCanvasState.currentSnapshot()->getRelativeLightCenter(),
381                mLightRadius);
382        ShadowOp* shadowOp = mAllocator.create<ShadowOp>(task, casterAlpha);
383        BakedOpState* bakedOpState = BakedOpState::tryShadowOpConstruct(
384                mAllocator, *mCanvasState.writableSnapshot(), shadowOp);
385        if (CC_LIKELY(bakedOpState)) {
386            currentLayer().deferUnmergeableOp(mAllocator, bakedOpState, OpBatchType::Shadow);
387        }
388    }
389}
390
391void FrameBuilder::deferProjectedChildren(const RenderNode& renderNode) {
392    int count = mCanvasState.save(SaveFlags::MatrixClip);
393    const SkPath* projectionReceiverOutline = renderNode.properties().getOutline().getPath();
394
395    SkPath transformedMaskPath; // on stack, since BakedOpState makes a deep copy
396    if (projectionReceiverOutline) {
397        // transform the mask for this projector into render target space
398        // TODO: consider combining both transforms by stashing transform instead of applying
399        SkMatrix skCurrentTransform;
400        mCanvasState.currentTransform()->copyTo(skCurrentTransform);
401        projectionReceiverOutline->transform(
402                skCurrentTransform,
403                &transformedMaskPath);
404        mCanvasState.setProjectionPathMask(mAllocator, &transformedMaskPath);
405    }
406
407    for (size_t i = 0; i < renderNode.mProjectedNodes.size(); i++) {
408        RenderNodeOp* childOp = renderNode.mProjectedNodes[i];
409        RenderNode& childNode = *childOp->renderNode;
410
411        // Draw child if it has content, but ignore state in childOp - matrix already applied to
412        // transformFromCompositingAncestor, and record-time clip is ignored when projecting
413        if (!childNode.nothingToDraw()) {
414            int restoreTo = mCanvasState.save(SaveFlags::MatrixClip);
415
416            // Apply transform between ancestor and projected descendant
417            mCanvasState.concatMatrix(childOp->transformFromCompositingAncestor);
418
419            deferNodePropsAndOps(childNode);
420
421            mCanvasState.restoreToCount(restoreTo);
422        }
423    }
424    mCanvasState.restoreToCount(count);
425}
426
427/**
428 * Used to define a list of lambdas referencing private FrameBuilder::onXX::defer() methods.
429 *
430 * This allows opIds embedded in the RecordedOps to be used for dispatching to these lambdas.
431 * E.g. a BitmapOp op then would be dispatched to FrameBuilder::onBitmapOp(const BitmapOp&)
432 */
433#define OP_RECEIVER(Type) \
434        [](FrameBuilder& frameBuilder, const RecordedOp& op) { frameBuilder.defer##Type(static_cast<const Type&>(op)); },
435void FrameBuilder::deferNodeOps(const RenderNode& renderNode) {
436    typedef void (*OpDispatcher) (FrameBuilder& frameBuilder, const RecordedOp& op);
437    static OpDispatcher receivers[] = BUILD_DEFERRABLE_OP_LUT(OP_RECEIVER);
438
439    // can't be null, since DL=null node rejection happens before deferNodePropsAndOps
440    const DisplayList& displayList = *(renderNode.getDisplayList());
441    for (const DisplayList::Chunk& chunk : displayList.getChunks()) {
442        FatVector<ZRenderNodeOpPair, 16> zTranslatedNodes;
443        buildZSortedChildList(&zTranslatedNodes, displayList, chunk);
444
445        defer3dChildren(ChildrenSelectMode::Negative, zTranslatedNodes);
446        for (size_t opIndex = chunk.beginOpIndex; opIndex < chunk.endOpIndex; opIndex++) {
447            const RecordedOp* op = displayList.getOps()[opIndex];
448            receivers[op->opId](*this, *op);
449
450            if (CC_UNLIKELY(!renderNode.mProjectedNodes.empty()
451                    && displayList.projectionReceiveIndex >= 0
452                    && static_cast<int>(opIndex) == displayList.projectionReceiveIndex)) {
453                deferProjectedChildren(renderNode);
454            }
455        }
456        defer3dChildren(ChildrenSelectMode::Positive, zTranslatedNodes);
457    }
458}
459
460void FrameBuilder::deferRenderNodeOpImpl(const RenderNodeOp& op) {
461    if (op.renderNode->nothingToDraw()) return;
462    int count = mCanvasState.save(SaveFlags::MatrixClip);
463
464    // apply state from RecordedOp (clip first, since op's clip is transformed by current matrix)
465    mCanvasState.writableSnapshot()->mutateClipArea().applyClip(op.localClip,
466            *mCanvasState.currentSnapshot()->transform);
467    mCanvasState.concatMatrix(op.localMatrix);
468
469    // then apply state from node properties, and defer ops
470    deferNodePropsAndOps(*op.renderNode);
471
472    mCanvasState.restoreToCount(count);
473}
474
475void FrameBuilder::deferRenderNodeOp(const RenderNodeOp& op) {
476    if (!op.skipInOrderDraw) {
477        deferRenderNodeOpImpl(op);
478    }
479}
480
481/**
482 * Defers an unmergeable, strokeable op, accounting correctly
483 * for paint's style on the bounds being computed.
484 */
485void FrameBuilder::deferStrokeableOp(const RecordedOp& op, batchid_t batchId,
486        BakedOpState::StrokeBehavior strokeBehavior) {
487    // Note: here we account for stroke when baking the op
488    BakedOpState* bakedState = BakedOpState::tryStrokeableOpConstruct(
489            mAllocator, *mCanvasState.writableSnapshot(), op, strokeBehavior);
490    if (!bakedState) return; // quick rejected
491    currentLayer().deferUnmergeableOp(mAllocator, bakedState, batchId);
492}
493
494/**
495 * Returns batch id for tessellatable shapes, based on paint. Checks to see if path effect/AA will
496 * be used, since they trigger significantly different rendering paths.
497 *
498 * Note: not used for lines/points, since they don't currently support path effects.
499 */
500static batchid_t tessBatchId(const RecordedOp& op) {
501    const SkPaint& paint = *(op.paint);
502    return paint.getPathEffect()
503            ? OpBatchType::AlphaMaskTexture
504            : (paint.isAntiAlias() ? OpBatchType::AlphaVertices : OpBatchType::Vertices);
505}
506
507void FrameBuilder::deferArcOp(const ArcOp& op) {
508    deferStrokeableOp(op, tessBatchId(op));
509}
510
511static bool hasMergeableClip(const BakedOpState& state) {
512    return state.computedState.clipState
513            || state.computedState.clipState->mode == ClipMode::Rectangle;
514}
515
516void FrameBuilder::deferBitmapOp(const BitmapOp& op) {
517    BakedOpState* bakedState = tryBakeOpState(op);
518    if (!bakedState) return; // quick rejected
519
520    currentLayer().deferUnmergeableOp(mAllocator, bakedState, OpBatchType::Bitmap);
521
522    // TODO: Fix this ( b/26569206 )
523/*
524    // Don't merge non-simply transformed or neg scale ops, SET_TEXTURE doesn't handle rotation
525    // Don't merge A8 bitmaps - the paint's color isn't compared by mergeId, or in
526    // MergingDrawBatch::canMergeWith()
527    if (bakedState->computedState.transform.isSimple()
528            && bakedState->computedState.transform.positiveScale()
529            && PaintUtils::getXfermodeDirect(op.paint) == SkXfermode::kSrcOver_Mode
530            && op.bitmap->colorType() != kAlpha_8_SkColorType
531            && hasMergeableClip(*bakedState)) {
532        mergeid_t mergeId = reinterpret_cast<mergeid_t>(op.bitmap->getGenerationID());
533        // TODO: AssetAtlas in mergeId
534        currentLayer().deferMergeableOp(mAllocator, bakedState, OpBatchType::Bitmap, mergeId);
535    } else {
536        currentLayer().deferUnmergeableOp(mAllocator, bakedState, OpBatchType::Bitmap);
537    }
538*/
539}
540
541void FrameBuilder::deferBitmapMeshOp(const BitmapMeshOp& op) {
542    BakedOpState* bakedState = tryBakeOpState(op);
543    if (!bakedState) return; // quick rejected
544    currentLayer().deferUnmergeableOp(mAllocator, bakedState, OpBatchType::Bitmap);
545}
546
547void FrameBuilder::deferBitmapRectOp(const BitmapRectOp& op) {
548    BakedOpState* bakedState = tryBakeOpState(op);
549    if (!bakedState) return; // quick rejected
550    currentLayer().deferUnmergeableOp(mAllocator, bakedState, OpBatchType::Bitmap);
551}
552
553void FrameBuilder::deferVectorDrawableOp(const VectorDrawableOp& op) {
554    const SkBitmap& bitmap = op.vectorDrawable->getBitmapUpdateIfDirty();
555    SkPaint* paint = op.vectorDrawable->getPaint();
556    const BitmapRectOp* resolvedOp = mAllocator.create_trivial<BitmapRectOp>(op.unmappedBounds,
557            op.localMatrix,
558            op.localClip,
559            paint,
560            &bitmap,
561            Rect(bitmap.width(), bitmap.height()));
562    deferBitmapRectOp(*resolvedOp);
563}
564
565void FrameBuilder::deferCirclePropsOp(const CirclePropsOp& op) {
566    // allocate a temporary oval op (with mAllocator, so it persists until render), so the
567    // renderer doesn't have to handle the RoundRectPropsOp type, and so state baking is simple.
568    float x = *(op.x);
569    float y = *(op.y);
570    float radius = *(op.radius);
571    Rect unmappedBounds(x - radius, y - radius, x + radius, y + radius);
572    const OvalOp* resolvedOp = mAllocator.create_trivial<OvalOp>(
573            unmappedBounds,
574            op.localMatrix,
575            op.localClip,
576            op.paint);
577    deferOvalOp(*resolvedOp);
578}
579
580void FrameBuilder::deferFunctorOp(const FunctorOp& op) {
581    BakedOpState* bakedState = tryBakeOpState(op);
582    if (!bakedState) return; // quick rejected
583    currentLayer().deferUnmergeableOp(mAllocator, bakedState, OpBatchType::Functor);
584}
585
586void FrameBuilder::deferLinesOp(const LinesOp& op) {
587    batchid_t batch = op.paint->isAntiAlias() ? OpBatchType::AlphaVertices : OpBatchType::Vertices;
588    deferStrokeableOp(op, batch, BakedOpState::StrokeBehavior::Forced);
589}
590
591void FrameBuilder::deferOvalOp(const OvalOp& op) {
592    deferStrokeableOp(op, tessBatchId(op));
593}
594
595void FrameBuilder::deferPatchOp(const PatchOp& op) {
596    BakedOpState* bakedState = tryBakeOpState(op);
597    if (!bakedState) return; // quick rejected
598
599    if (bakedState->computedState.transform.isPureTranslate()
600            && PaintUtils::getXfermodeDirect(op.paint) == SkXfermode::kSrcOver_Mode
601            && hasMergeableClip(*bakedState)) {
602        mergeid_t mergeId = reinterpret_cast<mergeid_t>(op.bitmap->getGenerationID());
603        // TODO: AssetAtlas in mergeId
604
605        // Only use the MergedPatch batchId when merged, so Bitmap+Patch don't try to merge together
606        currentLayer().deferMergeableOp(mAllocator, bakedState, OpBatchType::MergedPatch, mergeId);
607    } else {
608        // Use Bitmap batchId since Bitmap+Patch use same shader
609        currentLayer().deferUnmergeableOp(mAllocator, bakedState, OpBatchType::Bitmap);
610    }
611}
612
613void FrameBuilder::deferPathOp(const PathOp& op) {
614    deferStrokeableOp(op, OpBatchType::Bitmap);
615}
616
617void FrameBuilder::deferPointsOp(const PointsOp& op) {
618    batchid_t batch = op.paint->isAntiAlias() ? OpBatchType::AlphaVertices : OpBatchType::Vertices;
619    deferStrokeableOp(op, batch, BakedOpState::StrokeBehavior::Forced);
620}
621
622void FrameBuilder::deferRectOp(const RectOp& op) {
623    deferStrokeableOp(op, tessBatchId(op));
624}
625
626void FrameBuilder::deferRoundRectOp(const RoundRectOp& op) {
627    deferStrokeableOp(op, tessBatchId(op));
628}
629
630void FrameBuilder::deferRoundRectPropsOp(const RoundRectPropsOp& op) {
631    // allocate a temporary round rect op (with mAllocator, so it persists until render), so the
632    // renderer doesn't have to handle the RoundRectPropsOp type, and so state baking is simple.
633    const RoundRectOp* resolvedOp = mAllocator.create_trivial<RoundRectOp>(
634            Rect(*(op.left), *(op.top), *(op.right), *(op.bottom)),
635            op.localMatrix,
636            op.localClip,
637            op.paint, *op.rx, *op.ry);
638    deferRoundRectOp(*resolvedOp);
639}
640
641void FrameBuilder::deferSimpleRectsOp(const SimpleRectsOp& op) {
642    BakedOpState* bakedState = tryBakeOpState(op);
643    if (!bakedState) return; // quick rejected
644    currentLayer().deferUnmergeableOp(mAllocator, bakedState, OpBatchType::Vertices);
645}
646
647static batchid_t textBatchId(const SkPaint& paint) {
648    // TODO: better handling of shader (since we won't care about color then)
649    return paint.getColor() == SK_ColorBLACK ? OpBatchType::Text : OpBatchType::ColorText;
650}
651
652void FrameBuilder::deferTextOp(const TextOp& op) {
653    BakedOpState* bakedState = tryBakeOpState(op);
654    if (!bakedState) return; // quick rejected
655
656    batchid_t batchId = textBatchId(*(op.paint));
657    if (bakedState->computedState.transform.isPureTranslate()
658            && PaintUtils::getXfermodeDirect(op.paint) == SkXfermode::kSrcOver_Mode
659            && hasMergeableClip(*bakedState)) {
660        mergeid_t mergeId = reinterpret_cast<mergeid_t>(op.paint->getColor());
661        currentLayer().deferMergeableOp(mAllocator, bakedState, batchId, mergeId);
662    } else {
663        currentLayer().deferUnmergeableOp(mAllocator, bakedState, batchId);
664    }
665}
666
667void FrameBuilder::deferTextOnPathOp(const TextOnPathOp& op) {
668    BakedOpState* bakedState = tryBakeOpState(op);
669    if (!bakedState) return; // quick rejected
670    currentLayer().deferUnmergeableOp(mAllocator, bakedState, textBatchId(*(op.paint)));
671}
672
673void FrameBuilder::deferTextureLayerOp(const TextureLayerOp& op) {
674    BakedOpState* bakedState = tryBakeOpState(op);
675    if (!bakedState) return; // quick rejected
676    currentLayer().deferUnmergeableOp(mAllocator, bakedState, OpBatchType::TextureLayer);
677}
678
679void FrameBuilder::saveForLayer(uint32_t layerWidth, uint32_t layerHeight,
680        float contentTranslateX, float contentTranslateY,
681        const Rect& repaintRect,
682        const Vector3& lightCenter,
683        const BeginLayerOp* beginLayerOp, RenderNode* renderNode) {
684    mCanvasState.save(SaveFlags::MatrixClip);
685    mCanvasState.writableSnapshot()->initializeViewport(layerWidth, layerHeight);
686    mCanvasState.writableSnapshot()->roundRectClipState = nullptr;
687    mCanvasState.writableSnapshot()->setRelativeLightCenter(lightCenter);
688    mCanvasState.writableSnapshot()->transform->loadTranslate(
689            contentTranslateX, contentTranslateY, 0);
690    mCanvasState.writableSnapshot()->setClip(
691            repaintRect.left, repaintRect.top, repaintRect.right, repaintRect.bottom);
692
693    // create a new layer repaint, and push its index on the stack
694    mLayerStack.push_back(mLayerBuilders.size());
695    auto newFbo = mAllocator.create<LayerBuilder>(layerWidth, layerHeight,
696            repaintRect, beginLayerOp, renderNode);
697    mLayerBuilders.push_back(newFbo);
698}
699
700void FrameBuilder::restoreForLayer() {
701    // restore canvas, and pop finished layer off of the stack
702    mCanvasState.restore();
703    mLayerStack.pop_back();
704}
705
706// TODO: defer time rejection (when bounds become empty) + tests
707// Option - just skip layers with no bounds at playback + defer?
708void FrameBuilder::deferBeginLayerOp(const BeginLayerOp& op) {
709    uint32_t layerWidth = (uint32_t) op.unmappedBounds.getWidth();
710    uint32_t layerHeight = (uint32_t) op.unmappedBounds.getHeight();
711
712    auto previous = mCanvasState.currentSnapshot();
713    Vector3 lightCenter = previous->getRelativeLightCenter();
714
715    // Combine all transforms used to present saveLayer content:
716    // parent content transform * canvas transform * bounds offset
717    Matrix4 contentTransform(*(previous->transform));
718    contentTransform.multiply(op.localMatrix);
719    contentTransform.translate(op.unmappedBounds.left, op.unmappedBounds.top);
720
721    Matrix4 inverseContentTransform;
722    inverseContentTransform.loadInverse(contentTransform);
723
724    // map the light center into layer-relative space
725    inverseContentTransform.mapPoint3d(lightCenter);
726
727    // Clip bounds of temporary layer to parent's clip rect, so:
728    Rect saveLayerBounds(layerWidth, layerHeight);
729    //     1) transform Rect(width, height) into parent's space
730    //        note: left/top offsets put in contentTransform above
731    contentTransform.mapRect(saveLayerBounds);
732    //     2) intersect with parent's clip
733    saveLayerBounds.doIntersect(previous->getRenderTargetClip());
734    //     3) and transform back
735    inverseContentTransform.mapRect(saveLayerBounds);
736    saveLayerBounds.doIntersect(Rect(layerWidth, layerHeight));
737    saveLayerBounds.roundOut();
738
739    // if bounds are reduced, will clip the layer's area by reducing required bounds...
740    layerWidth = saveLayerBounds.getWidth();
741    layerHeight = saveLayerBounds.getHeight();
742    // ...and shifting drawing content to account for left/top side clipping
743    float contentTranslateX = -saveLayerBounds.left;
744    float contentTranslateY = -saveLayerBounds.top;
745
746    saveForLayer(layerWidth, layerHeight,
747            contentTranslateX, contentTranslateY,
748            Rect(layerWidth, layerHeight),
749            lightCenter,
750            &op, nullptr);
751}
752
753void FrameBuilder::deferEndLayerOp(const EndLayerOp& /* ignored */) {
754    const BeginLayerOp& beginLayerOp = *currentLayer().beginLayerOp;
755    int finishedLayerIndex = mLayerStack.back();
756
757    restoreForLayer();
758
759    // record the draw operation into the previous layer's list of draw commands
760    // uses state from the associated beginLayerOp, since it has all the state needed for drawing
761    LayerOp* drawLayerOp = mAllocator.create_trivial<LayerOp>(
762            beginLayerOp.unmappedBounds,
763            beginLayerOp.localMatrix,
764            beginLayerOp.localClip,
765            beginLayerOp.paint,
766            &(mLayerBuilders[finishedLayerIndex]->offscreenBuffer));
767    BakedOpState* bakedOpState = tryBakeOpState(*drawLayerOp);
768
769    if (bakedOpState) {
770        // Layer will be drawn into parent layer (which is now current, since we popped mLayerStack)
771        currentLayer().deferUnmergeableOp(mAllocator, bakedOpState, OpBatchType::Bitmap);
772    } else {
773        // Layer won't be drawn - delete its drawing batches to prevent it from doing any work
774        // TODO: need to prevent any render work from being done
775        // - create layerop earlier for reject purposes?
776        mLayerBuilders[finishedLayerIndex]->clear();
777        return;
778    }
779}
780
781void FrameBuilder::deferBeginUnclippedLayerOp(const BeginUnclippedLayerOp& op) {
782    Matrix4 boundsTransform(*(mCanvasState.currentSnapshot()->transform));
783    boundsTransform.multiply(op.localMatrix);
784
785    Rect dstRect(op.unmappedBounds);
786    boundsTransform.mapRect(dstRect);
787    dstRect.doIntersect(mCanvasState.currentSnapshot()->getRenderTargetClip());
788
789    if (dstRect.isEmpty()) {
790        // Unclipped layer rejected - push a null op, so next EndUnclippedLayerOp is ignored
791        currentLayer().activeUnclippedSaveLayers.push_back(nullptr);
792    } else {
793        // Allocate a holding position for the layer object (copyTo will produce, copyFrom will consume)
794        OffscreenBuffer** layerHandle = mAllocator.create<OffscreenBuffer*>(nullptr);
795
796        /**
797         * First, defer an operation to copy out the content from the rendertarget into a layer.
798         */
799        auto copyToOp = mAllocator.create_trivial<CopyToLayerOp>(op, layerHandle);
800        BakedOpState* bakedState = BakedOpState::directConstruct(mAllocator,
801                &(currentLayer().repaintClip), dstRect, *copyToOp);
802        currentLayer().deferUnmergeableOp(mAllocator, bakedState, OpBatchType::CopyToLayer);
803
804        /**
805         * Defer a clear rect, so that clears from multiple unclipped layers can be drawn
806         * both 1) simultaneously, and 2) as long after the copyToLayer executes as possible
807         */
808        currentLayer().deferLayerClear(dstRect);
809
810        /**
811         * And stash an operation to copy that layer back under the rendertarget until
812         * a balanced EndUnclippedLayerOp is seen
813         */
814        auto copyFromOp = mAllocator.create_trivial<CopyFromLayerOp>(op, layerHandle);
815        bakedState = BakedOpState::directConstruct(mAllocator,
816                &(currentLayer().repaintClip), dstRect, *copyFromOp);
817        currentLayer().activeUnclippedSaveLayers.push_back(bakedState);
818    }
819}
820
821void FrameBuilder::deferEndUnclippedLayerOp(const EndUnclippedLayerOp& /* ignored */) {
822    LOG_ALWAYS_FATAL_IF(currentLayer().activeUnclippedSaveLayers.empty(), "no layer to end!");
823
824    BakedOpState* copyFromLayerOp = currentLayer().activeUnclippedSaveLayers.back();
825    currentLayer().activeUnclippedSaveLayers.pop_back();
826    if (copyFromLayerOp) {
827        currentLayer().deferUnmergeableOp(mAllocator, copyFromLayerOp, OpBatchType::CopyFromLayer);
828    }
829}
830
831} // namespace uirenderer
832} // namespace android
833