blob: 3f492d507b0d6e6896749dcb4f7738ce5209857a [file] [log] [blame]
Chris Craikb565df12015-10-05 13:00:52 -07001/*
2 * Copyright (C) 2015 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 "OpReorderer.h"
18
Chris Craik0b7e8242015-10-28 16:50:44 -070019#include "LayerUpdateQueue.h"
Chris Craik161f54b2015-11-05 11:08:52 -080020#include "RenderNode.h"
Chris Craik98787e62015-11-13 10:55:30 -080021#include "renderstate/OffscreenBufferPool.h"
Chris Craik161f54b2015-11-05 11:08:52 -080022#include "utils/FatVector.h"
23#include "utils/PaintUtils.h"
Chris Craik8ecf41c2015-11-16 10:27:59 -080024#include "utils/TraceUtils.h"
Chris Craikb565df12015-10-05 13:00:52 -070025
Chris Craik161f54b2015-11-05 11:08:52 -080026#include <SkCanvas.h>
Chris Craikd3daa312015-11-06 10:59:56 -080027#include <SkPathOps.h>
Chris Craik161f54b2015-11-05 11:08:52 -080028#include <utils/TypeHelpers.h>
Chris Craikb565df12015-10-05 13:00:52 -070029
30namespace android {
31namespace uirenderer {
32
33class BatchBase {
34
35public:
36 BatchBase(batchid_t batchId, BakedOpState* op, bool merging)
Chris Craik98787e62015-11-13 10:55:30 -080037 : mBatchId(batchId)
38 , mMerging(merging) {
Chris Craikb565df12015-10-05 13:00:52 -070039 mBounds = op->computedState.clippedBounds;
40 mOps.push_back(op);
41 }
42
43 bool intersects(const Rect& rect) const {
44 if (!rect.intersects(mBounds)) return false;
45
46 for (const BakedOpState* op : mOps) {
47 if (rect.intersects(op->computedState.clippedBounds)) {
48 return true;
49 }
50 }
51 return false;
52 }
53
54 batchid_t getBatchId() const { return mBatchId; }
55 bool isMerging() const { return mMerging; }
56
57 const std::vector<BakedOpState*>& getOps() const { return mOps; }
58
59 void dump() const {
Chris Craik6fe991e52015-10-20 09:39:42 -070060 ALOGD(" Batch %p, id %d, merging %d, count %d, bounds " RECT_STRING,
61 this, mBatchId, mMerging, mOps.size(), RECT_ARGS(mBounds));
Chris Craikb565df12015-10-05 13:00:52 -070062 }
63protected:
64 batchid_t mBatchId;
65 Rect mBounds;
66 std::vector<BakedOpState*> mOps;
67 bool mMerging;
68};
69
70class OpBatch : public BatchBase {
71public:
72 static void* operator new(size_t size, LinearAllocator& allocator) {
73 return allocator.alloc(size);
74 }
75
76 OpBatch(batchid_t batchId, BakedOpState* op)
77 : BatchBase(batchId, op, false) {
78 }
79
80 void batchOp(BakedOpState* op) {
81 mBounds.unionWith(op->computedState.clippedBounds);
82 mOps.push_back(op);
83 }
84};
85
86class MergingOpBatch : public BatchBase {
87public:
88 static void* operator new(size_t size, LinearAllocator& allocator) {
89 return allocator.alloc(size);
90 }
91
92 MergingOpBatch(batchid_t batchId, BakedOpState* op)
Chris Craikd7448e62015-12-15 10:34:36 -080093 : BatchBase(batchId, op, true)
Chris Craik93e53e02015-12-17 18:42:44 -080094 , mClipSideFlags(op->computedState.clipSideFlags) {
Chris Craikb565df12015-10-05 13:00:52 -070095 }
96
97 /*
98 * Helper for determining if a new op can merge with a MergingDrawBatch based on their bounds
99 * and clip side flags. Positive bounds delta means new bounds fit in old.
100 */
101 static inline bool checkSide(const int currentFlags, const int newFlags, const int side,
102 float boundsDelta) {
103 bool currentClipExists = currentFlags & side;
104 bool newClipExists = newFlags & side;
105
106 // if current is clipped, we must be able to fit new bounds in current
107 if (boundsDelta > 0 && currentClipExists) return false;
108
109 // if new is clipped, we must be able to fit current bounds in new
110 if (boundsDelta < 0 && newClipExists) return false;
111
112 return true;
113 }
114
115 static bool paintIsDefault(const SkPaint& paint) {
116 return paint.getAlpha() == 255
117 && paint.getColorFilter() == nullptr
118 && paint.getShader() == nullptr;
119 }
120
121 static bool paintsAreEquivalent(const SkPaint& a, const SkPaint& b) {
122 return a.getAlpha() == b.getAlpha()
123 && a.getColorFilter() == b.getColorFilter()
124 && a.getShader() == b.getShader();
125 }
126
127 /*
128 * Checks if a (mergeable) op can be merged into this batch
129 *
130 * If true, the op's multiDraw must be guaranteed to handle both ops simultaneously, so it is
131 * important to consider all paint attributes used in the draw calls in deciding both a) if an
132 * op tries to merge at all, and b) if the op can merge with another set of ops
133 *
134 * False positives can lead to information from the paints of subsequent merged operations being
135 * dropped, so we make simplifying qualifications on the ops that can merge, per op type.
136 */
137 bool canMergeWith(BakedOpState* op) const {
138 bool isTextBatch = getBatchId() == OpBatchType::Text
139 || getBatchId() == OpBatchType::ColorText;
140
141 // Overlapping other operations is only allowed for text without shadow. For other ops,
142 // multiDraw isn't guaranteed to overdraw correctly
143 if (!isTextBatch || PaintUtils::hasTextShadow(op->op->paint)) {
144 if (intersects(op->computedState.clippedBounds)) return false;
145 }
146
147 const BakedOpState* lhs = op;
148 const BakedOpState* rhs = mOps[0];
149
150 if (!MathUtils::areEqual(lhs->alpha, rhs->alpha)) return false;
151
152 // Identical round rect clip state means both ops will clip in the same way, or not at all.
153 // As the state objects are const, we can compare their pointers to determine mergeability
154 if (lhs->roundRectClipState != rhs->roundRectClipState) return false;
155 if (lhs->projectionPathMask != rhs->projectionPathMask) return false;
156
157 /* Clipping compatibility check
158 *
159 * Exploits the fact that if a op or batch is clipped on a side, its bounds will equal its
160 * clip for that side.
161 */
162 const int currentFlags = mClipSideFlags;
163 const int newFlags = op->computedState.clipSideFlags;
164 if (currentFlags != OpClipSideFlags::None || newFlags != OpClipSideFlags::None) {
165 const Rect& opBounds = op->computedState.clippedBounds;
166 float boundsDelta = mBounds.left - opBounds.left;
167 if (!checkSide(currentFlags, newFlags, OpClipSideFlags::Left, boundsDelta)) return false;
168 boundsDelta = mBounds.top - opBounds.top;
169 if (!checkSide(currentFlags, newFlags, OpClipSideFlags::Top, boundsDelta)) return false;
170
171 // right and bottom delta calculation reversed to account for direction
172 boundsDelta = opBounds.right - mBounds.right;
173 if (!checkSide(currentFlags, newFlags, OpClipSideFlags::Right, boundsDelta)) return false;
174 boundsDelta = opBounds.bottom - mBounds.bottom;
175 if (!checkSide(currentFlags, newFlags, OpClipSideFlags::Bottom, boundsDelta)) return false;
176 }
177
178 const SkPaint* newPaint = op->op->paint;
179 const SkPaint* oldPaint = mOps[0]->op->paint;
180
181 if (newPaint == oldPaint) {
182 // if paints are equal, then modifiers + paint attribs don't need to be compared
183 return true;
184 } else if (newPaint && !oldPaint) {
185 return paintIsDefault(*newPaint);
186 } else if (!newPaint && oldPaint) {
187 return paintIsDefault(*oldPaint);
188 }
189 return paintsAreEquivalent(*newPaint, *oldPaint);
190 }
191
192 void mergeOp(BakedOpState* op) {
193 mBounds.unionWith(op->computedState.clippedBounds);
194 mOps.push_back(op);
195
Chris Craik93e53e02015-12-17 18:42:44 -0800196 // Because a new op must have passed canMergeWith(), we know it's passed the clipping compat
197 // check, and doesn't extend past a side of the clip that's in use by the merged batch.
198 // Therefore it's safe to simply always merge flags, and use the bounds as the clip rect.
199 mClipSideFlags |= op->computedState.clipSideFlags;
Chris Craikb565df12015-10-05 13:00:52 -0700200 }
201
Chris Craikd7448e62015-12-15 10:34:36 -0800202 int getClipSideFlags() const { return mClipSideFlags; }
Chris Craik93e53e02015-12-17 18:42:44 -0800203 const Rect& getClipRect() const { return mBounds; }
Chris Craik15c3f192015-12-03 12:16:56 -0800204
Chris Craikb565df12015-10-05 13:00:52 -0700205private:
Chris Craikd7448e62015-12-15 10:34:36 -0800206 int mClipSideFlags;
Chris Craikb565df12015-10-05 13:00:52 -0700207};
208
Chris Craik0b7e8242015-10-28 16:50:44 -0700209OpReorderer::LayerReorderer::LayerReorderer(uint32_t width, uint32_t height,
Chris Craik98787e62015-11-13 10:55:30 -0800210 const Rect& repaintRect, const BeginLayerOp* beginLayerOp, RenderNode* renderNode)
Chris Craik0b7e8242015-10-28 16:50:44 -0700211 : width(width)
212 , height(height)
Chris Craik98787e62015-11-13 10:55:30 -0800213 , repaintRect(repaintRect)
Chris Craik0b7e8242015-10-28 16:50:44 -0700214 , offscreenBuffer(renderNode ? renderNode->getLayer() : nullptr)
215 , beginLayerOp(beginLayerOp)
216 , renderNode(renderNode) {}
217
Chris Craik6fe991e52015-10-20 09:39:42 -0700218// iterate back toward target to see if anything drawn since should overlap the new op
Chris Craik818c9fb2015-10-23 14:33:42 -0700219// if no target, merging ops still iterate to find similar batch to insert after
Chris Craik6fe991e52015-10-20 09:39:42 -0700220void OpReorderer::LayerReorderer::locateInsertIndex(int batchId, const Rect& clippedBounds,
221 BatchBase** targetBatch, size_t* insertBatchIndex) const {
222 for (int i = mBatches.size() - 1; i >= 0; i--) {
223 BatchBase* overBatch = mBatches[i];
224
225 if (overBatch == *targetBatch) break;
226
227 // TODO: also consider shader shared between batch types
228 if (batchId == overBatch->getBatchId()) {
229 *insertBatchIndex = i + 1;
230 if (!*targetBatch) break; // found insert position, quit
231 }
232
233 if (overBatch->intersects(clippedBounds)) {
234 // NOTE: it may be possible to optimize for special cases where two operations
235 // of the same batch/paint could swap order, such as with a non-mergeable
236 // (clipped) and a mergeable text operation
237 *targetBatch = nullptr;
238 break;
239 }
240 }
241}
242
243void OpReorderer::LayerReorderer::deferUnmergeableOp(LinearAllocator& allocator,
244 BakedOpState* op, batchid_t batchId) {
245 OpBatch* targetBatch = mBatchLookup[batchId];
246
247 size_t insertBatchIndex = mBatches.size();
248 if (targetBatch) {
249 locateInsertIndex(batchId, op->computedState.clippedBounds,
250 (BatchBase**)(&targetBatch), &insertBatchIndex);
251 }
252
253 if (targetBatch) {
254 targetBatch->batchOp(op);
255 } else {
256 // new non-merging batch
257 targetBatch = new (allocator) OpBatch(batchId, op);
258 mBatchLookup[batchId] = targetBatch;
259 mBatches.insert(mBatches.begin() + insertBatchIndex, targetBatch);
260 }
261}
262
263// insertion point of a new batch, will hopefully be immediately after similar batch
264// (generally, should be similar shader)
265void OpReorderer::LayerReorderer::deferMergeableOp(LinearAllocator& allocator,
266 BakedOpState* op, batchid_t batchId, mergeid_t mergeId) {
267 MergingOpBatch* targetBatch = nullptr;
268
269 // Try to merge with any existing batch with same mergeId
270 auto getResult = mMergingBatchLookup[batchId].find(mergeId);
271 if (getResult != mMergingBatchLookup[batchId].end()) {
272 targetBatch = getResult->second;
273 if (!targetBatch->canMergeWith(op)) {
274 targetBatch = nullptr;
275 }
276 }
277
278 size_t insertBatchIndex = mBatches.size();
279 locateInsertIndex(batchId, op->computedState.clippedBounds,
280 (BatchBase**)(&targetBatch), &insertBatchIndex);
281
282 if (targetBatch) {
283 targetBatch->mergeOp(op);
284 } else {
285 // new merging batch
286 targetBatch = new (allocator) MergingOpBatch(batchId, op);
287 mMergingBatchLookup[batchId].insert(std::make_pair(mergeId, targetBatch));
288
289 mBatches.insert(mBatches.begin() + insertBatchIndex, targetBatch);
290 }
291}
292
Chris Craik15c3f192015-12-03 12:16:56 -0800293void OpReorderer::LayerReorderer::replayBakedOpsImpl(void* arg,
294 BakedOpReceiver* unmergedReceivers, MergedOpReceiver* mergedReceivers) const {
Chris Craik5854b342015-10-26 15:49:56 -0700295 ATRACE_NAME("flush drawing commands");
Chris Craik6fe991e52015-10-20 09:39:42 -0700296 for (const BatchBase* batch : mBatches) {
Chris Craik15c3f192015-12-03 12:16:56 -0800297 size_t size = batch->getOps().size();
298 if (size > 1 && batch->isMerging()) {
299 int opId = batch->getOps()[0]->op->opId;
300 const MergingOpBatch* mergingBatch = static_cast<const MergingOpBatch*>(batch);
301 MergedBakedOpList data = {
302 batch->getOps().data(),
303 size,
304 mergingBatch->getClipSideFlags(),
305 mergingBatch->getClipRect()
306 };
Chris Craik15c3f192015-12-03 12:16:56 -0800307 mergedReceivers[opId](arg, data);
308 } else {
309 for (const BakedOpState* op : batch->getOps()) {
310 unmergedReceivers[op->op->opId](arg, *op);
311 }
Chris Craik6fe991e52015-10-20 09:39:42 -0700312 }
313 }
314}
315
316void OpReorderer::LayerReorderer::dump() const {
Chris Craik0b7e8242015-10-28 16:50:44 -0700317 ALOGD("LayerReorderer %p, %ux%u buffer %p, blo %p, rn %p",
318 this, width, height, offscreenBuffer, beginLayerOp, renderNode);
Chris Craik6fe991e52015-10-20 09:39:42 -0700319 for (const BatchBase* batch : mBatches) {
320 batch->dump();
321 }
322}
Chris Craikb565df12015-10-05 13:00:52 -0700323
Chris Craik0b7e8242015-10-28 16:50:44 -0700324OpReorderer::OpReorderer(const LayerUpdateQueue& layers, const SkRect& clip,
325 uint32_t viewportWidth, uint32_t viewportHeight,
Chris Craik98787e62015-11-13 10:55:30 -0800326 const std::vector< sp<RenderNode> >& nodes, const Vector3& lightCenter)
Chris Craik6fe991e52015-10-20 09:39:42 -0700327 : mCanvasState(*this) {
Chris Craik818c9fb2015-10-23 14:33:42 -0700328 ATRACE_NAME("prepare drawing commands");
Chris Craikb565df12015-10-05 13:00:52 -0700329
Chris Craik98787e62015-11-13 10:55:30 -0800330 mLayerReorderers.reserve(layers.entries().size());
331 mLayerStack.reserve(layers.entries().size());
332
333 // Prepare to defer Fbo0
334 mLayerReorderers.emplace_back(viewportWidth, viewportHeight, Rect(clip));
335 mLayerStack.push_back(0);
Chris Craikb565df12015-10-05 13:00:52 -0700336 mCanvasState.initializeSaveStack(viewportWidth, viewportHeight,
Chris Craikddf22152015-10-14 17:42:47 -0700337 clip.fLeft, clip.fTop, clip.fRight, clip.fBottom,
Chris Craik98787e62015-11-13 10:55:30 -0800338 lightCenter);
Chris Craik0b7e8242015-10-28 16:50:44 -0700339
340 // Render all layers to be updated, in order. Defer in reverse order, so that they'll be
341 // updated in the order they're passed in (mLayerReorderers are issued to Renderer in reverse)
342 for (int i = layers.entries().size() - 1; i >= 0; i--) {
343 RenderNode* layerNode = layers.entries()[i].renderNode;
344 const Rect& layerDamage = layers.entries()[i].damage;
Chris Craik8d1f2122015-11-24 16:40:09 -0800345 layerNode->computeOrdering();
Chris Craik0b7e8242015-10-28 16:50:44 -0700346
Chris Craik8ecf41c2015-11-16 10:27:59 -0800347 // map current light center into RenderNode's coordinate space
348 Vector3 lightCenter = mCanvasState.currentSnapshot()->getRelativeLightCenter();
349 layerNode->getLayer()->inverseTransformInWindow.mapPoint3d(lightCenter);
350
351 saveForLayer(layerNode->getWidth(), layerNode->getHeight(), 0, 0,
352 layerDamage, lightCenter, nullptr, layerNode);
Chris Craik0b7e8242015-10-28 16:50:44 -0700353
354 if (layerNode->getDisplayList()) {
Chris Craik8d1f2122015-11-24 16:40:09 -0800355 deferNodeOps(*layerNode);
Chris Craik0b7e8242015-10-28 16:50:44 -0700356 }
357 restoreForLayer();
358 }
359
360 // Defer Fbo0
Chris Craikb565df12015-10-05 13:00:52 -0700361 for (const sp<RenderNode>& node : nodes) {
362 if (node->nothingToDraw()) continue;
Chris Craik8d1f2122015-11-24 16:40:09 -0800363 node->computeOrdering();
Chris Craikb565df12015-10-05 13:00:52 -0700364
Chris Craik0b7e8242015-10-28 16:50:44 -0700365 int count = mCanvasState.save(SkCanvas::kClip_SaveFlag | SkCanvas::kMatrix_SaveFlag);
366 deferNodePropsAndOps(*node);
367 mCanvasState.restoreToCount(count);
Chris Craikb565df12015-10-05 13:00:52 -0700368 }
369}
370
Chris Craik818c9fb2015-10-23 14:33:42 -0700371void OpReorderer::onViewportInitialized() {}
372
373void OpReorderer::onSnapshotRestored(const Snapshot& removed, const Snapshot& restored) {}
374
Chris Craik0b7e8242015-10-28 16:50:44 -0700375void OpReorderer::deferNodePropsAndOps(RenderNode& node) {
Chris Craik8ecf41c2015-11-16 10:27:59 -0800376 const RenderProperties& properties = node.properties();
377 const Outline& outline = properties.getOutline();
378 if (properties.getAlpha() <= 0
379 || (outline.getShouldClip() && outline.isEmpty())
380 || properties.getScaleX() == 0
381 || properties.getScaleY() == 0) {
382 return; // rejected
383 }
384
385 if (properties.getLeft() != 0 || properties.getTop() != 0) {
386 mCanvasState.translate(properties.getLeft(), properties.getTop());
387 }
388 if (properties.getStaticMatrix()) {
389 mCanvasState.concatMatrix(*properties.getStaticMatrix());
390 } else if (properties.getAnimationMatrix()) {
391 mCanvasState.concatMatrix(*properties.getAnimationMatrix());
392 }
393 if (properties.hasTransformMatrix()) {
394 if (properties.isTransformTranslateOnly()) {
395 mCanvasState.translate(properties.getTranslationX(), properties.getTranslationY());
396 } else {
397 mCanvasState.concatMatrix(*properties.getTransformMatrix());
398 }
399 }
400
401 const int width = properties.getWidth();
402 const int height = properties.getHeight();
403
404 Rect saveLayerBounds; // will be set to non-empty if saveLayer needed
405 const bool isLayer = properties.effectiveLayerType() != LayerType::None;
406 int clipFlags = properties.getClippingFlags();
407 if (properties.getAlpha() < 1) {
408 if (isLayer) {
409 clipFlags &= ~CLIP_TO_BOUNDS; // bounds clipping done by layer
410 }
411 if (CC_LIKELY(isLayer || !properties.getHasOverlappingRendering())) {
412 // simply scale rendering content's alpha
413 mCanvasState.scaleAlpha(properties.getAlpha());
414 } else {
415 // schedule saveLayer by initializing saveLayerBounds
416 saveLayerBounds.set(0, 0, width, height);
417 if (clipFlags) {
418 properties.getClippingRectForFlags(clipFlags, &saveLayerBounds);
419 clipFlags = 0; // all clipping done by savelayer
420 }
421 }
422
423 if (CC_UNLIKELY(ATRACE_ENABLED() && properties.promotedToLayer())) {
424 // pretend alpha always causes savelayer to warn about
425 // performance problem affecting old versions
426 ATRACE_FORMAT("%s alpha caused saveLayer %dx%d", node.getName(), width, height);
427 }
428 }
429 if (clipFlags) {
430 Rect clipRect;
431 properties.getClippingRectForFlags(clipFlags, &clipRect);
432 mCanvasState.clipRect(clipRect.left, clipRect.top, clipRect.right, clipRect.bottom,
433 SkRegion::kIntersect_Op);
434 }
435
436 if (properties.getRevealClip().willClip()) {
437 Rect bounds;
438 properties.getRevealClip().getBounds(&bounds);
439 mCanvasState.setClippingRoundRect(mAllocator,
440 bounds, properties.getRevealClip().getRadius());
441 } else if (properties.getOutline().willClip()) {
442 mCanvasState.setClippingOutline(mAllocator, &(properties.getOutline()));
443 }
444
445 if (!mCanvasState.quickRejectConservative(0, 0, width, height)) {
446 // not rejected, so defer render as either Layer, or direct (possibly wrapped in saveLayer)
Chris Craik0b7e8242015-10-28 16:50:44 -0700447 if (node.getLayer()) {
448 // HW layer
449 LayerOp* drawLayerOp = new (mAllocator) LayerOp(node);
450 BakedOpState* bakedOpState = tryBakeOpState(*drawLayerOp);
451 if (bakedOpState) {
Chris Craik8ecf41c2015-11-16 10:27:59 -0800452 // Node's layer already deferred, schedule it to render into parent layer
Chris Craik0b7e8242015-10-28 16:50:44 -0700453 currentLayer().deferUnmergeableOp(mAllocator, bakedOpState, OpBatchType::Bitmap);
454 }
Chris Craik8ecf41c2015-11-16 10:27:59 -0800455 } else if (CC_UNLIKELY(!saveLayerBounds.isEmpty())) {
456 // draw DisplayList contents within temporary, since persisted layer could not be used.
457 // (temp layers are clipped to viewport, since they don't persist offscreen content)
458 SkPaint saveLayerPaint;
459 saveLayerPaint.setAlpha(properties.getAlpha());
Chris Craik268a9c02015-12-09 18:05:12 -0800460 deferBeginLayerOp(*new (mAllocator) BeginLayerOp(
Chris Craik8ecf41c2015-11-16 10:27:59 -0800461 saveLayerBounds,
462 Matrix4::identity(),
Chris Craike4db79d2015-12-22 16:32:23 -0800463 nullptr, // no record-time clip - need only respect defer-time one
Chris Craik8ecf41c2015-11-16 10:27:59 -0800464 &saveLayerPaint));
Chris Craik8d1f2122015-11-24 16:40:09 -0800465 deferNodeOps(node);
Chris Craik268a9c02015-12-09 18:05:12 -0800466 deferEndLayerOp(*new (mAllocator) EndLayerOp());
Chris Craik0b7e8242015-10-28 16:50:44 -0700467 } else {
Chris Craik8d1f2122015-11-24 16:40:09 -0800468 deferNodeOps(node);
Chris Craik0b7e8242015-10-28 16:50:44 -0700469 }
470 }
471}
472
Chris Craik161f54b2015-11-05 11:08:52 -0800473typedef key_value_pair_t<float, const RenderNodeOp*> ZRenderNodeOpPair;
474
475template <typename V>
476static void buildZSortedChildList(V* zTranslatedNodes,
477 const DisplayList& displayList, const DisplayList::Chunk& chunk) {
478 if (chunk.beginChildIndex == chunk.endChildIndex) return;
479
480 for (size_t i = chunk.beginChildIndex; i < chunk.endChildIndex; i++) {
481 RenderNodeOp* childOp = displayList.getChildren()[i];
482 RenderNode* child = childOp->renderNode;
483 float childZ = child->properties().getZ();
484
485 if (!MathUtils::isZero(childZ) && chunk.reorderChildren) {
486 zTranslatedNodes->push_back(ZRenderNodeOpPair(childZ, childOp));
487 childOp->skipInOrderDraw = true;
488 } else if (!child->properties().getProjectBackwards()) {
489 // regular, in order drawing DisplayList
490 childOp->skipInOrderDraw = false;
491 }
492 }
493
494 // Z sort any 3d children (stable-ness makes z compare fall back to standard drawing order)
495 std::stable_sort(zTranslatedNodes->begin(), zTranslatedNodes->end());
496}
497
498template <typename V>
499static size_t findNonNegativeIndex(const V& zTranslatedNodes) {
500 for (size_t i = 0; i < zTranslatedNodes.size(); i++) {
501 if (zTranslatedNodes[i].key >= 0.0f) return i;
502 }
503 return zTranslatedNodes.size();
504}
505
506template <typename V>
507void OpReorderer::defer3dChildren(ChildrenSelectMode mode, const V& zTranslatedNodes) {
508 const int size = zTranslatedNodes.size();
509 if (size == 0
510 || (mode == ChildrenSelectMode::Negative&& zTranslatedNodes[0].key > 0.0f)
511 || (mode == ChildrenSelectMode::Positive && zTranslatedNodes[size - 1].key < 0.0f)) {
512 // no 3d children to draw
513 return;
514 }
515
516 /**
517 * Draw shadows and (potential) casters mostly in order, but allow the shadows of casters
518 * with very similar Z heights to draw together.
519 *
520 * This way, if Views A & B have the same Z height and are both casting shadows, the shadows are
521 * underneath both, and neither's shadow is drawn on top of the other.
522 */
523 const size_t nonNegativeIndex = findNonNegativeIndex(zTranslatedNodes);
524 size_t drawIndex, shadowIndex, endIndex;
525 if (mode == ChildrenSelectMode::Negative) {
526 drawIndex = 0;
527 endIndex = nonNegativeIndex;
528 shadowIndex = endIndex; // draw no shadows
529 } else {
530 drawIndex = nonNegativeIndex;
531 endIndex = size;
532 shadowIndex = drawIndex; // potentially draw shadow for each pos Z child
533 }
534
535 float lastCasterZ = 0.0f;
536 while (shadowIndex < endIndex || drawIndex < endIndex) {
537 if (shadowIndex < endIndex) {
538 const RenderNodeOp* casterNodeOp = zTranslatedNodes[shadowIndex].value;
539 const float casterZ = zTranslatedNodes[shadowIndex].key;
540 // attempt to render the shadow if the caster about to be drawn is its caster,
541 // OR if its caster's Z value is similar to the previous potential caster
542 if (shadowIndex == drawIndex || casterZ - lastCasterZ < 0.1f) {
543 deferShadow(*casterNodeOp);
544
545 lastCasterZ = casterZ; // must do this even if current caster not casting a shadow
546 shadowIndex++;
547 continue;
548 }
549 }
550
551 const RenderNodeOp* childOp = zTranslatedNodes[drawIndex].value;
Chris Craik268a9c02015-12-09 18:05:12 -0800552 deferRenderNodeOpImpl(*childOp);
Chris Craik161f54b2015-11-05 11:08:52 -0800553 drawIndex++;
554 }
555}
556
557void OpReorderer::deferShadow(const RenderNodeOp& casterNodeOp) {
Chris Craikd3daa312015-11-06 10:59:56 -0800558 auto& node = *casterNodeOp.renderNode;
559 auto& properties = node.properties();
560
561 if (properties.getAlpha() <= 0.0f
562 || properties.getOutline().getAlpha() <= 0.0f
563 || !properties.getOutline().getPath()
564 || properties.getScaleX() == 0
565 || properties.getScaleY() == 0) {
566 // no shadow to draw
567 return;
568 }
569
570 const SkPath* casterOutlinePath = properties.getOutline().getPath();
571 const SkPath* revealClipPath = properties.getRevealClip().getPath();
572 if (revealClipPath && revealClipPath->isEmpty()) return;
573
574 float casterAlpha = properties.getAlpha() * properties.getOutline().getAlpha();
575
576 // holds temporary SkPath to store the result of intersections
577 SkPath* frameAllocatedPath = nullptr;
578 const SkPath* casterPath = casterOutlinePath;
579
580 // intersect the shadow-casting path with the reveal, if present
581 if (revealClipPath) {
582 frameAllocatedPath = createFrameAllocatedPath();
583
584 Op(*casterPath, *revealClipPath, kIntersect_SkPathOp, frameAllocatedPath);
585 casterPath = frameAllocatedPath;
586 }
587
588 // intersect the shadow-casting path with the clipBounds, if present
589 if (properties.getClippingFlags() & CLIP_TO_CLIP_BOUNDS) {
590 if (!frameAllocatedPath) {
591 frameAllocatedPath = createFrameAllocatedPath();
592 }
593 Rect clipBounds;
594 properties.getClippingRectForFlags(CLIP_TO_CLIP_BOUNDS, &clipBounds);
595 SkPath clipBoundsPath;
596 clipBoundsPath.addRect(clipBounds.left, clipBounds.top,
597 clipBounds.right, clipBounds.bottom);
598
599 Op(*casterPath, clipBoundsPath, kIntersect_SkPathOp, frameAllocatedPath);
600 casterPath = frameAllocatedPath;
601 }
602
603 ShadowOp* shadowOp = new (mAllocator) ShadowOp(casterNodeOp, casterAlpha, casterPath,
Chris Craik98787e62015-11-13 10:55:30 -0800604 mCanvasState.getLocalClipBounds(),
605 mCanvasState.currentSnapshot()->getRelativeLightCenter());
Chris Craikd3daa312015-11-06 10:59:56 -0800606 BakedOpState* bakedOpState = BakedOpState::tryShadowOpConstruct(
Chris Craike4db79d2015-12-22 16:32:23 -0800607 mAllocator, *mCanvasState.writableSnapshot(), shadowOp);
Chris Craikd3daa312015-11-06 10:59:56 -0800608 if (CC_LIKELY(bakedOpState)) {
609 currentLayer().deferUnmergeableOp(mAllocator, bakedOpState, OpBatchType::Shadow);
610 }
Chris Craik161f54b2015-11-05 11:08:52 -0800611}
Chris Craikd3daa312015-11-06 10:59:56 -0800612
Chris Craik8d1f2122015-11-24 16:40:09 -0800613void OpReorderer::deferProjectedChildren(const RenderNode& renderNode) {
614 const SkPath* projectionReceiverOutline = renderNode.properties().getOutline().getPath();
615 int count = mCanvasState.save(SkCanvas::kMatrix_SaveFlag | SkCanvas::kClip_SaveFlag);
616
617 // can't be null, since DL=null node rejection happens before deferNodePropsAndOps
618 const DisplayList& displayList = *(renderNode.getDisplayList());
619
620 const RecordedOp* op = (displayList.getOps()[displayList.projectionReceiveIndex]);
621 const RenderNodeOp* backgroundOp = static_cast<const RenderNodeOp*>(op);
622 const RenderProperties& backgroundProps = backgroundOp->renderNode->properties();
623
624 // Transform renderer to match background we're projecting onto
625 // (by offsetting canvas by translationX/Y of background rendernode, since only those are set)
626 mCanvasState.translate(backgroundProps.getTranslationX(), backgroundProps.getTranslationY());
627
628 // If the projection receiver has an outline, we mask projected content to it
629 // (which we know, apriori, are all tessellated paths)
630 mCanvasState.setProjectionPathMask(mAllocator, projectionReceiverOutline);
631
632 // draw projected nodes
633 for (size_t i = 0; i < renderNode.mProjectedNodes.size(); i++) {
634 RenderNodeOp* childOp = renderNode.mProjectedNodes[i];
635
636 int restoreTo = mCanvasState.save(SkCanvas::kMatrix_SaveFlag);
637 mCanvasState.concatMatrix(childOp->transformFromCompositingAncestor);
Chris Craik268a9c02015-12-09 18:05:12 -0800638 deferRenderNodeOpImpl(*childOp);
Chris Craik8d1f2122015-11-24 16:40:09 -0800639 mCanvasState.restoreToCount(restoreTo);
640 }
641
642 mCanvasState.restoreToCount(count);
643}
644
Chris Craikb565df12015-10-05 13:00:52 -0700645/**
Chris Craik268a9c02015-12-09 18:05:12 -0800646 * Used to define a list of lambdas referencing private OpReorderer::onXX::defer() methods.
Chris Craikb565df12015-10-05 13:00:52 -0700647 *
Chris Craik8d1f2122015-11-24 16:40:09 -0800648 * This allows opIds embedded in the RecordedOps to be used for dispatching to these lambdas.
649 * E.g. a BitmapOp op then would be dispatched to OpReorderer::onBitmapOp(const BitmapOp&)
Chris Craikb565df12015-10-05 13:00:52 -0700650 */
Chris Craik6fe991e52015-10-20 09:39:42 -0700651#define OP_RECEIVER(Type) \
Chris Craik268a9c02015-12-09 18:05:12 -0800652 [](OpReorderer& reorderer, const RecordedOp& op) { reorderer.defer##Type(static_cast<const Type&>(op)); },
Chris Craik8d1f2122015-11-24 16:40:09 -0800653void OpReorderer::deferNodeOps(const RenderNode& renderNode) {
Chris Craik15c3f192015-12-03 12:16:56 -0800654 typedef void (*OpDispatcher) (OpReorderer& reorderer, const RecordedOp& op);
Chris Craik7cbf63d2016-01-06 13:46:52 -0800655 static OpDispatcher receivers[] = BUILD_DEFERRABLE_OP_LUT(OP_RECEIVER);
Chris Craik8d1f2122015-11-24 16:40:09 -0800656
657 // can't be null, since DL=null node rejection happens before deferNodePropsAndOps
658 const DisplayList& displayList = *(renderNode.getDisplayList());
Chris Craikb36af872015-10-16 14:23:12 -0700659 for (const DisplayList::Chunk& chunk : displayList.getChunks()) {
Chris Craik161f54b2015-11-05 11:08:52 -0800660 FatVector<ZRenderNodeOpPair, 16> zTranslatedNodes;
661 buildZSortedChildList(&zTranslatedNodes, displayList, chunk);
662
663 defer3dChildren(ChildrenSelectMode::Negative, zTranslatedNodes);
Chris Craikb565df12015-10-05 13:00:52 -0700664 for (size_t opIndex = chunk.beginOpIndex; opIndex < chunk.endOpIndex; opIndex++) {
Chris Craikb36af872015-10-16 14:23:12 -0700665 const RecordedOp* op = displayList.getOps()[opIndex];
Chris Craikb565df12015-10-05 13:00:52 -0700666 receivers[op->opId](*this, *op);
Chris Craik8d1f2122015-11-24 16:40:09 -0800667
668 if (CC_UNLIKELY(!renderNode.mProjectedNodes.empty()
669 && displayList.projectionReceiveIndex >= 0
670 && static_cast<int>(opIndex) == displayList.projectionReceiveIndex)) {
671 deferProjectedChildren(renderNode);
672 }
Chris Craikb565df12015-10-05 13:00:52 -0700673 }
Chris Craik161f54b2015-11-05 11:08:52 -0800674 defer3dChildren(ChildrenSelectMode::Positive, zTranslatedNodes);
Chris Craikb565df12015-10-05 13:00:52 -0700675 }
676}
677
Chris Craik268a9c02015-12-09 18:05:12 -0800678void OpReorderer::deferRenderNodeOpImpl(const RenderNodeOp& op) {
Chris Craik161f54b2015-11-05 11:08:52 -0800679 if (op.renderNode->nothingToDraw()) return;
Chris Craik6fe991e52015-10-20 09:39:42 -0700680 int count = mCanvasState.save(SkCanvas::kClip_SaveFlag | SkCanvas::kMatrix_SaveFlag);
Chris Craikb565df12015-10-05 13:00:52 -0700681
Chris Craike4db79d2015-12-22 16:32:23 -0800682 // apply state from RecordedOp (clip first, since op's clip is transformed by current matrix)
683 mCanvasState.writableSnapshot()->mutateClipArea().applyClip(op.localClip,
684 *mCanvasState.currentSnapshot()->transform);
Chris Craikb565df12015-10-05 13:00:52 -0700685 mCanvasState.concatMatrix(op.localMatrix);
Chris Craikb565df12015-10-05 13:00:52 -0700686
Chris Craik0b7e8242015-10-28 16:50:44 -0700687 // then apply state from node properties, and defer ops
688 deferNodePropsAndOps(*op.renderNode);
689
Chris Craik6fe991e52015-10-20 09:39:42 -0700690 mCanvasState.restoreToCount(count);
Chris Craikb565df12015-10-05 13:00:52 -0700691}
692
Chris Craik268a9c02015-12-09 18:05:12 -0800693void OpReorderer::deferRenderNodeOp(const RenderNodeOp& op) {
Chris Craik161f54b2015-11-05 11:08:52 -0800694 if (!op.skipInOrderDraw) {
Chris Craik268a9c02015-12-09 18:05:12 -0800695 deferRenderNodeOpImpl(op);
Chris Craik161f54b2015-11-05 11:08:52 -0800696 }
697}
698
Chris Craik386aa032015-12-07 17:08:25 -0800699/**
700 * Defers an unmergeable, strokeable op, accounting correctly
701 * for paint's style on the bounds being computed.
702 */
Chris Craik268a9c02015-12-09 18:05:12 -0800703void OpReorderer::deferStrokeableOp(const RecordedOp& op, batchid_t batchId,
Chris Craik386aa032015-12-07 17:08:25 -0800704 BakedOpState::StrokeBehavior strokeBehavior) {
705 // Note: here we account for stroke when baking the op
706 BakedOpState* bakedState = BakedOpState::tryStrokeableOpConstruct(
Chris Craike4db79d2015-12-22 16:32:23 -0800707 mAllocator, *mCanvasState.writableSnapshot(), op, strokeBehavior);
Chris Craik386aa032015-12-07 17:08:25 -0800708 if (!bakedState) return; // quick rejected
709 currentLayer().deferUnmergeableOp(mAllocator, bakedState, batchId);
710}
711
712/**
713 * Returns batch id for tessellatable shapes, based on paint. Checks to see if path effect/AA will
714 * be used, since they trigger significantly different rendering paths.
715 *
716 * Note: not used for lines/points, since they don't currently support path effects.
717 */
718static batchid_t tessBatchId(const RecordedOp& op) {
719 const SkPaint& paint = *(op.paint);
Chris Craikb565df12015-10-05 13:00:52 -0700720 return paint.getPathEffect()
721 ? OpBatchType::AlphaMaskTexture
722 : (paint.isAntiAlias() ? OpBatchType::AlphaVertices : OpBatchType::Vertices);
723}
724
Chris Craik268a9c02015-12-09 18:05:12 -0800725void OpReorderer::deferArcOp(const ArcOp& op) {
726 deferStrokeableOp(op, tessBatchId(op));
Chris Craik386aa032015-12-07 17:08:25 -0800727}
728
Chris Craik268a9c02015-12-09 18:05:12 -0800729void OpReorderer::deferBitmapOp(const BitmapOp& op) {
Chris Craik15c3f192015-12-03 12:16:56 -0800730 BakedOpState* bakedState = tryBakeOpState(op);
731 if (!bakedState) return; // quick rejected
Chris Craikb565df12015-10-05 13:00:52 -0700732
Chris Craik15c3f192015-12-03 12:16:56 -0800733 // Don't merge non-simply transformed or neg scale ops, SET_TEXTURE doesn't handle rotation
734 // Don't merge A8 bitmaps - the paint's color isn't compared by mergeId, or in
735 // MergingDrawBatch::canMergeWith()
736 if (bakedState->computedState.transform.isSimple()
737 && bakedState->computedState.transform.positiveScale()
738 && PaintUtils::getXfermodeDirect(op.paint) == SkXfermode::kSrcOver_Mode
739 && op.bitmap->colorType() != kAlpha_8_SkColorType) {
740 mergeid_t mergeId = (mergeid_t) op.bitmap->getGenerationID();
741 // TODO: AssetAtlas in mergeId
742 currentLayer().deferMergeableOp(mAllocator, bakedState, OpBatchType::Bitmap, mergeId);
743 } else {
744 currentLayer().deferUnmergeableOp(mAllocator, bakedState, OpBatchType::Bitmap);
745 }
Chris Craikb565df12015-10-05 13:00:52 -0700746}
747
Chris Craik268a9c02015-12-09 18:05:12 -0800748void OpReorderer::deferBitmapMeshOp(const BitmapMeshOp& op) {
Chris Craikf09ff5a2015-12-08 17:21:58 -0800749 BakedOpState* bakedState = tryBakeOpState(op);
750 if (!bakedState) return; // quick rejected
751 currentLayer().deferUnmergeableOp(mAllocator, bakedState, OpBatchType::Bitmap);
752}
753
Chris Craik268a9c02015-12-09 18:05:12 -0800754void OpReorderer::deferBitmapRectOp(const BitmapRectOp& op) {
Chris Craikf09ff5a2015-12-08 17:21:58 -0800755 BakedOpState* bakedState = tryBakeOpState(op);
756 if (!bakedState) return; // quick rejected
757 currentLayer().deferUnmergeableOp(mAllocator, bakedState, OpBatchType::Bitmap);
758}
759
Chris Craik268a9c02015-12-09 18:05:12 -0800760void OpReorderer::deferCirclePropsOp(const CirclePropsOp& op) {
761 // allocate a temporary oval op (with mAllocator, so it persists until render), so the
762 // renderer doesn't have to handle the RoundRectPropsOp type, and so state baking is simple.
763 float x = *(op.x);
764 float y = *(op.y);
765 float radius = *(op.radius);
766 Rect unmappedBounds(x - radius, y - radius, x + radius, y + radius);
767 const OvalOp* resolvedOp = new (mAllocator) OvalOp(
768 unmappedBounds,
769 op.localMatrix,
Chris Craike4db79d2015-12-22 16:32:23 -0800770 op.localClip,
Chris Craik268a9c02015-12-09 18:05:12 -0800771 op.paint);
772 deferOvalOp(*resolvedOp);
773}
774
Chris Craike29ce6f2015-12-10 16:25:13 -0800775void OpReorderer::deferFunctorOp(const FunctorOp& op) {
776 BakedOpState* bakedState = tryBakeOpState(op);
777 if (!bakedState) return; // quick rejected
Chris Craikd2dfd8f2015-12-16 14:27:20 -0800778 currentLayer().deferUnmergeableOp(mAllocator, bakedState, OpBatchType::Functor);
Chris Craike29ce6f2015-12-10 16:25:13 -0800779}
780
Chris Craik268a9c02015-12-09 18:05:12 -0800781void OpReorderer::deferLinesOp(const LinesOp& op) {
Chris Craik386aa032015-12-07 17:08:25 -0800782 batchid_t batch = op.paint->isAntiAlias() ? OpBatchType::AlphaVertices : OpBatchType::Vertices;
Chris Craik268a9c02015-12-09 18:05:12 -0800783 deferStrokeableOp(op, batch, BakedOpState::StrokeBehavior::Forced);
Chris Craik386aa032015-12-07 17:08:25 -0800784}
785
Chris Craik268a9c02015-12-09 18:05:12 -0800786void OpReorderer::deferOvalOp(const OvalOp& op) {
787 deferStrokeableOp(op, tessBatchId(op));
Chris Craik386aa032015-12-07 17:08:25 -0800788}
789
Chris Craik268a9c02015-12-09 18:05:12 -0800790void OpReorderer::deferPatchOp(const PatchOp& op) {
Chris Craikf09ff5a2015-12-08 17:21:58 -0800791 BakedOpState* bakedState = tryBakeOpState(op);
792 if (!bakedState) return; // quick rejected
793
794 if (bakedState->computedState.transform.isPureTranslate()
795 && PaintUtils::getXfermodeDirect(op.paint) == SkXfermode::kSrcOver_Mode) {
796 mergeid_t mergeId = (mergeid_t) op.bitmap->getGenerationID();
797 // TODO: AssetAtlas in mergeId
798
799 // Only use the MergedPatch batchId when merged, so Bitmap+Patch don't try to merge together
800 currentLayer().deferMergeableOp(mAllocator, bakedState, OpBatchType::MergedPatch, mergeId);
801 } else {
802 // Use Bitmap batchId since Bitmap+Patch use same shader
803 currentLayer().deferUnmergeableOp(mAllocator, bakedState, OpBatchType::Bitmap);
804 }
805}
806
Chris Craik268a9c02015-12-09 18:05:12 -0800807void OpReorderer::deferPathOp(const PathOp& op) {
808 deferStrokeableOp(op, OpBatchType::Bitmap);
Chris Craik386aa032015-12-07 17:08:25 -0800809}
810
Chris Craik268a9c02015-12-09 18:05:12 -0800811void OpReorderer::deferPointsOp(const PointsOp& op) {
Chris Craik386aa032015-12-07 17:08:25 -0800812 batchid_t batch = op.paint->isAntiAlias() ? OpBatchType::AlphaVertices : OpBatchType::Vertices;
Chris Craik268a9c02015-12-09 18:05:12 -0800813 deferStrokeableOp(op, batch, BakedOpState::StrokeBehavior::Forced);
Chris Craika1717272015-11-19 13:02:43 -0800814}
815
Chris Craik268a9c02015-12-09 18:05:12 -0800816void OpReorderer::deferRectOp(const RectOp& op) {
817 deferStrokeableOp(op, tessBatchId(op));
Chris Craik386aa032015-12-07 17:08:25 -0800818}
819
Chris Craik268a9c02015-12-09 18:05:12 -0800820void OpReorderer::deferRoundRectOp(const RoundRectOp& op) {
821 deferStrokeableOp(op, tessBatchId(op));
Chris Craikb565df12015-10-05 13:00:52 -0700822}
823
Chris Craik268a9c02015-12-09 18:05:12 -0800824void OpReorderer::deferRoundRectPropsOp(const RoundRectPropsOp& op) {
825 // allocate a temporary round rect op (with mAllocator, so it persists until render), so the
826 // renderer doesn't have to handle the RoundRectPropsOp type, and so state baking is simple.
827 const RoundRectOp* resolvedOp = new (mAllocator) RoundRectOp(
828 Rect(*(op.left), *(op.top), *(op.right), *(op.bottom)),
829 op.localMatrix,
Chris Craike4db79d2015-12-22 16:32:23 -0800830 op.localClip,
Chris Craik268a9c02015-12-09 18:05:12 -0800831 op.paint, *op.rx, *op.ry);
832 deferRoundRectOp(*resolvedOp);
833}
834
835void OpReorderer::deferSimpleRectsOp(const SimpleRectsOp& op) {
Chris Craik15c3f192015-12-03 12:16:56 -0800836 BakedOpState* bakedState = tryBakeOpState(op);
837 if (!bakedState) return; // quick rejected
838 currentLayer().deferUnmergeableOp(mAllocator, bakedState, OpBatchType::Vertices);
Chris Craikb565df12015-10-05 13:00:52 -0700839}
840
Chris Craikd7448e62015-12-15 10:34:36 -0800841static batchid_t textBatchId(const SkPaint& paint) {
842 // TODO: better handling of shader (since we won't care about color then)
843 return paint.getColor() == SK_ColorBLACK ? OpBatchType::Text : OpBatchType::ColorText;
844}
845
Chris Craik268a9c02015-12-09 18:05:12 -0800846void OpReorderer::deferTextOp(const TextOp& op) {
Chris Craik15c3f192015-12-03 12:16:56 -0800847 BakedOpState* bakedState = tryBakeOpState(op);
848 if (!bakedState) return; // quick rejected
Chris Craika1717272015-11-19 13:02:43 -0800849
Chris Craikd7448e62015-12-15 10:34:36 -0800850 batchid_t batchId = textBatchId(*(op.paint));
Chris Craik15c3f192015-12-03 12:16:56 -0800851 if (bakedState->computedState.transform.isPureTranslate()
852 && PaintUtils::getXfermodeDirect(op.paint) == SkXfermode::kSrcOver_Mode) {
853 mergeid_t mergeId = reinterpret_cast<mergeid_t>(op.paint->getColor());
854 currentLayer().deferMergeableOp(mAllocator, bakedState, batchId, mergeId);
855 } else {
856 currentLayer().deferUnmergeableOp(mAllocator, bakedState, batchId);
857 }
Chris Craika1717272015-11-19 13:02:43 -0800858}
859
Chris Craikd7448e62015-12-15 10:34:36 -0800860void OpReorderer::deferTextOnPathOp(const TextOnPathOp& op) {
861 BakedOpState* bakedState = tryBakeOpState(op);
862 if (!bakedState) return; // quick rejected
863 currentLayer().deferUnmergeableOp(mAllocator, bakedState, textBatchId(*(op.paint)));
864}
865
Chris Craikd2dfd8f2015-12-16 14:27:20 -0800866void OpReorderer::deferTextureLayerOp(const TextureLayerOp& op) {
867 BakedOpState* bakedState = tryBakeOpState(op);
868 if (!bakedState) return; // quick rejected
869 currentLayer().deferUnmergeableOp(mAllocator, bakedState, OpBatchType::TextureLayer);
870}
871
Chris Craik8ecf41c2015-11-16 10:27:59 -0800872void OpReorderer::saveForLayer(uint32_t layerWidth, uint32_t layerHeight,
873 float contentTranslateX, float contentTranslateY,
874 const Rect& repaintRect,
875 const Vector3& lightCenter,
Chris Craik0b7e8242015-10-28 16:50:44 -0700876 const BeginLayerOp* beginLayerOp, RenderNode* renderNode) {
Chris Craik6fe991e52015-10-20 09:39:42 -0700877 mCanvasState.save(SkCanvas::kClip_SaveFlag | SkCanvas::kMatrix_SaveFlag);
Chris Craik818c9fb2015-10-23 14:33:42 -0700878 mCanvasState.writableSnapshot()->initializeViewport(layerWidth, layerHeight);
Chris Craik6fe991e52015-10-20 09:39:42 -0700879 mCanvasState.writableSnapshot()->roundRectClipState = nullptr;
Chris Craik98787e62015-11-13 10:55:30 -0800880 mCanvasState.writableSnapshot()->setRelativeLightCenter(lightCenter);
Chris Craik8ecf41c2015-11-16 10:27:59 -0800881 mCanvasState.writableSnapshot()->transform->loadTranslate(
882 contentTranslateX, contentTranslateY, 0);
883 mCanvasState.writableSnapshot()->setClip(
884 repaintRect.left, repaintRect.top, repaintRect.right, repaintRect.bottom);
Chris Craik98787e62015-11-13 10:55:30 -0800885
Chris Craik8ecf41c2015-11-16 10:27:59 -0800886 // create a new layer repaint, and push its index on the stack
Chris Craik6fe991e52015-10-20 09:39:42 -0700887 mLayerStack.push_back(mLayerReorderers.size());
Chris Craik98787e62015-11-13 10:55:30 -0800888 mLayerReorderers.emplace_back(layerWidth, layerHeight, repaintRect, beginLayerOp, renderNode);
Chris Craik0b7e8242015-10-28 16:50:44 -0700889}
890
891void OpReorderer::restoreForLayer() {
892 // restore canvas, and pop finished layer off of the stack
893 mCanvasState.restore();
894 mLayerStack.pop_back();
895}
896
897// TODO: test rejection at defer time, where the bounds become empty
Chris Craik268a9c02015-12-09 18:05:12 -0800898void OpReorderer::deferBeginLayerOp(const BeginLayerOp& op) {
Chris Craik8ecf41c2015-11-16 10:27:59 -0800899 uint32_t layerWidth = (uint32_t) op.unmappedBounds.getWidth();
900 uint32_t layerHeight = (uint32_t) op.unmappedBounds.getHeight();
901
902 auto previous = mCanvasState.currentSnapshot();
903 Vector3 lightCenter = previous->getRelativeLightCenter();
904
905 // Combine all transforms used to present saveLayer content:
906 // parent content transform * canvas transform * bounds offset
907 Matrix4 contentTransform(*previous->transform);
908 contentTransform.multiply(op.localMatrix);
909 contentTransform.translate(op.unmappedBounds.left, op.unmappedBounds.top);
910
911 Matrix4 inverseContentTransform;
912 inverseContentTransform.loadInverse(contentTransform);
913
914 // map the light center into layer-relative space
915 inverseContentTransform.mapPoint3d(lightCenter);
916
917 // Clip bounds of temporary layer to parent's clip rect, so:
918 Rect saveLayerBounds(layerWidth, layerHeight);
919 // 1) transform Rect(width, height) into parent's space
920 // note: left/top offsets put in contentTransform above
921 contentTransform.mapRect(saveLayerBounds);
922 // 2) intersect with parent's clip
923 saveLayerBounds.doIntersect(previous->getRenderTargetClip());
924 // 3) and transform back
925 inverseContentTransform.mapRect(saveLayerBounds);
926 saveLayerBounds.doIntersect(Rect(layerWidth, layerHeight));
927 saveLayerBounds.roundOut();
928
929 // if bounds are reduced, will clip the layer's area by reducing required bounds...
930 layerWidth = saveLayerBounds.getWidth();
931 layerHeight = saveLayerBounds.getHeight();
932 // ...and shifting drawing content to account for left/top side clipping
933 float contentTranslateX = -saveLayerBounds.left;
934 float contentTranslateY = -saveLayerBounds.top;
935
936 saveForLayer(layerWidth, layerHeight,
937 contentTranslateX, contentTranslateY,
938 Rect(layerWidth, layerHeight),
939 lightCenter,
940 &op, nullptr);
Chris Craik6fe991e52015-10-20 09:39:42 -0700941}
Chris Craikb565df12015-10-05 13:00:52 -0700942
Chris Craik268a9c02015-12-09 18:05:12 -0800943void OpReorderer::deferEndLayerOp(const EndLayerOp& /* ignored */) {
Chris Craik6fe991e52015-10-20 09:39:42 -0700944 const BeginLayerOp& beginLayerOp = *currentLayer().beginLayerOp;
Chris Craik6fe991e52015-10-20 09:39:42 -0700945 int finishedLayerIndex = mLayerStack.back();
Chris Craik0b7e8242015-10-28 16:50:44 -0700946
947 restoreForLayer();
Chris Craik6fe991e52015-10-20 09:39:42 -0700948
949 // record the draw operation into the previous layer's list of draw commands
950 // uses state from the associated beginLayerOp, since it has all the state needed for drawing
951 LayerOp* drawLayerOp = new (mAllocator) LayerOp(
952 beginLayerOp.unmappedBounds,
953 beginLayerOp.localMatrix,
Chris Craike4db79d2015-12-22 16:32:23 -0800954 beginLayerOp.localClip,
Chris Craik818c9fb2015-10-23 14:33:42 -0700955 beginLayerOp.paint,
Chris Craik5854b342015-10-26 15:49:56 -0700956 &mLayerReorderers[finishedLayerIndex].offscreenBuffer);
Chris Craik6fe991e52015-10-20 09:39:42 -0700957 BakedOpState* bakedOpState = tryBakeOpState(*drawLayerOp);
958
959 if (bakedOpState) {
960 // Layer will be drawn into parent layer (which is now current, since we popped mLayerStack)
961 currentLayer().deferUnmergeableOp(mAllocator, bakedOpState, OpBatchType::Bitmap);
962 } else {
963 // Layer won't be drawn - delete its drawing batches to prevent it from doing any work
964 mLayerReorderers[finishedLayerIndex].clear();
965 return;
Chris Craikb565df12015-10-05 13:00:52 -0700966 }
967}
968
Chris Craikb565df12015-10-05 13:00:52 -0700969} // namespace uirenderer
970} // namespace android