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