FrameBuilder.cpp revision 80d2ade939153da87b3cd3b0a69a713bf68b64ba
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 "LayerUpdateQueue.h" 20#include "RenderNode.h" 21#include "VectorDrawable.h" 22#include "renderstate/OffscreenBufferPool.h" 23#include "hwui/Canvas.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 = mCanvasState.currentSnapshot()->getRenderTargetClip().isEmpty() 207 || (properties.getClipToBounds() 208 && mCanvasState.quickRejectConservative(0, 0, width, height)); 209 if (!quickRejected) { 210 // not rejected, so defer render as either Layer, or direct (possibly wrapped in saveLayer) 211 if (node.getLayer()) { 212 // HW layer 213 LayerOp* drawLayerOp = mAllocator.create_trivial<LayerOp>(node); 214 BakedOpState* bakedOpState = tryBakeOpState(*drawLayerOp); 215 if (bakedOpState) { 216 // Node's layer already deferred, schedule it to render into parent layer 217 currentLayer().deferUnmergeableOp(mAllocator, bakedOpState, OpBatchType::Bitmap); 218 } 219 } else if (CC_UNLIKELY(!saveLayerBounds.isEmpty())) { 220 // draw DisplayList contents within temporary, since persisted layer could not be used. 221 // (temp layers are clipped to viewport, since they don't persist offscreen content) 222 SkPaint saveLayerPaint; 223 saveLayerPaint.setAlpha(properties.getAlpha()); 224 deferBeginLayerOp(*mAllocator.create_trivial<BeginLayerOp>( 225 saveLayerBounds, 226 Matrix4::identity(), 227 nullptr, // no record-time clip - need only respect defer-time one 228 &saveLayerPaint)); 229 deferNodeOps(node); 230 deferEndLayerOp(*mAllocator.create_trivial<EndLayerOp>()); 231 } else { 232 deferNodeOps(node); 233 } 234 } 235} 236 237typedef key_value_pair_t<float, const RenderNodeOp*> ZRenderNodeOpPair; 238 239template <typename V> 240static void buildZSortedChildList(V* zTranslatedNodes, 241 const DisplayList& displayList, const DisplayList::Chunk& chunk) { 242 if (chunk.beginChildIndex == chunk.endChildIndex) return; 243 244 for (size_t i = chunk.beginChildIndex; i < chunk.endChildIndex; i++) { 245 RenderNodeOp* childOp = displayList.getChildren()[i]; 246 RenderNode* child = childOp->renderNode; 247 float childZ = child->properties().getZ(); 248 249 if (!MathUtils::isZero(childZ) && chunk.reorderChildren) { 250 zTranslatedNodes->push_back(ZRenderNodeOpPair(childZ, childOp)); 251 childOp->skipInOrderDraw = true; 252 } else if (!child->properties().getProjectBackwards()) { 253 // regular, in order drawing DisplayList 254 childOp->skipInOrderDraw = false; 255 } 256 } 257 258 // Z sort any 3d children (stable-ness makes z compare fall back to standard drawing order) 259 std::stable_sort(zTranslatedNodes->begin(), zTranslatedNodes->end()); 260} 261 262template <typename V> 263static size_t findNonNegativeIndex(const V& zTranslatedNodes) { 264 for (size_t i = 0; i < zTranslatedNodes.size(); i++) { 265 if (zTranslatedNodes[i].key >= 0.0f) return i; 266 } 267 return zTranslatedNodes.size(); 268} 269 270template <typename V> 271void FrameBuilder::defer3dChildren(ChildrenSelectMode mode, const V& zTranslatedNodes) { 272 const int size = zTranslatedNodes.size(); 273 if (size == 0 274 || (mode == ChildrenSelectMode::Negative&& zTranslatedNodes[0].key > 0.0f) 275 || (mode == ChildrenSelectMode::Positive && zTranslatedNodes[size - 1].key < 0.0f)) { 276 // no 3d children to draw 277 return; 278 } 279 280 /** 281 * Draw shadows and (potential) casters mostly in order, but allow the shadows of casters 282 * with very similar Z heights to draw together. 283 * 284 * This way, if Views A & B have the same Z height and are both casting shadows, the shadows are 285 * underneath both, and neither's shadow is drawn on top of the other. 286 */ 287 const size_t nonNegativeIndex = findNonNegativeIndex(zTranslatedNodes); 288 size_t drawIndex, shadowIndex, endIndex; 289 if (mode == ChildrenSelectMode::Negative) { 290 drawIndex = 0; 291 endIndex = nonNegativeIndex; 292 shadowIndex = endIndex; // draw no shadows 293 } else { 294 drawIndex = nonNegativeIndex; 295 endIndex = size; 296 shadowIndex = drawIndex; // potentially draw shadow for each pos Z child 297 } 298 299 float lastCasterZ = 0.0f; 300 while (shadowIndex < endIndex || drawIndex < endIndex) { 301 if (shadowIndex < endIndex) { 302 const RenderNodeOp* casterNodeOp = zTranslatedNodes[shadowIndex].value; 303 const float casterZ = zTranslatedNodes[shadowIndex].key; 304 // attempt to render the shadow if the caster about to be drawn is its caster, 305 // OR if its caster's Z value is similar to the previous potential caster 306 if (shadowIndex == drawIndex || casterZ - lastCasterZ < 0.1f) { 307 deferShadow(*casterNodeOp); 308 309 lastCasterZ = casterZ; // must do this even if current caster not casting a shadow 310 shadowIndex++; 311 continue; 312 } 313 } 314 315 const RenderNodeOp* childOp = zTranslatedNodes[drawIndex].value; 316 deferRenderNodeOpImpl(*childOp); 317 drawIndex++; 318 } 319} 320 321void FrameBuilder::deferShadow(const RenderNodeOp& casterNodeOp) { 322 auto& node = *casterNodeOp.renderNode; 323 auto& properties = node.properties(); 324 325 if (properties.getAlpha() <= 0.0f 326 || properties.getOutline().getAlpha() <= 0.0f 327 || !properties.getOutline().getPath() 328 || properties.getScaleX() == 0 329 || properties.getScaleY() == 0) { 330 // no shadow to draw 331 return; 332 } 333 334 const SkPath* casterOutlinePath = properties.getOutline().getPath(); 335 const SkPath* revealClipPath = properties.getRevealClip().getPath(); 336 if (revealClipPath && revealClipPath->isEmpty()) return; 337 338 float casterAlpha = properties.getAlpha() * properties.getOutline().getAlpha(); 339 340 // holds temporary SkPath to store the result of intersections 341 SkPath* frameAllocatedPath = nullptr; 342 const SkPath* casterPath = casterOutlinePath; 343 344 // intersect the shadow-casting path with the reveal, if present 345 if (revealClipPath) { 346 frameAllocatedPath = createFrameAllocatedPath(); 347 348 Op(*casterPath, *revealClipPath, kIntersect_SkPathOp, frameAllocatedPath); 349 casterPath = frameAllocatedPath; 350 } 351 352 // intersect the shadow-casting path with the clipBounds, if present 353 if (properties.getClippingFlags() & CLIP_TO_CLIP_BOUNDS) { 354 if (!frameAllocatedPath) { 355 frameAllocatedPath = createFrameAllocatedPath(); 356 } 357 Rect clipBounds; 358 properties.getClippingRectForFlags(CLIP_TO_CLIP_BOUNDS, &clipBounds); 359 SkPath clipBoundsPath; 360 clipBoundsPath.addRect(clipBounds.left, clipBounds.top, 361 clipBounds.right, clipBounds.bottom); 362 363 Op(*casterPath, clipBoundsPath, kIntersect_SkPathOp, frameAllocatedPath); 364 casterPath = frameAllocatedPath; 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 sp<TessellationCache::ShadowTask> task = mCaches.tessellationCache.getShadowTask( 374 mCanvasState.currentTransform(), 375 mCanvasState.getLocalClipBounds(), 376 casterAlpha >= 1.0f, 377 casterPath, 378 &shadowMatrixXY, &shadowMatrixZ, 379 mCanvasState.currentSnapshot()->getRelativeLightCenter(), 380 mLightRadius); 381 ShadowOp* shadowOp = mAllocator.create<ShadowOp>(task, casterAlpha); 382 BakedOpState* bakedOpState = BakedOpState::tryShadowOpConstruct( 383 mAllocator, *mCanvasState.writableSnapshot(), shadowOp); 384 if (CC_LIKELY(bakedOpState)) { 385 currentLayer().deferUnmergeableOp(mAllocator, bakedOpState, OpBatchType::Shadow); 386 } 387 } 388} 389 390void FrameBuilder::deferProjectedChildren(const RenderNode& renderNode) { 391 int count = mCanvasState.save(SaveFlags::MatrixClip); 392 const SkPath* projectionReceiverOutline = renderNode.properties().getOutline().getPath(); 393 394 SkPath transformedMaskPath; // on stack, since BakedOpState makes a deep copy 395 if (projectionReceiverOutline) { 396 // transform the mask for this projector into render target space 397 // TODO: consider combining both transforms by stashing transform instead of applying 398 SkMatrix skCurrentTransform; 399 mCanvasState.currentTransform()->copyTo(skCurrentTransform); 400 projectionReceiverOutline->transform( 401 skCurrentTransform, 402 &transformedMaskPath); 403 mCanvasState.setProjectionPathMask(mAllocator, &transformedMaskPath); 404 } 405 406 for (size_t i = 0; i < renderNode.mProjectedNodes.size(); i++) { 407 RenderNodeOp* childOp = renderNode.mProjectedNodes[i]; 408 RenderNode& childNode = *childOp->renderNode; 409 410 // Draw child if it has content, but ignore state in childOp - matrix already applied to 411 // transformFromCompositingAncestor, and record-time clip is ignored when projecting 412 if (!childNode.nothingToDraw()) { 413 int restoreTo = mCanvasState.save(SaveFlags::MatrixClip); 414 415 // Apply transform between ancestor and projected descendant 416 mCanvasState.concatMatrix(childOp->transformFromCompositingAncestor); 417 418 deferNodePropsAndOps(childNode); 419 420 mCanvasState.restoreToCount(restoreTo); 421 } 422 } 423 mCanvasState.restoreToCount(count); 424} 425 426/** 427 * Used to define a list of lambdas referencing private FrameBuilder::onXX::defer() methods. 428 * 429 * This allows opIds embedded in the RecordedOps to be used for dispatching to these lambdas. 430 * E.g. a BitmapOp op then would be dispatched to FrameBuilder::onBitmapOp(const BitmapOp&) 431 */ 432#define OP_RECEIVER(Type) \ 433 [](FrameBuilder& frameBuilder, const RecordedOp& op) { frameBuilder.defer##Type(static_cast<const Type&>(op)); }, 434void FrameBuilder::deferNodeOps(const RenderNode& renderNode) { 435 typedef void (*OpDispatcher) (FrameBuilder& frameBuilder, const RecordedOp& op); 436 static OpDispatcher receivers[] = BUILD_DEFERRABLE_OP_LUT(OP_RECEIVER); 437 438 // can't be null, since DL=null node rejection happens before deferNodePropsAndOps 439 const DisplayList& displayList = *(renderNode.getDisplayList()); 440 for (const DisplayList::Chunk& chunk : displayList.getChunks()) { 441 FatVector<ZRenderNodeOpPair, 16> zTranslatedNodes; 442 buildZSortedChildList(&zTranslatedNodes, displayList, chunk); 443 444 defer3dChildren(ChildrenSelectMode::Negative, zTranslatedNodes); 445 for (size_t opIndex = chunk.beginOpIndex; opIndex < chunk.endOpIndex; opIndex++) { 446 const RecordedOp* op = displayList.getOps()[opIndex]; 447 receivers[op->opId](*this, *op); 448 449 if (CC_UNLIKELY(!renderNode.mProjectedNodes.empty() 450 && displayList.projectionReceiveIndex >= 0 451 && static_cast<int>(opIndex) == displayList.projectionReceiveIndex)) { 452 deferProjectedChildren(renderNode); 453 } 454 } 455 defer3dChildren(ChildrenSelectMode::Positive, zTranslatedNodes); 456 } 457} 458 459void FrameBuilder::deferRenderNodeOpImpl(const RenderNodeOp& op) { 460 if (op.renderNode->nothingToDraw()) return; 461 int count = mCanvasState.save(SaveFlags::MatrixClip); 462 463 // apply state from RecordedOp (clip first, since op's clip is transformed by current matrix) 464 mCanvasState.writableSnapshot()->mutateClipArea().applyClip(op.localClip, 465 *mCanvasState.currentSnapshot()->transform); 466 mCanvasState.concatMatrix(op.localMatrix); 467 468 // then apply state from node properties, and defer ops 469 deferNodePropsAndOps(*op.renderNode); 470 471 mCanvasState.restoreToCount(count); 472} 473 474void FrameBuilder::deferRenderNodeOp(const RenderNodeOp& op) { 475 if (!op.skipInOrderDraw) { 476 deferRenderNodeOpImpl(op); 477 } 478} 479 480/** 481 * Defers an unmergeable, strokeable op, accounting correctly 482 * for paint's style on the bounds being computed. 483 */ 484BakedOpState* FrameBuilder::deferStrokeableOp(const RecordedOp& op, batchid_t batchId, 485 BakedOpState::StrokeBehavior strokeBehavior) { 486 // Note: here we account for stroke when baking the op 487 BakedOpState* bakedState = BakedOpState::tryStrokeableOpConstruct( 488 mAllocator, *mCanvasState.writableSnapshot(), op, strokeBehavior); 489 if (!bakedState) return nullptr; // quick rejected 490 491 if (op.opId == RecordedOpId::RectOp && op.paint->getStyle() != SkPaint::kStroke_Style) { 492 bakedState->setupOpacity(op.paint); 493 } 494 495 currentLayer().deferUnmergeableOp(mAllocator, bakedState, batchId); 496 return bakedState; 497} 498 499/** 500 * Returns batch id for tessellatable shapes, based on paint. Checks to see if path effect/AA will 501 * be used, since they trigger significantly different rendering paths. 502 * 503 * Note: not used for lines/points, since they don't currently support path effects. 504 */ 505static batchid_t tessBatchId(const RecordedOp& op) { 506 const SkPaint& paint = *(op.paint); 507 return paint.getPathEffect() 508 ? OpBatchType::AlphaMaskTexture 509 : (paint.isAntiAlias() ? OpBatchType::AlphaVertices : OpBatchType::Vertices); 510} 511 512void FrameBuilder::deferArcOp(const ArcOp& op) { 513 deferStrokeableOp(op, tessBatchId(op)); 514} 515 516static bool hasMergeableClip(const BakedOpState& state) { 517 return state.computedState.clipState 518 || state.computedState.clipState->mode == ClipMode::Rectangle; 519} 520 521void FrameBuilder::deferBitmapOp(const BitmapOp& op) { 522 BakedOpState* bakedState = tryBakeOpState(op); 523 if (!bakedState) return; // quick rejected 524 bakedState->setupOpacity(op.paint); 525 526 // Don't merge non-simply transformed or neg scale ops, SET_TEXTURE doesn't handle rotation 527 // Don't merge A8 bitmaps - the paint's color isn't compared by mergeId, or in 528 // MergingDrawBatch::canMergeWith() 529 if (bakedState->computedState.transform.isSimple() 530 && bakedState->computedState.transform.positiveScale() 531 && PaintUtils::getXfermodeDirect(op.paint) == SkXfermode::kSrcOver_Mode 532 && op.bitmap->colorType() != kAlpha_8_SkColorType 533 && hasMergeableClip(*bakedState)) { 534 mergeid_t mergeId = reinterpret_cast<mergeid_t>(op.bitmap->getGenerationID()); 535 // TODO: AssetAtlas in mergeId 536 currentLayer().deferMergeableOp(mAllocator, bakedState, OpBatchType::Bitmap, mergeId); 537 } else { 538 currentLayer().deferUnmergeableOp(mAllocator, bakedState, OpBatchType::Bitmap); 539 } 540} 541 542void FrameBuilder::deferBitmapMeshOp(const BitmapMeshOp& op) { 543 BakedOpState* bakedState = tryBakeOpState(op); 544 if (!bakedState) return; // quick rejected 545 currentLayer().deferUnmergeableOp(mAllocator, bakedState, OpBatchType::Bitmap); 546} 547 548void FrameBuilder::deferBitmapRectOp(const BitmapRectOp& op) { 549 BakedOpState* bakedState = tryBakeOpState(op); 550 if (!bakedState) return; // quick rejected 551 currentLayer().deferUnmergeableOp(mAllocator, bakedState, OpBatchType::Bitmap); 552} 553 554void FrameBuilder::deferVectorDrawableOp(const VectorDrawableOp& op) { 555 const SkBitmap& bitmap = op.vectorDrawable->getBitmapUpdateIfDirty(); 556 SkPaint* paint = op.vectorDrawable->getPaint(); 557 const BitmapRectOp* resolvedOp = mAllocator.create_trivial<BitmapRectOp>(op.unmappedBounds, 558 op.localMatrix, 559 op.localClip, 560 paint, 561 &bitmap, 562 Rect(bitmap.width(), bitmap.height())); 563 deferBitmapRectOp(*resolvedOp); 564} 565 566void FrameBuilder::deferCirclePropsOp(const CirclePropsOp& op) { 567 // allocate a temporary oval op (with mAllocator, so it persists until render), so the 568 // renderer doesn't have to handle the RoundRectPropsOp type, and so state baking is simple. 569 float x = *(op.x); 570 float y = *(op.y); 571 float radius = *(op.radius); 572 Rect unmappedBounds(x - radius, y - radius, x + radius, y + radius); 573 const OvalOp* resolvedOp = mAllocator.create_trivial<OvalOp>( 574 unmappedBounds, 575 op.localMatrix, 576 op.localClip, 577 op.paint); 578 deferOvalOp(*resolvedOp); 579} 580 581void FrameBuilder::deferColorOp(const ColorOp& op) { 582 BakedOpState* bakedState = tryBakeUnboundedOpState(op); 583 if (!bakedState) return; // quick rejected 584 currentLayer().deferUnmergeableOp(mAllocator, bakedState, OpBatchType::Vertices); 585} 586 587void FrameBuilder::deferFunctorOp(const FunctorOp& op) { 588 BakedOpState* bakedState = tryBakeUnboundedOpState(op); 589 if (!bakedState) return; // quick rejected 590 currentLayer().deferUnmergeableOp(mAllocator, bakedState, OpBatchType::Functor); 591} 592 593void FrameBuilder::deferLinesOp(const LinesOp& op) { 594 batchid_t batch = op.paint->isAntiAlias() ? OpBatchType::AlphaVertices : OpBatchType::Vertices; 595 deferStrokeableOp(op, batch, BakedOpState::StrokeBehavior::Forced); 596} 597 598void FrameBuilder::deferOvalOp(const OvalOp& op) { 599 deferStrokeableOp(op, tessBatchId(op)); 600} 601 602void FrameBuilder::deferPatchOp(const PatchOp& op) { 603 BakedOpState* bakedState = tryBakeOpState(op); 604 if (!bakedState) return; // quick rejected 605 606 if (bakedState->computedState.transform.isPureTranslate() 607 && PaintUtils::getXfermodeDirect(op.paint) == SkXfermode::kSrcOver_Mode 608 && hasMergeableClip(*bakedState)) { 609 mergeid_t mergeId = reinterpret_cast<mergeid_t>(op.bitmap->getGenerationID()); 610 // TODO: AssetAtlas in mergeId 611 612 // Only use the MergedPatch batchId when merged, so Bitmap+Patch don't try to merge together 613 currentLayer().deferMergeableOp(mAllocator, bakedState, OpBatchType::MergedPatch, mergeId); 614 } else { 615 // Use Bitmap batchId since Bitmap+Patch use same shader 616 currentLayer().deferUnmergeableOp(mAllocator, bakedState, OpBatchType::Bitmap); 617 } 618} 619 620void FrameBuilder::deferPathOp(const PathOp& op) { 621 auto state = deferStrokeableOp(op, OpBatchType::AlphaMaskTexture); 622 if (CC_LIKELY(state)) { 623 mCaches.pathCache.precache(op.path, op.paint); 624 } 625} 626 627void FrameBuilder::deferPointsOp(const PointsOp& op) { 628 batchid_t batch = op.paint->isAntiAlias() ? OpBatchType::AlphaVertices : OpBatchType::Vertices; 629 deferStrokeableOp(op, batch, BakedOpState::StrokeBehavior::Forced); 630} 631 632void FrameBuilder::deferRectOp(const RectOp& op) { 633 deferStrokeableOp(op, tessBatchId(op)); 634} 635 636void FrameBuilder::deferRoundRectOp(const RoundRectOp& op) { 637 auto state = deferStrokeableOp(op, tessBatchId(op)); 638 if (CC_LIKELY(state && !op.paint->getPathEffect())) { 639 // TODO: consider storing tessellation task in BakedOpState 640 mCaches.tessellationCache.precacheRoundRect(state->computedState.transform, *(op.paint), 641 op.unmappedBounds.getWidth(), op.unmappedBounds.getHeight(), op.rx, op.ry); 642 } 643} 644 645void FrameBuilder::deferRoundRectPropsOp(const RoundRectPropsOp& op) { 646 // allocate a temporary round rect op (with mAllocator, so it persists until render), so the 647 // renderer doesn't have to handle the RoundRectPropsOp type, and so state baking is simple. 648 const RoundRectOp* resolvedOp = mAllocator.create_trivial<RoundRectOp>( 649 Rect(*(op.left), *(op.top), *(op.right), *(op.bottom)), 650 op.localMatrix, 651 op.localClip, 652 op.paint, *op.rx, *op.ry); 653 deferRoundRectOp(*resolvedOp); 654} 655 656void FrameBuilder::deferSimpleRectsOp(const SimpleRectsOp& op) { 657 BakedOpState* bakedState = tryBakeOpState(op); 658 if (!bakedState) return; // quick rejected 659 currentLayer().deferUnmergeableOp(mAllocator, bakedState, OpBatchType::Vertices); 660} 661 662static batchid_t textBatchId(const SkPaint& paint) { 663 // TODO: better handling of shader (since we won't care about color then) 664 return paint.getColor() == SK_ColorBLACK ? OpBatchType::Text : OpBatchType::ColorText; 665} 666 667void FrameBuilder::deferTextOp(const TextOp& op) { 668 BakedOpState* bakedState = BakedOpState::tryStrokeableOpConstruct( 669 mAllocator, *mCanvasState.writableSnapshot(), op, 670 BakedOpState::StrokeBehavior::StyleDefined); 671 if (!bakedState) return; // quick rejected 672 673 batchid_t batchId = textBatchId(*(op.paint)); 674 if (bakedState->computedState.transform.isPureTranslate() 675 && PaintUtils::getXfermodeDirect(op.paint) == SkXfermode::kSrcOver_Mode 676 && hasMergeableClip(*bakedState)) { 677 mergeid_t mergeId = reinterpret_cast<mergeid_t>(op.paint->getColor()); 678 currentLayer().deferMergeableOp(mAllocator, bakedState, batchId, mergeId); 679 } else { 680 currentLayer().deferUnmergeableOp(mAllocator, bakedState, batchId); 681 } 682 683 FontRenderer& fontRenderer = mCaches.fontRenderer.getFontRenderer(); 684 auto& totalTransform = bakedState->computedState.transform; 685 if (totalTransform.isPureTranslate() || totalTransform.isPerspective()) { 686 fontRenderer.precache(op.paint, op.glyphs, op.glyphCount, SkMatrix::I()); 687 } else { 688 // Partial transform case, see BakedOpDispatcher::renderTextOp 689 float sx, sy; 690 totalTransform.decomposeScale(sx, sy); 691 fontRenderer.precache(op.paint, op.glyphs, op.glyphCount, SkMatrix::MakeScale( 692 roundf(std::max(1.0f, sx)), 693 roundf(std::max(1.0f, sy)))); 694 } 695} 696 697void FrameBuilder::deferTextOnPathOp(const TextOnPathOp& op) { 698 BakedOpState* bakedState = tryBakeUnboundedOpState(op); 699 if (!bakedState) return; // quick rejected 700 currentLayer().deferUnmergeableOp(mAllocator, bakedState, textBatchId(*(op.paint))); 701 702 mCaches.fontRenderer.getFontRenderer().precache( 703 op.paint, op.glyphs, op.glyphCount, SkMatrix::I()); 704} 705 706void FrameBuilder::deferTextureLayerOp(const TextureLayerOp& op) { 707 if (CC_UNLIKELY(!op.layer->isRenderable())) return; 708 709 const TextureLayerOp* textureLayerOp = &op; 710 // Now safe to access transform (which was potentially unready at record time) 711 if (!op.layer->getTransform().isIdentity()) { 712 // non-identity transform present, so 'inject it' into op by copying + replacing matrix 713 Matrix4 combinedMatrix(op.localMatrix); 714 combinedMatrix.multiply(op.layer->getTransform()); 715 textureLayerOp = mAllocator.create<TextureLayerOp>(op, combinedMatrix); 716 } 717 BakedOpState* bakedState = tryBakeOpState(*textureLayerOp); 718 719 if (!bakedState) return; // quick rejected 720 currentLayer().deferUnmergeableOp(mAllocator, bakedState, OpBatchType::TextureLayer); 721} 722 723void FrameBuilder::saveForLayer(uint32_t layerWidth, uint32_t layerHeight, 724 float contentTranslateX, float contentTranslateY, 725 const Rect& repaintRect, 726 const Vector3& lightCenter, 727 const BeginLayerOp* beginLayerOp, RenderNode* renderNode) { 728 mCanvasState.save(SaveFlags::MatrixClip); 729 mCanvasState.writableSnapshot()->initializeViewport(layerWidth, layerHeight); 730 mCanvasState.writableSnapshot()->roundRectClipState = nullptr; 731 mCanvasState.writableSnapshot()->setRelativeLightCenter(lightCenter); 732 mCanvasState.writableSnapshot()->transform->loadTranslate( 733 contentTranslateX, contentTranslateY, 0); 734 mCanvasState.writableSnapshot()->setClip( 735 repaintRect.left, repaintRect.top, repaintRect.right, repaintRect.bottom); 736 737 // create a new layer repaint, and push its index on the stack 738 mLayerStack.push_back(mLayerBuilders.size()); 739 auto newFbo = mAllocator.create<LayerBuilder>(layerWidth, layerHeight, 740 repaintRect, beginLayerOp, renderNode); 741 mLayerBuilders.push_back(newFbo); 742} 743 744void FrameBuilder::restoreForLayer() { 745 // restore canvas, and pop finished layer off of the stack 746 mCanvasState.restore(); 747 mLayerStack.pop_back(); 748} 749 750// TODO: defer time rejection (when bounds become empty) + tests 751// Option - just skip layers with no bounds at playback + defer? 752void FrameBuilder::deferBeginLayerOp(const BeginLayerOp& op) { 753 uint32_t layerWidth = (uint32_t) op.unmappedBounds.getWidth(); 754 uint32_t layerHeight = (uint32_t) op.unmappedBounds.getHeight(); 755 756 auto previous = mCanvasState.currentSnapshot(); 757 Vector3 lightCenter = previous->getRelativeLightCenter(); 758 759 // Combine all transforms used to present saveLayer content: 760 // parent content transform * canvas transform * bounds offset 761 Matrix4 contentTransform(*(previous->transform)); 762 contentTransform.multiply(op.localMatrix); 763 contentTransform.translate(op.unmappedBounds.left, op.unmappedBounds.top); 764 765 Matrix4 inverseContentTransform; 766 inverseContentTransform.loadInverse(contentTransform); 767 768 // map the light center into layer-relative space 769 inverseContentTransform.mapPoint3d(lightCenter); 770 771 // Clip bounds of temporary layer to parent's clip rect, so: 772 Rect saveLayerBounds(layerWidth, layerHeight); 773 // 1) transform Rect(width, height) into parent's space 774 // note: left/top offsets put in contentTransform above 775 contentTransform.mapRect(saveLayerBounds); 776 // 2) intersect with parent's clip 777 saveLayerBounds.doIntersect(previous->getRenderTargetClip()); 778 // 3) and transform back 779 inverseContentTransform.mapRect(saveLayerBounds); 780 saveLayerBounds.doIntersect(Rect(layerWidth, layerHeight)); 781 saveLayerBounds.roundOut(); 782 783 // if bounds are reduced, will clip the layer's area by reducing required bounds... 784 layerWidth = saveLayerBounds.getWidth(); 785 layerHeight = saveLayerBounds.getHeight(); 786 // ...and shifting drawing content to account for left/top side clipping 787 float contentTranslateX = -saveLayerBounds.left; 788 float contentTranslateY = -saveLayerBounds.top; 789 790 saveForLayer(layerWidth, layerHeight, 791 contentTranslateX, contentTranslateY, 792 Rect(layerWidth, layerHeight), 793 lightCenter, 794 &op, nullptr); 795} 796 797void FrameBuilder::deferEndLayerOp(const EndLayerOp& /* ignored */) { 798 const BeginLayerOp& beginLayerOp = *currentLayer().beginLayerOp; 799 int finishedLayerIndex = mLayerStack.back(); 800 801 restoreForLayer(); 802 803 // record the draw operation into the previous layer's list of draw commands 804 // uses state from the associated beginLayerOp, since it has all the state needed for drawing 805 LayerOp* drawLayerOp = mAllocator.create_trivial<LayerOp>( 806 beginLayerOp.unmappedBounds, 807 beginLayerOp.localMatrix, 808 beginLayerOp.localClip, 809 beginLayerOp.paint, 810 &(mLayerBuilders[finishedLayerIndex]->offscreenBuffer)); 811 BakedOpState* bakedOpState = tryBakeOpState(*drawLayerOp); 812 813 if (bakedOpState) { 814 // Layer will be drawn into parent layer (which is now current, since we popped mLayerStack) 815 currentLayer().deferUnmergeableOp(mAllocator, bakedOpState, OpBatchType::Bitmap); 816 } else { 817 // Layer won't be drawn - delete its drawing batches to prevent it from doing any work 818 // TODO: need to prevent any render work from being done 819 // - create layerop earlier for reject purposes? 820 mLayerBuilders[finishedLayerIndex]->clear(); 821 return; 822 } 823} 824 825void FrameBuilder::deferBeginUnclippedLayerOp(const BeginUnclippedLayerOp& op) { 826 Matrix4 boundsTransform(*(mCanvasState.currentSnapshot()->transform)); 827 boundsTransform.multiply(op.localMatrix); 828 829 Rect dstRect(op.unmappedBounds); 830 boundsTransform.mapRect(dstRect); 831 dstRect.doIntersect(mCanvasState.currentSnapshot()->getRenderTargetClip()); 832 833 if (dstRect.isEmpty()) { 834 // Unclipped layer rejected - push a null op, so next EndUnclippedLayerOp is ignored 835 currentLayer().activeUnclippedSaveLayers.push_back(nullptr); 836 } else { 837 // Allocate a holding position for the layer object (copyTo will produce, copyFrom will consume) 838 OffscreenBuffer** layerHandle = mAllocator.create<OffscreenBuffer*>(nullptr); 839 840 /** 841 * First, defer an operation to copy out the content from the rendertarget into a layer. 842 */ 843 auto copyToOp = mAllocator.create_trivial<CopyToLayerOp>(op, layerHandle); 844 BakedOpState* bakedState = BakedOpState::directConstruct(mAllocator, 845 &(currentLayer().repaintClip), dstRect, *copyToOp); 846 currentLayer().deferUnmergeableOp(mAllocator, bakedState, OpBatchType::CopyToLayer); 847 848 /** 849 * Defer a clear rect, so that clears from multiple unclipped layers can be drawn 850 * both 1) simultaneously, and 2) as long after the copyToLayer executes as possible 851 */ 852 currentLayer().deferLayerClear(dstRect); 853 854 /** 855 * And stash an operation to copy that layer back under the rendertarget until 856 * a balanced EndUnclippedLayerOp is seen 857 */ 858 auto copyFromOp = mAllocator.create_trivial<CopyFromLayerOp>(op, layerHandle); 859 bakedState = BakedOpState::directConstruct(mAllocator, 860 &(currentLayer().repaintClip), dstRect, *copyFromOp); 861 currentLayer().activeUnclippedSaveLayers.push_back(bakedState); 862 } 863} 864 865void FrameBuilder::deferEndUnclippedLayerOp(const EndUnclippedLayerOp& /* ignored */) { 866 LOG_ALWAYS_FATAL_IF(currentLayer().activeUnclippedSaveLayers.empty(), "no layer to end!"); 867 868 BakedOpState* copyFromLayerOp = currentLayer().activeUnclippedSaveLayers.back(); 869 currentLayer().activeUnclippedSaveLayers.pop_back(); 870 if (copyFromLayerOp) { 871 currentLayer().deferUnmergeableOp(mAllocator, copyFromLayerOp, OpBatchType::CopyFromLayer); 872 } 873} 874 875void FrameBuilder::finishDefer() { 876 mCaches.fontRenderer.endPrecaching(); 877} 878 879} // namespace uirenderer 880} // namespace android 881