WebKit merge 128969:128981
[chromium-blink-merge.git] / cc / CCLayerTreeHostCommon.cpp
blobd60d43c0930631c4e7b40bcb53bf1ec85b11c05d
1 // Copyright 2011 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
6 #include "config.h"
8 #include "CCLayerTreeHostCommon.h"
10 #include "CCLayerImpl.h"
11 #include "CCLayerIterator.h"
12 #include "CCLayerSorter.h"
13 #include "CCMathUtil.h"
14 #include "CCRenderSurface.h"
15 #include "FloatQuad.h"
16 #include "IntRect.h"
17 #include "LayerChromium.h"
18 #include "RenderSurfaceChromium.h"
19 #include <public/WebTransformationMatrix.h>
21 using WebKit::WebTransformationMatrix;
23 namespace cc {
25 IntRect CCLayerTreeHostCommon::calculateVisibleRect(const IntRect& targetSurfaceRect, const IntRect& layerBoundRect, const WebTransformationMatrix& transform)
27 // Is this layer fully contained within the target surface?
28 IntRect layerInSurfaceSpace = CCMathUtil::mapClippedRect(transform, layerBoundRect);
29 if (targetSurfaceRect.contains(layerInSurfaceSpace))
30 return layerBoundRect;
32 // If the layer doesn't fill up the entire surface, then find the part of
33 // the surface rect where the layer could be visible. This avoids trying to
34 // project surface rect points that are behind the projection point.
35 IntRect minimalSurfaceRect = targetSurfaceRect;
36 minimalSurfaceRect.intersect(layerInSurfaceSpace);
38 // Project the corners of the target surface rect into the layer space.
39 // This bounding rectangle may be larger than it needs to be (being
40 // axis-aligned), but is a reasonable filter on the space to consider.
41 // Non-invertible transforms will create an empty rect here.
42 const WebTransformationMatrix surfaceToLayer = transform.inverse();
43 IntRect layerRect = enclosingIntRect(CCMathUtil::projectClippedRect(surfaceToLayer, FloatRect(minimalSurfaceRect)));
44 layerRect.intersect(layerBoundRect);
45 return layerRect;
48 template<typename LayerType>
49 static inline bool layerIsInExisting3DRenderingContext(LayerType* layer)
51 // According to current W3C spec on CSS transforms, a layer is part of an established
52 // 3d rendering context if its parent has transform-style of preserves-3d.
53 return layer->parent() && layer->parent()->preserves3D();
56 template<typename LayerType>
57 static bool layerIsRootOfNewRenderingContext(LayerType* layer)
59 // According to current W3C spec on CSS transforms (Section 6.1), a layer is the
60 // beginning of 3d rendering context if its parent does not have transform-style:
61 // preserve-3d, but this layer itself does.
62 if (layer->parent())
63 return !layer->parent()->preserves3D() && layer->preserves3D();
65 return layer->preserves3D();
68 template<typename LayerType>
69 static bool isLayerBackFaceVisible(LayerType* layer)
71 // The current W3C spec on CSS transforms says that backface visibility should be
72 // determined differently depending on whether the layer is in a "3d rendering
73 // context" or not. For Chromium code, we can determine whether we are in a 3d
74 // rendering context by checking if the parent preserves 3d.
76 if (layerIsInExisting3DRenderingContext(layer))
77 return layer->drawTransform().isBackFaceVisible();
79 // In this case, either the layer establishes a new 3d rendering context, or is not in
80 // a 3d rendering context at all.
81 return layer->transform().isBackFaceVisible();
84 template<typename LayerType>
85 static bool isSurfaceBackFaceVisible(LayerType* layer, const WebTransformationMatrix& drawTransform)
87 if (layerIsInExisting3DRenderingContext(layer))
88 return drawTransform.isBackFaceVisible();
90 if (layerIsRootOfNewRenderingContext(layer))
91 return layer->transform().isBackFaceVisible();
93 // If the renderSurface is not part of a new or existing rendering context, then the
94 // layers that contribute to this surface will decide back-face visibility for themselves.
95 return false;
98 template<typename LayerType>
99 static inline bool layerClipsSubtree(LayerType* layer)
101 return layer->masksToBounds() || layer->maskLayer();
104 template<typename LayerType>
105 static IntRect calculateVisibleContentRect(LayerType* layer)
107 ASSERT(layer->renderTarget());
109 IntRect targetSurfaceRect = layer->renderTarget()->renderSurface()->contentRect();
111 targetSurfaceRect.intersect(layer->drawableContentRect());
113 if (targetSurfaceRect.isEmpty() || layer->contentBounds().isEmpty())
114 return IntRect();
116 const IntRect contentRect = IntRect(IntPoint(), layer->contentBounds());
117 IntRect visibleContentRect = CCLayerTreeHostCommon::calculateVisibleRect(targetSurfaceRect, contentRect, layer->drawTransform());
118 return visibleContentRect;
121 static bool isScaleOrTranslation(const WebTransformationMatrix& m)
123 return !m.m12() && !m.m13() && !m.m14()
124 && !m.m21() && !m.m23() && !m.m24()
125 && !m.m31() && !m.m32() && !m.m43()
126 && m.m44();
129 static inline bool transformToParentIsKnown(CCLayerImpl*)
131 return true;
134 static inline bool transformToParentIsKnown(LayerChromium* layer)
136 return !layer->transformIsAnimating();
139 static inline bool transformToScreenIsKnown(CCLayerImpl*)
141 return true;
144 static inline bool transformToScreenIsKnown(LayerChromium* layer)
146 return !layer->screenSpaceTransformIsAnimating();
149 template<typename LayerType>
150 static bool layerShouldBeSkipped(LayerType* layer)
152 // Layers can be skipped if any of these conditions are met.
153 // - does not draw content.
154 // - is transparent
155 // - has empty bounds
156 // - the layer is not double-sided, but its back face is visible.
158 // Some additional conditions need to be computed at a later point after the recursion is finished.
159 // - the intersection of render surface content and layer clipRect is empty
160 // - the visibleContentRect is empty
162 // Note, if the layer should not have been drawn due to being fully transparent,
163 // we would have skipped the entire subtree and never made it into this function,
164 // so it is safe to omit this check here.
166 if (!layer->drawsContent() || layer->bounds().isEmpty())
167 return true;
169 LayerType* backfaceTestLayer = layer;
170 if (layer->useParentBackfaceVisibility()) {
171 ASSERT(layer->parent());
172 ASSERT(!layer->parent()->useParentBackfaceVisibility());
173 backfaceTestLayer = layer->parent();
176 // The layer should not be drawn if (1) it is not double-sided and (2) the back of the layer is known to be facing the screen.
177 if (!backfaceTestLayer->doubleSided() && transformToScreenIsKnown(backfaceTestLayer) && isLayerBackFaceVisible(backfaceTestLayer))
178 return true;
180 return false;
183 static inline bool subtreeShouldBeSkipped(CCLayerImpl* layer)
185 // The opacity of a layer always applies to its children (either implicitly
186 // via a render surface or explicitly if the parent preserves 3D), so the
187 // entire subtree can be skipped if this layer is fully transparent.
188 return !layer->opacity();
191 static inline bool subtreeShouldBeSkipped(LayerChromium* layer)
193 // If the opacity is being animated then the opacity on the main thread is unreliable
194 // (since the impl thread may be using a different opacity), so it should not be trusted.
195 // In particular, it should not cause the subtree to be skipped.
196 return !layer->opacity() && !layer->opacityIsAnimating();
199 template<typename LayerType>
200 static bool subtreeShouldRenderToSeparateSurface(LayerType* layer, bool axisAlignedWithRespectToParent)
202 // The root layer has a special render surface that is set up externally, so
203 // it shouldn't be treated as a surface in this code.
204 if (!layer->parent())
205 return false;
207 // Cache this value, because otherwise it walks the entire subtree several times.
208 bool descendantDrawsContent = layer->descendantDrawsContent();
211 // A layer and its descendants should render onto a new RenderSurface if any of these rules hold:
214 // If we force it.
215 if (layer->forceRenderSurface())
216 return true;
218 // If the layer uses a mask.
219 if (layer->maskLayer())
220 return true;
222 // If the layer has a reflection.
223 if (layer->replicaLayer())
224 return true;
226 // If the layer uses a CSS filter.
227 if (!layer->filters().isEmpty() || !layer->backgroundFilters().isEmpty())
228 return true;
230 // If the layer flattens its subtree (i.e. the layer doesn't preserve-3d), but it is
231 // treated as a 3D object by its parent (i.e. parent does preserve-3d).
232 if (layerIsInExisting3DRenderingContext(layer) && !layer->preserves3D() && descendantDrawsContent)
233 return true;
235 // If the layer clips its descendants but it is not axis-aligned with respect to its parent.
236 if (layerClipsSubtree(layer) && !axisAlignedWithRespectToParent && descendantDrawsContent)
237 return true;
239 // If the layer has opacity != 1 and does not have a preserves-3d transform style.
240 if (layer->opacity() != 1 && !layer->preserves3D() && descendantDrawsContent)
241 return true;
243 return false;
246 WebTransformationMatrix computeScrollCompensationForThisLayer(CCLayerImpl* scrollingLayer, const WebTransformationMatrix& parentMatrix)
248 // For every layer that has non-zero scrollDelta, we have to compute a transform that can undo the
249 // scrollDelta translation. In particular, we want this matrix to premultiply a fixed-position layer's
250 // parentMatrix, so we design this transform in three steps as follows. The steps described here apply
251 // from right-to-left, so Step 1 would be the right-most matrix:
253 // Step 1. transform from target surface space to the exact space where scrollDelta is actually applied.
254 // -- this is inverse of the matrix in step 3
255 // Step 2. undo the scrollDelta
256 // -- this is just a translation by scrollDelta.
257 // Step 3. transform back to target surface space.
258 // -- this transform is the "partialLayerOriginTransform" = (parentMatrix * scale(layer->pageScaleDelta()));
260 // These steps create a matrix that both start and end in targetSurfaceSpace. So this matrix can
261 // pre-multiply any fixed-position layer's drawTransform to undo the scrollDeltas -- as long as
262 // that fixed position layer is fixed onto the same renderTarget as this scrollingLayer.
265 WebTransformationMatrix partialLayerOriginTransform = parentMatrix;
266 partialLayerOriginTransform.scale(scrollingLayer->pageScaleDelta());
268 WebTransformationMatrix scrollCompensationForThisLayer = partialLayerOriginTransform; // Step 3
269 scrollCompensationForThisLayer.translate(scrollingLayer->scrollDelta().width(), scrollingLayer->scrollDelta().height()); // Step 2
270 scrollCompensationForThisLayer.multiply(partialLayerOriginTransform.inverse()); // Step 1
271 return scrollCompensationForThisLayer;
274 WebTransformationMatrix computeScrollCompensationMatrixForChildren(LayerChromium* currentLayer, const WebTransformationMatrix& currentParentMatrix, const WebTransformationMatrix& currentScrollCompensation)
276 // The main thread (i.e. LayerChromium) does not need to worry about scroll compensation.
277 // So we can just return an identity matrix here.
278 return WebTransformationMatrix();
281 WebTransformationMatrix computeScrollCompensationMatrixForChildren(CCLayerImpl* layer, const WebTransformationMatrix& parentMatrix, const WebTransformationMatrix& currentScrollCompensationMatrix)
283 // "Total scroll compensation" is the transform needed to cancel out all scrollDelta translations that
284 // occurred since the nearest container layer, even if there are renderSurfaces in-between.
286 // There are some edge cases to be aware of, that are not explicit in the code:
287 // - A layer that is both a fixed-position and container should not be its own container, instead, that means
288 // it is fixed to an ancestor, and is a container for any fixed-position descendants.
289 // - A layer that is a fixed-position container and has a renderSurface should behave the same as a container
290 // without a renderSurface, the renderSurface is irrelevant in that case.
291 // - A layer that does not have an explicit container is simply fixed to the viewport
292 // (i.e. the root renderSurface, and it would still compensate for root layer's scrollDelta).
293 // - If the fixed-position layer has its own renderSurface, then the renderSurface is
294 // the one who gets fixed.
296 // This function needs to be called AFTER layers create their own renderSurfaces.
299 // Avoid the overheads (including stack allocation and matrix initialization/copy) if we know that the scroll compensation doesn't need to be reset or adjusted.
300 if (!layer->isContainerForFixedPositionLayers() && layer->scrollDelta().isZero() && !layer->renderSurface())
301 return currentScrollCompensationMatrix;
303 // Start as identity matrix.
304 WebTransformationMatrix nextScrollCompensationMatrix;
306 // If this layer is not a container, then it inherits the existing scroll compensations.
307 if (!layer->isContainerForFixedPositionLayers())
308 nextScrollCompensationMatrix = currentScrollCompensationMatrix;
310 // If the current layer has a non-zero scrollDelta, then we should compute its local scrollCompensation
311 // and accumulate it to the nextScrollCompensationMatrix.
312 if (!layer->scrollDelta().isZero()) {
313 WebTransformationMatrix scrollCompensationForThisLayer = computeScrollCompensationForThisLayer(layer, parentMatrix);
314 nextScrollCompensationMatrix.multiply(scrollCompensationForThisLayer);
317 // If the layer created its own renderSurface, we have to adjust nextScrollCompensationMatrix.
318 // The adjustment allows us to continue using the scrollCompensation on the next surface.
319 // Step 1 (right-most in the math): transform from the new surface to the original ancestor surface
320 // Step 2: apply the scroll compensation
321 // Step 3: transform back to the new surface.
322 if (layer->renderSurface() && !nextScrollCompensationMatrix.isIdentity())
323 nextScrollCompensationMatrix = layer->renderSurface()->drawTransform().inverse() * nextScrollCompensationMatrix * layer->renderSurface()->drawTransform();
325 return nextScrollCompensationMatrix;
328 // Should be called just before the recursive calculateDrawTransformsInternal().
329 template<typename LayerType, typename LayerList>
330 void setupRootLayerAndSurfaceForRecursion(LayerType* rootLayer, LayerList& renderSurfaceLayerList, const IntSize& deviceViewportSize)
332 if (!rootLayer->renderSurface())
333 rootLayer->createRenderSurface();
335 rootLayer->renderSurface()->setContentRect(IntRect(IntPoint::zero(), deviceViewportSize));
336 rootLayer->renderSurface()->clearLayerList();
338 ASSERT(renderSurfaceLayerList.isEmpty());
339 renderSurfaceLayerList.append(rootLayer);
342 // Recursively walks the layer tree starting at the given node and computes all the
343 // necessary transformations, clipRects, render surfaces, etc.
344 template<typename LayerType, typename LayerList, typename RenderSurfaceType, typename LayerSorter>
345 static void calculateDrawTransformsInternal(LayerType* layer, LayerType* rootLayer, const WebTransformationMatrix& parentMatrix,
346 const WebTransformationMatrix& fullHierarchyMatrix, const WebTransformationMatrix& currentScrollCompensationMatrix,
347 const IntRect& clipRectFromAncestor, bool ancestorClipsSubtree,
348 RenderSurfaceType* nearestAncestorThatMovesPixels, LayerList& renderSurfaceLayerList, LayerList& layerList,
349 LayerSorter* layerSorter, int maxTextureSize, float deviceScaleFactor, IntRect& drawableContentRectOfSubtree)
351 // This function computes the new matrix transformations recursively for this
352 // layer and all its descendants. It also computes the appropriate render surfaces.
353 // Some important points to remember:
355 // 0. Here, transforms are notated in Matrix x Vector order, and in words we describe what
356 // the transform does from left to right.
358 // 1. In our terminology, the "layer origin" refers to the top-left corner of a layer, and the
359 // positive Y-axis points downwards. This interpretation is valid because the orthographic
360 // projection applied at draw time flips the Y axis appropriately.
362 // 2. The anchor point, when given as a FloatPoint object, is specified in "unit layer space",
363 // where the bounds of the layer map to [0, 1]. However, as a WebTransformationMatrix object,
364 // the transform to the anchor point is specified in "pixel layer space", where the bounds
365 // of the layer map to [bounds.width(), bounds.height()].
367 // 3. Definition of various transforms used:
368 // M[parent] is the parent matrix, with respect to the nearest render surface, passed down recursively.
369 // M[root] is the full hierarchy, with respect to the root, passed down recursively.
370 // Tr[origin] is the translation matrix from the parent's origin to this layer's origin.
371 // Tr[origin2anchor] is the translation from the layer's origin to its anchor point
372 // Tr[origin2center] is the translation from the layer's origin to its center
373 // M[layer] is the layer's matrix (applied at the anchor point)
374 // M[sublayer] is the layer's sublayer transform (applied at the layer's center)
375 // Tr[anchor2center] is the translation offset from the anchor point and the center of the layer
376 // S[content2layer] is the ratio of a layer's contentBounds() to its bounds().
378 // Some shortcuts and substitutions are used in the code to reduce matrix multiplications:
379 // Tr[anchor2center] = Tr[origin2anchor].inverse() * Tr[origin2center]
381 // Some composite transforms can help in understanding the sequence of transforms:
382 // compositeLayerTransform = Tr[origin2anchor] * M[layer] * Tr[origin2anchor].inverse()
383 // compositeSublayerTransform = Tr[origin2center] * M[sublayer] * Tr[origin2center].inverse()
385 // In words, the layer transform is applied about the anchor point, and the sublayer transform is
386 // applied about the center of the layer.
388 // 4. When a layer (or render surface) is drawn, it is drawn into a "target render surface". Therefore the draw
389 // transform does not necessarily transform from screen space to local layer space. Instead, the draw transform
390 // is the transform between the "target render surface space" and local layer space. Note that render surfaces,
391 // except for the root, also draw themselves into a different target render surface, and so their draw
392 // transform and origin transforms are also described with respect to the target.
394 // Using these definitions, then:
396 // The draw transform for the layer is:
397 // M[draw] = M[parent] * Tr[origin] * compositeLayerTransform * S[content2layer]
398 // = M[parent] * Tr[layer->position()] * M[layer] * Tr[anchor2origin] * S[content2layer]
400 // Interpreting the math left-to-right, this transforms from the layer's render surface to the origin of the layer in content space.
402 // The screen space transform is:
403 // M[screenspace] = M[root] * Tr[origin] * compositeLayerTransform * S[content2layer]
404 // = M[root] * Tr[layer->position()] * M[layer] * Tr[origin2anchor].inverse() * S[content2layer]
406 // Interpreting the math left-to-right, this transforms from the root render surface's content space to the local layer's origin in layer space.
408 // The transform hierarchy that is passed on to children (i.e. the child's parentMatrix) is:
409 // M[parent]_for_child = M[parent] * Tr[origin] * compositeLayerTransform * compositeSublayerTransform
410 // = M[parent] * Tr[layer->position()] * M[layer] * Tr[anchor2center] * M[sublayer] * Tr[origin2center].inverse()
411 // = M[draw] * M[sublayer] * Tr[origin2center].inverse()
413 // and a similar matrix for the full hierarchy with respect to the root.
415 // Finally, note that the final matrix used by the shader for the layer is P * M[draw] * S . This final product
416 // is computed in drawTexturedQuad(), where:
417 // P is the projection matrix
418 // S is the scale adjustment (to scale up to the layer size)
420 // When a render surface has a replica layer, that layer's transform is used to draw a second copy of the surface.
421 // Transforms named here are relative to the surface, unless they specify they are relative to the replica layer.
423 // We will denote a scale by device scale S[deviceScale]
425 // The render surface draw transform to its target surface origin is:
426 // M[surfaceDraw] = M[owningLayer->Draw]
428 // The render surface origin transform to its the root (screen space) origin is:
429 // M[surface2root] = M[owningLayer->screenspace] * S[deviceScale].inverse()
431 // The replica draw transform to its target surface origin is:
432 // M[replicaDraw] = S[deviceScale] * M[surfaceDraw] * Tr[replica->position() + replica->anchor()] * Tr[replica] * Tr[origin2anchor].inverse() * S[contentsScale].inverse()
434 // The replica draw transform to the root (screen space) origin is:
435 // M[replica2root] = M[surface2root] * Tr[replica->position()] * Tr[replica] * Tr[origin2anchor].inverse()
438 // If we early-exit anywhere in this function, the drawableContentRect of this subtree should be considered empty.
439 drawableContentRectOfSubtree = IntRect();
441 if (subtreeShouldBeSkipped(layer))
442 return;
444 IntRect clipRectForSubtree;
445 bool subtreeShouldBeClipped = false;
447 float drawOpacity = layer->opacity();
448 bool drawOpacityIsAnimating = layer->opacityIsAnimating();
449 if (layer->parent() && layer->parent()->preserves3D()) {
450 drawOpacity *= layer->parent()->drawOpacity();
451 drawOpacityIsAnimating |= layer->parent()->drawOpacityIsAnimating();
454 IntSize bounds = layer->bounds();
455 FloatPoint anchorPoint = layer->anchorPoint();
456 FloatPoint position = layer->position() - layer->scrollDelta();
458 // Offset between anchor point and the center of the quad.
459 float centerOffsetX = (0.5 - anchorPoint.x()) * bounds.width();
460 float centerOffsetY = (0.5 - anchorPoint.y()) * bounds.height();
462 WebTransformationMatrix layerLocalTransform;
463 // LT = S[pageScaleDelta]
464 layerLocalTransform.scale(layer->pageScaleDelta());
465 // LT = S[pageScaleDelta] * Tr[origin] * Tr[origin2anchor]
466 layerLocalTransform.translate3d(position.x() + anchorPoint.x() * bounds.width(), position.y() + anchorPoint.y() * bounds.height(), layer->anchorPointZ());
467 // LT = S[pageScaleDelta] * Tr[origin] * Tr[origin2anchor] * M[layer]
468 layerLocalTransform.multiply(layer->transform());
469 // LT = S[pageScaleDelta] * Tr[origin] * Tr[origin2anchor] * M[layer] * Tr[anchor2center]
470 layerLocalTransform.translate3d(centerOffsetX, centerOffsetY, -layer->anchorPointZ());
472 WebTransformationMatrix combinedTransform = parentMatrix;
473 combinedTransform.multiply(layerLocalTransform);
475 if (layer->fixedToContainerLayer()) {
476 // Special case: this layer is a composited fixed-position layer; we need to
477 // explicitly compensate for all ancestors' nonzero scrollDeltas to keep this layer
478 // fixed correctly.
479 combinedTransform = currentScrollCompensationMatrix * combinedTransform;
482 // The drawTransform that gets computed below is effectively the layer's drawTransform, unless
483 // the layer itself creates a renderSurface. In that case, the renderSurface re-parents the transforms.
484 WebTransformationMatrix drawTransform = combinedTransform;
485 // M[draw] = M[parent] * LT * Tr[anchor2center] * Tr[center2origin]
486 drawTransform.translate(-layer->bounds().width() / 2.0, -layer->bounds().height() / 2.0);
487 if (!layer->contentBounds().isEmpty() && !layer->bounds().isEmpty()) {
488 // M[draw] = M[parent] * LT * Tr[anchor2origin] * S[layer2content]
489 drawTransform.scaleNonUniform(layer->bounds().width() / static_cast<double>(layer->contentBounds().width()),
490 layer->bounds().height() / static_cast<double>(layer->contentBounds().height()));
493 // layerScreenSpaceTransform represents the transform between root layer's "screen space" and local content space.
494 WebTransformationMatrix layerScreenSpaceTransform = fullHierarchyMatrix;
495 if (!layer->preserves3D())
496 CCMathUtil::flattenTransformTo2d(layerScreenSpaceTransform);
497 layerScreenSpaceTransform.multiply(drawTransform);
498 layer->setScreenSpaceTransform(layerScreenSpaceTransform);
500 bool animatingTransformToTarget = layer->transformIsAnimating();
501 bool animatingTransformToScreen = animatingTransformToTarget;
502 if (layer->parent()) {
503 animatingTransformToTarget |= layer->parent()->drawTransformIsAnimating();
504 animatingTransformToScreen |= layer->parent()->screenSpaceTransformIsAnimating();
507 FloatRect contentRect(FloatPoint(), layer->contentBounds());
509 // fullHierarchyMatrix is the matrix that transforms objects between screen space (except projection matrix) and the most recent RenderSurface's space.
510 // nextHierarchyMatrix will only change if this layer uses a new RenderSurface, otherwise remains the same.
511 WebTransformationMatrix nextHierarchyMatrix = fullHierarchyMatrix;
512 WebTransformationMatrix sublayerMatrix;
514 if (subtreeShouldRenderToSeparateSurface(layer, isScaleOrTranslation(combinedTransform))) {
515 // Check back-face visibility before continuing with this surface and its subtree
516 if (!layer->doubleSided() && transformToParentIsKnown(layer) && isSurfaceBackFaceVisible(layer, combinedTransform))
517 return;
519 if (!layer->renderSurface())
520 layer->createRenderSurface();
522 RenderSurfaceType* renderSurface = layer->renderSurface();
523 renderSurface->clearLayerList();
525 // The origin of the new surface is the upper left corner of the layer.
526 renderSurface->setDrawTransform(drawTransform);
527 WebTransformationMatrix layerDrawTransform;
528 layerDrawTransform.scale(deviceScaleFactor);
529 if (!layer->contentBounds().isEmpty() && !layer->bounds().isEmpty()) {
530 layerDrawTransform.scaleNonUniform(layer->bounds().width() / static_cast<double>(layer->contentBounds().width()),
531 layer->bounds().height() / static_cast<double>(layer->contentBounds().height()));
533 layer->setDrawTransform(layerDrawTransform);
535 // The sublayer matrix transforms centered layer rects into target
536 // surface content space.
537 sublayerMatrix.makeIdentity();
538 sublayerMatrix.scale(deviceScaleFactor);
539 sublayerMatrix.translate(0.5 * bounds.width(), 0.5 * bounds.height());
541 // The opacity value is moved from the layer to its surface, so that the entire subtree properly inherits opacity.
542 renderSurface->setDrawOpacity(drawOpacity);
543 renderSurface->setDrawOpacityIsAnimating(drawOpacityIsAnimating);
544 layer->setDrawOpacity(1);
545 layer->setDrawOpacityIsAnimating(false);
547 renderSurface->setTargetSurfaceTransformsAreAnimating(animatingTransformToTarget);
548 renderSurface->setScreenSpaceTransformsAreAnimating(animatingTransformToScreen);
549 animatingTransformToTarget = false;
550 layer->setDrawTransformIsAnimating(animatingTransformToTarget);
551 layer->setScreenSpaceTransformIsAnimating(animatingTransformToScreen);
553 // Update the aggregate hierarchy matrix to include the transform of the
554 // newly created RenderSurface.
555 nextHierarchyMatrix.multiply(renderSurface->drawTransform());
557 // The new renderSurface here will correctly clip the entire subtree. So, we do
558 // not need to continue propagating the clipping state further down the tree. This
559 // way, we can avoid transforming clipRects from ancestor target surface space to
560 // current target surface space that could cause more w < 0 headaches.
561 subtreeShouldBeClipped = false;
563 if (layer->maskLayer())
564 layer->maskLayer()->setRenderTarget(layer);
566 if (layer->replicaLayer() && layer->replicaLayer()->maskLayer())
567 layer->replicaLayer()->maskLayer()->setRenderTarget(layer);
569 if (layer->filters().hasFilterThatMovesPixels())
570 nearestAncestorThatMovesPixels = renderSurface;
572 renderSurface->setNearestAncestorThatMovesPixels(nearestAncestorThatMovesPixels);
574 renderSurfaceLayerList.append(layer);
575 } else {
576 layer->setDrawTransform(drawTransform);
577 layer->setDrawTransformIsAnimating(animatingTransformToTarget);
578 layer->setScreenSpaceTransformIsAnimating(animatingTransformToScreen);
579 sublayerMatrix = combinedTransform;
581 layer->setDrawOpacity(drawOpacity);
582 layer->setDrawOpacityIsAnimating(drawOpacityIsAnimating);
584 if (layer != rootLayer) {
585 ASSERT(layer->parent());
586 layer->clearRenderSurface();
588 // Layers without renderSurfaces directly inherit the ancestor's clip status.
589 subtreeShouldBeClipped = ancestorClipsSubtree;
590 if (ancestorClipsSubtree)
591 clipRectForSubtree = clipRectFromAncestor;
593 // Layers that are not their own renderTarget will render into the target of their nearest ancestor.
594 layer->setRenderTarget(layer->parent()->renderTarget());
595 } else {
596 // FIXME: This root layer special case code should eventually go away. https://bugs.webkit.org/show_bug.cgi?id=92290
597 ASSERT(!layer->parent());
598 ASSERT(layer->renderSurface());
599 ASSERT(ancestorClipsSubtree);
600 layer->renderSurface()->setClipRect(clipRectFromAncestor);
601 subtreeShouldBeClipped = false;
605 IntRect rectInTargetSpace = enclosingIntRect(CCMathUtil::mapClippedRect(layer->drawTransform(), contentRect));
607 if (layerClipsSubtree(layer)) {
608 subtreeShouldBeClipped = true;
609 if (ancestorClipsSubtree && !layer->renderSurface()) {
610 clipRectForSubtree = clipRectFromAncestor;
611 clipRectForSubtree.intersect(rectInTargetSpace);
612 } else
613 clipRectForSubtree = rectInTargetSpace;
616 // Flatten to 2D if the layer doesn't preserve 3D.
617 if (!layer->preserves3D())
618 CCMathUtil::flattenTransformTo2d(sublayerMatrix);
620 // Apply the sublayer transform at the center of the layer.
621 sublayerMatrix.multiply(layer->sublayerTransform());
623 // The coordinate system given to children is located at the layer's origin, not the center.
624 sublayerMatrix.translate3d(-bounds.width() * 0.5, -bounds.height() * 0.5, 0);
626 LayerList& descendants = (layer->renderSurface() ? layer->renderSurface()->layerList() : layerList);
628 // Any layers that are appended after this point are in the layer's subtree and should be included in the sorting process.
629 unsigned sortingStartIndex = descendants.size();
631 if (!layerShouldBeSkipped(layer))
632 descendants.append(layer);
634 WebTransformationMatrix nextScrollCompensationMatrix = computeScrollCompensationMatrixForChildren(layer, parentMatrix, currentScrollCompensationMatrix);;
636 IntRect accumulatedDrawableContentRectOfChildren;
637 for (size_t i = 0; i < layer->children().size(); ++i) {
638 LayerType* child = layer->children()[i].get();
639 IntRect drawableContentRectOfChildSubtree;
640 calculateDrawTransformsInternal<LayerType, LayerList, RenderSurfaceType, LayerSorter>(child, rootLayer, sublayerMatrix, nextHierarchyMatrix, nextScrollCompensationMatrix,
641 clipRectForSubtree, subtreeShouldBeClipped, nearestAncestorThatMovesPixels,
642 renderSurfaceLayerList, descendants, layerSorter, maxTextureSize, deviceScaleFactor, drawableContentRectOfChildSubtree);
643 if (!drawableContentRectOfChildSubtree.isEmpty()) {
644 accumulatedDrawableContentRectOfChildren.unite(drawableContentRectOfChildSubtree);
645 if (child->renderSurface())
646 descendants.append(child);
650 // Compute the total drawableContentRect for this subtree (the rect is in targetSurface space)
651 IntRect localDrawableContentRectOfSubtree = accumulatedDrawableContentRectOfChildren;
652 if (layer->drawsContent())
653 localDrawableContentRectOfSubtree.unite(rectInTargetSpace);
654 if (subtreeShouldBeClipped)
655 localDrawableContentRectOfSubtree.intersect(clipRectForSubtree);
657 // Compute the layer's drawable content rect (the rect is in targetSurface space)
658 IntRect drawableContentRectOfLayer = rectInTargetSpace;
659 if (subtreeShouldBeClipped)
660 drawableContentRectOfLayer.intersect(clipRectForSubtree);
661 layer->setDrawableContentRect(drawableContentRectOfLayer);
663 // Compute the remaining properties for the render surface, if the layer has one.
664 if (layer->renderSurface() && layer != rootLayer) {
665 RenderSurfaceType* renderSurface = layer->renderSurface();
666 IntRect clippedContentRect = localDrawableContentRectOfSubtree;
668 // The render surface clipRect is expressed in the space where this surface draws, i.e. the same space as clipRectFromAncestor.
669 if (ancestorClipsSubtree)
670 renderSurface->setClipRect(clipRectFromAncestor);
671 else
672 renderSurface->setClipRect(IntRect());
674 // Don't clip if the layer is reflected as the reflection shouldn't be
675 // clipped. If the layer is animating, then the surface's transform to
676 // its target is not known on the main thread, and we should not use it
677 // to clip.
678 if (!layer->replicaLayer() && transformToParentIsKnown(layer)) {
679 // Note, it is correct to use ancestorClipsSubtree here, because we are looking at this layer's renderSurface, not the layer itself.
680 if (ancestorClipsSubtree && !clippedContentRect.isEmpty()) {
681 IntRect surfaceClipRect = CCLayerTreeHostCommon::calculateVisibleRect(renderSurface->clipRect(), clippedContentRect, renderSurface->drawTransform());
682 clippedContentRect.intersect(surfaceClipRect);
686 // The RenderSurface backing texture cannot exceed the maximum supported
687 // texture size.
688 clippedContentRect.setWidth(std::min(clippedContentRect.width(), maxTextureSize));
689 clippedContentRect.setHeight(std::min(clippedContentRect.height(), maxTextureSize));
691 if (clippedContentRect.isEmpty())
692 renderSurface->clearLayerList();
694 renderSurface->setContentRect(clippedContentRect);
695 renderSurface->setScreenSpaceTransform(layer->screenSpaceTransform());
697 if (layer->replicaLayer()) {
698 WebTransformationMatrix surfaceOriginToReplicaOriginTransform;
699 surfaceOriginToReplicaOriginTransform.scale(deviceScaleFactor);
700 surfaceOriginToReplicaOriginTransform.translate(layer->replicaLayer()->position().x() + layer->replicaLayer()->anchorPoint().x() * bounds.width(),
701 layer->replicaLayer()->position().y() + layer->replicaLayer()->anchorPoint().y() * bounds.height());
702 surfaceOriginToReplicaOriginTransform.multiply(layer->replicaLayer()->transform());
703 surfaceOriginToReplicaOriginTransform.translate(-layer->replicaLayer()->anchorPoint().x() * bounds.width(), -layer->replicaLayer()->anchorPoint().y() * bounds.height());
704 surfaceOriginToReplicaOriginTransform.scale(1 / deviceScaleFactor);
706 // Compute the replica's "originTransform" that maps from the replica's origin space to the target surface origin space.
707 WebTransformationMatrix replicaOriginTransform = layer->renderSurface()->drawTransform() * surfaceOriginToReplicaOriginTransform;
708 renderSurface->setReplicaDrawTransform(replicaOriginTransform);
710 // Compute the replica's "screenSpaceTransform" that maps from the replica's origin space to the screen's origin space.
711 WebTransformationMatrix replicaScreenSpaceTransform = layer->renderSurface()->screenSpaceTransform() * surfaceOriginToReplicaOriginTransform;
712 renderSurface->setReplicaScreenSpaceTransform(replicaScreenSpaceTransform);
715 // If a render surface has no layer list, then it and none of its children needed to get drawn.
716 if (!layer->renderSurface()->layerList().size()) {
717 // FIXME: Originally we asserted that this layer was already at the end of the
718 // list, and only needed to remove that layer. For now, we remove the
719 // entire subtree of surfaces to fix a crash bug. The root cause is
720 // https://bugs.webkit.org/show_bug.cgi?id=74147 and we should be able
721 // to put the original assert after fixing that.
722 while (renderSurfaceLayerList.last() != layer) {
723 renderSurfaceLayerList.last()->clearRenderSurface();
724 renderSurfaceLayerList.removeLast();
726 ASSERT(renderSurfaceLayerList.last() == layer);
727 renderSurfaceLayerList.removeLast();
728 layer->clearRenderSurface();
729 return;
733 // If neither this layer nor any of its children were added, early out.
734 if (sortingStartIndex == descendants.size())
735 return;
737 // If preserves-3d then sort all the descendants in 3D so that they can be
738 // drawn from back to front. If the preserves-3d property is also set on the parent then
739 // skip the sorting as the parent will sort all the descendants anyway.
740 if (descendants.size() && layer->preserves3D() && (!layer->parent() || !layer->parent()->preserves3D()))
741 sortLayers(&descendants.at(sortingStartIndex), descendants.end(), layerSorter);
743 if (layer->renderSurface())
744 drawableContentRectOfSubtree = enclosingIntRect(layer->renderSurface()->drawableContentRect());
745 else
746 drawableContentRectOfSubtree = localDrawableContentRectOfSubtree;
748 return;
751 // FIXME: Instead of using the following function to set visibility rects on a second
752 // tree pass, revise calculateVisibleContentRect() so that this can be done in a single
753 // pass inside calculateDrawTransformsInternal<>().
754 template<typename LayerType, typename LayerList, typename RenderSurfaceType>
755 static void calculateVisibleRectsInternal(const LayerList& renderSurfaceLayerList)
757 // Use BackToFront since it's cheap and this isn't order-dependent.
758 typedef CCLayerIterator<LayerType, LayerList, RenderSurfaceType, CCLayerIteratorActions::BackToFront> CCLayerIteratorType;
760 CCLayerIteratorType end = CCLayerIteratorType::end(&renderSurfaceLayerList);
761 for (CCLayerIteratorType it = CCLayerIteratorType::begin(&renderSurfaceLayerList); it != end; ++it) {
762 if (it.representsTargetRenderSurface()) {
763 LayerType* maskLayer = it->maskLayer();
764 if (maskLayer)
765 maskLayer->setVisibleContentRect(IntRect(IntPoint(), it->contentBounds()));
766 LayerType* replicaMaskLayer = it->replicaLayer() ? it->replicaLayer()->maskLayer() : 0;
767 if (replicaMaskLayer)
768 replicaMaskLayer->setVisibleContentRect(IntRect(IntPoint(), it->contentBounds()));
769 } else if (it.representsItself()) {
770 IntRect visibleContentRect = calculateVisibleContentRect(*it);
771 it->setVisibleContentRect(visibleContentRect);
776 void CCLayerTreeHostCommon::calculateDrawTransforms(LayerChromium* rootLayer, const IntSize& deviceViewportSize, float deviceScaleFactor, int maxTextureSize, Vector<RefPtr<LayerChromium> >& renderSurfaceLayerList)
778 IntRect totalDrawableContentRect;
779 WebTransformationMatrix identityMatrix;
780 WebTransformationMatrix deviceScaleTransform;
781 deviceScaleTransform.scale(deviceScaleFactor);
783 setupRootLayerAndSurfaceForRecursion<LayerChromium, Vector<RefPtr<LayerChromium> > >(rootLayer, renderSurfaceLayerList, deviceViewportSize);
785 cc::calculateDrawTransformsInternal<LayerChromium, Vector<RefPtr<LayerChromium> >, RenderSurfaceChromium, void>(rootLayer, rootLayer, deviceScaleTransform, identityMatrix, identityMatrix,
786 rootLayer->renderSurface()->contentRect(), true, 0, renderSurfaceLayerList,
787 rootLayer->renderSurface()->layerList(), 0, maxTextureSize, deviceScaleFactor, totalDrawableContentRect);
790 void CCLayerTreeHostCommon::calculateDrawTransforms(CCLayerImpl* rootLayer, const IntSize& deviceViewportSize, float deviceScaleFactor, CCLayerSorter* layerSorter, int maxTextureSize, Vector<CCLayerImpl*>& renderSurfaceLayerList)
792 IntRect totalDrawableContentRect;
793 WebTransformationMatrix identityMatrix;
794 WebTransformationMatrix deviceScaleTransform;
795 deviceScaleTransform.scale(deviceScaleFactor);
797 setupRootLayerAndSurfaceForRecursion<CCLayerImpl, Vector<CCLayerImpl*> >(rootLayer, renderSurfaceLayerList, deviceViewportSize);
799 cc::calculateDrawTransformsInternal<CCLayerImpl, Vector<CCLayerImpl*>, CCRenderSurface, CCLayerSorter>(rootLayer, rootLayer, deviceScaleTransform, identityMatrix, identityMatrix,
800 rootLayer->renderSurface()->contentRect(), true, 0, renderSurfaceLayerList,
801 rootLayer->renderSurface()->layerList(), layerSorter, maxTextureSize, deviceScaleFactor, totalDrawableContentRect);
804 void CCLayerTreeHostCommon::calculateVisibleRects(Vector<RefPtr<LayerChromium> >& renderSurfaceLayerList)
806 calculateVisibleRectsInternal<LayerChromium, Vector<RefPtr<LayerChromium> >, RenderSurfaceChromium>(renderSurfaceLayerList);
809 void CCLayerTreeHostCommon::calculateVisibleRects(Vector<CCLayerImpl*>& renderSurfaceLayerList)
811 calculateVisibleRectsInternal<CCLayerImpl, Vector<CCLayerImpl*>, CCRenderSurface>(renderSurfaceLayerList);
814 static bool pointHitsRect(const IntPoint& viewportPoint, const WebTransformationMatrix& localSpaceToScreenSpaceTransform, FloatRect localSpaceRect)
816 // If the transform is not invertible, then assume that this point doesn't hit this rect.
817 if (!localSpaceToScreenSpaceTransform.isInvertible())
818 return false;
820 // Transform the hit test point from screen space to the local space of the given rect.
821 bool clipped = false;
822 FloatPoint hitTestPointInLocalSpace = CCMathUtil::projectPoint(localSpaceToScreenSpaceTransform.inverse(), FloatPoint(viewportPoint), clipped);
824 // If projectPoint could not project to a valid value, then we assume that this point doesn't hit this rect.
825 if (clipped)
826 return false;
828 return localSpaceRect.contains(hitTestPointInLocalSpace);
831 static bool pointIsClippedBySurfaceOrClipRect(const IntPoint& viewportPoint, CCLayerImpl* layer)
833 CCLayerImpl* currentLayer = layer;
835 // Walk up the layer tree and hit-test any renderSurfaces and any layer clipRects that are active.
836 while (currentLayer) {
837 if (currentLayer->renderSurface() && !pointHitsRect(viewportPoint, currentLayer->renderSurface()->screenSpaceTransform(), currentLayer->renderSurface()->contentRect()))
838 return true;
840 // Note that drawableContentRects are actually in targetSurface space, so the transform we
841 // have to provide is the target surface's screenSpaceTransform.
842 CCLayerImpl* renderTarget = currentLayer->renderTarget();
843 if (layerClipsSubtree(currentLayer) && !pointHitsRect(viewportPoint, renderTarget->renderSurface()->screenSpaceTransform(), currentLayer->drawableContentRect()))
844 return true;
846 currentLayer = currentLayer->parent();
849 // If we have finished walking all ancestors without having already exited, then the point is not clipped by any ancestors.
850 return false;
853 CCLayerImpl* CCLayerTreeHostCommon::findLayerThatIsHitByPoint(const IntPoint& viewportPoint, Vector<CCLayerImpl*>& renderSurfaceLayerList)
855 CCLayerImpl* foundLayer = 0;
857 typedef CCLayerIterator<CCLayerImpl, Vector<CCLayerImpl*>, CCRenderSurface, CCLayerIteratorActions::FrontToBack> CCLayerIteratorType;
858 CCLayerIteratorType end = CCLayerIteratorType::end(&renderSurfaceLayerList);
860 for (CCLayerIteratorType it = CCLayerIteratorType::begin(&renderSurfaceLayerList); it != end; ++it) {
861 // We don't want to consider renderSurfaces for hit testing.
862 if (!it.representsItself())
863 continue;
865 CCLayerImpl* currentLayer = (*it);
867 FloatRect contentRect(FloatPoint::zero(), currentLayer->contentBounds());
868 if (!pointHitsRect(viewportPoint, currentLayer->screenSpaceTransform(), contentRect))
869 continue;
871 // At this point, we think the point does hit the layer, but we need to walk up
872 // the parents to ensure that the layer was not clipped in such a way that the
873 // hit point actually should not hit the layer.
874 if (pointIsClippedBySurfaceOrClipRect(viewportPoint, currentLayer))
875 continue;
877 foundLayer = currentLayer;
878 break;
881 // This can potentially return 0, which means the viewportPoint did not successfully hit test any layers, not even the root layer.
882 return foundLayer;
885 } // namespace cc