Remove non-async content protection entry points in NativeDisplayDelegate
[chromium-blink-merge.git] / cc / trees / layer_tree_host_common.cc
blob31f64d66627f2caab098e66bdafd1bec16e89bca
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/trees/layer_tree_host_common.h"
7 #include <algorithm>
9 #include "base/trace_event/trace_event.h"
10 #include "cc/base/math_util.h"
11 #include "cc/layers/heads_up_display_layer_impl.h"
12 #include "cc/layers/layer.h"
13 #include "cc/layers/layer_impl.h"
14 #include "cc/layers/layer_iterator.h"
15 #include "cc/layers/render_surface.h"
16 #include "cc/layers/render_surface_impl.h"
17 #include "cc/trees/draw_property_utils.h"
18 #include "cc/trees/layer_tree_host.h"
19 #include "cc/trees/layer_tree_impl.h"
20 #include "ui/gfx/geometry/rect_conversions.h"
21 #include "ui/gfx/geometry/vector2d_conversions.h"
22 #include "ui/gfx/transform.h"
23 #include "ui/gfx/transform_util.h"
25 namespace cc {
27 ScrollAndScaleSet::ScrollAndScaleSet()
28 : page_scale_delta(1.f), top_controls_delta(0.f) {
31 ScrollAndScaleSet::~ScrollAndScaleSet() {}
33 template <typename LayerType>
34 static gfx::Vector2dF GetEffectiveScrollDelta(LayerType* layer) {
35 // Layer's scroll offset can have an integer part and fractional part.
36 // Due to Blink's limitation, it only counter-scrolls the position-fixed
37 // layer using the integer part of Layer's scroll offset.
38 // CC scrolls the layer using the full scroll offset, so we have to
39 // add the ScrollCompensationAdjustment (fractional part of the scroll
40 // offset) to the effective scroll delta which is used to counter-scroll
41 // the position-fixed layer.
42 gfx::Vector2dF scroll_delta =
43 layer->ScrollDelta() + layer->ScrollCompensationAdjustment();
44 // The scroll parent's scroll delta is the amount we've scrolled on the
45 // compositor thread since the commit for this layer tree's source frame.
46 // we last reported to the main thread. I.e., it's the discrepancy between
47 // a scroll parent's scroll delta and offset, so we must add it here.
48 if (layer->scroll_parent())
49 scroll_delta += layer->scroll_parent()->ScrollDelta() +
50 layer->ScrollCompensationAdjustment();
51 return scroll_delta;
54 template <typename LayerType>
55 static gfx::ScrollOffset GetEffectiveCurrentScrollOffset(LayerType* layer) {
56 gfx::ScrollOffset offset = layer->CurrentScrollOffset();
57 // The scroll parent's total scroll offset (scroll offset + scroll delta)
58 // can't be used because its scroll offset has already been applied to the
59 // scroll children's positions by the main thread layer positioning code.
60 if (layer->scroll_parent())
61 offset += gfx::ScrollOffset(layer->scroll_parent()->ScrollDelta());
62 return offset;
65 inline gfx::Rect CalculateVisibleRectWithCachedLayerRect(
66 const gfx::Rect& target_surface_rect,
67 const gfx::Rect& layer_bound_rect,
68 const gfx::Rect& layer_rect_in_target_space,
69 const gfx::Transform& transform) {
70 if (layer_rect_in_target_space.IsEmpty())
71 return gfx::Rect();
73 // Is this layer fully contained within the target surface?
74 if (target_surface_rect.Contains(layer_rect_in_target_space))
75 return layer_bound_rect;
77 // If the layer doesn't fill up the entire surface, then find the part of
78 // the surface rect where the layer could be visible. This avoids trying to
79 // project surface rect points that are behind the projection point.
80 gfx::Rect minimal_surface_rect = target_surface_rect;
81 minimal_surface_rect.Intersect(layer_rect_in_target_space);
83 if (minimal_surface_rect.IsEmpty())
84 return gfx::Rect();
86 // Project the corners of the target surface rect into the layer space.
87 // This bounding rectangle may be larger than it needs to be (being
88 // axis-aligned), but is a reasonable filter on the space to consider.
89 // Non-invertible transforms will create an empty rect here.
91 gfx::Transform surface_to_layer(gfx::Transform::kSkipInitialization);
92 if (!transform.GetInverse(&surface_to_layer)) {
93 // Because we cannot use the surface bounds to determine what portion of
94 // the layer is visible, we must conservatively assume the full layer is
95 // visible.
96 return layer_bound_rect;
99 gfx::Rect layer_rect = MathUtil::ProjectEnclosingClippedRect(
100 surface_to_layer, minimal_surface_rect);
101 layer_rect.Intersect(layer_bound_rect);
102 return layer_rect;
105 gfx::Rect LayerTreeHostCommon::CalculateVisibleRect(
106 const gfx::Rect& target_surface_rect,
107 const gfx::Rect& layer_bound_rect,
108 const gfx::Transform& transform) {
109 gfx::Rect layer_in_surface_space =
110 MathUtil::MapEnclosingClippedRect(transform, layer_bound_rect);
111 return CalculateVisibleRectWithCachedLayerRect(
112 target_surface_rect, layer_bound_rect, layer_in_surface_space, transform);
115 template <typename LayerType>
116 static LayerType* NextTargetSurface(LayerType* layer) {
117 return layer->parent() ? layer->parent()->render_target() : 0;
120 // Given two layers, this function finds their respective render targets and,
121 // computes a change of basis translation. It does this by accumulating the
122 // translation components of the draw transforms of each target between the
123 // ancestor and descendant. These transforms must be 2D translations, and this
124 // requirement is enforced at every step.
125 template <typename LayerType>
126 static gfx::Vector2dF ComputeChangeOfBasisTranslation(
127 const LayerType& ancestor_layer,
128 const LayerType& descendant_layer) {
129 DCHECK(descendant_layer.HasAncestor(&ancestor_layer));
130 const LayerType* descendant_target = descendant_layer.render_target();
131 DCHECK(descendant_target);
132 const LayerType* ancestor_target = ancestor_layer.render_target();
133 DCHECK(ancestor_target);
135 gfx::Vector2dF translation;
136 for (const LayerType* target = descendant_target; target != ancestor_target;
137 target = NextTargetSurface(target)) {
138 const gfx::Transform& trans = target->render_surface()->draw_transform();
139 // Ensure that this translation is truly 2d.
140 DCHECK(trans.IsIdentityOrTranslation());
141 DCHECK_EQ(0.f, trans.matrix().get(2, 3));
142 translation += trans.To2dTranslation();
145 return translation;
148 enum TranslateRectDirection {
149 TRANSLATE_RECT_DIRECTION_TO_ANCESTOR,
150 TRANSLATE_RECT_DIRECTION_TO_DESCENDANT
153 template <typename LayerType>
154 static gfx::Rect TranslateRectToTargetSpace(const LayerType& ancestor_layer,
155 const LayerType& descendant_layer,
156 const gfx::Rect& rect,
157 TranslateRectDirection direction) {
158 gfx::Vector2dF translation = ComputeChangeOfBasisTranslation<LayerType>(
159 ancestor_layer, descendant_layer);
160 if (direction == TRANSLATE_RECT_DIRECTION_TO_DESCENDANT)
161 translation.Scale(-1.f);
162 return gfx::ToEnclosingRect(
163 gfx::RectF(rect.origin() + translation, rect.size()));
166 // Attempts to update the clip rects for the given layer. If the layer has a
167 // clip_parent, it may not inherit its immediate ancestor's clip.
168 template <typename LayerType>
169 static void UpdateClipRectsForClipChild(
170 const LayerType* layer,
171 gfx::Rect* clip_rect_in_parent_target_space,
172 bool* subtree_should_be_clipped) {
173 // If the layer has no clip_parent, or the ancestor is the same as its actual
174 // parent, then we don't need special clip rects. Bail now and leave the out
175 // parameters untouched.
176 const LayerType* clip_parent = layer->scroll_parent();
178 if (!clip_parent)
179 clip_parent = layer->clip_parent();
181 if (!clip_parent || clip_parent == layer->parent())
182 return;
184 // The root layer is never a clip child.
185 DCHECK(layer->parent());
187 // Grab the cached values.
188 *clip_rect_in_parent_target_space = clip_parent->clip_rect();
189 *subtree_should_be_clipped = clip_parent->is_clipped();
191 // We may have to project the clip rect into our parent's target space. Note,
192 // it must be our parent's target space, not ours. For one, we haven't
193 // computed our transforms, so we couldn't put it in our space yet even if we
194 // wanted to. But more importantly, this matches the expectations of
195 // CalculateDrawPropertiesInternal. If we, say, create a render surface, these
196 // clip rects will want to be in its target space, not ours.
197 if (clip_parent == layer->clip_parent()) {
198 *clip_rect_in_parent_target_space = TranslateRectToTargetSpace<LayerType>(
199 *clip_parent, *layer->parent(), *clip_rect_in_parent_target_space,
200 TRANSLATE_RECT_DIRECTION_TO_DESCENDANT);
201 } else {
202 // If we're being clipped by our scroll parent, we must translate through
203 // our common ancestor. This happens to be our parent, so it is sufficent to
204 // translate from our clip parent's space to the space of its ancestor (our
205 // parent).
206 *clip_rect_in_parent_target_space = TranslateRectToTargetSpace<LayerType>(
207 *layer->parent(), *clip_parent, *clip_rect_in_parent_target_space,
208 TRANSLATE_RECT_DIRECTION_TO_ANCESTOR);
212 // We collect an accumulated drawable content rect per render surface.
213 // Typically, a layer will contribute to only one surface, the surface
214 // associated with its render target. Clip children, however, may affect
215 // several surfaces since there may be several surfaces between the clip child
216 // and its parent.
218 // NB: we accumulate the layer's *clipped* drawable content rect.
219 template <typename LayerType>
220 struct AccumulatedSurfaceState {
221 explicit AccumulatedSurfaceState(LayerType* render_target)
222 : render_target(render_target) {}
224 // The accumulated drawable content rect for the surface associated with the
225 // given |render_target|.
226 gfx::Rect drawable_content_rect;
228 // The target owning the surface. (We hang onto the target rather than the
229 // surface so that we can DCHECK that the surface's draw transform is simply
230 // a translation when |render_target| reports that it has no unclipped
231 // descendants).
232 LayerType* render_target;
235 template <typename LayerType>
236 void UpdateAccumulatedSurfaceState(
237 LayerType* layer,
238 const gfx::Rect& drawable_content_rect,
239 std::vector<AccumulatedSurfaceState<LayerType>>*
240 accumulated_surface_state) {
241 if (IsRootLayer(layer))
242 return;
244 // We will apply our drawable content rect to the accumulated rects for all
245 // surfaces between us and |render_target| (inclusive). This is either our
246 // clip parent's target if we are a clip child, or else simply our parent's
247 // target. We use our parent's target because we're either the owner of a
248 // render surface and we'll want to add our rect to our *surface's* target, or
249 // we're not and our target is the same as our parent's. In both cases, the
250 // parent's target gives us what we want.
251 LayerType* render_target = layer->clip_parent()
252 ? layer->clip_parent()->render_target()
253 : layer->parent()->render_target();
255 // If the layer owns a surface, then the content rect is in the wrong space.
256 // Instead, we will use the surface's DrawableContentRect which is in target
257 // space as required.
258 gfx::Rect target_rect = drawable_content_rect;
259 if (layer->render_surface()) {
260 target_rect =
261 gfx::ToEnclosedRect(layer->render_surface()->DrawableContentRect());
264 if (render_target->is_clipped()) {
265 gfx::Rect clip_rect = render_target->clip_rect();
266 // If the layer has a clip parent, the clip rect may be in the wrong space,
267 // so we'll need to transform it before it is applied.
268 if (layer->clip_parent()) {
269 clip_rect = TranslateRectToTargetSpace<LayerType>(
270 *layer->clip_parent(), *layer, clip_rect,
271 TRANSLATE_RECT_DIRECTION_TO_DESCENDANT);
273 target_rect.Intersect(clip_rect);
276 // We must have at least one entry in the vector for the root.
277 DCHECK_LT(0ul, accumulated_surface_state->size());
279 typedef typename std::vector<AccumulatedSurfaceState<LayerType>>
280 AccumulatedSurfaceStateVector;
281 typedef typename AccumulatedSurfaceStateVector::reverse_iterator
282 AccumulatedSurfaceStateIterator;
283 AccumulatedSurfaceStateIterator current_state =
284 accumulated_surface_state->rbegin();
286 // Add this rect to the accumulated content rect for all surfaces until we
287 // reach the target surface.
288 bool found_render_target = false;
289 for (; current_state != accumulated_surface_state->rend(); ++current_state) {
290 current_state->drawable_content_rect.Union(target_rect);
292 // If we've reached |render_target| our work is done and we can bail.
293 if (current_state->render_target == render_target) {
294 found_render_target = true;
295 break;
298 // Transform rect from the current target's space to the next.
299 LayerType* current_target = current_state->render_target;
300 DCHECK(current_target->render_surface());
301 const gfx::Transform& current_draw_transform =
302 current_target->render_surface()->draw_transform();
304 // If we have unclipped descendants, the draw transform is a translation.
305 DCHECK(current_target->num_unclipped_descendants() == 0 ||
306 current_draw_transform.IsIdentityOrTranslation());
308 target_rect = gfx::ToEnclosingRect(
309 MathUtil::MapClippedRect(current_draw_transform, target_rect));
312 // It is an error to not reach |render_target|. If this happens, it means that
313 // either the clip parent is not an ancestor of the clip child or the surface
314 // state vector is empty, both of which should be impossible.
315 DCHECK(found_render_target);
318 template <typename LayerType> static inline bool IsRootLayer(LayerType* layer) {
319 return !layer->parent();
322 template <typename LayerType>
323 static inline bool LayerIsInExisting3DRenderingContext(LayerType* layer) {
324 return layer->Is3dSorted() && layer->parent() &&
325 layer->parent()->Is3dSorted() &&
326 (layer->parent()->sorting_context_id() == layer->sorting_context_id());
329 template <typename LayerType>
330 static bool IsRootLayerOfNewRenderingContext(LayerType* layer) {
331 if (layer->parent())
332 return !layer->parent()->Is3dSorted() && layer->Is3dSorted();
334 return layer->Is3dSorted();
337 template <typename LayerType>
338 static bool IsLayerBackFaceVisible(LayerType* layer) {
339 // The current W3C spec on CSS transforms says that backface visibility should
340 // be determined differently depending on whether the layer is in a "3d
341 // rendering context" or not. For Chromium code, we can determine whether we
342 // are in a 3d rendering context by checking if the parent preserves 3d.
344 if (LayerIsInExisting3DRenderingContext(layer))
345 return layer->draw_transform().IsBackFaceVisible();
347 // In this case, either the layer establishes a new 3d rendering context, or
348 // is not in a 3d rendering context at all.
349 return layer->transform().IsBackFaceVisible();
352 template <typename LayerType>
353 static bool IsSurfaceBackFaceVisible(LayerType* layer,
354 const gfx::Transform& draw_transform) {
355 if (LayerIsInExisting3DRenderingContext(layer))
356 return draw_transform.IsBackFaceVisible();
358 if (IsRootLayerOfNewRenderingContext(layer))
359 return layer->transform().IsBackFaceVisible();
361 // If the render_surface is not part of a new or existing rendering context,
362 // then the layers that contribute to this surface will decide back-face
363 // visibility for themselves.
364 return false;
367 template <typename LayerType>
368 static inline bool LayerClipsSubtree(LayerType* layer) {
369 return layer->masks_to_bounds() || layer->mask_layer();
372 template <typename LayerType>
373 static gfx::Rect CalculateVisibleContentRect(
374 LayerType* layer,
375 const gfx::Rect& clip_rect_of_target_surface_in_target_space,
376 const gfx::Rect& layer_rect_in_target_space) {
377 DCHECK(layer->render_target());
379 // Nothing is visible if the layer bounds are empty.
380 if (!layer->DrawsContent() || layer->content_bounds().IsEmpty() ||
381 layer->drawable_content_rect().IsEmpty())
382 return gfx::Rect();
384 // Compute visible bounds in target surface space.
385 gfx::Rect visible_rect_in_target_surface_space =
386 layer->drawable_content_rect();
388 if (layer->render_target()->render_surface()->is_clipped()) {
389 // The |layer| L has a target T which owns a surface Ts. The surface Ts
390 // has a target TsT.
392 // In this case the target surface Ts does clip the layer L that contributes
393 // to it. So, we have to convert the clip rect of Ts from the target space
394 // of Ts (that is the space of TsT), to the current render target's space
395 // (that is the space of T). This conversion is done outside this function
396 // so that it can be cached instead of computing it redundantly for every
397 // layer.
398 visible_rect_in_target_surface_space.Intersect(
399 clip_rect_of_target_surface_in_target_space);
402 if (visible_rect_in_target_surface_space.IsEmpty())
403 return gfx::Rect();
405 return CalculateVisibleRectWithCachedLayerRect(
406 visible_rect_in_target_surface_space,
407 gfx::Rect(layer->content_bounds()),
408 layer_rect_in_target_space,
409 layer->draw_transform());
412 static inline bool TransformToParentIsKnown(LayerImpl* layer) { return true; }
414 static inline bool TransformToParentIsKnown(Layer* layer) {
415 return !layer->TransformIsAnimating();
418 static inline bool TransformToScreenIsKnown(LayerImpl* layer) { return true; }
420 static inline bool TransformToScreenIsKnown(Layer* layer) {
421 return !layer->screen_space_transform_is_animating();
424 template <typename LayerType>
425 static bool LayerShouldBeSkipped(LayerType* layer, bool layer_is_drawn) {
426 // Layers can be skipped if any of these conditions are met.
427 // - is not drawn due to it or one of its ancestors being hidden (or having
428 // no copy requests).
429 // - does not draw content.
430 // - is transparent.
431 // - has empty bounds
432 // - the layer is not double-sided, but its back face is visible.
434 // Some additional conditions need to be computed at a later point after the
435 // recursion is finished.
436 // - the intersection of render_surface content and layer clip_rect is empty
437 // - the visible_content_rect is empty
439 // Note, if the layer should not have been drawn due to being fully
440 // transparent, we would have skipped the entire subtree and never made it
441 // into this function, so it is safe to omit this check here.
443 if (!layer_is_drawn)
444 return true;
446 if (!layer->DrawsContent() || layer->bounds().IsEmpty())
447 return true;
449 LayerType* backface_test_layer = layer;
450 if (layer->use_parent_backface_visibility()) {
451 DCHECK(layer->parent());
452 DCHECK(!layer->parent()->use_parent_backface_visibility());
453 backface_test_layer = layer->parent();
456 // The layer should not be drawn if (1) it is not double-sided and (2) the
457 // back of the layer is known to be facing the screen.
458 if (!backface_test_layer->double_sided() &&
459 TransformToScreenIsKnown(backface_test_layer) &&
460 IsLayerBackFaceVisible(backface_test_layer))
461 return true;
463 return false;
466 template <typename LayerType>
467 static bool HasInvertibleOrAnimatedTransform(LayerType* layer) {
468 return layer->transform_is_invertible() || layer->TransformIsAnimating();
471 static inline bool SubtreeShouldBeSkipped(LayerImpl* layer,
472 bool layer_is_drawn) {
473 // If the layer transform is not invertible, it should not be drawn.
474 // TODO(ajuma): Correctly process subtrees with singular transform for the
475 // case where we may animate to a non-singular transform and wish to
476 // pre-raster.
477 if (!HasInvertibleOrAnimatedTransform(layer))
478 return true;
480 // When we need to do a readback/copy of a layer's output, we can not skip
481 // it or any of its ancestors.
482 if (layer->draw_properties().layer_or_descendant_has_copy_request)
483 return false;
485 // We cannot skip the the subtree if a descendant has a wheel or touch handler
486 // or the hit testing code will break (it requires fresh transforms, etc).
487 if (layer->draw_properties().layer_or_descendant_has_input_handler)
488 return false;
490 // If the layer is not drawn, then skip it and its subtree.
491 if (!layer_is_drawn)
492 return true;
494 // If layer is on the pending tree and opacity is being animated then
495 // this subtree can't be skipped as we need to create, prioritize and
496 // include tiles for this layer when deciding if tree can be activated.
497 if (layer->layer_tree_impl()->IsPendingTree() && layer->OpacityIsAnimating())
498 return false;
500 // The opacity of a layer always applies to its children (either implicitly
501 // via a render surface or explicitly if the parent preserves 3D), so the
502 // entire subtree can be skipped if this layer is fully transparent.
503 return !layer->opacity();
506 static inline bool SubtreeShouldBeSkipped(Layer* layer, bool layer_is_drawn) {
507 // If the layer transform is not invertible, it should not be drawn.
508 if (!layer->transform_is_invertible() && !layer->TransformIsAnimating())
509 return true;
511 // When we need to do a readback/copy of a layer's output, we can not skip
512 // it or any of its ancestors.
513 if (layer->draw_properties().layer_or_descendant_has_copy_request)
514 return false;
516 // We cannot skip the the subtree if a descendant has a wheel or touch handler
517 // or the hit testing code will break (it requires fresh transforms, etc).
518 if (layer->draw_properties().layer_or_descendant_has_input_handler)
519 return false;
521 // If the layer is not drawn, then skip it and its subtree.
522 if (!layer_is_drawn)
523 return true;
525 // If the opacity is being animated then the opacity on the main thread is
526 // unreliable (since the impl thread may be using a different opacity), so it
527 // should not be trusted.
528 // In particular, it should not cause the subtree to be skipped.
529 // Similarly, for layers that might animate opacity using an impl-only
530 // animation, their subtree should also not be skipped.
531 return !layer->opacity() && !layer->OpacityIsAnimating() &&
532 !layer->OpacityCanAnimateOnImplThread();
535 static inline void SavePaintPropertiesLayer(LayerImpl* layer) {}
537 static inline void SavePaintPropertiesLayer(Layer* layer) {
538 layer->SavePaintProperties();
540 if (layer->mask_layer())
541 layer->mask_layer()->SavePaintProperties();
542 if (layer->replica_layer() && layer->replica_layer()->mask_layer())
543 layer->replica_layer()->mask_layer()->SavePaintProperties();
546 static bool SubtreeShouldRenderToSeparateSurface(
547 Layer* layer,
548 bool axis_aligned_with_respect_to_parent) {
550 // A layer and its descendants should render onto a new RenderSurfaceImpl if
551 // any of these rules hold:
554 // The root layer owns a render surface, but it never acts as a contributing
555 // surface to another render target. Compositor features that are applied via
556 // a contributing surface can not be applied to the root layer. In order to
557 // use these effects, another child of the root would need to be introduced
558 // in order to act as a contributing surface to the root layer's surface.
559 bool is_root = IsRootLayer(layer);
561 // If the layer uses a mask.
562 if (layer->mask_layer()) {
563 DCHECK(!is_root);
564 return true;
567 // If the layer has a reflection.
568 if (layer->replica_layer()) {
569 DCHECK(!is_root);
570 return true;
573 // If the layer uses a CSS filter.
574 if (!layer->filters().IsEmpty() || !layer->background_filters().IsEmpty()) {
575 DCHECK(!is_root);
576 return true;
579 // If the layer will use a CSS filter. In this case, the animation
580 // will start and add a filter to this layer, so it needs a surface.
581 if (layer->FilterIsAnimating()) {
582 DCHECK(!is_root);
583 return true;
586 int num_descendants_that_draw_content =
587 layer->NumDescendantsThatDrawContent();
589 // If the layer flattens its subtree, but it is treated as a 3D object by its
590 // parent (i.e. parent participates in a 3D rendering context).
591 if (LayerIsInExisting3DRenderingContext(layer) &&
592 layer->should_flatten_transform() &&
593 num_descendants_that_draw_content > 0) {
594 TRACE_EVENT_INSTANT0(
595 "cc",
596 "LayerTreeHostCommon::SubtreeShouldRenderToSeparateSurface flattening",
597 TRACE_EVENT_SCOPE_THREAD);
598 DCHECK(!is_root);
599 return true;
602 // If the layer has blending.
603 // TODO(rosca): this is temporary, until blending is implemented for other
604 // types of quads than RenderPassDrawQuad. Layers having descendants that draw
605 // content will still create a separate rendering surface.
606 if (!layer->uses_default_blend_mode()) {
607 TRACE_EVENT_INSTANT0(
608 "cc",
609 "LayerTreeHostCommon::SubtreeShouldRenderToSeparateSurface blending",
610 TRACE_EVENT_SCOPE_THREAD);
611 DCHECK(!is_root);
612 return true;
615 // If the layer clips its descendants but it is not axis-aligned with respect
616 // to its parent.
617 bool layer_clips_external_content =
618 LayerClipsSubtree(layer) || layer->HasDelegatedContent();
619 if (layer_clips_external_content && !axis_aligned_with_respect_to_parent &&
620 num_descendants_that_draw_content > 0) {
621 TRACE_EVENT_INSTANT0(
622 "cc",
623 "LayerTreeHostCommon::SubtreeShouldRenderToSeparateSurface clipping",
624 TRACE_EVENT_SCOPE_THREAD);
625 DCHECK(!is_root);
626 return true;
629 // If the layer has some translucency and does not have a preserves-3d
630 // transform style. This condition only needs a render surface if two or more
631 // layers in the subtree overlap. But checking layer overlaps is unnecessarily
632 // costly so instead we conservatively create a surface whenever at least two
633 // layers draw content for this subtree.
634 bool at_least_two_layers_in_subtree_draw_content =
635 num_descendants_that_draw_content > 0 &&
636 (layer->DrawsContent() || num_descendants_that_draw_content > 1);
638 if (layer->opacity() != 1.f && layer->should_flatten_transform() &&
639 at_least_two_layers_in_subtree_draw_content) {
640 TRACE_EVENT_INSTANT0(
641 "cc",
642 "LayerTreeHostCommon::SubtreeShouldRenderToSeparateSurface opacity",
643 TRACE_EVENT_SCOPE_THREAD);
644 DCHECK(!is_root);
645 return true;
648 // The root layer should always have a render_surface.
649 if (is_root)
650 return true;
653 // These are allowed on the root surface, as they don't require the surface to
654 // be used as a contributing surface in order to apply correctly.
657 // If the layer has isolation.
658 // TODO(rosca): to be optimized - create separate rendering surface only when
659 // the blending descendants might have access to the content behind this layer
660 // (layer has transparent background or descendants overflow).
661 // https://code.google.com/p/chromium/issues/detail?id=301738
662 if (layer->is_root_for_isolated_group()) {
663 TRACE_EVENT_INSTANT0(
664 "cc",
665 "LayerTreeHostCommon::SubtreeShouldRenderToSeparateSurface isolation",
666 TRACE_EVENT_SCOPE_THREAD);
667 return true;
670 // If we force it.
671 if (layer->force_render_surface())
672 return true;
674 // If we'll make a copy of the layer's contents.
675 if (layer->HasCopyRequest())
676 return true;
678 return false;
681 // This function returns a translation matrix that can be applied on a vector
682 // that's in the layer's target surface coordinate, while the position offset is
683 // specified in some ancestor layer's coordinate.
684 template <typename LayerType>
685 gfx::Transform ComputeSizeDeltaCompensation(
686 LayerType* layer,
687 LayerType* container,
688 const gfx::Vector2dF& position_offset) {
689 gfx::Transform result_transform;
691 // To apply a translate in the container's layer space,
692 // the following steps need to be done:
693 // Step 1a. transform from target surface space to the container's target
694 // surface space
695 // Step 1b. transform from container's target surface space to the
696 // container's layer space
697 // Step 2. apply the compensation
698 // Step 3. transform back to target surface space
700 gfx::Transform target_surface_space_to_container_layer_space;
701 // Calculate step 1a
702 LayerType* container_target_surface = container->render_target();
703 for (LayerType* current_target_surface = NextTargetSurface(layer);
704 current_target_surface &&
705 current_target_surface != container_target_surface;
706 current_target_surface = NextTargetSurface(current_target_surface)) {
707 // Note: Concat is used here to convert the result coordinate space from
708 // current render surface to the next render surface.
709 target_surface_space_to_container_layer_space.ConcatTransform(
710 current_target_surface->render_surface()->draw_transform());
712 // Calculate step 1b
713 gfx::Transform container_layer_space_to_container_target_surface_space =
714 container->draw_transform();
715 container_layer_space_to_container_target_surface_space.Scale(
716 container->contents_scale_x(), container->contents_scale_y());
718 gfx::Transform container_target_surface_space_to_container_layer_space;
719 if (container_layer_space_to_container_target_surface_space.GetInverse(
720 &container_target_surface_space_to_container_layer_space)) {
721 // Note: Again, Concat is used to conver the result coordinate space from
722 // the container render surface to the container layer.
723 target_surface_space_to_container_layer_space.ConcatTransform(
724 container_target_surface_space_to_container_layer_space);
727 // Apply step 3
728 gfx::Transform container_layer_space_to_target_surface_space;
729 if (target_surface_space_to_container_layer_space.GetInverse(
730 &container_layer_space_to_target_surface_space)) {
731 result_transform.PreconcatTransform(
732 container_layer_space_to_target_surface_space);
733 } else {
734 // TODO(shawnsingh): A non-invertible matrix could still make meaningful
735 // projection. For example ScaleZ(0) is non-invertible but the layer is
736 // still visible.
737 return gfx::Transform();
740 // Apply step 2
741 result_transform.Translate(position_offset.x(), position_offset.y());
743 // Apply step 1
744 result_transform.PreconcatTransform(
745 target_surface_space_to_container_layer_space);
747 return result_transform;
750 template <typename LayerType>
751 void ApplyPositionAdjustment(
752 LayerType* layer,
753 LayerType* container,
754 const gfx::Transform& scroll_compensation,
755 gfx::Transform* combined_transform) {
756 if (!layer->position_constraint().is_fixed_position())
757 return;
759 // Special case: this layer is a composited fixed-position layer; we need to
760 // explicitly compensate for all ancestors' nonzero scroll_deltas to keep
761 // this layer fixed correctly.
762 // Note carefully: this is Concat, not Preconcat
763 // (current_scroll_compensation * combined_transform).
764 combined_transform->ConcatTransform(scroll_compensation);
766 // For right-edge or bottom-edge anchored fixed position layers,
767 // the layer should relocate itself if the container changes its size.
768 bool fixed_to_right_edge =
769 layer->position_constraint().is_fixed_to_right_edge();
770 bool fixed_to_bottom_edge =
771 layer->position_constraint().is_fixed_to_bottom_edge();
772 gfx::Vector2dF position_offset = container->FixedContainerSizeDelta();
773 position_offset.set_x(fixed_to_right_edge ? position_offset.x() : 0);
774 position_offset.set_y(fixed_to_bottom_edge ? position_offset.y() : 0);
775 if (position_offset.IsZero())
776 return;
778 // Note: Again, this is Concat. The compensation matrix will be applied on
779 // the vector in target surface space.
780 combined_transform->ConcatTransform(
781 ComputeSizeDeltaCompensation(layer, container, position_offset));
784 template <typename LayerType>
785 gfx::Transform ComputeScrollCompensationForThisLayer(
786 LayerType* scrolling_layer,
787 const gfx::Transform& parent_matrix,
788 const gfx::Vector2dF& scroll_delta) {
789 // For every layer that has non-zero scroll_delta, we have to compute a
790 // transform that can undo the scroll_delta translation. In particular, we
791 // want this matrix to premultiply a fixed-position layer's parent_matrix, so
792 // we design this transform in three steps as follows. The steps described
793 // here apply from right-to-left, so Step 1 would be the right-most matrix:
795 // Step 1. transform from target surface space to the exact space where
796 // scroll_delta is actually applied.
797 // -- this is inverse of parent_matrix
798 // Step 2. undo the scroll_delta
799 // -- this is just a translation by scroll_delta.
800 // Step 3. transform back to target surface space.
801 // -- this transform is the parent_matrix
803 // These steps create a matrix that both start and end in target surface
804 // space. So this matrix can pre-multiply any fixed-position layer's
805 // draw_transform to undo the scroll_deltas -- as long as that fixed position
806 // layer is fixed onto the same render_target as this scrolling_layer.
809 gfx::Transform scroll_compensation_for_this_layer = parent_matrix; // Step 3
810 scroll_compensation_for_this_layer.Translate(
811 scroll_delta.x(),
812 scroll_delta.y()); // Step 2
814 gfx::Transform inverse_parent_matrix(gfx::Transform::kSkipInitialization);
815 if (!parent_matrix.GetInverse(&inverse_parent_matrix)) {
816 // TODO(shawnsingh): Either we need to handle uninvertible transforms
817 // here, or DCHECK that the transform is invertible.
819 scroll_compensation_for_this_layer.PreconcatTransform(
820 inverse_parent_matrix); // Step 1
821 return scroll_compensation_for_this_layer;
824 template <typename LayerType>
825 gfx::Transform ComputeScrollCompensationMatrixForChildren(
826 LayerType* layer,
827 const gfx::Transform& parent_matrix,
828 const gfx::Transform& current_scroll_compensation_matrix,
829 const gfx::Vector2dF& scroll_delta) {
830 // "Total scroll compensation" is the transform needed to cancel out all
831 // scroll_delta translations that occurred since the nearest container layer,
832 // even if there are render_surfaces in-between.
834 // There are some edge cases to be aware of, that are not explicit in the
835 // code:
836 // - A layer that is both a fixed-position and container should not be its
837 // own container, instead, that means it is fixed to an ancestor, and is a
838 // container for any fixed-position descendants.
839 // - A layer that is a fixed-position container and has a render_surface
840 // should behave the same as a container without a render_surface, the
841 // render_surface is irrelevant in that case.
842 // - A layer that does not have an explicit container is simply fixed to the
843 // viewport. (i.e. the root render_surface.)
844 // - If the fixed-position layer has its own render_surface, then the
845 // render_surface is the one who gets fixed.
847 // This function needs to be called AFTER layers create their own
848 // render_surfaces.
851 // Scroll compensation restarts from identity under two possible conditions:
852 // - the current layer is a container for fixed-position descendants
853 // - the current layer is fixed-position itself, so any fixed-position
854 // descendants are positioned with respect to this layer. Thus, any
855 // fixed position descendants only need to compensate for scrollDeltas
856 // that occur below this layer.
857 bool current_layer_resets_scroll_compensation_for_descendants =
858 layer->IsContainerForFixedPositionLayers() ||
859 layer->position_constraint().is_fixed_position();
861 // Avoid the overheads (including stack allocation and matrix
862 // initialization/copy) if we know that the scroll compensation doesn't need
863 // to be reset or adjusted.
864 if (!current_layer_resets_scroll_compensation_for_descendants &&
865 scroll_delta.IsZero() && !layer->render_surface())
866 return current_scroll_compensation_matrix;
868 // Start as identity matrix.
869 gfx::Transform next_scroll_compensation_matrix;
871 // If this layer does not reset scroll compensation, then it inherits the
872 // existing scroll compensations.
873 if (!current_layer_resets_scroll_compensation_for_descendants)
874 next_scroll_compensation_matrix = current_scroll_compensation_matrix;
876 // If the current layer has a non-zero scroll_delta, then we should compute
877 // its local scroll compensation and accumulate it to the
878 // next_scroll_compensation_matrix.
879 if (!scroll_delta.IsZero()) {
880 gfx::Transform scroll_compensation_for_this_layer =
881 ComputeScrollCompensationForThisLayer(
882 layer, parent_matrix, scroll_delta);
883 next_scroll_compensation_matrix.PreconcatTransform(
884 scroll_compensation_for_this_layer);
887 // If the layer created its own render_surface, we have to adjust
888 // next_scroll_compensation_matrix. The adjustment allows us to continue
889 // using the scroll compensation on the next surface.
890 // Step 1 (right-most in the math): transform from the new surface to the
891 // original ancestor surface
892 // Step 2: apply the scroll compensation
893 // Step 3: transform back to the new surface.
894 if (layer->render_surface() &&
895 !next_scroll_compensation_matrix.IsIdentity()) {
896 gfx::Transform inverse_surface_draw_transform(
897 gfx::Transform::kSkipInitialization);
898 if (!layer->render_surface()->draw_transform().GetInverse(
899 &inverse_surface_draw_transform)) {
900 // TODO(shawnsingh): Either we need to handle uninvertible transforms
901 // here, or DCHECK that the transform is invertible.
903 next_scroll_compensation_matrix =
904 inverse_surface_draw_transform * next_scroll_compensation_matrix *
905 layer->render_surface()->draw_transform();
908 return next_scroll_compensation_matrix;
911 template <typename LayerType>
912 static inline void UpdateLayerScaleDrawProperties(
913 LayerType* layer,
914 float ideal_contents_scale,
915 float maximum_animation_contents_scale,
916 float page_scale_factor,
917 float device_scale_factor) {
918 layer->draw_properties().ideal_contents_scale = ideal_contents_scale;
919 layer->draw_properties().maximum_animation_contents_scale =
920 maximum_animation_contents_scale;
921 layer->draw_properties().page_scale_factor = page_scale_factor;
922 layer->draw_properties().device_scale_factor = device_scale_factor;
925 static inline void CalculateContentsScale(LayerImpl* layer,
926 float contents_scale) {
927 // LayerImpl has all of its content scales and bounds pushed from the Main
928 // thread during commit and just uses those values as-is.
931 static inline void CalculateContentsScale(Layer* layer, float contents_scale) {
932 layer->CalculateContentsScale(contents_scale,
933 &layer->draw_properties().contents_scale_x,
934 &layer->draw_properties().contents_scale_y,
935 &layer->draw_properties().content_bounds);
937 Layer* mask_layer = layer->mask_layer();
938 if (mask_layer) {
939 mask_layer->CalculateContentsScale(
940 contents_scale,
941 &mask_layer->draw_properties().contents_scale_x,
942 &mask_layer->draw_properties().contents_scale_y,
943 &mask_layer->draw_properties().content_bounds);
946 Layer* replica_mask_layer =
947 layer->replica_layer() ? layer->replica_layer()->mask_layer() : NULL;
948 if (replica_mask_layer) {
949 replica_mask_layer->CalculateContentsScale(
950 contents_scale,
951 &replica_mask_layer->draw_properties().contents_scale_x,
952 &replica_mask_layer->draw_properties().contents_scale_y,
953 &replica_mask_layer->draw_properties().content_bounds);
957 static inline void UpdateLayerContentsScale(
958 LayerImpl* layer,
959 bool can_adjust_raster_scale,
960 float ideal_contents_scale,
961 float device_scale_factor,
962 float page_scale_factor,
963 bool animating_transform_to_screen) {
964 CalculateContentsScale(layer, ideal_contents_scale);
967 static inline void UpdateLayerContentsScale(
968 Layer* layer,
969 bool can_adjust_raster_scale,
970 float ideal_contents_scale,
971 float device_scale_factor,
972 float page_scale_factor,
973 bool animating_transform_to_screen) {
974 if (can_adjust_raster_scale) {
975 float ideal_raster_scale =
976 ideal_contents_scale / (device_scale_factor * page_scale_factor);
978 bool need_to_set_raster_scale = layer->raster_scale_is_unknown();
980 // If we've previously saved a raster_scale but the ideal changes, things
981 // are unpredictable and we should just use 1.
982 if (!need_to_set_raster_scale && layer->raster_scale() != 1.f &&
983 ideal_raster_scale != layer->raster_scale()) {
984 ideal_raster_scale = 1.f;
985 need_to_set_raster_scale = true;
988 if (need_to_set_raster_scale) {
989 bool use_and_save_ideal_scale =
990 ideal_raster_scale >= 1.f && !animating_transform_to_screen;
991 if (use_and_save_ideal_scale)
992 layer->set_raster_scale(ideal_raster_scale);
996 float raster_scale = 1.f;
997 if (!layer->raster_scale_is_unknown())
998 raster_scale = layer->raster_scale();
1000 gfx::Size old_content_bounds = layer->content_bounds();
1001 float old_contents_scale_x = layer->contents_scale_x();
1002 float old_contents_scale_y = layer->contents_scale_y();
1004 float contents_scale = raster_scale * device_scale_factor * page_scale_factor;
1005 CalculateContentsScale(layer, contents_scale);
1007 if (layer->content_bounds() != old_content_bounds ||
1008 layer->contents_scale_x() != old_contents_scale_x ||
1009 layer->contents_scale_y() != old_contents_scale_y)
1010 layer->SetNeedsPushProperties();
1013 static inline void CalculateAnimationContentsScale(
1014 Layer* layer,
1015 bool ancestor_is_animating_scale,
1016 float ancestor_maximum_animation_contents_scale,
1017 const gfx::Transform& parent_transform,
1018 const gfx::Transform& combined_transform,
1019 bool* combined_is_animating_scale,
1020 float* combined_maximum_animation_contents_scale) {
1021 *combined_is_animating_scale = false;
1022 *combined_maximum_animation_contents_scale = 0.f;
1025 static inline void CalculateAnimationContentsScale(
1026 LayerImpl* layer,
1027 bool ancestor_is_animating_scale,
1028 float ancestor_maximum_animation_contents_scale,
1029 const gfx::Transform& ancestor_transform,
1030 const gfx::Transform& combined_transform,
1031 bool* combined_is_animating_scale,
1032 float* combined_maximum_animation_contents_scale) {
1033 if (ancestor_is_animating_scale &&
1034 ancestor_maximum_animation_contents_scale == 0.f) {
1035 // We've already failed to compute a maximum animated scale at an
1036 // ancestor, so we'll continue to fail.
1037 *combined_maximum_animation_contents_scale = 0.f;
1038 *combined_is_animating_scale = true;
1039 return;
1042 if (!combined_transform.IsScaleOrTranslation()) {
1043 // Computing maximum animated scale in the presence of
1044 // non-scale/translation transforms isn't supported.
1045 *combined_maximum_animation_contents_scale = 0.f;
1046 *combined_is_animating_scale = true;
1047 return;
1050 // We currently only support computing maximum scale for combinations of
1051 // scales and translations. We treat all non-translations as potentially
1052 // affecting scale. Animations that include non-translation/scale components
1053 // will cause the computation of MaximumScale below to fail.
1054 bool layer_is_animating_scale =
1055 !layer->layer_animation_controller()->HasOnlyTranslationTransforms();
1057 if (!layer_is_animating_scale && !ancestor_is_animating_scale) {
1058 *combined_maximum_animation_contents_scale = 0.f;
1059 *combined_is_animating_scale = false;
1060 return;
1063 // We don't attempt to accumulate animation scale from multiple nodes,
1064 // because of the risk of significant overestimation. For example, one node
1065 // may be increasing scale from 1 to 10 at the same time as a descendant is
1066 // decreasing scale from 10 to 1. Naively combining these scales would produce
1067 // a scale of 100.
1068 if (layer_is_animating_scale && ancestor_is_animating_scale) {
1069 *combined_maximum_animation_contents_scale = 0.f;
1070 *combined_is_animating_scale = true;
1071 return;
1074 // At this point, we know either the layer or an ancestor, but not both,
1075 // is animating scale.
1076 *combined_is_animating_scale = true;
1077 if (!layer_is_animating_scale) {
1078 gfx::Vector2dF layer_transform_scales =
1079 MathUtil::ComputeTransform2dScaleComponents(layer->transform(), 0.f);
1080 *combined_maximum_animation_contents_scale =
1081 ancestor_maximum_animation_contents_scale *
1082 std::max(layer_transform_scales.x(), layer_transform_scales.y());
1083 return;
1086 float layer_maximum_animated_scale = 0.f;
1087 if (!layer->layer_animation_controller()->MaximumTargetScale(
1088 &layer_maximum_animated_scale)) {
1089 *combined_maximum_animation_contents_scale = 0.f;
1090 return;
1092 gfx::Vector2dF ancestor_transform_scales =
1093 MathUtil::ComputeTransform2dScaleComponents(ancestor_transform, 0.f);
1094 *combined_maximum_animation_contents_scale =
1095 layer_maximum_animated_scale *
1096 std::max(ancestor_transform_scales.x(), ancestor_transform_scales.y());
1099 template <typename LayerTypePtr>
1100 static inline void MarkLayerWithRenderSurfaceLayerListId(
1101 LayerTypePtr layer,
1102 int current_render_surface_layer_list_id) {
1103 layer->draw_properties().last_drawn_render_surface_layer_list_id =
1104 current_render_surface_layer_list_id;
1105 layer->draw_properties().layer_or_descendant_is_drawn =
1106 !!current_render_surface_layer_list_id;
1109 template <typename LayerTypePtr>
1110 static inline void MarkMasksWithRenderSurfaceLayerListId(
1111 LayerTypePtr layer,
1112 int current_render_surface_layer_list_id) {
1113 if (layer->mask_layer()) {
1114 MarkLayerWithRenderSurfaceLayerListId(layer->mask_layer(),
1115 current_render_surface_layer_list_id);
1117 if (layer->replica_layer() && layer->replica_layer()->mask_layer()) {
1118 MarkLayerWithRenderSurfaceLayerListId(layer->replica_layer()->mask_layer(),
1119 current_render_surface_layer_list_id);
1123 template <typename LayerListType>
1124 static inline void MarkLayerListWithRenderSurfaceLayerListId(
1125 LayerListType* layer_list,
1126 int current_render_surface_layer_list_id) {
1127 for (typename LayerListType::iterator it = layer_list->begin();
1128 it != layer_list->end();
1129 ++it) {
1130 MarkLayerWithRenderSurfaceLayerListId(*it,
1131 current_render_surface_layer_list_id);
1132 MarkMasksWithRenderSurfaceLayerListId(*it,
1133 current_render_surface_layer_list_id);
1137 template <typename LayerType>
1138 static inline void RemoveSurfaceForEarlyExit(
1139 LayerType* layer_to_remove,
1140 typename LayerType::RenderSurfaceListType* render_surface_layer_list) {
1141 DCHECK(layer_to_remove->render_surface());
1142 // Technically, we know that the layer we want to remove should be
1143 // at the back of the render_surface_layer_list. However, we have had
1144 // bugs before that added unnecessary layers here
1145 // (https://bugs.webkit.org/show_bug.cgi?id=74147), but that causes
1146 // things to crash. So here we proactively remove any additional
1147 // layers from the end of the list.
1148 while (render_surface_layer_list->back() != layer_to_remove) {
1149 MarkLayerListWithRenderSurfaceLayerListId(
1150 &render_surface_layer_list->back()->render_surface()->layer_list(), 0);
1151 MarkLayerWithRenderSurfaceLayerListId(render_surface_layer_list->back(), 0);
1153 render_surface_layer_list->back()->ClearRenderSurfaceLayerList();
1154 render_surface_layer_list->pop_back();
1156 DCHECK_EQ(render_surface_layer_list->back(), layer_to_remove);
1157 MarkLayerListWithRenderSurfaceLayerListId(
1158 &layer_to_remove->render_surface()->layer_list(), 0);
1159 MarkLayerWithRenderSurfaceLayerListId(layer_to_remove, 0);
1160 render_surface_layer_list->pop_back();
1161 layer_to_remove->ClearRenderSurfaceLayerList();
1164 struct PreCalculateMetaInformationRecursiveData {
1165 bool layer_or_descendant_has_copy_request;
1166 bool layer_or_descendant_has_input_handler;
1167 int num_unclipped_descendants;
1169 PreCalculateMetaInformationRecursiveData()
1170 : layer_or_descendant_has_copy_request(false),
1171 layer_or_descendant_has_input_handler(false),
1172 num_unclipped_descendants(0) {}
1174 void Merge(const PreCalculateMetaInformationRecursiveData& data) {
1175 layer_or_descendant_has_copy_request |=
1176 data.layer_or_descendant_has_copy_request;
1177 layer_or_descendant_has_input_handler |=
1178 data.layer_or_descendant_has_input_handler;
1179 num_unclipped_descendants += data.num_unclipped_descendants;
1183 static void ValidateRenderSurface(LayerImpl* layer) {
1184 // This test verifies that there are no cases where a LayerImpl needs
1185 // a render surface, but doesn't have one.
1186 if (layer->render_surface())
1187 return;
1189 DCHECK(layer->filters().IsEmpty()) << "layer: " << layer->id();
1190 DCHECK(layer->background_filters().IsEmpty()) << "layer: " << layer->id();
1191 DCHECK(!layer->mask_layer()) << "layer: " << layer->id();
1192 DCHECK(!layer->replica_layer()) << "layer: " << layer->id();
1193 DCHECK(!IsRootLayer(layer)) << "layer: " << layer->id();
1194 DCHECK(!layer->is_root_for_isolated_group()) << "layer: " << layer->id();
1195 DCHECK(!layer->HasCopyRequest()) << "layer: " << layer->id();
1198 static void ValidateRenderSurface(Layer* layer) {
1201 // Recursively walks the layer tree to compute any information that is needed
1202 // before doing the main recursion.
1203 template <typename LayerType>
1204 static void PreCalculateMetaInformation(
1205 LayerType* layer,
1206 PreCalculateMetaInformationRecursiveData* recursive_data) {
1207 ValidateRenderSurface(layer);
1209 layer->draw_properties().sorted_for_recursion = false;
1210 layer->draw_properties().has_child_with_a_scroll_parent = false;
1211 layer->draw_properties().layer_or_descendant_is_drawn = false;
1212 layer->draw_properties().visited = false;
1214 if (!HasInvertibleOrAnimatedTransform(layer)) {
1215 // Layers with singular transforms should not be drawn, the whole subtree
1216 // can be skipped.
1217 return;
1220 if (layer->clip_parent())
1221 recursive_data->num_unclipped_descendants++;
1223 for (size_t i = 0; i < layer->children().size(); ++i) {
1224 LayerType* child_layer =
1225 LayerTreeHostCommon::get_layer_as_raw_ptr(layer->children(), i);
1227 PreCalculateMetaInformationRecursiveData data_for_child;
1228 PreCalculateMetaInformation(child_layer, &data_for_child);
1230 if (child_layer->scroll_parent())
1231 layer->draw_properties().has_child_with_a_scroll_parent = true;
1232 recursive_data->Merge(data_for_child);
1235 if (layer->clip_children()) {
1236 int num_clip_children = layer->clip_children()->size();
1237 DCHECK_GE(recursive_data->num_unclipped_descendants, num_clip_children);
1238 recursive_data->num_unclipped_descendants -= num_clip_children;
1241 if (layer->HasCopyRequest())
1242 recursive_data->layer_or_descendant_has_copy_request = true;
1244 if (!layer->touch_event_handler_region().IsEmpty() ||
1245 layer->have_wheel_event_handlers())
1246 recursive_data->layer_or_descendant_has_input_handler = true;
1248 layer->draw_properties().num_unclipped_descendants =
1249 recursive_data->num_unclipped_descendants;
1250 layer->draw_properties().layer_or_descendant_has_copy_request =
1251 recursive_data->layer_or_descendant_has_copy_request;
1252 layer->draw_properties().layer_or_descendant_has_input_handler =
1253 recursive_data->layer_or_descendant_has_input_handler;
1256 template <typename LayerType>
1257 struct SubtreeGlobals {
1258 int max_texture_size;
1259 float device_scale_factor;
1260 float page_scale_factor;
1261 const LayerType* page_scale_application_layer;
1262 gfx::Vector2dF elastic_overscroll;
1263 const LayerType* elastic_overscroll_application_layer;
1264 bool can_adjust_raster_scales;
1265 bool can_render_to_separate_surface;
1266 bool layers_always_allowed_lcd_text;
1269 template<typename LayerType>
1270 struct DataForRecursion {
1271 // The accumulated sequence of transforms a layer will use to determine its
1272 // own draw transform.
1273 gfx::Transform parent_matrix;
1275 // The accumulated sequence of transforms a layer will use to determine its
1276 // own screen-space transform.
1277 gfx::Transform full_hierarchy_matrix;
1279 // The transform that removes all scrolling that may have occurred between a
1280 // fixed-position layer and its container, so that the layer actually does
1281 // remain fixed.
1282 gfx::Transform scroll_compensation_matrix;
1284 // The ancestor that would be the container for any fixed-position / sticky
1285 // layers.
1286 LayerType* fixed_container;
1288 // This is the normal clip rect that is propagated from parent to child.
1289 gfx::Rect clip_rect_in_target_space;
1291 // When the layer's children want to compute their visible content rect, they
1292 // want to know what their target surface's clip rect will be. BUT - they
1293 // want to know this clip rect represented in their own target space. This
1294 // requires inverse-projecting the surface's clip rect from the surface's
1295 // render target space down to the surface's own space. Instead of computing
1296 // this value redundantly for each child layer, it is computed only once
1297 // while dealing with the parent layer, and then this precomputed value is
1298 // passed down the recursion to the children that actually use it.
1299 gfx::Rect clip_rect_of_target_surface_in_target_space;
1301 // The maximum amount by which this layer will be scaled during the lifetime
1302 // of currently running animations.
1303 float maximum_animation_contents_scale;
1305 bool ancestor_is_animating_scale;
1306 bool ancestor_clips_subtree;
1307 typename LayerType::RenderSurfaceType*
1308 nearest_occlusion_immune_ancestor_surface;
1309 bool in_subtree_of_page_scale_application_layer;
1310 bool subtree_can_use_lcd_text;
1311 bool subtree_is_visible_from_ancestor;
1314 template <typename LayerType>
1315 static LayerType* GetChildContainingLayer(const LayerType& parent,
1316 LayerType* layer) {
1317 for (LayerType* ancestor = layer; ancestor; ancestor = ancestor->parent()) {
1318 if (ancestor->parent() == &parent)
1319 return ancestor;
1321 NOTREACHED();
1322 return 0;
1325 template <typename LayerType>
1326 static void AddScrollParentChain(std::vector<LayerType*>* out,
1327 const LayerType& parent,
1328 LayerType* layer) {
1329 // At a high level, this function walks up the chain of scroll parents
1330 // recursively, and once we reach the end of the chain, we add the child
1331 // of |parent| containing each scroll ancestor as we unwind. The result is
1332 // an ordering of parent's children that ensures that scroll parents are
1333 // visited before their descendants.
1334 // Take for example this layer tree:
1336 // + stacking_context
1337 // + scroll_child (1)
1338 // + scroll_parent_graphics_layer (*)
1339 // | + scroll_parent_scrolling_layer
1340 // | + scroll_parent_scrolling_content_layer (2)
1341 // + scroll_grandparent_graphics_layer (**)
1342 // + scroll_grandparent_scrolling_layer
1343 // + scroll_grandparent_scrolling_content_layer (3)
1345 // The scroll child is (1), its scroll parent is (2) and its scroll
1346 // grandparent is (3). Note, this doesn't mean that (2)'s scroll parent is
1347 // (3), it means that (*)'s scroll parent is (3). We don't want our list to
1348 // look like [ (3), (2), (1) ], even though that does have the ancestor chain
1349 // in the right order. Instead, we want [ (**), (*), (1) ]. That is, only want
1350 // (1)'s siblings in the list, but we want them to appear in such an order
1351 // that the scroll ancestors get visited in the correct order.
1353 // So our first task at this step of the recursion is to determine the layer
1354 // that we will potentionally add to the list. That is, the child of parent
1355 // containing |layer|.
1356 LayerType* child = GetChildContainingLayer(parent, layer);
1357 if (child->draw_properties().sorted_for_recursion)
1358 return;
1360 if (LayerType* scroll_parent = child->scroll_parent())
1361 AddScrollParentChain(out, parent, scroll_parent);
1363 out->push_back(child);
1364 child->draw_properties().sorted_for_recursion = true;
1367 template <typename LayerType>
1368 static bool SortChildrenForRecursion(std::vector<LayerType*>* out,
1369 const LayerType& parent) {
1370 out->reserve(parent.children().size());
1371 bool order_changed = false;
1372 for (size_t i = 0; i < parent.children().size(); ++i) {
1373 LayerType* current =
1374 LayerTreeHostCommon::get_layer_as_raw_ptr(parent.children(), i);
1376 if (current->draw_properties().sorted_for_recursion) {
1377 order_changed = true;
1378 continue;
1381 AddScrollParentChain(out, parent, current);
1384 DCHECK_EQ(parent.children().size(), out->size());
1385 return order_changed;
1388 template <typename LayerType>
1389 static void GetNewDescendantsStartIndexAndCount(LayerType* layer,
1390 size_t* start_index,
1391 size_t* count) {
1392 *start_index = layer->draw_properties().index_of_first_descendants_addition;
1393 *count = layer->draw_properties().num_descendants_added;
1396 template <typename LayerType>
1397 static void GetNewRenderSurfacesStartIndexAndCount(LayerType* layer,
1398 size_t* start_index,
1399 size_t* count) {
1400 *start_index = layer->draw_properties()
1401 .index_of_first_render_surface_layer_list_addition;
1402 *count = layer->draw_properties().num_render_surfaces_added;
1405 // We need to extract a list from the the two flavors of RenderSurfaceListType
1406 // for use in the sorting function below.
1407 static LayerList* GetLayerListForSorting(RenderSurfaceLayerList* rsll) {
1408 return &rsll->AsLayerList();
1411 static LayerImplList* GetLayerListForSorting(LayerImplList* layer_list) {
1412 return layer_list;
1415 static inline gfx::Vector2d BoundsDelta(Layer* layer) {
1416 return gfx::Vector2d();
1419 static inline gfx::Vector2d BoundsDelta(LayerImpl* layer) {
1420 return gfx::ToCeiledVector2d(layer->bounds_delta());
1423 template <typename LayerType, typename GetIndexAndCountType>
1424 static void SortLayerListContributions(
1425 const LayerType& parent,
1426 typename LayerType::LayerListType* unsorted,
1427 size_t start_index_for_all_contributions,
1428 GetIndexAndCountType get_index_and_count) {
1429 typename LayerType::LayerListType buffer;
1430 for (size_t i = 0; i < parent.children().size(); ++i) {
1431 LayerType* child =
1432 LayerTreeHostCommon::get_layer_as_raw_ptr(parent.children(), i);
1434 size_t start_index = 0;
1435 size_t count = 0;
1436 get_index_and_count(child, &start_index, &count);
1437 for (size_t j = start_index; j < start_index + count; ++j)
1438 buffer.push_back(unsorted->at(j));
1441 DCHECK_EQ(buffer.size(),
1442 unsorted->size() - start_index_for_all_contributions);
1444 for (size_t i = 0; i < buffer.size(); ++i)
1445 (*unsorted)[i + start_index_for_all_contributions] = buffer[i];
1448 // Recursively walks the layer tree starting at the given node and computes all
1449 // the necessary transformations, clip rects, render surfaces, etc.
1450 template <typename LayerType>
1451 static void CalculateDrawPropertiesInternal(
1452 LayerType* layer,
1453 const SubtreeGlobals<LayerType>& globals,
1454 const DataForRecursion<LayerType>& data_from_ancestor,
1455 typename LayerType::RenderSurfaceListType* render_surface_layer_list,
1456 typename LayerType::LayerListType* layer_list,
1457 std::vector<AccumulatedSurfaceState<LayerType>>* accumulated_surface_state,
1458 int current_render_surface_layer_list_id) {
1459 // This function computes the new matrix transformations recursively for this
1460 // layer and all its descendants. It also computes the appropriate render
1461 // surfaces.
1462 // Some important points to remember:
1464 // 0. Here, transforms are notated in Matrix x Vector order, and in words we
1465 // describe what the transform does from left to right.
1467 // 1. In our terminology, the "layer origin" refers to the top-left corner of
1468 // a layer, and the positive Y-axis points downwards. This interpretation is
1469 // valid because the orthographic projection applied at draw time flips the Y
1470 // axis appropriately.
1472 // 2. The anchor point, when given as a PointF object, is specified in "unit
1473 // layer space", where the bounds of the layer map to [0, 1]. However, as a
1474 // Transform object, the transform to the anchor point is specified in "layer
1475 // space", where the bounds of the layer map to [bounds.width(),
1476 // bounds.height()].
1478 // 3. Definition of various transforms used:
1479 // M[parent] is the parent matrix, with respect to the nearest render
1480 // surface, passed down recursively.
1482 // M[root] is the full hierarchy, with respect to the root, passed down
1483 // recursively.
1485 // Tr[origin] is the translation matrix from the parent's origin to
1486 // this layer's origin.
1488 // Tr[origin2anchor] is the translation from the layer's origin to its
1489 // anchor point
1491 // Tr[origin2center] is the translation from the layer's origin to its
1492 // center
1494 // M[layer] is the layer's matrix (applied at the anchor point)
1496 // S[layer2content] is the ratio of a layer's content_bounds() to its
1497 // Bounds().
1499 // Some composite transforms can help in understanding the sequence of
1500 // transforms:
1501 // composite_layer_transform = Tr[origin2anchor] * M[layer] *
1502 // Tr[origin2anchor].inverse()
1504 // 4. When a layer (or render surface) is drawn, it is drawn into a "target
1505 // render surface". Therefore the draw transform does not necessarily
1506 // transform from screen space to local layer space. Instead, the draw
1507 // transform is the transform between the "target render surface space" and
1508 // local layer space. Note that render surfaces, except for the root, also
1509 // draw themselves into a different target render surface, and so their draw
1510 // transform and origin transforms are also described with respect to the
1511 // target.
1513 // Using these definitions, then:
1515 // The draw transform for the layer is:
1516 // M[draw] = M[parent] * Tr[origin] * composite_layer_transform *
1517 // S[layer2content] = M[parent] * Tr[layer->position() + anchor] *
1518 // M[layer] * Tr[anchor2origin] * S[layer2content]
1520 // Interpreting the math left-to-right, this transforms from the
1521 // layer's render surface to the origin of the layer in content space.
1523 // The screen space transform is:
1524 // M[screenspace] = M[root] * Tr[origin] * composite_layer_transform *
1525 // S[layer2content]
1526 // = M[root] * Tr[layer->position() + anchor] * M[layer]
1527 // * Tr[anchor2origin] * S[layer2content]
1529 // Interpreting the math left-to-right, this transforms from the root
1530 // render surface's content space to the origin of the layer in content
1531 // space.
1533 // The transform hierarchy that is passed on to children (i.e. the child's
1534 // parent_matrix) is:
1535 // M[parent]_for_child = M[parent] * Tr[origin] *
1536 // composite_layer_transform
1537 // = M[parent] * Tr[layer->position() + anchor] *
1538 // M[layer] * Tr[anchor2origin]
1540 // and a similar matrix for the full hierarchy with respect to the
1541 // root.
1543 // Finally, note that the final matrix used by the shader for the layer is P *
1544 // M[draw] * S . This final product is computed in drawTexturedQuad(), where:
1545 // P is the projection matrix
1546 // S is the scale adjustment (to scale up a canonical quad to the
1547 // layer's size)
1549 // When a render surface has a replica layer, that layer's transform is used
1550 // to draw a second copy of the surface. gfx::Transforms named here are
1551 // relative to the surface, unless they specify they are relative to the
1552 // replica layer.
1554 // We will denote a scale by device scale S[deviceScale]
1556 // The render surface draw transform to its target surface origin is:
1557 // M[surfaceDraw] = M[owningLayer->Draw]
1559 // The render surface origin transform to its the root (screen space) origin
1560 // is:
1561 // M[surface2root] = M[owningLayer->screenspace] *
1562 // S[deviceScale].inverse()
1564 // The replica draw transform to its target surface origin is:
1565 // M[replicaDraw] = S[deviceScale] * M[surfaceDraw] *
1566 // Tr[replica->position() + replica->anchor()] * Tr[replica] *
1567 // Tr[origin2anchor].inverse() * S[contents_scale].inverse()
1569 // The replica draw transform to the root (screen space) origin is:
1570 // M[replica2root] = M[surface2root] * Tr[replica->position()] *
1571 // Tr[replica] * Tr[origin2anchor].inverse()
1574 // It makes no sense to have a non-unit page_scale_factor without specifying
1575 // which layer roots the subtree the scale is applied to.
1576 DCHECK(globals.page_scale_application_layer ||
1577 (globals.page_scale_factor == 1.f));
1579 CHECK(!layer->draw_properties().visited);
1580 layer->draw_properties().visited = true;
1582 DataForRecursion<LayerType> data_for_children;
1583 typename LayerType::RenderSurfaceType*
1584 nearest_occlusion_immune_ancestor_surface =
1585 data_from_ancestor.nearest_occlusion_immune_ancestor_surface;
1586 data_for_children.in_subtree_of_page_scale_application_layer =
1587 data_from_ancestor.in_subtree_of_page_scale_application_layer;
1588 data_for_children.subtree_can_use_lcd_text =
1589 data_from_ancestor.subtree_can_use_lcd_text;
1591 // Layers that are marked as hidden will hide themselves and their subtree.
1592 // Exception: Layers with copy requests, whether hidden or not, must be drawn
1593 // anyway. In this case, we will inform their subtree they are visible to get
1594 // the right results.
1595 const bool layer_is_visible =
1596 data_from_ancestor.subtree_is_visible_from_ancestor &&
1597 !layer->hide_layer_and_subtree();
1598 const bool layer_is_drawn = layer_is_visible || layer->HasCopyRequest();
1600 // The root layer cannot skip CalcDrawProperties.
1601 if (!IsRootLayer(layer) && SubtreeShouldBeSkipped(layer, layer_is_drawn)) {
1602 if (layer->render_surface())
1603 layer->ClearRenderSurfaceLayerList();
1604 layer->draw_properties().render_target = nullptr;
1605 return;
1608 // We need to circumvent the normal recursive flow of information for clip
1609 // children (they don't inherit their direct ancestor's clip information).
1610 // This is unfortunate, and would be unnecessary if we were to formally
1611 // separate the clipping hierarchy from the layer hierarchy.
1612 bool ancestor_clips_subtree = data_from_ancestor.ancestor_clips_subtree;
1613 gfx::Rect ancestor_clip_rect_in_target_space =
1614 data_from_ancestor.clip_rect_in_target_space;
1616 // Update our clipping state. If we have a clip parent we will need to pull
1617 // from the clip state cache rather than using the clip state passed from our
1618 // immediate ancestor.
1619 UpdateClipRectsForClipChild<LayerType>(
1620 layer, &ancestor_clip_rect_in_target_space, &ancestor_clips_subtree);
1622 // As this function proceeds, these are the properties for the current
1623 // layer that actually get computed. To avoid unnecessary copies
1624 // (particularly for matrices), we do computations directly on these values
1625 // when possible.
1626 DrawProperties<LayerType>& layer_draw_properties = layer->draw_properties();
1628 gfx::Rect clip_rect_in_target_space;
1629 bool layer_or_ancestor_clips_descendants = false;
1631 // This value is cached on the stack so that we don't have to inverse-project
1632 // the surface's clip rect redundantly for every layer. This value is the
1633 // same as the target surface's clip rect, except that instead of being
1634 // described in the target surface's target's space, it is described in the
1635 // current render target's space.
1636 gfx::Rect clip_rect_of_target_surface_in_target_space;
1638 float accumulated_draw_opacity = layer->opacity();
1639 bool animating_opacity_to_target = layer->OpacityIsAnimating();
1640 bool animating_opacity_to_screen = animating_opacity_to_target;
1641 if (layer->parent()) {
1642 accumulated_draw_opacity *= layer->parent()->draw_opacity();
1643 animating_opacity_to_target |= layer->parent()->draw_opacity_is_animating();
1644 animating_opacity_to_screen |=
1645 layer->parent()->screen_space_opacity_is_animating();
1648 bool animating_transform_to_target = layer->TransformIsAnimating();
1649 bool animating_transform_to_screen = animating_transform_to_target;
1650 if (layer->parent()) {
1651 animating_transform_to_target |=
1652 layer->parent()->draw_transform_is_animating();
1653 animating_transform_to_screen |=
1654 layer->parent()->screen_space_transform_is_animating();
1656 gfx::Point3F transform_origin = layer->transform_origin();
1657 gfx::ScrollOffset scroll_offset = GetEffectiveCurrentScrollOffset(layer);
1658 gfx::PointF position =
1659 layer->position() - ScrollOffsetToVector2dF(scroll_offset);
1660 gfx::Transform combined_transform = data_from_ancestor.parent_matrix;
1661 if (!layer->transform().IsIdentity()) {
1662 // LT = Tr[origin] * Tr[origin2transformOrigin]
1663 combined_transform.Translate3d(position.x() + transform_origin.x(),
1664 position.y() + transform_origin.y(),
1665 transform_origin.z());
1666 // LT = Tr[origin] * Tr[origin2origin] * M[layer]
1667 combined_transform.PreconcatTransform(layer->transform());
1668 // LT = Tr[origin] * Tr[origin2origin] * M[layer] *
1669 // Tr[transformOrigin2origin]
1670 combined_transform.Translate3d(
1671 -transform_origin.x(), -transform_origin.y(), -transform_origin.z());
1672 } else {
1673 combined_transform.Translate(position.x(), position.y());
1676 gfx::Vector2dF effective_scroll_delta = GetEffectiveScrollDelta(layer);
1677 if (!animating_transform_to_target && layer->scrollable() &&
1678 combined_transform.IsScaleOrTranslation()) {
1679 // Align the scrollable layer's position to screen space pixels to avoid
1680 // blurriness. To avoid side-effects, do this only if the transform is
1681 // simple.
1682 gfx::Vector2dF previous_translation = combined_transform.To2dTranslation();
1683 combined_transform.RoundTranslationComponents();
1684 gfx::Vector2dF current_translation = combined_transform.To2dTranslation();
1686 // This rounding changes the scroll delta, and so must be included
1687 // in the scroll compensation matrix. The scaling converts from physical
1688 // coordinates to the scroll delta's CSS coordinates (using the parent
1689 // matrix instead of combined transform since scrolling is applied before
1690 // the layer's transform). For example, if we have a total scale factor of
1691 // 3.0, then 1 physical pixel is only 1/3 of a CSS pixel.
1692 gfx::Vector2dF parent_scales = MathUtil::ComputeTransform2dScaleComponents(
1693 data_from_ancestor.parent_matrix, 1.f);
1694 effective_scroll_delta -=
1695 gfx::ScaleVector2d(current_translation - previous_translation,
1696 1.f / parent_scales.x(),
1697 1.f / parent_scales.y());
1700 // Apply adjustment from position constraints.
1701 ApplyPositionAdjustment(layer, data_from_ancestor.fixed_container,
1702 data_from_ancestor.scroll_compensation_matrix, &combined_transform);
1704 bool combined_is_animating_scale = false;
1705 float combined_maximum_animation_contents_scale = 0.f;
1706 if (globals.can_adjust_raster_scales) {
1707 CalculateAnimationContentsScale(
1708 layer,
1709 data_from_ancestor.ancestor_is_animating_scale,
1710 data_from_ancestor.maximum_animation_contents_scale,
1711 data_from_ancestor.parent_matrix,
1712 combined_transform,
1713 &combined_is_animating_scale,
1714 &combined_maximum_animation_contents_scale);
1716 data_for_children.ancestor_is_animating_scale = combined_is_animating_scale;
1717 data_for_children.maximum_animation_contents_scale =
1718 combined_maximum_animation_contents_scale;
1720 // Compute the 2d scale components of the transform hierarchy up to the target
1721 // surface. From there, we can decide on a contents scale for the layer.
1722 float layer_scale_factors = globals.device_scale_factor;
1723 if (data_from_ancestor.in_subtree_of_page_scale_application_layer)
1724 layer_scale_factors *= globals.page_scale_factor;
1725 gfx::Vector2dF combined_transform_scales =
1726 MathUtil::ComputeTransform2dScaleComponents(
1727 combined_transform,
1728 layer_scale_factors);
1730 float ideal_contents_scale =
1731 globals.can_adjust_raster_scales
1732 ? std::max(combined_transform_scales.x(),
1733 combined_transform_scales.y())
1734 : layer_scale_factors;
1735 UpdateLayerContentsScale(
1736 layer,
1737 globals.can_adjust_raster_scales,
1738 ideal_contents_scale,
1739 globals.device_scale_factor,
1740 data_from_ancestor.in_subtree_of_page_scale_application_layer
1741 ? globals.page_scale_factor
1742 : 1.f,
1743 animating_transform_to_screen);
1745 UpdateLayerScaleDrawProperties(
1746 layer,
1747 ideal_contents_scale,
1748 combined_maximum_animation_contents_scale,
1749 data_from_ancestor.in_subtree_of_page_scale_application_layer
1750 ? globals.page_scale_factor
1751 : 1.f,
1752 globals.device_scale_factor);
1754 LayerType* mask_layer = layer->mask_layer();
1755 if (mask_layer) {
1756 UpdateLayerScaleDrawProperties(
1757 mask_layer,
1758 ideal_contents_scale,
1759 combined_maximum_animation_contents_scale,
1760 data_from_ancestor.in_subtree_of_page_scale_application_layer
1761 ? globals.page_scale_factor
1762 : 1.f,
1763 globals.device_scale_factor);
1766 LayerType* replica_mask_layer =
1767 layer->replica_layer() ? layer->replica_layer()->mask_layer() : NULL;
1768 if (replica_mask_layer) {
1769 UpdateLayerScaleDrawProperties(
1770 replica_mask_layer,
1771 ideal_contents_scale,
1772 combined_maximum_animation_contents_scale,
1773 data_from_ancestor.in_subtree_of_page_scale_application_layer
1774 ? globals.page_scale_factor
1775 : 1.f,
1776 globals.device_scale_factor);
1779 // The draw_transform that gets computed below is effectively the layer's
1780 // draw_transform, unless the layer itself creates a render_surface. In that
1781 // case, the render_surface re-parents the transforms.
1782 layer_draw_properties.target_space_transform = combined_transform;
1783 // M[draw] = M[parent] * LT * S[layer2content]
1784 layer_draw_properties.target_space_transform.Scale(
1785 SK_MScalar1 / layer->contents_scale_x(),
1786 SK_MScalar1 / layer->contents_scale_y());
1788 // The layer's screen_space_transform represents the transform between root
1789 // layer's "screen space" and local content space.
1790 layer_draw_properties.screen_space_transform =
1791 data_from_ancestor.full_hierarchy_matrix;
1792 layer_draw_properties.screen_space_transform.PreconcatTransform
1793 (layer_draw_properties.target_space_transform);
1795 // Adjusting text AA method during animation may cause repaints, which in-turn
1796 // causes jank.
1797 bool adjust_text_aa =
1798 !animating_opacity_to_screen && !animating_transform_to_screen;
1799 bool layer_can_use_lcd_text = true;
1800 bool subtree_can_use_lcd_text = true;
1801 if (!globals.layers_always_allowed_lcd_text) {
1802 // To avoid color fringing, LCD text should only be used on opaque layers
1803 // with just integral translation.
1804 subtree_can_use_lcd_text = data_from_ancestor.subtree_can_use_lcd_text &&
1805 accumulated_draw_opacity == 1.f &&
1806 layer_draw_properties.target_space_transform
1807 .IsIdentityOrIntegerTranslation();
1808 // Also disable LCD text locally for non-opaque content.
1809 layer_can_use_lcd_text = subtree_can_use_lcd_text &&
1810 layer->contents_opaque();
1813 // full_hierarchy_matrix is the matrix that transforms objects between screen
1814 // space (except projection matrix) and the most recent RenderSurfaceImpl's
1815 // space. next_hierarchy_matrix will only change if this layer uses a new
1816 // RenderSurfaceImpl, otherwise remains the same.
1817 data_for_children.full_hierarchy_matrix =
1818 data_from_ancestor.full_hierarchy_matrix;
1820 bool render_to_separate_surface =
1821 IsRootLayer(layer) ||
1822 (globals.can_render_to_separate_surface && layer->render_surface());
1824 if (render_to_separate_surface) {
1825 DCHECK(layer->render_surface());
1826 // Check back-face visibility before continuing with this surface and its
1827 // subtree
1828 if (!layer->double_sided() && TransformToParentIsKnown(layer) &&
1829 IsSurfaceBackFaceVisible(layer, combined_transform)) {
1830 layer->ClearRenderSurfaceLayerList();
1831 layer->draw_properties().render_target = nullptr;
1832 return;
1835 typename LayerType::RenderSurfaceType* render_surface =
1836 layer->render_surface();
1837 layer->ClearRenderSurfaceLayerList();
1839 layer_draw_properties.render_target = layer;
1840 if (IsRootLayer(layer)) {
1841 // The root layer's render surface size is predetermined and so the root
1842 // layer can't directly support non-identity transforms. It should just
1843 // forward top-level transforms to the rest of the tree.
1844 data_for_children.parent_matrix = combined_transform;
1846 // The root surface does not contribute to any other surface, it has no
1847 // target.
1848 layer->render_surface()->set_contributes_to_drawn_surface(false);
1849 } else {
1850 // The owning layer's draw transform has a scale from content to layer
1851 // space which we do not want; so here we use the combined_transform
1852 // instead of the draw_transform. However, we do need to add a different
1853 // scale factor that accounts for the surface's pixel dimensions.
1854 // Remove the combined_transform scale from the draw transform.
1855 gfx::Transform draw_transform = combined_transform;
1856 draw_transform.Scale(1.0 / combined_transform_scales.x(),
1857 1.0 / combined_transform_scales.y());
1858 render_surface->SetDrawTransform(draw_transform);
1860 // The owning layer's transform was re-parented by the surface, so the
1861 // layer's new draw_transform only needs to scale the layer to surface
1862 // space.
1863 layer_draw_properties.target_space_transform.MakeIdentity();
1864 layer_draw_properties.target_space_transform.Scale(
1865 combined_transform_scales.x() / layer->contents_scale_x(),
1866 combined_transform_scales.y() / layer->contents_scale_y());
1868 // Inside the surface's subtree, we scale everything to the owning layer's
1869 // scale. The sublayer matrix transforms layer rects into target surface
1870 // content space. Conceptually, all layers in the subtree inherit the
1871 // scale at the point of the render surface in the transform hierarchy,
1872 // but we apply it explicitly to the owning layer and the remainder of the
1873 // subtree independently.
1874 DCHECK(data_for_children.parent_matrix.IsIdentity());
1875 data_for_children.parent_matrix.Scale(combined_transform_scales.x(),
1876 combined_transform_scales.y());
1878 // Even if the |layer_is_drawn|, it only contributes to a drawn surface
1879 // when the |layer_is_visible|.
1880 layer->render_surface()->set_contributes_to_drawn_surface(
1881 layer_is_visible);
1884 // The opacity value is moved from the layer to its surface, so that the
1885 // entire subtree properly inherits opacity.
1886 render_surface->SetDrawOpacity(accumulated_draw_opacity);
1887 render_surface->SetDrawOpacityIsAnimating(animating_opacity_to_target);
1888 animating_opacity_to_target = false;
1889 layer_draw_properties.opacity = 1.f;
1890 layer_draw_properties.blend_mode = SkXfermode::kSrcOver_Mode;
1891 layer_draw_properties.opacity_is_animating = animating_opacity_to_target;
1892 layer_draw_properties.screen_space_opacity_is_animating =
1893 animating_opacity_to_screen;
1895 render_surface->SetTargetSurfaceTransformsAreAnimating(
1896 animating_transform_to_target);
1897 render_surface->SetScreenSpaceTransformsAreAnimating(
1898 animating_transform_to_screen);
1899 animating_transform_to_target = false;
1900 layer_draw_properties.target_space_transform_is_animating =
1901 animating_transform_to_target;
1902 layer_draw_properties.screen_space_transform_is_animating =
1903 animating_transform_to_screen;
1905 // Update the aggregate hierarchy matrix to include the transform of the
1906 // newly created RenderSurfaceImpl.
1907 data_for_children.full_hierarchy_matrix.PreconcatTransform(
1908 render_surface->draw_transform());
1910 // A render surface inherently acts as a flattening point for the content of
1911 // its descendants.
1912 data_for_children.full_hierarchy_matrix.FlattenTo2d();
1914 if (layer->mask_layer()) {
1915 DrawProperties<LayerType>& mask_layer_draw_properties =
1916 layer->mask_layer()->draw_properties();
1917 mask_layer_draw_properties.render_target = layer;
1918 mask_layer_draw_properties.visible_content_rect =
1919 gfx::Rect(layer->content_bounds());
1922 if (layer->replica_layer() && layer->replica_layer()->mask_layer()) {
1923 DrawProperties<LayerType>& replica_mask_draw_properties =
1924 layer->replica_layer()->mask_layer()->draw_properties();
1925 replica_mask_draw_properties.render_target = layer;
1926 replica_mask_draw_properties.visible_content_rect =
1927 gfx::Rect(layer->content_bounds());
1930 // Ignore occlusion from outside the surface when surface contents need to
1931 // be fully drawn. Layers with copy-request need to be complete.
1932 // We could be smarter about layers with replica and exclude regions
1933 // where both layer and the replica are occluded, but this seems like an
1934 // overkill. The same is true for layers with filters that move pixels.
1935 // TODO(senorblanco): make this smarter for the SkImageFilter case (check
1936 // for pixel-moving filters)
1937 if (layer->HasCopyRequest() ||
1938 layer->has_replica() ||
1939 layer->filters().HasReferenceFilter() ||
1940 layer->filters().HasFilterThatMovesPixels()) {
1941 nearest_occlusion_immune_ancestor_surface = render_surface;
1943 render_surface->SetNearestOcclusionImmuneAncestor(
1944 nearest_occlusion_immune_ancestor_surface);
1946 layer_or_ancestor_clips_descendants = false;
1947 bool subtree_is_clipped_by_surface_bounds = false;
1948 if (ancestor_clips_subtree) {
1949 // It may be the layer or the surface doing the clipping of the subtree,
1950 // but in either case, we'll be clipping to the projected clip rect of our
1951 // ancestor.
1952 gfx::Transform inverse_surface_draw_transform(
1953 gfx::Transform::kSkipInitialization);
1954 if (!render_surface->draw_transform().GetInverse(
1955 &inverse_surface_draw_transform)) {
1956 // TODO(shawnsingh): Either we need to handle uninvertible transforms
1957 // here, or DCHECK that the transform is invertible.
1960 gfx::Rect surface_clip_rect_in_target_space = gfx::IntersectRects(
1961 data_from_ancestor.clip_rect_of_target_surface_in_target_space,
1962 ancestor_clip_rect_in_target_space);
1963 gfx::Rect projected_surface_rect = MathUtil::ProjectEnclosingClippedRect(
1964 inverse_surface_draw_transform, surface_clip_rect_in_target_space);
1966 if (layer_draw_properties.num_unclipped_descendants > 0) {
1967 // If we have unclipped descendants, we cannot count on the render
1968 // surface's bounds clipping our subtree: the unclipped descendants
1969 // could cause us to expand our bounds. In this case, we must rely on
1970 // layer clipping for correctess. NB: since we can only encounter
1971 // translations between a clip child and its clip parent, clipping is
1972 // guaranteed to be exact in this case.
1973 layer_or_ancestor_clips_descendants = true;
1974 clip_rect_in_target_space = projected_surface_rect;
1975 } else {
1976 // The new render_surface here will correctly clip the entire subtree.
1977 // So, we do not need to continue propagating the clipping state further
1978 // down the tree. This way, we can avoid transforming clip rects from
1979 // ancestor target surface space to current target surface space that
1980 // could cause more w < 0 headaches. The render surface clip rect is
1981 // expressed in the space where this surface draws, i.e. the same space
1982 // as clip_rect_from_ancestor_in_ancestor_target_space.
1983 render_surface->SetClipRect(ancestor_clip_rect_in_target_space);
1984 clip_rect_of_target_surface_in_target_space = projected_surface_rect;
1985 subtree_is_clipped_by_surface_bounds = true;
1989 DCHECK(layer->render_surface());
1990 DCHECK(!layer->parent() || layer->parent()->render_target() ==
1991 accumulated_surface_state->back().render_target);
1993 accumulated_surface_state->push_back(
1994 AccumulatedSurfaceState<LayerType>(layer));
1996 render_surface->SetIsClipped(subtree_is_clipped_by_surface_bounds);
1997 if (!subtree_is_clipped_by_surface_bounds) {
1998 render_surface->SetClipRect(gfx::Rect());
1999 clip_rect_of_target_surface_in_target_space =
2000 data_from_ancestor.clip_rect_of_target_surface_in_target_space;
2003 // If the new render surface is drawn translucent or with a non-integral
2004 // translation then the subtree that gets drawn on this render surface
2005 // cannot use LCD text.
2006 data_for_children.subtree_can_use_lcd_text = subtree_can_use_lcd_text;
2008 render_surface_layer_list->push_back(layer);
2009 } else {
2010 DCHECK(layer->parent());
2012 // Note: layer_draw_properties.target_space_transform is computed above,
2013 // before this if-else statement.
2014 layer_draw_properties.target_space_transform_is_animating =
2015 animating_transform_to_target;
2016 layer_draw_properties.screen_space_transform_is_animating =
2017 animating_transform_to_screen;
2018 layer_draw_properties.opacity = accumulated_draw_opacity;
2019 layer_draw_properties.blend_mode = layer->blend_mode();
2020 layer_draw_properties.opacity_is_animating = animating_opacity_to_target;
2021 layer_draw_properties.screen_space_opacity_is_animating =
2022 animating_opacity_to_screen;
2023 data_for_children.parent_matrix = combined_transform;
2025 // Layers without render_surfaces directly inherit the ancestor's clip
2026 // status.
2027 layer_or_ancestor_clips_descendants = ancestor_clips_subtree;
2028 if (ancestor_clips_subtree) {
2029 clip_rect_in_target_space =
2030 ancestor_clip_rect_in_target_space;
2033 // The surface's cached clip rect value propagates regardless of what
2034 // clipping goes on between layers here.
2035 clip_rect_of_target_surface_in_target_space =
2036 data_from_ancestor.clip_rect_of_target_surface_in_target_space;
2038 // Layers that are not their own render_target will render into the target
2039 // of their nearest ancestor.
2040 layer_draw_properties.render_target = layer->parent()->render_target();
2043 if (adjust_text_aa)
2044 layer_draw_properties.can_use_lcd_text = layer_can_use_lcd_text;
2046 gfx::Size content_size_affected_by_delta(layer->content_bounds());
2048 // Non-zero BoundsDelta imply the contents_scale of 1.0
2049 // because BoundsDela is only set on Android where
2050 // ContentScalingLayer is never used.
2051 DCHECK_IMPLIES(!BoundsDelta(layer).IsZero(),
2052 (layer->contents_scale_x() == 1.0 &&
2053 layer->contents_scale_y() == 1.0));
2055 // Thus we can omit contents scale in the following calculation.
2056 gfx::Vector2d bounds_delta = BoundsDelta(layer);
2057 content_size_affected_by_delta.Enlarge(bounds_delta.x(), bounds_delta.y());
2059 gfx::Rect rect_in_target_space = MathUtil::MapEnclosingClippedRect(
2060 layer->draw_transform(),
2061 gfx::Rect(content_size_affected_by_delta));
2063 if (LayerClipsSubtree(layer)) {
2064 layer_or_ancestor_clips_descendants = true;
2065 if (ancestor_clips_subtree && !render_to_separate_surface) {
2066 // A layer without render surface shares the same target as its ancestor.
2067 clip_rect_in_target_space =
2068 ancestor_clip_rect_in_target_space;
2069 clip_rect_in_target_space.Intersect(rect_in_target_space);
2070 } else {
2071 clip_rect_in_target_space = rect_in_target_space;
2075 // Tell the layer the rect that it's clipped by. In theory we could use a
2076 // tighter clip rect here (drawable_content_rect), but that actually does not
2077 // reduce how much would be drawn, and instead it would create unnecessary
2078 // changes to scissor state affecting GPU performance. Our clip information
2079 // is used in the recursion below, so we must set it beforehand.
2080 layer_draw_properties.is_clipped = layer_or_ancestor_clips_descendants;
2081 if (layer_or_ancestor_clips_descendants) {
2082 layer_draw_properties.clip_rect = clip_rect_in_target_space;
2083 } else {
2084 // Initialize the clip rect to a safe value that will not clip the
2085 // layer, just in case clipping is still accidentally used.
2086 layer_draw_properties.clip_rect = rect_in_target_space;
2089 typename LayerType::LayerListType& descendants =
2090 (render_to_separate_surface ? layer->render_surface()->layer_list()
2091 : *layer_list);
2093 // Any layers that are appended after this point are in the layer's subtree
2094 // and should be included in the sorting process.
2095 size_t sorting_start_index = descendants.size();
2097 if (!LayerShouldBeSkipped(layer, layer_is_drawn)) {
2098 MarkLayerWithRenderSurfaceLayerListId(layer,
2099 current_render_surface_layer_list_id);
2100 descendants.push_back(layer);
2103 // Any layers that are appended after this point may need to be sorted if we
2104 // visit the children out of order.
2105 size_t render_surface_layer_list_child_sorting_start_index =
2106 render_surface_layer_list->size();
2107 size_t layer_list_child_sorting_start_index = descendants.size();
2109 if (!layer->children().empty()) {
2110 if (layer == globals.page_scale_application_layer) {
2111 data_for_children.parent_matrix.Scale(
2112 globals.page_scale_factor,
2113 globals.page_scale_factor);
2114 data_for_children.in_subtree_of_page_scale_application_layer = true;
2116 if (layer == globals.elastic_overscroll_application_layer) {
2117 data_for_children.parent_matrix.Translate(
2118 -globals.elastic_overscroll.x(), -globals.elastic_overscroll.y());
2121 // Flatten to 2D if the layer doesn't preserve 3D.
2122 if (layer->should_flatten_transform())
2123 data_for_children.parent_matrix.FlattenTo2d();
2125 data_for_children.scroll_compensation_matrix =
2126 ComputeScrollCompensationMatrixForChildren(
2127 layer,
2128 data_from_ancestor.parent_matrix,
2129 data_from_ancestor.scroll_compensation_matrix,
2130 effective_scroll_delta);
2131 data_for_children.fixed_container =
2132 layer->IsContainerForFixedPositionLayers() ?
2133 layer : data_from_ancestor.fixed_container;
2135 data_for_children.clip_rect_in_target_space = clip_rect_in_target_space;
2136 data_for_children.clip_rect_of_target_surface_in_target_space =
2137 clip_rect_of_target_surface_in_target_space;
2138 data_for_children.ancestor_clips_subtree =
2139 layer_or_ancestor_clips_descendants;
2140 data_for_children.nearest_occlusion_immune_ancestor_surface =
2141 nearest_occlusion_immune_ancestor_surface;
2142 data_for_children.subtree_is_visible_from_ancestor = layer_is_drawn;
2145 std::vector<LayerType*> sorted_children;
2146 bool child_order_changed = false;
2147 if (layer_draw_properties.has_child_with_a_scroll_parent)
2148 child_order_changed = SortChildrenForRecursion(&sorted_children, *layer);
2150 for (size_t i = 0; i < layer->children().size(); ++i) {
2151 // If one of layer's children has a scroll parent, then we may have to
2152 // visit the children out of order. The new order is stored in
2153 // sorted_children. Otherwise, we'll grab the child directly from the
2154 // layer's list of children.
2155 LayerType* child =
2156 layer_draw_properties.has_child_with_a_scroll_parent
2157 ? sorted_children[i]
2158 : LayerTreeHostCommon::get_layer_as_raw_ptr(layer->children(), i);
2160 child->draw_properties().index_of_first_descendants_addition =
2161 descendants.size();
2162 child->draw_properties().index_of_first_render_surface_layer_list_addition =
2163 render_surface_layer_list->size();
2165 CalculateDrawPropertiesInternal<LayerType>(
2166 child,
2167 globals,
2168 data_for_children,
2169 render_surface_layer_list,
2170 &descendants,
2171 accumulated_surface_state,
2172 current_render_surface_layer_list_id);
2173 // If the child is its own render target, then it has a render surface.
2174 if (child->render_target() == child &&
2175 !child->render_surface()->layer_list().empty() &&
2176 !child->render_surface()->content_rect().IsEmpty()) {
2177 // This child will contribute its render surface, which means
2178 // we need to mark just the mask layer (and replica mask layer)
2179 // with the id.
2180 MarkMasksWithRenderSurfaceLayerListId(
2181 child, current_render_surface_layer_list_id);
2182 descendants.push_back(child);
2185 child->draw_properties().num_descendants_added =
2186 descendants.size() -
2187 child->draw_properties().index_of_first_descendants_addition;
2188 child->draw_properties().num_render_surfaces_added =
2189 render_surface_layer_list->size() -
2190 child->draw_properties()
2191 .index_of_first_render_surface_layer_list_addition;
2192 layer_draw_properties.layer_or_descendant_is_drawn |=
2193 child->draw_properties().layer_or_descendant_is_drawn;
2196 // Add the unsorted layer list contributions, if necessary.
2197 if (child_order_changed) {
2198 SortLayerListContributions(
2199 *layer,
2200 GetLayerListForSorting(render_surface_layer_list),
2201 render_surface_layer_list_child_sorting_start_index,
2202 &GetNewRenderSurfacesStartIndexAndCount<LayerType>);
2204 SortLayerListContributions(
2205 *layer,
2206 &descendants,
2207 layer_list_child_sorting_start_index,
2208 &GetNewDescendantsStartIndexAndCount<LayerType>);
2211 // Compute the total drawable_content_rect for this subtree (the rect is in
2212 // target surface space).
2213 gfx::Rect local_drawable_content_rect_of_subtree =
2214 accumulated_surface_state->back().drawable_content_rect;
2215 if (render_to_separate_surface) {
2216 DCHECK(accumulated_surface_state->back().render_target == layer);
2217 accumulated_surface_state->pop_back();
2220 if (render_to_separate_surface && !IsRootLayer(layer) &&
2221 layer->render_surface()->layer_list().empty()) {
2222 RemoveSurfaceForEarlyExit(layer, render_surface_layer_list);
2223 return;
2226 // Compute the layer's drawable content rect (the rect is in target surface
2227 // space).
2228 layer_draw_properties.drawable_content_rect = rect_in_target_space;
2229 if (layer_or_ancestor_clips_descendants) {
2230 layer_draw_properties.drawable_content_rect.Intersect(
2231 clip_rect_in_target_space);
2233 if (layer->DrawsContent()) {
2234 local_drawable_content_rect_of_subtree.Union(
2235 layer_draw_properties.drawable_content_rect);
2238 // Compute the layer's visible content rect (the rect is in content space).
2239 layer_draw_properties.visible_content_rect = CalculateVisibleContentRect(
2240 layer, clip_rect_of_target_surface_in_target_space, rect_in_target_space);
2242 // Compute the remaining properties for the render surface, if the layer has
2243 // one.
2244 if (IsRootLayer(layer)) {
2245 // The root layer's surface's content_rect is always the entire viewport.
2246 DCHECK(render_to_separate_surface);
2247 layer->render_surface()->SetContentRect(
2248 ancestor_clip_rect_in_target_space);
2249 } else if (render_to_separate_surface) {
2250 typename LayerType::RenderSurfaceType* render_surface =
2251 layer->render_surface();
2252 gfx::Rect clipped_content_rect = local_drawable_content_rect_of_subtree;
2254 // Don't clip if the layer is reflected as the reflection shouldn't be
2255 // clipped. If the layer is animating, then the surface's transform to
2256 // its target is not known on the main thread, and we should not use it
2257 // to clip.
2258 if (!layer->replica_layer() && TransformToParentIsKnown(layer)) {
2259 // Note, it is correct to use data_from_ancestor.ancestor_clips_subtree
2260 // here, because we are looking at this layer's render_surface, not the
2261 // layer itself.
2262 if (render_surface->is_clipped() && !clipped_content_rect.IsEmpty()) {
2263 gfx::Rect surface_clip_rect = LayerTreeHostCommon::CalculateVisibleRect(
2264 render_surface->clip_rect(),
2265 clipped_content_rect,
2266 render_surface->draw_transform());
2267 clipped_content_rect.Intersect(surface_clip_rect);
2271 // The RenderSurfaceImpl backing texture cannot exceed the maximum supported
2272 // texture size.
2273 clipped_content_rect.set_width(
2274 std::min(clipped_content_rect.width(), globals.max_texture_size));
2275 clipped_content_rect.set_height(
2276 std::min(clipped_content_rect.height(), globals.max_texture_size));
2278 if (clipped_content_rect.IsEmpty()) {
2279 RemoveSurfaceForEarlyExit(layer, render_surface_layer_list);
2280 return;
2283 // Layers having a non-default blend mode will blend with the content
2284 // inside its parent's render target. This render target should be
2285 // either root_for_isolated_group, or the root of the layer tree.
2286 // Otherwise, this layer will use an incomplete backdrop, limited to its
2287 // render target and the blending result will be incorrect.
2288 DCHECK(layer->uses_default_blend_mode() || IsRootLayer(layer) ||
2289 !layer->parent()->render_target() ||
2290 IsRootLayer(layer->parent()->render_target()) ||
2291 layer->parent()->render_target()->is_root_for_isolated_group());
2293 render_surface->SetContentRect(clipped_content_rect);
2295 // The owning layer's screen_space_transform has a scale from content to
2296 // layer space which we need to undo and replace with a scale from the
2297 // surface's subtree into layer space.
2298 gfx::Transform screen_space_transform = layer->screen_space_transform();
2299 screen_space_transform.Scale(
2300 layer->contents_scale_x() / combined_transform_scales.x(),
2301 layer->contents_scale_y() / combined_transform_scales.y());
2302 render_surface->SetScreenSpaceTransform(screen_space_transform);
2304 if (layer->replica_layer()) {
2305 gfx::Transform surface_origin_to_replica_origin_transform;
2306 surface_origin_to_replica_origin_transform.Scale(
2307 combined_transform_scales.x(), combined_transform_scales.y());
2308 surface_origin_to_replica_origin_transform.Translate(
2309 layer->replica_layer()->position().x() +
2310 layer->replica_layer()->transform_origin().x(),
2311 layer->replica_layer()->position().y() +
2312 layer->replica_layer()->transform_origin().y());
2313 surface_origin_to_replica_origin_transform.PreconcatTransform(
2314 layer->replica_layer()->transform());
2315 surface_origin_to_replica_origin_transform.Translate(
2316 -layer->replica_layer()->transform_origin().x(),
2317 -layer->replica_layer()->transform_origin().y());
2318 surface_origin_to_replica_origin_transform.Scale(
2319 1.0 / combined_transform_scales.x(),
2320 1.0 / combined_transform_scales.y());
2322 // Compute the replica's "originTransform" that maps from the replica's
2323 // origin space to the target surface origin space.
2324 gfx::Transform replica_origin_transform =
2325 layer->render_surface()->draw_transform() *
2326 surface_origin_to_replica_origin_transform;
2327 render_surface->SetReplicaDrawTransform(replica_origin_transform);
2329 // Compute the replica's "screen_space_transform" that maps from the
2330 // replica's origin space to the screen's origin space.
2331 gfx::Transform replica_screen_space_transform =
2332 layer->render_surface()->screen_space_transform() *
2333 surface_origin_to_replica_origin_transform;
2334 render_surface->SetReplicaScreenSpaceTransform(
2335 replica_screen_space_transform);
2339 SavePaintPropertiesLayer(layer);
2341 // If neither this layer nor any of its children were added, early out.
2342 if (sorting_start_index == descendants.size()) {
2343 DCHECK(!render_to_separate_surface || IsRootLayer(layer));
2344 return;
2347 UpdateAccumulatedSurfaceState<LayerType>(
2348 layer, local_drawable_content_rect_of_subtree, accumulated_surface_state);
2350 if (layer->HasContributingDelegatedRenderPasses()) {
2351 layer->render_target()->render_surface()->
2352 AddContributingDelegatedRenderPassLayer(layer);
2354 } // NOLINT(readability/fn_size)
2356 template <typename LayerType, typename RenderSurfaceLayerListType>
2357 static void ProcessCalcDrawPropsInputs(
2358 const LayerTreeHostCommon::CalcDrawPropsInputs<LayerType,
2359 RenderSurfaceLayerListType>&
2360 inputs,
2361 SubtreeGlobals<LayerType>* globals,
2362 DataForRecursion<LayerType>* data_for_recursion) {
2363 DCHECK(inputs.root_layer);
2364 DCHECK(IsRootLayer(inputs.root_layer));
2365 DCHECK(inputs.render_surface_layer_list);
2367 gfx::Transform identity_matrix;
2369 // The root layer's render_surface should receive the device viewport as the
2370 // initial clip rect.
2371 gfx::Rect device_viewport_rect(inputs.device_viewport_size);
2373 gfx::Vector2dF device_transform_scale_components =
2374 MathUtil::ComputeTransform2dScaleComponents(inputs.device_transform, 1.f);
2375 // Not handling the rare case of different x and y device scale.
2376 float device_transform_scale =
2377 std::max(device_transform_scale_components.x(),
2378 device_transform_scale_components.y());
2380 gfx::Transform scaled_device_transform = inputs.device_transform;
2381 scaled_device_transform.Scale(inputs.device_scale_factor,
2382 inputs.device_scale_factor);
2384 globals->max_texture_size = inputs.max_texture_size;
2385 globals->device_scale_factor =
2386 inputs.device_scale_factor * device_transform_scale;
2387 globals->page_scale_factor = inputs.page_scale_factor;
2388 globals->page_scale_application_layer = inputs.page_scale_application_layer;
2389 globals->elastic_overscroll = inputs.elastic_overscroll;
2390 globals->elastic_overscroll_application_layer =
2391 inputs.elastic_overscroll_application_layer;
2392 globals->can_render_to_separate_surface =
2393 inputs.can_render_to_separate_surface;
2394 globals->can_adjust_raster_scales = inputs.can_adjust_raster_scales;
2395 globals->layers_always_allowed_lcd_text =
2396 inputs.layers_always_allowed_lcd_text;
2398 data_for_recursion->parent_matrix = scaled_device_transform;
2399 data_for_recursion->full_hierarchy_matrix = identity_matrix;
2400 data_for_recursion->scroll_compensation_matrix = identity_matrix;
2401 data_for_recursion->fixed_container = inputs.root_layer;
2402 data_for_recursion->clip_rect_in_target_space = device_viewport_rect;
2403 data_for_recursion->clip_rect_of_target_surface_in_target_space =
2404 device_viewport_rect;
2405 data_for_recursion->maximum_animation_contents_scale = 0.f;
2406 data_for_recursion->ancestor_is_animating_scale = false;
2407 data_for_recursion->ancestor_clips_subtree = true;
2408 data_for_recursion->nearest_occlusion_immune_ancestor_surface = NULL;
2409 data_for_recursion->in_subtree_of_page_scale_application_layer = false;
2410 data_for_recursion->subtree_can_use_lcd_text = inputs.can_use_lcd_text;
2411 data_for_recursion->subtree_is_visible_from_ancestor = true;
2414 void LayerTreeHostCommon::UpdateRenderSurface(
2415 Layer* layer,
2416 bool can_render_to_separate_surface,
2417 gfx::Transform* transform,
2418 bool* draw_transform_is_axis_aligned) {
2419 bool preserves_2d_axis_alignment =
2420 transform->Preserves2dAxisAlignment() && *draw_transform_is_axis_aligned;
2421 if (IsRootLayer(layer) || (can_render_to_separate_surface &&
2422 SubtreeShouldRenderToSeparateSurface(
2423 layer, preserves_2d_axis_alignment))) {
2424 // We reset the transform here so that any axis-changing transforms
2425 // will now be relative to this RenderSurface.
2426 transform->MakeIdentity();
2427 *draw_transform_is_axis_aligned = true;
2428 if (!layer->render_surface()) {
2429 layer->CreateRenderSurface();
2431 layer->SetHasRenderSurface(true);
2432 return;
2434 layer->SetHasRenderSurface(false);
2435 if (layer->render_surface())
2436 layer->ClearRenderSurface();
2439 void LayerTreeHostCommon::UpdateRenderSurfaces(
2440 Layer* layer,
2441 bool can_render_to_separate_surface,
2442 const gfx::Transform& parent_transform,
2443 bool draw_transform_is_axis_aligned) {
2444 gfx::Transform transform_for_children = layer->transform();
2445 transform_for_children *= parent_transform;
2446 draw_transform_is_axis_aligned &= layer->AnimationsPreserveAxisAlignment();
2447 UpdateRenderSurface(layer, can_render_to_separate_surface,
2448 &transform_for_children, &draw_transform_is_axis_aligned);
2450 for (size_t i = 0; i < layer->children().size(); ++i) {
2451 UpdateRenderSurfaces(layer->children()[i].get(),
2452 can_render_to_separate_surface, transform_for_children,
2453 draw_transform_is_axis_aligned);
2457 static bool ApproximatelyEqual(const gfx::Rect& r1, const gfx::Rect& r2) {
2458 // TODO(vollick): This tolerance should be lower: crbug.com/471786
2459 static const int tolerance = 3;
2461 if (r1.IsEmpty())
2462 return std::min(r2.width(), r2.height()) < tolerance;
2464 if (r2.IsEmpty())
2465 return std::min(r1.width(), r1.height()) < tolerance;
2467 return std::abs(r1.x() - r2.x()) <= tolerance &&
2468 std::abs(r1.y() - r2.y()) <= tolerance &&
2469 std::abs(r1.right() - r2.right()) <= tolerance &&
2470 std::abs(r1.bottom() - r2.bottom()) <= tolerance;
2473 static bool ApproximatelyEqual(const gfx::Transform& a,
2474 const gfx::Transform& b) {
2475 static const float component_tolerance = 0.1f;
2477 // We may have a larger discrepancy in the scroll components due to snapping
2478 // (floating point error might round the other way).
2479 static const float translation_tolerance = 1.f;
2481 for (int row = 0; row < 4; row++) {
2482 for (int col = 0; col < 4; col++) {
2483 static const float delta =
2484 std::abs(a.matrix().get(row, col) - b.matrix().get(row, col));
2485 const float tolerance =
2486 col == 3 && row < 3 ? translation_tolerance : component_tolerance;
2487 if (delta > tolerance)
2488 return false;
2492 return true;
2495 void VerifyPropertyTreeValues(
2496 LayerTreeHostCommon::CalcDrawPropsMainInputs* inputs) {
2497 LayerIterator<Layer> it, end;
2498 for (it = LayerIterator<Layer>::Begin(inputs->render_surface_layer_list),
2499 end = LayerIterator<Layer>::End(inputs->render_surface_layer_list);
2500 it != end; ++it) {
2501 Layer* current_layer = *it;
2502 if (!it.represents_itself() || !current_layer->DrawsContent())
2503 continue;
2505 const bool visible_rects_match =
2506 ApproximatelyEqual(current_layer->visible_content_rect(),
2507 current_layer->visible_rect_from_property_trees());
2508 CHECK(visible_rects_match)
2509 << "expected: " << current_layer->visible_content_rect().ToString()
2510 << " actual: "
2511 << current_layer->visible_rect_from_property_trees().ToString();
2513 const bool draw_transforms_match = ApproximatelyEqual(
2514 current_layer->draw_transform(),
2515 DrawTransformFromPropertyTrees(current_layer,
2516 inputs->property_trees->transform_tree));
2517 CHECK(draw_transforms_match)
2518 << "expected: " << current_layer->draw_transform().ToString()
2519 << " actual: "
2520 << DrawTransformFromPropertyTrees(
2521 current_layer, inputs->property_trees->transform_tree)
2522 .ToString();
2524 const bool draw_opacities_match =
2525 current_layer->draw_opacity() ==
2526 DrawOpacityFromPropertyTrees(current_layer,
2527 inputs->property_trees->opacity_tree);
2528 CHECK(draw_opacities_match)
2529 << "expected: " << current_layer->draw_opacity() << " actual: "
2530 << DrawOpacityFromPropertyTrees(current_layer,
2531 inputs->property_trees->opacity_tree);
2535 void VerifyPropertyTreeValues(
2536 LayerTreeHostCommon::CalcDrawPropsImplInputs* inputs) {
2537 // TODO(enne): need to synchronize compositor thread changes
2538 // for animation and scrolling to the property trees before these
2539 // can be correct.
2542 enum PropertyTreeOption {
2543 BUILD_PROPERTY_TREES_IF_NEEDED,
2544 DONT_BUILD_PROPERTY_TREES
2547 template <typename LayerType, typename RenderSurfaceLayerListType>
2548 void CalculateDrawPropertiesAndVerify(LayerTreeHostCommon::CalcDrawPropsInputs<
2549 LayerType,
2550 RenderSurfaceLayerListType>* inputs,
2551 PropertyTreeOption property_tree_option) {
2552 typename LayerType::LayerListType dummy_layer_list;
2553 SubtreeGlobals<LayerType> globals;
2554 DataForRecursion<LayerType> data_for_recursion;
2556 ProcessCalcDrawPropsInputs(*inputs, &globals, &data_for_recursion);
2557 PreCalculateMetaInformationRecursiveData recursive_data;
2558 PreCalculateMetaInformation(inputs->root_layer, &recursive_data);
2560 const bool should_measure_property_tree_performance =
2561 inputs->verify_property_trees &&
2562 (property_tree_option == BUILD_PROPERTY_TREES_IF_NEEDED);
2564 if (should_measure_property_tree_performance) {
2565 TRACE_EVENT_BEGIN0(TRACE_DISABLED_BY_DEFAULT("cc.debug.cdp-perf"),
2566 "LayerTreeHostCommon::CalculateDrawProperties");
2569 std::vector<AccumulatedSurfaceState<LayerType>> accumulated_surface_state;
2570 CalculateDrawPropertiesInternal<LayerType>(
2571 inputs->root_layer, globals, data_for_recursion,
2572 inputs->render_surface_layer_list, &dummy_layer_list,
2573 &accumulated_surface_state, inputs->current_render_surface_layer_list_id);
2575 if (should_measure_property_tree_performance) {
2576 TRACE_EVENT_END0(TRACE_DISABLED_BY_DEFAULT("cc.debug.cdp-perf"),
2577 "LayerTreeHostCommon::CalculateDrawProperties");
2580 if (inputs->verify_property_trees) {
2581 // For testing purposes, sometimes property trees need to be built on the
2582 // compositor thread, so this can't just switch on Layer vs LayerImpl,
2583 // even though in practice only the main thread builds property trees.
2584 switch (property_tree_option) {
2585 case BUILD_PROPERTY_TREES_IF_NEEDED: {
2586 // The translation from layer to property trees is an intermediate
2587 // state. We will eventually get these data passed directly to the
2588 // compositor.
2589 if (should_measure_property_tree_performance) {
2590 TRACE_EVENT_BEGIN0(
2591 TRACE_DISABLED_BY_DEFAULT("cc.debug.cdp-perf"),
2592 "LayerTreeHostCommon::ComputeVisibleRectsWithPropertyTrees");
2595 BuildPropertyTreesAndComputeVisibleRects(
2596 inputs->root_layer, inputs->page_scale_application_layer,
2597 inputs->page_scale_factor, inputs->device_scale_factor,
2598 gfx::Rect(inputs->device_viewport_size), inputs->device_transform,
2599 inputs->property_trees);
2601 if (should_measure_property_tree_performance) {
2602 TRACE_EVENT_END0(
2603 TRACE_DISABLED_BY_DEFAULT("cc.debug.cdp-perf"),
2604 "LayerTreeHostCommon::ComputeVisibleRectsWithPropertyTrees");
2607 break;
2609 case DONT_BUILD_PROPERTY_TREES: {
2610 TRACE_EVENT0(
2611 TRACE_DISABLED_BY_DEFAULT("cc.debug.cdp-perf"),
2612 "LayerTreeHostCommon::ComputeJustVisibleRectsWithPropertyTrees");
2613 ComputeVisibleRectsUsingPropertyTrees(inputs->root_layer,
2614 inputs->property_trees);
2615 break;
2619 VerifyPropertyTreeValues(inputs);
2622 // The dummy layer list should not have been used.
2623 DCHECK_EQ(0u, dummy_layer_list.size());
2624 // A root layer render_surface should always exist after
2625 // CalculateDrawProperties.
2626 DCHECK(inputs->root_layer->render_surface());
2629 void LayerTreeHostCommon::CalculateDrawProperties(
2630 CalcDrawPropsMainInputs* inputs) {
2631 UpdateRenderSurfaces(inputs->root_layer,
2632 inputs->can_render_to_separate_surface, gfx::Transform(),
2633 false);
2634 CalculateDrawPropertiesAndVerify(inputs, BUILD_PROPERTY_TREES_IF_NEEDED);
2637 void LayerTreeHostCommon::CalculateDrawProperties(
2638 CalcDrawPropsImplInputs* inputs) {
2639 CalculateDrawPropertiesAndVerify(inputs, DONT_BUILD_PROPERTY_TREES);
2642 void LayerTreeHostCommon::CalculateDrawProperties(
2643 CalcDrawPropsImplInputsForTesting* inputs) {
2644 CalculateDrawPropertiesAndVerify(inputs, BUILD_PROPERTY_TREES_IF_NEEDED);
2647 PropertyTrees* GetPropertyTrees(Layer* layer,
2648 PropertyTrees* trees_from_inputs) {
2649 return layer->layer_tree_host()->property_trees();
2652 PropertyTrees* GetPropertyTrees(LayerImpl* layer,
2653 PropertyTrees* trees_from_inputs) {
2654 return trees_from_inputs;
2657 } // namespace cc