Add intro to any Chrome app API with no overview docs.
[chromium-blink-merge.git] / cc / layer_tree_host_common.cc
blob8aff2029e27fd339917cf9b5afdec7beac69b28e
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.
5 #include "cc/layer_tree_host_common.h"
7 #include <algorithm>
9 #include "cc/layer.h"
10 #include "cc/layer_impl.h"
11 #include "cc/layer_iterator.h"
12 #include "cc/layer_sorter.h"
13 #include "cc/math_util.h"
14 #include "cc/render_surface.h"
15 #include "cc/render_surface_impl.h"
16 #include "ui/gfx/point_conversions.h"
17 #include "ui/gfx/rect_conversions.h"
18 #include "ui/gfx/transform.h"
20 namespace cc {
22 ScrollAndScaleSet::ScrollAndScaleSet()
26 ScrollAndScaleSet::~ScrollAndScaleSet()
30 gfx::Rect LayerTreeHostCommon::calculateVisibleRect(const gfx::Rect& targetSurfaceRect, const gfx::Rect& layerBoundRect, const gfx::Transform& transform)
32 // Is this layer fully contained within the target surface?
33 gfx::Rect layerInSurfaceSpace = MathUtil::mapClippedRect(transform, layerBoundRect);
34 if (targetSurfaceRect.Contains(layerInSurfaceSpace))
35 return layerBoundRect;
37 // If the layer doesn't fill up the entire surface, then find the part of
38 // the surface rect where the layer could be visible. This avoids trying to
39 // project surface rect points that are behind the projection point.
40 gfx::Rect minimalSurfaceRect = targetSurfaceRect;
41 minimalSurfaceRect.Intersect(layerInSurfaceSpace);
43 // Project the corners of the target surface rect into the layer space.
44 // This bounding rectangle may be larger than it needs to be (being
45 // axis-aligned), but is a reasonable filter on the space to consider.
46 // Non-invertible transforms will create an empty rect here.
47 const gfx::Transform surfaceToLayer = MathUtil::inverse(transform);
48 gfx::Rect layerRect = gfx::ToEnclosingRect(MathUtil::projectClippedRect(surfaceToLayer, gfx::RectF(minimalSurfaceRect)));
49 layerRect.Intersect(layerBoundRect);
50 return layerRect;
53 template <typename LayerType>
54 static inline bool isRootLayer(LayerType* layer)
56 return !layer->parent();
59 template<typename LayerType>
60 static inline bool layerIsInExisting3DRenderingContext(LayerType* layer)
62 // According to current W3C spec on CSS transforms, a layer is part of an established
63 // 3d rendering context if its parent has transform-style of preserves-3d.
64 return layer->parent() && layer->parent()->preserves3D();
67 template<typename LayerType>
68 static bool isRootLayerOfNewRenderingContext(LayerType* layer)
70 // According to current W3C spec on CSS transforms (Section 6.1), a layer is the
71 // beginning of 3d rendering context if its parent does not have transform-style:
72 // preserve-3d, but this layer itself does.
73 if (layer->parent())
74 return !layer->parent()->preserves3D() && layer->preserves3D();
76 return layer->preserves3D();
79 template<typename LayerType>
80 static bool isLayerBackFaceVisible(LayerType* layer)
82 // The current W3C spec on CSS transforms says that backface visibility should be
83 // determined differently depending on whether the layer is in a "3d rendering
84 // context" or not. For Chromium code, we can determine whether we are in a 3d
85 // rendering context by checking if the parent preserves 3d.
87 if (layerIsInExisting3DRenderingContext(layer))
88 return layer->drawTransform().IsBackFaceVisible();
90 // In this case, either the layer establishes a new 3d rendering context, or is not in
91 // a 3d rendering context at all.
92 return layer->transform().IsBackFaceVisible();
95 template<typename LayerType>
96 static bool isSurfaceBackFaceVisible(LayerType* layer, const gfx::Transform& drawTransform)
98 if (layerIsInExisting3DRenderingContext(layer))
99 return drawTransform.IsBackFaceVisible();
101 if (isRootLayerOfNewRenderingContext(layer))
102 return layer->transform().IsBackFaceVisible();
104 // If the renderSurface is not part of a new or existing rendering context, then the
105 // layers that contribute to this surface will decide back-face visibility for themselves.
106 return false;
109 template<typename LayerType>
110 static inline bool layerClipsSubtree(LayerType* layer)
112 return layer->masksToBounds() || layer->maskLayer();
115 template<typename LayerType>
116 static gfx::Rect calculateVisibleContentRect(LayerType* layer)
118 DCHECK(layer->renderTarget());
120 // Nothing is visible if the layer bounds are empty.
121 if (!layer->drawsContent() || layer->contentBounds().IsEmpty() || layer->drawableContentRect().IsEmpty())
122 return gfx::Rect();
124 gfx::Rect targetSurfaceClipRect;
126 // First, compute visible bounds in target surface space.
127 if (layer->renderTarget()->renderSurface()->clipRect().IsEmpty())
128 targetSurfaceClipRect = layer->drawableContentRect();
129 else {
130 // In this case the target surface does clip layers that contribute to it. So, we
131 // have convert the current surface's clipRect from its ancestor surface space to
132 // the current surface space.
133 targetSurfaceClipRect = gfx::ToEnclosingRect(MathUtil::projectClippedRect(MathUtil::inverse(layer->renderTarget()->renderSurface()->drawTransform()), layer->renderTarget()->renderSurface()->clipRect()));
134 targetSurfaceClipRect.Intersect(layer->drawableContentRect());
137 if (targetSurfaceClipRect.IsEmpty())
138 return gfx::Rect();
140 return LayerTreeHostCommon::calculateVisibleRect(targetSurfaceClipRect, gfx::Rect(gfx::Point(), layer->contentBounds()), layer->drawTransform());
143 static inline bool transformToParentIsKnown(LayerImpl*)
145 return true;
148 static inline bool transformToParentIsKnown(Layer* layer)
150 return !layer->transformIsAnimating();
153 static inline bool transformToScreenIsKnown(LayerImpl*)
155 return true;
158 static inline bool transformToScreenIsKnown(Layer* layer)
160 return !layer->screenSpaceTransformIsAnimating();
163 template<typename LayerType>
164 static bool layerShouldBeSkipped(LayerType* layer)
166 // Layers can be skipped if any of these conditions are met.
167 // - does not draw content.
168 // - is transparent
169 // - has empty bounds
170 // - the layer is not double-sided, but its back face is visible.
172 // Some additional conditions need to be computed at a later point after the recursion is finished.
173 // - the intersection of render surface content and layer clipRect is empty
174 // - the visibleContentRect is empty
176 // Note, if the layer should not have been drawn due to being fully transparent,
177 // we would have skipped the entire subtree and never made it into this function,
178 // so it is safe to omit this check here.
180 if (!layer->drawsContent() || layer->bounds().IsEmpty())
181 return true;
183 LayerType* backfaceTestLayer = layer;
184 if (layer->useParentBackfaceVisibility()) {
185 DCHECK(layer->parent());
186 DCHECK(!layer->parent()->useParentBackfaceVisibility());
187 backfaceTestLayer = layer->parent();
190 // 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.
191 if (!backfaceTestLayer->doubleSided() && transformToScreenIsKnown(backfaceTestLayer) && isLayerBackFaceVisible(backfaceTestLayer))
192 return true;
194 return false;
197 static inline bool subtreeShouldBeSkipped(LayerImpl* layer)
199 // The opacity of a layer always applies to its children (either implicitly
200 // via a render surface or explicitly if the parent preserves 3D), so the
201 // entire subtree can be skipped if this layer is fully transparent.
202 return !layer->opacity();
205 static inline bool subtreeShouldBeSkipped(Layer* layer)
207 // If the opacity is being animated then the opacity on the main thread is unreliable
208 // (since the impl thread may be using a different opacity), so it should not be trusted.
209 // In particular, it should not cause the subtree to be skipped.
210 return !layer->opacity() && !layer->opacityIsAnimating();
213 // Called on each layer that could be drawn after all information from
214 // calcDrawTransforms has been updated on that layer. May have some false
215 // positives (e.g. layers get this called on them but don't actually get drawn).
216 static inline void markLayerAsUpdated(LayerImpl* layer)
218 layer->didUpdateTransforms();
221 static inline void markLayerAsUpdated(Layer* layer)
225 template<typename LayerType>
226 static bool subtreeShouldRenderToSeparateSurface(LayerType* layer, bool axisAlignedWithRespectToParent)
229 // A layer and its descendants should render onto a new RenderSurfaceImpl if any of these rules hold:
232 // The root layer should always have a renderSurface.
233 if (isRootLayer(layer))
234 return true;
236 // If we force it.
237 if (layer->forceRenderSurface())
238 return true;
240 // If the layer uses a mask.
241 if (layer->maskLayer())
242 return true;
244 // If the layer has a reflection.
245 if (layer->replicaLayer())
246 return true;
248 // If the layer uses a CSS filter.
249 if (!layer->filters().isEmpty() || !layer->backgroundFilters().isEmpty() || layer->filter())
250 return true;
252 // Cache this value, because otherwise it walks the entire subtree several times.
253 int descendantsDrawContent = layer->descendantsDrawContent();
255 // If the layer flattens its subtree (i.e. the layer doesn't preserve-3d), but it is
256 // treated as a 3D object by its parent (i.e. parent does preserve-3d).
257 if (layerIsInExisting3DRenderingContext(layer) && !layer->preserves3D() && descendantsDrawContent > 0)
258 return true;
260 // If the layer clips its descendants but it is not axis-aligned with respect to its parent.
261 if (layerClipsSubtree(layer) && !axisAlignedWithRespectToParent && descendantsDrawContent > 0)
262 return true;
264 // If the layer has opacity != 1 and does not have a preserves-3d transform style.
265 if (layer->opacity() != 1 && !layer->preserves3D() && descendantsDrawContent > 0
266 && (layer->drawsContent() || descendantsDrawContent > 1))
267 return true;
269 return false;
272 gfx::Transform computeScrollCompensationForThisLayer(LayerImpl* scrollingLayer, const gfx::Transform& parentMatrix)
274 // For every layer that has non-zero scrollDelta, we have to compute a transform that can undo the
275 // scrollDelta translation. In particular, we want this matrix to premultiply a fixed-position layer's
276 // parentMatrix, so we design this transform in three steps as follows. The steps described here apply
277 // from right-to-left, so Step 1 would be the right-most matrix:
279 // Step 1. transform from target surface space to the exact space where scrollDelta is actually applied.
280 // -- this is inverse of the matrix in step 3
281 // Step 2. undo the scrollDelta
282 // -- this is just a translation by scrollDelta.
283 // Step 3. transform back to target surface space.
284 // -- this transform is the "partialLayerOriginTransform" = (parentMatrix * scale(layer->pageScaleDelta()));
286 // These steps create a matrix that both start and end in targetSurfaceSpace. So this matrix can
287 // pre-multiply any fixed-position layer's drawTransform to undo the scrollDeltas -- as long as
288 // that fixed position layer is fixed onto the same renderTarget as this scrollingLayer.
291 gfx::Transform partialLayerOriginTransform = parentMatrix;
292 partialLayerOriginTransform.PreconcatTransform(scrollingLayer->implTransform());
294 gfx::Transform scrollCompensationForThisLayer = partialLayerOriginTransform; // Step 3
295 scrollCompensationForThisLayer.Translate(scrollingLayer->scrollDelta().x(), scrollingLayer->scrollDelta().y()); // Step 2
296 scrollCompensationForThisLayer.PreconcatTransform(MathUtil::inverse(partialLayerOriginTransform)); // Step 1
297 return scrollCompensationForThisLayer;
300 gfx::Transform computeScrollCompensationMatrixForChildren(Layer* currentLayer, const gfx::Transform& currentParentMatrix, const gfx::Transform& currentScrollCompensation)
302 // The main thread (i.e. Layer) does not need to worry about scroll compensation.
303 // So we can just return an identity matrix here.
304 return gfx::Transform();
307 gfx::Transform computeScrollCompensationMatrixForChildren(LayerImpl* layer, const gfx::Transform& parentMatrix, const gfx::Transform& currentScrollCompensationMatrix)
309 // "Total scroll compensation" is the transform needed to cancel out all scrollDelta translations that
310 // occurred since the nearest container layer, even if there are renderSurfaces in-between.
312 // There are some edge cases to be aware of, that are not explicit in the code:
313 // - A layer that is both a fixed-position and container should not be its own container, instead, that means
314 // it is fixed to an ancestor, and is a container for any fixed-position descendants.
315 // - A layer that is a fixed-position container and has a renderSurface should behave the same as a container
316 // without a renderSurface, the renderSurface is irrelevant in that case.
317 // - A layer that does not have an explicit container is simply fixed to the viewport.
318 // (i.e. the root renderSurface.)
319 // - If the fixed-position layer has its own renderSurface, then the renderSurface is
320 // the one who gets fixed.
322 // This function needs to be called AFTER layers create their own renderSurfaces.
325 // 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.
326 if (!layer->isContainerForFixedPositionLayers() && layer->scrollDelta().IsZero() && !layer->renderSurface())
327 return currentScrollCompensationMatrix;
329 // Start as identity matrix.
330 gfx::Transform nextScrollCompensationMatrix;
332 // If this layer is not a container, then it inherits the existing scroll compensations.
333 if (!layer->isContainerForFixedPositionLayers())
334 nextScrollCompensationMatrix = currentScrollCompensationMatrix;
336 // If the current layer has a non-zero scrollDelta, then we should compute its local scrollCompensation
337 // and accumulate it to the nextScrollCompensationMatrix.
338 if (!layer->scrollDelta().IsZero()) {
339 gfx::Transform scrollCompensationForThisLayer = computeScrollCompensationForThisLayer(layer, parentMatrix);
340 nextScrollCompensationMatrix.PreconcatTransform(scrollCompensationForThisLayer);
343 // If the layer created its own renderSurface, we have to adjust nextScrollCompensationMatrix.
344 // The adjustment allows us to continue using the scrollCompensation on the next surface.
345 // Step 1 (right-most in the math): transform from the new surface to the original ancestor surface
346 // Step 2: apply the scroll compensation
347 // Step 3: transform back to the new surface.
348 if (layer->renderSurface() && !nextScrollCompensationMatrix.IsIdentity())
349 nextScrollCompensationMatrix = MathUtil::inverse(layer->renderSurface()->drawTransform()) * nextScrollCompensationMatrix * layer->renderSurface()->drawTransform();
351 return nextScrollCompensationMatrix;
354 // There is no contentsScale on impl thread.
355 static inline void updateLayerContentsScale(LayerImpl*, const gfx::Transform&, float, float, bool) { }
357 static inline void updateLayerContentsScale(Layer* layer, const gfx::Transform& combinedTransform, float deviceScaleFactor, float pageScaleFactor, bool animatingTransformToScreen)
359 float rasterScale = layer->rasterScale();
360 if (!rasterScale) {
361 rasterScale = 1;
363 if (!animatingTransformToScreen && layer->automaticallyComputeRasterScale()) {
364 gfx::Vector2dF transformScale = MathUtil::computeTransform2dScaleComponents(combinedTransform);
365 float combinedScale = std::max(transformScale.x(), transformScale.y());
366 rasterScale = combinedScale / deviceScaleFactor;
367 if (!layer->boundsContainPageScale())
368 rasterScale /= pageScaleFactor;
369 // Prevent scale factors below 1 from being used or saved.
370 if (rasterScale < 1)
371 rasterScale = 1;
372 else
373 layer->setRasterScale(rasterScale);
377 float contentsScale = rasterScale * deviceScaleFactor;
378 if (!layer->boundsContainPageScale())
379 contentsScale *= pageScaleFactor;
380 layer->setContentsScale(contentsScale);
382 Layer* maskLayer = layer->maskLayer();
383 if (maskLayer)
384 maskLayer->setContentsScale(contentsScale);
386 Layer* replicaMaskLayer = layer->replicaLayer() ? layer->replicaLayer()->maskLayer() : 0;
387 if (replicaMaskLayer)
388 replicaMaskLayer->setContentsScale(contentsScale);
391 // Recursively walks the layer tree starting at the given node and computes all the
392 // necessary transformations, clipRects, render surfaces, etc.
393 template<typename LayerType, typename LayerList, typename RenderSurfaceType, typename LayerSorter>
394 static void calculateDrawTransformsInternal(LayerType* layer, const gfx::Transform& parentMatrix,
395 const gfx::Transform& fullHierarchyMatrix, const gfx::Transform& currentScrollCompensationMatrix,
396 const gfx::Rect& clipRectFromAncestor, bool ancestorClipsSubtree,
397 RenderSurfaceType* nearestAncestorThatMovesPixels, LayerList& renderSurfaceLayerList, LayerList& layerList,
398 LayerSorter* layerSorter, int maxTextureSize, float deviceScaleFactor, float pageScaleFactor, gfx::Rect& drawableContentRectOfSubtree)
400 // This function computes the new matrix transformations recursively for this
401 // layer and all its descendants. It also computes the appropriate render surfaces.
402 // Some important points to remember:
404 // 0. Here, transforms are notated in Matrix x Vector order, and in words we describe what
405 // the transform does from left to right.
407 // 1. In our terminology, the "layer origin" refers to the top-left corner of a layer, and the
408 // positive Y-axis points downwards. This interpretation is valid because the orthographic
409 // projection applied at draw time flips the Y axis appropriately.
411 // 2. The anchor point, when given as a PointF object, is specified in "unit layer space",
412 // where the bounds of the layer map to [0, 1]. However, as a Transform object,
413 // the transform to the anchor point is specified in "layer space", where the bounds
414 // of the layer map to [bounds.width(), bounds.height()].
416 // 3. Definition of various transforms used:
417 // M[parent] is the parent matrix, with respect to the nearest render surface, passed down recursively.
418 // M[root] is the full hierarchy, with respect to the root, passed down recursively.
419 // Tr[origin] is the translation matrix from the parent's origin to this layer's origin.
420 // Tr[origin2anchor] is the translation from the layer's origin to its anchor point
421 // Tr[origin2center] is the translation from the layer's origin to its center
422 // M[layer] is the layer's matrix (applied at the anchor point)
423 // M[sublayer] is the layer's sublayer transform (applied at the layer's center)
424 // S[layer2content] is the ratio of a layer's contentBounds() to its bounds().
426 // Some composite transforms can help in understanding the sequence of transforms:
427 // compositeLayerTransform = Tr[origin2anchor] * M[layer] * Tr[origin2anchor].inverse()
428 // compositeSublayerTransform = Tr[origin2center] * M[sublayer] * Tr[origin2center].inverse()
430 // In words, the layer transform is applied about the anchor point, and the sublayer transform is
431 // applied about the center of the layer.
433 // 4. When a layer (or render surface) is drawn, it is drawn into a "target render surface". Therefore the draw
434 // transform does not necessarily transform from screen space to local layer space. Instead, the draw transform
435 // is the transform between the "target render surface space" and local layer space. Note that render surfaces,
436 // except for the root, also draw themselves into a different target render surface, and so their draw
437 // transform and origin transforms are also described with respect to the target.
439 // Using these definitions, then:
441 // The draw transform for the layer is:
442 // M[draw] = M[parent] * Tr[origin] * compositeLayerTransform * S[layer2content]
443 // = M[parent] * Tr[layer->position() + anchor] * M[layer] * Tr[anchor2origin] * S[layer2content]
445 // Interpreting the math left-to-right, this transforms from the layer's render surface to the origin of the layer in content space.
447 // The screen space transform is:
448 // M[screenspace] = M[root] * Tr[origin] * compositeLayerTransform * S[layer2content]
449 // = M[root] * Tr[layer->position() + anchor] * M[layer] * Tr[anchor2origin] * S[layer2content]
451 // Interpreting the math left-to-right, this transforms from the root render surface's content space to the origin of the layer in content space.
453 // The transform hierarchy that is passed on to children (i.e. the child's parentMatrix) is:
454 // M[parent]_for_child = M[parent] * Tr[origin] * compositeLayerTransform * compositeSublayerTransform
455 // = M[parent] * Tr[layer->position() + anchor] * M[layer] * Tr[anchor2origin] * compositeSublayerTransform
457 // and a similar matrix for the full hierarchy with respect to the root.
459 // Finally, note that the final matrix used by the shader for the layer is P * M[draw] * S . This final product
460 // is computed in drawTexturedQuad(), where:
461 // P is the projection matrix
462 // S is the scale adjustment (to scale up a canonical quad to the layer's size)
464 // When a render surface has a replica layer, that layer's transform is used to draw a second copy of the surface.
465 // gfx::Transforms named here are relative to the surface, unless they specify they are relative to the replica layer.
467 // We will denote a scale by device scale S[deviceScale]
469 // The render surface draw transform to its target surface origin is:
470 // M[surfaceDraw] = M[owningLayer->Draw]
472 // The render surface origin transform to its the root (screen space) origin is:
473 // M[surface2root] = M[owningLayer->screenspace] * S[deviceScale].inverse()
475 // The replica draw transform to its target surface origin is:
476 // M[replicaDraw] = S[deviceScale] * M[surfaceDraw] * Tr[replica->position() + replica->anchor()] * Tr[replica] * Tr[origin2anchor].inverse() * S[contentsScale].inverse()
478 // The replica draw transform to the root (screen space) origin is:
479 // M[replica2root] = M[surface2root] * Tr[replica->position()] * Tr[replica] * Tr[origin2anchor].inverse()
482 // If we early-exit anywhere in this function, the drawableContentRect of this subtree should be considered empty.
483 drawableContentRectOfSubtree = gfx::Rect();
485 // The root layer cannot skip calcDrawTransforms.
486 if (!isRootLayer(layer) && subtreeShouldBeSkipped(layer))
487 return;
489 gfx::Rect clipRectForSubtree;
490 bool subtreeShouldBeClipped = false;
492 float drawOpacity = layer->opacity();
493 bool drawOpacityIsAnimating = layer->opacityIsAnimating();
494 if (layer->parent()) {
495 drawOpacity *= layer->parent()->drawOpacity();
496 drawOpacityIsAnimating |= layer->parent()->drawOpacityIsAnimating();
499 bool animatingTransformToTarget = layer->transformIsAnimating();
500 bool animatingTransformToScreen = animatingTransformToTarget;
501 if (layer->parent()) {
502 animatingTransformToTarget |= layer->parent()->drawTransformIsAnimating();
503 animatingTransformToScreen |= layer->parent()->screenSpaceTransformIsAnimating();
506 gfx::Size bounds = layer->bounds();
507 gfx::PointF anchorPoint = layer->anchorPoint();
508 gfx::PointF position = layer->position() - layer->scrollDelta();
510 gfx::Transform layerLocalTransform;
511 // LT = Tr[origin] * Tr[origin2anchor]
512 layerLocalTransform.Translate3d(position.x() + anchorPoint.x() * bounds.width(), position.y() + anchorPoint.y() * bounds.height(), layer->anchorPointZ());
513 // LT = Tr[origin] * Tr[origin2anchor] * M[layer]
514 layerLocalTransform.PreconcatTransform(layer->transform());
515 // LT = Tr[origin] * Tr[origin2anchor] * M[layer] * Tr[anchor2origin]
516 layerLocalTransform.Translate3d(-anchorPoint.x() * bounds.width(), -anchorPoint.y() * bounds.height(), -layer->anchorPointZ());
518 gfx::Transform combinedTransform = parentMatrix;
519 combinedTransform.PreconcatTransform(layerLocalTransform);
521 // The layer's contentsSize is determined from the combinedTransform, which then informs the
522 // layer's drawTransform.
523 updateLayerContentsScale(layer, combinedTransform, deviceScaleFactor, pageScaleFactor, animatingTransformToScreen);
525 // If there is a tranformation from the impl thread then it should be at the
526 // start of the combinedTransform, but we don't want it to affect the contentsScale.
527 combinedTransform = layer->implTransform() * combinedTransform;
529 if (layer->fixedToContainerLayer()) {
530 // Special case: this layer is a composited fixed-position layer; we need to
531 // explicitly compensate for all ancestors' nonzero scrollDeltas to keep this layer
532 // fixed correctly.
533 combinedTransform = currentScrollCompensationMatrix * combinedTransform;
536 // The drawTransform that gets computed below is effectively the layer's drawTransform, unless
537 // the layer itself creates a renderSurface. In that case, the renderSurface re-parents the transforms.
538 gfx::Transform drawTransform = combinedTransform;
539 // M[draw] = M[parent] * LT * S[layer2content]
540 drawTransform.Scale(1.0 / layer->contentsScaleX(), 1.0 / layer->contentsScaleY());
542 // layerScreenSpaceTransform represents the transform between root layer's "screen space" and local content space.
543 gfx::Transform layerScreenSpaceTransform = fullHierarchyMatrix;
544 if (!layer->preserves3D())
545 MathUtil::flattenTransformTo2d(layerScreenSpaceTransform);
546 layerScreenSpaceTransform.PreconcatTransform(drawTransform);
547 layer->setScreenSpaceTransform(layerScreenSpaceTransform);
549 gfx::RectF contentRect(gfx::PointF(), layer->contentBounds());
551 // fullHierarchyMatrix is the matrix that transforms objects between screen space (except projection matrix) and the most recent RenderSurfaceImpl's space.
552 // nextHierarchyMatrix will only change if this layer uses a new RenderSurfaceImpl, otherwise remains the same.
553 gfx::Transform nextHierarchyMatrix = fullHierarchyMatrix;
554 gfx::Transform sublayerMatrix;
556 gfx::Vector2dF renderSurfaceSublayerScale = MathUtil::computeTransform2dScaleComponents(combinedTransform);
558 if (subtreeShouldRenderToSeparateSurface(layer, combinedTransform.IsScaleOrTranslation())) {
559 // Check back-face visibility before continuing with this surface and its subtree
560 if (!layer->doubleSided() && transformToParentIsKnown(layer) && isSurfaceBackFaceVisible(layer, combinedTransform))
561 return;
563 if (!layer->renderSurface())
564 layer->createRenderSurface();
566 RenderSurfaceType* renderSurface = layer->renderSurface();
567 renderSurface->clearLayerLists();
569 // The owning layer's draw transform has a scale from content to layer space which we need to undo and
570 // replace with a scale from the surface's subtree into layer space.
571 drawTransform.Scale(layer->contentsScaleX(), layer->contentsScaleY());
572 drawTransform.Scale(1 / renderSurfaceSublayerScale.x(), 1 / renderSurfaceSublayerScale.y());
573 renderSurface->setDrawTransform(drawTransform);
575 // The origin of the new surface is the upper left corner of the layer.
576 gfx::Transform layerDrawTransform;
577 layerDrawTransform.Scale(renderSurfaceSublayerScale.x(), renderSurfaceSublayerScale.y());
578 layerDrawTransform.Scale(1.0 / layer->contentsScaleX(), 1.0 / layer->contentsScaleY());
579 layer->setDrawTransform(layerDrawTransform);
581 // Inside the surface's subtree, we scale everything to the owning layer's scale.
582 // The sublayer matrix transforms centered layer rects into target
583 // surface content space.
584 sublayerMatrix.MakeIdentity();
585 sublayerMatrix.Scale(renderSurfaceSublayerScale.x(), renderSurfaceSublayerScale.y());
587 // The opacity value is moved from the layer to its surface, so that the entire subtree properly inherits opacity.
588 renderSurface->setDrawOpacity(drawOpacity);
589 renderSurface->setDrawOpacityIsAnimating(drawOpacityIsAnimating);
590 layer->setDrawOpacity(1);
591 layer->setDrawOpacityIsAnimating(false);
593 renderSurface->setTargetSurfaceTransformsAreAnimating(animatingTransformToTarget);
594 renderSurface->setScreenSpaceTransformsAreAnimating(animatingTransformToScreen);
595 animatingTransformToTarget = false;
596 layer->setDrawTransformIsAnimating(animatingTransformToTarget);
597 layer->setScreenSpaceTransformIsAnimating(animatingTransformToScreen);
599 // Update the aggregate hierarchy matrix to include the transform of the
600 // newly created RenderSurfaceImpl.
601 nextHierarchyMatrix.PreconcatTransform(renderSurface->drawTransform());
603 // The new renderSurface here will correctly clip the entire subtree. So, we do
604 // not need to continue propagating the clipping state further down the tree. This
605 // way, we can avoid transforming clipRects from ancestor target surface space to
606 // current target surface space that could cause more w < 0 headaches.
607 subtreeShouldBeClipped = false;
609 if (layer->maskLayer()) {
610 layer->maskLayer()->setRenderTarget(layer);
611 layer->maskLayer()->setVisibleContentRect(gfx::Rect(gfx::Point(), layer->contentBounds()));
614 if (layer->replicaLayer() && layer->replicaLayer()->maskLayer()) {
615 layer->replicaLayer()->maskLayer()->setRenderTarget(layer);
616 layer->replicaLayer()->maskLayer()->setVisibleContentRect(gfx::Rect(gfx::Point(), layer->contentBounds()));
619 // FIXME: make this smarter for the SkImageFilter case (check for
620 // pixel-moving filters)
621 if (layer->filters().hasFilterThatMovesPixels() || layer->filter())
622 nearestAncestorThatMovesPixels = renderSurface;
624 // The render surface clipRect is expressed in the space where this surface draws, i.e. the same space as clipRectFromAncestor.
625 renderSurface->setIsClipped(ancestorClipsSubtree);
626 if (ancestorClipsSubtree)
627 renderSurface->setClipRect(clipRectFromAncestor);
628 else
629 renderSurface->setClipRect(gfx::Rect());
631 renderSurface->setNearestAncestorThatMovesPixels(nearestAncestorThatMovesPixels);
633 renderSurfaceLayerList.push_back(layer);
634 } else {
635 DCHECK(layer->parent());
637 layer->setDrawTransform(drawTransform);
638 layer->setDrawTransformIsAnimating(animatingTransformToTarget);
639 layer->setScreenSpaceTransformIsAnimating(animatingTransformToScreen);
640 sublayerMatrix = combinedTransform;
642 layer->setDrawOpacity(drawOpacity);
643 layer->setDrawOpacityIsAnimating(drawOpacityIsAnimating);
645 layer->clearRenderSurface();
647 // Layers without renderSurfaces directly inherit the ancestor's clip status.
648 subtreeShouldBeClipped = ancestorClipsSubtree;
649 if (ancestorClipsSubtree)
650 clipRectForSubtree = clipRectFromAncestor;
652 // Layers that are not their own renderTarget will render into the target of their nearest ancestor.
653 layer->setRenderTarget(layer->parent()->renderTarget());
656 gfx::Rect rectInTargetSpace = ToEnclosingRect(MathUtil::mapClippedRect(layer->drawTransform(), contentRect));
658 if (layerClipsSubtree(layer)) {
659 subtreeShouldBeClipped = true;
660 if (ancestorClipsSubtree && !layer->renderSurface()) {
661 clipRectForSubtree = clipRectFromAncestor;
662 clipRectForSubtree.Intersect(rectInTargetSpace);
663 } else
664 clipRectForSubtree = rectInTargetSpace;
667 // Flatten to 2D if the layer doesn't preserve 3D.
668 if (!layer->preserves3D())
669 MathUtil::flattenTransformTo2d(sublayerMatrix);
671 // Apply the sublayer transform at the center of the layer.
672 sublayerMatrix.Translate(0.5 * bounds.width(), 0.5 * bounds.height());
673 sublayerMatrix.PreconcatTransform(layer->sublayerTransform());
674 sublayerMatrix.Translate(-0.5 * bounds.width(), -0.5 * bounds.height());
676 LayerList& descendants = (layer->renderSurface() ? layer->renderSurface()->layerList() : layerList);
678 // Any layers that are appended after this point are in the layer's subtree and should be included in the sorting process.
679 unsigned sortingStartIndex = descendants.size();
681 if (!layerShouldBeSkipped(layer))
682 descendants.push_back(layer);
684 gfx::Transform nextScrollCompensationMatrix = computeScrollCompensationMatrixForChildren(layer, parentMatrix, currentScrollCompensationMatrix);;
686 gfx::Rect accumulatedDrawableContentRectOfChildren;
687 for (size_t i = 0; i < layer->children().size(); ++i) {
688 LayerType* child = LayerTreeHostCommon::getChildAsRawPtr(layer->children(), i);
689 gfx::Rect drawableContentRectOfChildSubtree;
690 calculateDrawTransformsInternal<LayerType, LayerList, RenderSurfaceType, LayerSorter>(child, sublayerMatrix, nextHierarchyMatrix, nextScrollCompensationMatrix,
691 clipRectForSubtree, subtreeShouldBeClipped, nearestAncestorThatMovesPixels,
692 renderSurfaceLayerList, descendants, layerSorter, maxTextureSize, deviceScaleFactor, pageScaleFactor, drawableContentRectOfChildSubtree);
693 if (!drawableContentRectOfChildSubtree.IsEmpty()) {
694 accumulatedDrawableContentRectOfChildren.Union(drawableContentRectOfChildSubtree);
695 if (child->renderSurface())
696 descendants.push_back(child);
700 // Compute the total drawableContentRect for this subtree (the rect is in targetSurface space)
701 gfx::Rect localDrawableContentRectOfSubtree = accumulatedDrawableContentRectOfChildren;
702 if (layer->drawsContent())
703 localDrawableContentRectOfSubtree.Union(rectInTargetSpace);
704 if (subtreeShouldBeClipped)
705 localDrawableContentRectOfSubtree.Intersect(clipRectForSubtree);
707 // Compute the layer's drawable content rect (the rect is in targetSurface space)
708 gfx::Rect drawableContentRectOfLayer = rectInTargetSpace;
709 if (subtreeShouldBeClipped)
710 drawableContentRectOfLayer.Intersect(clipRectForSubtree);
711 layer->setDrawableContentRect(drawableContentRectOfLayer);
713 // Tell the layer the rect that is clipped by. In theory we could use a
714 // tighter clipRect here (drawableContentRect), but that actually does not
715 // reduce how much would be drawn, and instead it would create unnecessary
716 // changes to scissor state affecting GPU performance.
717 layer->setIsClipped(subtreeShouldBeClipped);
718 if (subtreeShouldBeClipped)
719 layer->setClipRect(clipRectForSubtree);
720 else {
721 // Initialize the clipRect to a safe value that will not clip the
722 // layer, just in case clipping is still accidentally used.
723 layer->setClipRect(rectInTargetSpace);
726 // Compute the layer's visible content rect (the rect is in content space)
727 gfx::Rect visibleContentRectOfLayer = calculateVisibleContentRect(layer);
728 layer->setVisibleContentRect(visibleContentRectOfLayer);
730 // Compute the remaining properties for the render surface, if the layer has one.
731 if (isRootLayer(layer)) {
732 // The root layer's surface's contentRect is always the entire viewport.
733 DCHECK(layer->renderSurface());
734 layer->renderSurface()->setContentRect(clipRectFromAncestor);
735 } else if (layer->renderSurface() && !isRootLayer(layer)) {
736 RenderSurfaceType* renderSurface = layer->renderSurface();
737 gfx::Rect clippedContentRect = localDrawableContentRectOfSubtree;
739 // Don't clip if the layer is reflected as the reflection shouldn't be
740 // clipped. If the layer is animating, then the surface's transform to
741 // its target is not known on the main thread, and we should not use it
742 // to clip.
743 if (!layer->replicaLayer() && transformToParentIsKnown(layer)) {
744 // Note, it is correct to use ancestorClipsSubtree here, because we are looking at this layer's renderSurface, not the layer itself.
745 if (ancestorClipsSubtree && !clippedContentRect.IsEmpty()) {
746 gfx::Rect surfaceClipRect = LayerTreeHostCommon::calculateVisibleRect(renderSurface->clipRect(), clippedContentRect, renderSurface->drawTransform());
747 clippedContentRect.Intersect(surfaceClipRect);
751 // The RenderSurfaceImpl backing texture cannot exceed the maximum supported
752 // texture size.
753 clippedContentRect.set_width(std::min(clippedContentRect.width(), maxTextureSize));
754 clippedContentRect.set_height(std::min(clippedContentRect.height(), maxTextureSize));
756 if (clippedContentRect.IsEmpty())
757 renderSurface->clearLayerLists();
759 renderSurface->setContentRect(clippedContentRect);
761 // The owning layer's screenSpaceTransform has a scale from content to layer space which we need to undo and
762 // replace with a scale from the surface's subtree into layer space.
763 gfx::Transform screenSpaceTransform = layer->screenSpaceTransform();
764 screenSpaceTransform.Scale(layer->contentsScaleX(), layer->contentsScaleY());
765 screenSpaceTransform.Scale(1 / renderSurfaceSublayerScale.x(), 1 / renderSurfaceSublayerScale.y());
766 renderSurface->setScreenSpaceTransform(screenSpaceTransform);
768 if (layer->replicaLayer()) {
769 gfx::Transform surfaceOriginToReplicaOriginTransform;
770 surfaceOriginToReplicaOriginTransform.Scale(renderSurfaceSublayerScale.x(), renderSurfaceSublayerScale.y());
771 surfaceOriginToReplicaOriginTransform.Translate(layer->replicaLayer()->position().x() + layer->replicaLayer()->anchorPoint().x() * bounds.width(),
772 layer->replicaLayer()->position().y() + layer->replicaLayer()->anchorPoint().y() * bounds.height());
773 surfaceOriginToReplicaOriginTransform.PreconcatTransform(layer->replicaLayer()->transform());
774 surfaceOriginToReplicaOriginTransform.Translate(-layer->replicaLayer()->anchorPoint().x() * bounds.width(), -layer->replicaLayer()->anchorPoint().y() * bounds.height());
775 surfaceOriginToReplicaOriginTransform.Scale(1 / renderSurfaceSublayerScale.x(), 1 / renderSurfaceSublayerScale.y());
777 // Compute the replica's "originTransform" that maps from the replica's origin space to the target surface origin space.
778 gfx::Transform replicaOriginTransform = layer->renderSurface()->drawTransform() * surfaceOriginToReplicaOriginTransform;
779 renderSurface->setReplicaDrawTransform(replicaOriginTransform);
781 // Compute the replica's "screenSpaceTransform" that maps from the replica's origin space to the screen's origin space.
782 gfx::Transform replicaScreenSpaceTransform = layer->renderSurface()->screenSpaceTransform() * surfaceOriginToReplicaOriginTransform;
783 renderSurface->setReplicaScreenSpaceTransform(replicaScreenSpaceTransform);
786 // If a render surface has no layer list, then it and none of its children needed to get drawn.
787 if (!layer->renderSurface()->layerList().size()) {
788 // FIXME: Originally we asserted that this layer was already at the end of the
789 // list, and only needed to remove that layer. For now, we remove the
790 // entire subtree of surfaces to fix a crash bug. The root cause is
791 // https://bugs.webkit.org/show_bug.cgi?id=74147 and we should be able
792 // to put the original assert after fixing that.
793 while (renderSurfaceLayerList.back() != layer) {
794 renderSurfaceLayerList.back()->clearRenderSurface();
795 renderSurfaceLayerList.pop_back();
797 DCHECK(renderSurfaceLayerList.back() == layer);
798 renderSurfaceLayerList.pop_back();
799 layer->clearRenderSurface();
800 return;
804 markLayerAsUpdated(layer);
806 // If neither this layer nor any of its children were added, early out.
807 if (sortingStartIndex == descendants.size())
808 return;
810 // If preserves-3d then sort all the descendants in 3D so that they can be
811 // drawn from back to front. If the preserves-3d property is also set on the parent then
812 // skip the sorting as the parent will sort all the descendants anyway.
813 if (descendants.size() && layer->preserves3D() && (!layer->parent() || !layer->parent()->preserves3D()))
814 sortLayers(descendants.begin() + sortingStartIndex, descendants.end(), layerSorter);
816 if (layer->renderSurface())
817 drawableContentRectOfSubtree = gfx::ToEnclosingRect(layer->renderSurface()->drawableContentRect());
818 else
819 drawableContentRectOfSubtree = localDrawableContentRectOfSubtree;
821 if (layer->hasContributingDelegatedRenderPasses())
822 layer->renderTarget()->renderSurface()->addContributingDelegatedRenderPassLayer(layer);
825 void LayerTreeHostCommon::calculateDrawTransforms(Layer* rootLayer, const gfx::Size& deviceViewportSize, float deviceScaleFactor, float pageScaleFactor, int maxTextureSize, std::vector<scoped_refptr<Layer> >& renderSurfaceLayerList)
827 gfx::Rect totalDrawableContentRect;
828 gfx::Transform identityMatrix;
829 gfx::Transform deviceScaleTransform;
830 deviceScaleTransform.Scale(deviceScaleFactor, deviceScaleFactor);
831 std::vector<scoped_refptr<Layer> > dummyLayerList;
833 // The root layer's renderSurface should receive the deviceViewport as the initial clipRect.
834 bool subtreeShouldBeClipped = true;
835 gfx::Rect deviceViewportRect(gfx::Point(), deviceViewportSize);
837 // This function should have received a root layer.
838 DCHECK(isRootLayer(rootLayer));
840 cc::calculateDrawTransformsInternal<Layer, std::vector<scoped_refptr<Layer> >, RenderSurface, void>(
841 rootLayer, deviceScaleTransform, identityMatrix, identityMatrix,
842 deviceViewportRect, subtreeShouldBeClipped, 0, renderSurfaceLayerList,
843 dummyLayerList, 0, maxTextureSize,
844 deviceScaleFactor, pageScaleFactor, totalDrawableContentRect);
846 // The dummy layer list should not have been used.
847 DCHECK(dummyLayerList.size() == 0);
848 // A root layer renderSurface should always exist after calculateDrawTransforms.
849 DCHECK(rootLayer->renderSurface());
852 void LayerTreeHostCommon::calculateDrawTransforms(LayerImpl* rootLayer, const gfx::Size& deviceViewportSize, float deviceScaleFactor, float pageScaleFactor, LayerSorter* layerSorter, int maxTextureSize, std::vector<LayerImpl*>& renderSurfaceLayerList)
854 gfx::Rect totalDrawableContentRect;
855 gfx::Transform identityMatrix;
856 gfx::Transform deviceScaleTransform;
857 deviceScaleTransform.Scale(deviceScaleFactor, deviceScaleFactor);
858 std::vector<LayerImpl*> dummyLayerList;
860 // The root layer's renderSurface should receive the deviceViewport as the initial clipRect.
861 bool subtreeShouldBeClipped = true;
862 gfx::Rect deviceViewportRect(gfx::Point(), deviceViewportSize);
864 // This function should have received a root layer.
865 DCHECK(isRootLayer(rootLayer));
867 cc::calculateDrawTransformsInternal<LayerImpl, std::vector<LayerImpl*>, RenderSurfaceImpl, LayerSorter>(
868 rootLayer, deviceScaleTransform, identityMatrix, identityMatrix,
869 deviceViewportRect, subtreeShouldBeClipped, 0, renderSurfaceLayerList,
870 dummyLayerList, layerSorter, maxTextureSize,
871 deviceScaleFactor, pageScaleFactor, totalDrawableContentRect);
873 // The dummy layer list should not have been used.
874 DCHECK(dummyLayerList.size() == 0);
875 // A root layer renderSurface should always exist after calculateDrawTransforms.
876 DCHECK(rootLayer->renderSurface());
879 static bool pointHitsRect(const gfx::PointF& screenSpacePoint, const gfx::Transform& localSpaceToScreenSpaceTransform, gfx::RectF localSpaceRect)
881 // If the transform is not invertible, then assume that this point doesn't hit this rect.
882 if (!localSpaceToScreenSpaceTransform.IsInvertible())
883 return false;
885 // Transform the hit test point from screen space to the local space of the given rect.
886 bool clipped = false;
887 gfx::PointF hitTestPointInLocalSpace = MathUtil::projectPoint(MathUtil::inverse(localSpaceToScreenSpaceTransform), screenSpacePoint, clipped);
889 // If projectPoint could not project to a valid value, then we assume that this point doesn't hit this rect.
890 if (clipped)
891 return false;
893 return localSpaceRect.Contains(hitTestPointInLocalSpace);
896 static bool pointHitsRegion(gfx::PointF screenSpacePoint, const gfx::Transform& screenSpaceTransform, const Region& layerSpaceRegion, float layerContentScaleX, float layerContentScaleY)
898 // If the transform is not invertible, then assume that this point doesn't hit this region.
899 if (!screenSpaceTransform.IsInvertible())
900 return false;
902 // Transform the hit test point from screen space to the local space of the given region.
903 bool clipped = false;
904 gfx::PointF hitTestPointInContentSpace = MathUtil::projectPoint(MathUtil::inverse(screenSpaceTransform), screenSpacePoint, clipped);
905 gfx::PointF hitTestPointInLayerSpace = gfx::ScalePoint(hitTestPointInContentSpace, 1 / layerContentScaleX, 1 / layerContentScaleY);
907 // If projectPoint could not project to a valid value, then we assume that this point doesn't hit this region.
908 if (clipped)
909 return false;
911 return layerSpaceRegion.Contains(gfx::ToRoundedPoint(hitTestPointInLayerSpace));
914 static bool pointIsClippedBySurfaceOrClipRect(const gfx::PointF& screenSpacePoint, LayerImpl* layer)
916 LayerImpl* currentLayer = layer;
918 // Walk up the layer tree and hit-test any renderSurfaces and any layer clipRects that are active.
919 while (currentLayer) {
920 if (currentLayer->renderSurface() && !pointHitsRect(screenSpacePoint, currentLayer->renderSurface()->screenSpaceTransform(), currentLayer->renderSurface()->contentRect()))
921 return true;
923 // Note that drawableContentRects are actually in targetSurface space, so the transform we
924 // have to provide is the target surface's screenSpaceTransform.
925 LayerImpl* renderTarget = currentLayer->renderTarget();
926 if (layerClipsSubtree(currentLayer) && !pointHitsRect(screenSpacePoint, renderTarget->renderSurface()->screenSpaceTransform(), currentLayer->drawableContentRect()))
927 return true;
929 currentLayer = currentLayer->parent();
932 // If we have finished walking all ancestors without having already exited, then the point is not clipped by any ancestors.
933 return false;
936 LayerImpl* LayerTreeHostCommon::findLayerThatIsHitByPoint(const gfx::PointF& screenSpacePoint, std::vector<LayerImpl*>& renderSurfaceLayerList)
938 LayerImpl* foundLayer = 0;
940 typedef LayerIterator<LayerImpl, std::vector<LayerImpl*>, RenderSurfaceImpl, LayerIteratorActions::FrontToBack> LayerIteratorType;
941 LayerIteratorType end = LayerIteratorType::end(&renderSurfaceLayerList);
943 for (LayerIteratorType it = LayerIteratorType::begin(&renderSurfaceLayerList); it != end; ++it) {
944 // We don't want to consider renderSurfaces for hit testing.
945 if (!it.representsItself())
946 continue;
948 LayerImpl* currentLayer = (*it);
950 gfx::RectF contentRect(gfx::PointF(), currentLayer->contentBounds());
951 if (!pointHitsRect(screenSpacePoint, currentLayer->screenSpaceTransform(), contentRect))
952 continue;
954 // At this point, we think the point does hit the layer, but we need to walk up
955 // the parents to ensure that the layer was not clipped in such a way that the
956 // hit point actually should not hit the layer.
957 if (pointIsClippedBySurfaceOrClipRect(screenSpacePoint, currentLayer))
958 continue;
960 foundLayer = currentLayer;
961 break;
964 // This can potentially return 0, which means the screenSpacePoint did not successfully hit test any layers, not even the root layer.
965 return foundLayer;
968 LayerImpl* LayerTreeHostCommon::findLayerThatIsHitByPointInTouchHandlerRegion(const gfx::PointF& screenSpacePoint, std::vector<LayerImpl*>& renderSurfaceLayerList)
970 LayerImpl* foundLayer = 0;
972 typedef LayerIterator<LayerImpl, std::vector<LayerImpl*>, RenderSurfaceImpl, LayerIteratorActions::FrontToBack> LayerIteratorType;
973 LayerIteratorType end = LayerIteratorType::end(&renderSurfaceLayerList);
975 for (LayerIteratorType it = LayerIteratorType::begin(&renderSurfaceLayerList); it != end; ++it) {
976 // We don't want to consider renderSurfaces for hit testing.
977 if (!it.representsItself())
978 continue;
980 LayerImpl* currentLayer = (*it);
982 if (currentLayer->touchEventHandlerRegion().IsEmpty())
983 continue;
985 if (!pointHitsRegion(screenSpacePoint, currentLayer->screenSpaceTransform(), currentLayer->touchEventHandlerRegion(), currentLayer->contentsScaleX(), currentLayer->contentsScaleY()))
986 continue;
988 // At this point, we think the point does hit the touch event handler region on the layer, but we need to walk up
989 // the parents to ensure that the layer was not clipped in such a way that the
990 // hit point actually should not hit the layer.
991 if (pointIsClippedBySurfaceOrClipRect(screenSpacePoint, currentLayer))
992 continue;
994 foundLayer = currentLayer;
995 break;
998 // This can potentially return 0, which means the screenSpacePoint did not successfully hit test any layers, not even the root layer.
999 return foundLayer;
1002 } // namespace cc