Revert "Reland c91b178b07b0d - Delete dead signin code (SigninGlobalError)"
[chromium-blink-merge.git] / cc / trees / layer_tree_host_common.cc
blob322ed9506f5a7f54a40c6897be7fefcac5becc3a
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_impl.h"
16 #include "cc/trees/draw_property_utils.h"
17 #include "cc/trees/layer_tree_host.h"
18 #include "cc/trees/layer_tree_impl.h"
19 #include "ui/gfx/geometry/rect_conversions.h"
20 #include "ui/gfx/geometry/vector2d_conversions.h"
21 #include "ui/gfx/transform.h"
22 #include "ui/gfx/transform_util.h"
24 namespace cc {
26 LayerTreeHostCommon::CalcDrawPropsMainInputs::CalcDrawPropsMainInputs(
27 Layer* root_layer,
28 const gfx::Size& device_viewport_size,
29 const gfx::Transform& device_transform,
30 float device_scale_factor,
31 float page_scale_factor,
32 const Layer* page_scale_layer,
33 const Layer* inner_viewport_scroll_layer,
34 const Layer* outer_viewport_scroll_layer)
35 : root_layer(root_layer),
36 device_viewport_size(device_viewport_size),
37 device_transform(device_transform),
38 device_scale_factor(device_scale_factor),
39 page_scale_factor(page_scale_factor),
40 page_scale_layer(page_scale_layer),
41 inner_viewport_scroll_layer(inner_viewport_scroll_layer),
42 outer_viewport_scroll_layer(outer_viewport_scroll_layer) {}
44 LayerTreeHostCommon::CalcDrawPropsMainInputs::CalcDrawPropsMainInputs(
45 Layer* root_layer,
46 const gfx::Size& device_viewport_size,
47 const gfx::Transform& device_transform)
48 : CalcDrawPropsMainInputs(root_layer,
49 device_viewport_size,
50 device_transform,
51 1.f,
52 1.f,
53 NULL,
54 NULL,
55 NULL) {}
57 LayerTreeHostCommon::CalcDrawPropsMainInputs::CalcDrawPropsMainInputs(
58 Layer* root_layer,
59 const gfx::Size& device_viewport_size)
60 : CalcDrawPropsMainInputs(root_layer,
61 device_viewport_size,
62 gfx::Transform()) {}
64 LayerTreeHostCommon::CalcDrawPropsImplInputs::CalcDrawPropsImplInputs(
65 LayerImpl* root_layer,
66 const gfx::Size& device_viewport_size,
67 const gfx::Transform& device_transform,
68 float device_scale_factor,
69 float page_scale_factor,
70 const LayerImpl* page_scale_layer,
71 const LayerImpl* inner_viewport_scroll_layer,
72 const LayerImpl* outer_viewport_scroll_layer,
73 const gfx::Vector2dF& elastic_overscroll,
74 const LayerImpl* elastic_overscroll_application_layer,
75 int max_texture_size,
76 bool can_use_lcd_text,
77 bool layers_always_allowed_lcd_text,
78 bool can_render_to_separate_surface,
79 bool can_adjust_raster_scales,
80 bool verify_property_trees,
81 LayerImplList* render_surface_layer_list,
82 int current_render_surface_layer_list_id,
83 PropertyTrees* property_trees)
84 : root_layer(root_layer),
85 device_viewport_size(device_viewport_size),
86 device_transform(device_transform),
87 device_scale_factor(device_scale_factor),
88 page_scale_factor(page_scale_factor),
89 page_scale_layer(page_scale_layer),
90 inner_viewport_scroll_layer(inner_viewport_scroll_layer),
91 outer_viewport_scroll_layer(outer_viewport_scroll_layer),
92 elastic_overscroll(elastic_overscroll),
93 elastic_overscroll_application_layer(
94 elastic_overscroll_application_layer),
95 max_texture_size(max_texture_size),
96 can_use_lcd_text(can_use_lcd_text),
97 layers_always_allowed_lcd_text(layers_always_allowed_lcd_text),
98 can_render_to_separate_surface(can_render_to_separate_surface),
99 can_adjust_raster_scales(can_adjust_raster_scales),
100 verify_property_trees(verify_property_trees),
101 render_surface_layer_list(render_surface_layer_list),
102 current_render_surface_layer_list_id(
103 current_render_surface_layer_list_id),
104 property_trees(property_trees) {}
106 LayerTreeHostCommon::CalcDrawPropsImplInputsForTesting::
107 CalcDrawPropsImplInputsForTesting(LayerImpl* root_layer,
108 const gfx::Size& device_viewport_size,
109 const gfx::Transform& device_transform,
110 LayerImplList* render_surface_layer_list)
111 : CalcDrawPropsImplInputs(root_layer,
112 device_viewport_size,
113 device_transform,
114 1.f,
115 1.f,
116 NULL,
117 NULL,
118 NULL,
119 gfx::Vector2dF(),
120 NULL,
121 std::numeric_limits<int>::max() / 2,
122 false,
123 false,
124 true,
125 false,
126 true,
127 render_surface_layer_list,
129 GetPropertyTrees(root_layer)) {
130 DCHECK(root_layer);
131 DCHECK(render_surface_layer_list);
134 LayerTreeHostCommon::CalcDrawPropsImplInputsForTesting::
135 CalcDrawPropsImplInputsForTesting(LayerImpl* root_layer,
136 const gfx::Size& device_viewport_size,
137 LayerImplList* render_surface_layer_list)
138 : CalcDrawPropsImplInputsForTesting(root_layer,
139 device_viewport_size,
140 gfx::Transform(),
141 render_surface_layer_list) {}
143 ScrollAndScaleSet::ScrollAndScaleSet()
144 : page_scale_delta(1.f), top_controls_delta(0.f) {
147 ScrollAndScaleSet::~ScrollAndScaleSet() {}
149 static gfx::Vector2dF GetEffectiveScrollDelta(LayerImpl* layer) {
150 // Layer's scroll offset can have an integer part and fractional part.
151 // Due to Blink's limitation, it only counter-scrolls the position-fixed
152 // layer using the integer part of Layer's scroll offset.
153 // CC scrolls the layer using the full scroll offset, so we have to
154 // add the ScrollCompensationAdjustment (fractional part of the scroll
155 // offset) to the effective scroll delta which is used to counter-scroll
156 // the position-fixed layer.
157 gfx::Vector2dF scroll_delta =
158 layer->ScrollDelta() + layer->ScrollCompensationAdjustment();
159 // The scroll parent's scroll delta is the amount we've scrolled on the
160 // compositor thread since the commit for this layer tree's source frame.
161 // we last reported to the main thread. I.e., it's the discrepancy between
162 // a scroll parent's scroll delta and offset, so we must add it here.
163 if (layer->scroll_parent())
164 scroll_delta += layer->scroll_parent()->ScrollDelta() +
165 layer->ScrollCompensationAdjustment();
166 return scroll_delta;
169 static gfx::ScrollOffset GetEffectiveCurrentScrollOffset(LayerImpl* layer) {
170 gfx::ScrollOffset offset = layer->CurrentScrollOffset();
171 // The scroll parent's total scroll offset (scroll offset + scroll delta)
172 // can't be used because its scroll offset has already been applied to the
173 // scroll children's positions by the main thread layer positioning code.
174 if (layer->scroll_parent())
175 offset += gfx::ScrollOffset(layer->scroll_parent()->ScrollDelta());
176 return offset;
179 inline gfx::Rect CalculateVisibleRectWithCachedLayerRect(
180 const gfx::Rect& target_surface_rect,
181 const gfx::Rect& layer_bound_rect,
182 const gfx::Rect& layer_rect_in_target_space,
183 const gfx::Transform& transform) {
184 if (layer_rect_in_target_space.IsEmpty())
185 return gfx::Rect();
187 // Is this layer fully contained within the target surface?
188 if (target_surface_rect.Contains(layer_rect_in_target_space))
189 return layer_bound_rect;
191 // If the layer doesn't fill up the entire surface, then find the part of
192 // the surface rect where the layer could be visible. This avoids trying to
193 // project surface rect points that are behind the projection point.
194 gfx::Rect minimal_surface_rect = target_surface_rect;
195 minimal_surface_rect.Intersect(layer_rect_in_target_space);
197 if (minimal_surface_rect.IsEmpty())
198 return gfx::Rect();
200 // Project the corners of the target surface rect into the layer space.
201 // This bounding rectangle may be larger than it needs to be (being
202 // axis-aligned), but is a reasonable filter on the space to consider.
203 // Non-invertible transforms will create an empty rect here.
205 gfx::Transform surface_to_layer(gfx::Transform::kSkipInitialization);
206 if (!transform.GetInverse(&surface_to_layer)) {
207 // Because we cannot use the surface bounds to determine what portion of
208 // the layer is visible, we must conservatively assume the full layer is
209 // visible.
210 return layer_bound_rect;
213 gfx::Rect layer_rect = MathUtil::ProjectEnclosingClippedRect(
214 surface_to_layer, minimal_surface_rect);
215 layer_rect.Intersect(layer_bound_rect);
216 return layer_rect;
219 gfx::Rect LayerTreeHostCommon::CalculateVisibleRect(
220 const gfx::Rect& target_surface_rect,
221 const gfx::Rect& layer_bound_rect,
222 const gfx::Transform& transform) {
223 gfx::Rect layer_in_surface_space =
224 MathUtil::MapEnclosingClippedRect(transform, layer_bound_rect);
225 return CalculateVisibleRectWithCachedLayerRect(
226 target_surface_rect, layer_bound_rect, layer_in_surface_space, transform);
229 static const LayerImpl* NextTargetSurface(const LayerImpl* layer) {
230 return layer->parent() ? layer->parent()->render_target() : 0;
233 // Given two layers, this function finds their respective render targets and,
234 // computes a change of basis translation. It does this by accumulating the
235 // translation components of the draw transforms of each target between the
236 // ancestor and descendant. These transforms must be 2D translations, and this
237 // requirement is enforced at every step.
238 static gfx::Vector2dF ComputeChangeOfBasisTranslation(
239 const LayerImpl& ancestor_layer,
240 const LayerImpl& descendant_layer) {
241 DCHECK(descendant_layer.HasAncestor(&ancestor_layer));
242 const LayerImpl* descendant_target = descendant_layer.render_target();
243 DCHECK(descendant_target);
244 const LayerImpl* ancestor_target = ancestor_layer.render_target();
245 DCHECK(ancestor_target);
247 gfx::Vector2dF translation;
248 for (const LayerImpl* target = descendant_target; target != ancestor_target;
249 target = NextTargetSurface(target)) {
250 const gfx::Transform& trans = target->render_surface()->draw_transform();
251 // Ensure that this translation is truly 2d.
252 DCHECK(trans.IsIdentityOrTranslation());
253 DCHECK_EQ(0.f, trans.matrix().get(2, 3));
254 translation += trans.To2dTranslation();
257 return translation;
260 enum TranslateRectDirection {
261 TRANSLATE_RECT_DIRECTION_TO_ANCESTOR,
262 TRANSLATE_RECT_DIRECTION_TO_DESCENDANT
265 static gfx::Rect TranslateRectToTargetSpace(const LayerImpl& ancestor_layer,
266 const LayerImpl& descendant_layer,
267 const gfx::Rect& rect,
268 TranslateRectDirection direction) {
269 gfx::Vector2dF translation =
270 ComputeChangeOfBasisTranslation(ancestor_layer, descendant_layer);
271 if (direction == TRANSLATE_RECT_DIRECTION_TO_DESCENDANT)
272 translation.Scale(-1.f);
273 return gfx::ToEnclosingRect(
274 gfx::RectF(rect.origin() + translation, rect.size()));
277 // Attempts to update the clip rects for the given layer. If the layer has a
278 // clip_parent, it may not inherit its immediate ancestor's clip.
279 static void UpdateClipRectsForClipChild(
280 const LayerImpl* layer,
281 gfx::Rect* clip_rect_in_parent_target_space,
282 bool* subtree_should_be_clipped) {
283 // If the layer has no clip_parent, or the ancestor is the same as its actual
284 // parent, then we don't need special clip rects. Bail now and leave the out
285 // parameters untouched.
286 const LayerImpl* clip_parent = layer->scroll_parent();
288 if (!clip_parent)
289 clip_parent = layer->clip_parent();
291 if (!clip_parent || clip_parent == layer->parent())
292 return;
294 // The root layer is never a clip child.
295 DCHECK(layer->parent());
297 // Grab the cached values.
298 *clip_rect_in_parent_target_space = clip_parent->clip_rect();
299 *subtree_should_be_clipped = clip_parent->is_clipped();
301 // We may have to project the clip rect into our parent's target space. Note,
302 // it must be our parent's target space, not ours. For one, we haven't
303 // computed our transforms, so we couldn't put it in our space yet even if we
304 // wanted to. But more importantly, this matches the expectations of
305 // CalculateDrawPropertiesInternal. If we, say, create a render surface, these
306 // clip rects will want to be in its target space, not ours.
307 if (clip_parent == layer->clip_parent()) {
308 *clip_rect_in_parent_target_space = TranslateRectToTargetSpace(
309 *clip_parent, *layer->parent(), *clip_rect_in_parent_target_space,
310 TRANSLATE_RECT_DIRECTION_TO_DESCENDANT);
311 } else {
312 // If we're being clipped by our scroll parent, we must translate through
313 // our common ancestor. This happens to be our parent, so it is sufficent to
314 // translate from our clip parent's space to the space of its ancestor (our
315 // parent).
316 *clip_rect_in_parent_target_space = TranslateRectToTargetSpace(
317 *layer->parent(), *clip_parent, *clip_rect_in_parent_target_space,
318 TRANSLATE_RECT_DIRECTION_TO_ANCESTOR);
322 // We collect an accumulated drawable content rect per render surface.
323 // Typically, a layer will contribute to only one surface, the surface
324 // associated with its render target. Clip children, however, may affect
325 // several surfaces since there may be several surfaces between the clip child
326 // and its parent.
328 // NB: we accumulate the layer's *clipped* drawable content rect.
329 struct AccumulatedSurfaceState {
330 explicit AccumulatedSurfaceState(LayerImpl* render_target)
331 : render_target(render_target) {}
333 // The accumulated drawable content rect for the surface associated with the
334 // given |render_target|.
335 gfx::Rect drawable_content_rect;
337 // The target owning the surface. (We hang onto the target rather than the
338 // surface so that we can DCHECK that the surface's draw transform is simply
339 // a translation when |render_target| reports that it has no unclipped
340 // descendants).
341 LayerImpl* render_target;
344 template <typename LayerType>
345 static inline bool IsRootLayer(LayerType* layer) {
346 return !layer->parent();
349 void UpdateAccumulatedSurfaceState(
350 LayerImpl* layer,
351 const gfx::Rect& drawable_content_rect,
352 std::vector<AccumulatedSurfaceState>* accumulated_surface_state) {
353 if (IsRootLayer(layer))
354 return;
356 // We will apply our drawable content rect to the accumulated rects for all
357 // surfaces between us and |render_target| (inclusive). This is either our
358 // clip parent's target if we are a clip child, or else simply our parent's
359 // target. We use our parent's target because we're either the owner of a
360 // render surface and we'll want to add our rect to our *surface's* target, or
361 // we're not and our target is the same as our parent's. In both cases, the
362 // parent's target gives us what we want.
363 LayerImpl* render_target = layer->clip_parent()
364 ? layer->clip_parent()->render_target()
365 : layer->parent()->render_target();
367 // If the layer owns a surface, then the content rect is in the wrong space.
368 // Instead, we will use the surface's DrawableContentRect which is in target
369 // space as required.
370 gfx::Rect target_rect = drawable_content_rect;
371 if (layer->render_surface()) {
372 target_rect =
373 gfx::ToEnclosedRect(layer->render_surface()->DrawableContentRect());
376 if (render_target->is_clipped()) {
377 gfx::Rect clip_rect = render_target->clip_rect();
378 // If the layer has a clip parent, the clip rect may be in the wrong space,
379 // so we'll need to transform it before it is applied.
380 if (layer->clip_parent()) {
381 clip_rect =
382 TranslateRectToTargetSpace(*layer->clip_parent(), *layer, clip_rect,
383 TRANSLATE_RECT_DIRECTION_TO_DESCENDANT);
385 target_rect.Intersect(clip_rect);
388 // We must have at least one entry in the vector for the root.
389 DCHECK_LT(0ul, accumulated_surface_state->size());
391 typedef std::vector<AccumulatedSurfaceState> AccumulatedSurfaceStateVector;
392 typedef AccumulatedSurfaceStateVector::reverse_iterator
393 AccumulatedSurfaceStateIterator;
394 AccumulatedSurfaceStateIterator current_state =
395 accumulated_surface_state->rbegin();
397 // Add this rect to the accumulated content rect for all surfaces until we
398 // reach the target surface.
399 bool found_render_target = false;
400 for (; current_state != accumulated_surface_state->rend(); ++current_state) {
401 current_state->drawable_content_rect.Union(target_rect);
403 // If we've reached |render_target| our work is done and we can bail.
404 if (current_state->render_target == render_target) {
405 found_render_target = true;
406 break;
409 // Transform rect from the current target's space to the next.
410 LayerImpl* current_target = current_state->render_target;
411 DCHECK(current_target->render_surface());
412 const gfx::Transform& current_draw_transform =
413 current_target->render_surface()->draw_transform();
415 // If we have unclipped descendants, the draw transform is a translation.
416 DCHECK_IMPLIES(current_target->num_unclipped_descendants(),
417 current_draw_transform.IsIdentityOrTranslation());
419 target_rect = gfx::ToEnclosingRect(
420 MathUtil::MapClippedRect(current_draw_transform, target_rect));
423 // It is an error to not reach |render_target|. If this happens, it means that
424 // either the clip parent is not an ancestor of the clip child or the surface
425 // state vector is empty, both of which should be impossible.
426 DCHECK(found_render_target);
429 template <typename LayerType>
430 static inline bool LayerIsInExisting3DRenderingContext(LayerType* layer) {
431 return layer->Is3dSorted() && layer->parent() &&
432 layer->parent()->Is3dSorted() &&
433 (layer->parent()->sorting_context_id() == layer->sorting_context_id());
436 static bool IsRootLayerOfNewRenderingContext(LayerImpl* layer) {
437 if (layer->parent())
438 return !layer->parent()->Is3dSorted() && layer->Is3dSorted();
440 return layer->Is3dSorted();
443 static bool IsLayerBackFaceVisible(LayerImpl* layer) {
444 // The current W3C spec on CSS transforms says that backface visibility should
445 // be determined differently depending on whether the layer is in a "3d
446 // rendering context" or not. For Chromium code, we can determine whether we
447 // are in a 3d rendering context by checking if the parent preserves 3d.
449 if (LayerIsInExisting3DRenderingContext(layer))
450 return layer->draw_transform().IsBackFaceVisible();
452 // In this case, either the layer establishes a new 3d rendering context, or
453 // is not in a 3d rendering context at all.
454 return layer->transform().IsBackFaceVisible();
457 static bool IsSurfaceBackFaceVisible(LayerImpl* layer,
458 const gfx::Transform& draw_transform) {
459 if (LayerIsInExisting3DRenderingContext(layer))
460 return draw_transform.IsBackFaceVisible();
462 if (IsRootLayerOfNewRenderingContext(layer))
463 return layer->transform().IsBackFaceVisible();
465 // If the render_surface is not part of a new or existing rendering context,
466 // then the layers that contribute to this surface will decide back-face
467 // visibility for themselves.
468 return false;
471 template <typename LayerType>
472 static inline bool LayerClipsSubtree(LayerType* layer) {
473 return layer->masks_to_bounds() || layer->mask_layer();
476 static gfx::Rect CalculateVisibleLayerRect(
477 LayerImpl* layer,
478 const gfx::Rect& clip_rect_of_target_surface_in_target_space,
479 const gfx::Rect& layer_rect_in_target_space) {
480 DCHECK(layer->render_target());
482 // Nothing is visible if the layer bounds are empty.
483 if (!layer->DrawsContent() || layer->bounds().IsEmpty() ||
484 layer->drawable_content_rect().IsEmpty())
485 return gfx::Rect();
487 // Compute visible bounds in target surface space.
488 gfx::Rect visible_rect_in_target_surface_space =
489 layer->drawable_content_rect();
491 if (layer->render_target()->render_surface()->is_clipped()) {
492 // The |layer| L has a target T which owns a surface Ts. The surface Ts
493 // has a target TsT.
495 // In this case the target surface Ts does clip the layer L that contributes
496 // to it. So, we have to convert the clip rect of Ts from the target space
497 // of Ts (that is the space of TsT), to the current render target's space
498 // (that is the space of T). This conversion is done outside this function
499 // so that it can be cached instead of computing it redundantly for every
500 // layer.
501 visible_rect_in_target_surface_space.Intersect(
502 clip_rect_of_target_surface_in_target_space);
505 if (visible_rect_in_target_surface_space.IsEmpty())
506 return gfx::Rect();
508 return CalculateVisibleRectWithCachedLayerRect(
509 visible_rect_in_target_surface_space, gfx::Rect(layer->bounds()),
510 layer_rect_in_target_space, layer->draw_transform());
513 static bool LayerShouldBeSkipped(LayerImpl* layer, bool layer_is_drawn) {
514 // Layers can be skipped if any of these conditions are met.
515 // - is not drawn due to it or one of its ancestors being hidden (or having
516 // no copy requests).
517 // - does not draw content.
518 // - is transparent.
519 // - has empty bounds
520 // - the layer is not double-sided, but its back face is visible.
522 // Some additional conditions need to be computed at a later point after the
523 // recursion is finished.
524 // - the intersection of render_surface content and layer clip_rect is empty
525 // - the visible_layer_rect is empty
527 // Note, if the layer should not have been drawn due to being fully
528 // transparent, we would have skipped the entire subtree and never made it
529 // into this function, so it is safe to omit this check here.
531 if (!layer_is_drawn)
532 return true;
534 if (!layer->DrawsContent() || layer->bounds().IsEmpty())
535 return true;
537 LayerImpl* backface_test_layer = layer;
538 if (layer->use_parent_backface_visibility()) {
539 DCHECK(layer->parent());
540 DCHECK(!layer->parent()->use_parent_backface_visibility());
541 backface_test_layer = layer->parent();
544 // The layer should not be drawn if (1) it is not double-sided and (2) the
545 // back of the layer is known to be facing the screen.
546 if (!backface_test_layer->double_sided() &&
547 IsLayerBackFaceVisible(backface_test_layer))
548 return true;
550 return false;
553 template <typename LayerType>
554 static bool HasInvertibleOrAnimatedTransform(LayerType* layer) {
555 return layer->transform_is_invertible() ||
556 layer->HasPotentiallyRunningTransformAnimation();
559 static inline bool SubtreeShouldBeSkipped(LayerImpl* layer,
560 bool layer_is_drawn) {
561 // If the layer transform is not invertible, it should not be drawn.
562 // TODO(ajuma): Correctly process subtrees with singular transform for the
563 // case where we may animate to a non-singular transform and wish to
564 // pre-raster.
565 if (!HasInvertibleOrAnimatedTransform(layer))
566 return true;
568 // When we need to do a readback/copy of a layer's output, we can not skip
569 // it or any of its ancestors.
570 if (layer->draw_properties().layer_or_descendant_has_copy_request)
571 return false;
573 // We cannot skip the the subtree if a descendant has a wheel or touch handler
574 // or the hit testing code will break (it requires fresh transforms, etc).
575 if (layer->draw_properties().layer_or_descendant_has_input_handler)
576 return false;
578 // If the layer is not drawn, then skip it and its subtree.
579 if (!layer_is_drawn)
580 return true;
582 // If layer is on the pending tree and opacity is being animated then
583 // this subtree can't be skipped as we need to create, prioritize and
584 // include tiles for this layer when deciding if tree can be activated.
585 if (layer->layer_tree_impl()->IsPendingTree() &&
586 layer->HasPotentiallyRunningOpacityAnimation())
587 return false;
589 // The opacity of a layer always applies to its children (either implicitly
590 // via a render surface or explicitly if the parent preserves 3D), so the
591 // entire subtree can be skipped if this layer is fully transparent.
592 return !layer->opacity();
595 static inline void SavePaintPropertiesLayer(LayerImpl* layer) {}
597 static bool SubtreeShouldRenderToSeparateSurface(
598 Layer* layer,
599 bool axis_aligned_with_respect_to_parent) {
601 // A layer and its descendants should render onto a new RenderSurfaceImpl if
602 // any of these rules hold:
605 // The root layer owns a render surface, but it never acts as a contributing
606 // surface to another render target. Compositor features that are applied via
607 // a contributing surface can not be applied to the root layer. In order to
608 // use these effects, another child of the root would need to be introduced
609 // in order to act as a contributing surface to the root layer's surface.
610 bool is_root = IsRootLayer(layer);
612 // If the layer uses a mask.
613 if (layer->mask_layer()) {
614 DCHECK(!is_root);
615 return true;
618 // If the layer has a reflection.
619 if (layer->replica_layer()) {
620 DCHECK(!is_root);
621 return true;
624 // If the layer uses a CSS filter.
625 if (!layer->filters().IsEmpty() || !layer->background_filters().IsEmpty()) {
626 DCHECK(!is_root);
627 return true;
630 // If the layer will use a CSS filter. In this case, the animation
631 // will start and add a filter to this layer, so it needs a surface.
632 if (layer->HasPotentiallyRunningFilterAnimation()) {
633 DCHECK(!is_root);
634 return true;
637 int num_descendants_that_draw_content =
638 layer->NumDescendantsThatDrawContent();
640 // If the layer flattens its subtree, but it is treated as a 3D object by its
641 // parent (i.e. parent participates in a 3D rendering context).
642 if (LayerIsInExisting3DRenderingContext(layer) &&
643 layer->should_flatten_transform() &&
644 num_descendants_that_draw_content > 0) {
645 TRACE_EVENT_INSTANT0(
646 "cc",
647 "LayerTreeHostCommon::SubtreeShouldRenderToSeparateSurface flattening",
648 TRACE_EVENT_SCOPE_THREAD);
649 DCHECK(!is_root);
650 return true;
653 // If the layer has blending.
654 // TODO(rosca): this is temporary, until blending is implemented for other
655 // types of quads than RenderPassDrawQuad. Layers having descendants that draw
656 // content will still create a separate rendering surface.
657 if (!layer->uses_default_blend_mode()) {
658 TRACE_EVENT_INSTANT0(
659 "cc",
660 "LayerTreeHostCommon::SubtreeShouldRenderToSeparateSurface blending",
661 TRACE_EVENT_SCOPE_THREAD);
662 DCHECK(!is_root);
663 return true;
666 // If the layer clips its descendants but it is not axis-aligned with respect
667 // to its parent.
668 bool layer_clips_external_content =
669 LayerClipsSubtree(layer) || layer->HasDelegatedContent();
670 if (layer_clips_external_content && !axis_aligned_with_respect_to_parent &&
671 num_descendants_that_draw_content > 0) {
672 TRACE_EVENT_INSTANT0(
673 "cc",
674 "LayerTreeHostCommon::SubtreeShouldRenderToSeparateSurface clipping",
675 TRACE_EVENT_SCOPE_THREAD);
676 DCHECK(!is_root);
677 return true;
680 // If the layer has some translucency and does not have a preserves-3d
681 // transform style. This condition only needs a render surface if two or more
682 // layers in the subtree overlap. But checking layer overlaps is unnecessarily
683 // costly so instead we conservatively create a surface whenever at least two
684 // layers draw content for this subtree.
685 bool at_least_two_layers_in_subtree_draw_content =
686 num_descendants_that_draw_content > 0 &&
687 (layer->DrawsContent() || num_descendants_that_draw_content > 1);
689 if (layer->opacity() != 1.f && layer->should_flatten_transform() &&
690 at_least_two_layers_in_subtree_draw_content) {
691 TRACE_EVENT_INSTANT0(
692 "cc",
693 "LayerTreeHostCommon::SubtreeShouldRenderToSeparateSurface opacity",
694 TRACE_EVENT_SCOPE_THREAD);
695 DCHECK(!is_root);
696 return true;
699 // The root layer should always have a render_surface.
700 if (is_root)
701 return true;
704 // These are allowed on the root surface, as they don't require the surface to
705 // be used as a contributing surface in order to apply correctly.
708 // If the layer has isolation.
709 // TODO(rosca): to be optimized - create separate rendering surface only when
710 // the blending descendants might have access to the content behind this layer
711 // (layer has transparent background or descendants overflow).
712 // https://code.google.com/p/chromium/issues/detail?id=301738
713 if (layer->is_root_for_isolated_group()) {
714 TRACE_EVENT_INSTANT0(
715 "cc",
716 "LayerTreeHostCommon::SubtreeShouldRenderToSeparateSurface isolation",
717 TRACE_EVENT_SCOPE_THREAD);
718 return true;
721 // If we force it.
722 if (layer->force_render_surface())
723 return true;
725 // If we'll make a copy of the layer's contents.
726 if (layer->HasCopyRequest())
727 return true;
729 return false;
732 // This function returns a translation matrix that can be applied on a vector
733 // that's in the layer's target surface coordinate, while the position offset is
734 // specified in some ancestor layer's coordinate.
735 gfx::Transform ComputeSizeDeltaCompensation(
736 LayerImpl* layer,
737 LayerImpl* container,
738 const gfx::Vector2dF& position_offset) {
739 gfx::Transform result_transform;
741 // To apply a translate in the container's layer space,
742 // the following steps need to be done:
743 // Step 1a. transform from target surface space to the container's target
744 // surface space
745 // Step 1b. transform from container's target surface space to the
746 // container's layer space
747 // Step 2. apply the compensation
748 // Step 3. transform back to target surface space
750 gfx::Transform target_surface_space_to_container_layer_space;
751 // Calculate step 1a
752 LayerImpl* container_target_surface = container->render_target();
753 for (const LayerImpl* current_target_surface = NextTargetSurface(layer);
754 current_target_surface &&
755 current_target_surface != container_target_surface;
756 current_target_surface = NextTargetSurface(current_target_surface)) {
757 // Note: Concat is used here to convert the result coordinate space from
758 // current render surface to the next render surface.
759 target_surface_space_to_container_layer_space.ConcatTransform(
760 current_target_surface->render_surface()->draw_transform());
762 // Calculate step 1b
763 gfx::Transform container_layer_space_to_container_target_surface_space =
764 container->draw_transform();
765 gfx::Transform container_target_surface_space_to_container_layer_space;
766 if (container_layer_space_to_container_target_surface_space.GetInverse(
767 &container_target_surface_space_to_container_layer_space)) {
768 // Note: Again, Concat is used to conver the result coordinate space from
769 // the container render surface to the container layer.
770 target_surface_space_to_container_layer_space.ConcatTransform(
771 container_target_surface_space_to_container_layer_space);
774 // Apply step 3
775 gfx::Transform container_layer_space_to_target_surface_space;
776 if (target_surface_space_to_container_layer_space.GetInverse(
777 &container_layer_space_to_target_surface_space)) {
778 result_transform.PreconcatTransform(
779 container_layer_space_to_target_surface_space);
780 } else {
781 // TODO(shawnsingh): A non-invertible matrix could still make meaningful
782 // projection. For example ScaleZ(0) is non-invertible but the layer is
783 // still visible.
784 return gfx::Transform();
787 // Apply step 2
788 result_transform.Translate(position_offset.x(), position_offset.y());
790 // Apply step 1
791 result_transform.PreconcatTransform(
792 target_surface_space_to_container_layer_space);
794 return result_transform;
797 void ApplyPositionAdjustment(LayerImpl* layer,
798 LayerImpl* container,
799 const gfx::Transform& scroll_compensation,
800 gfx::Transform* combined_transform) {
801 if (!layer->position_constraint().is_fixed_position())
802 return;
804 // Special case: this layer is a composited fixed-position layer; we need to
805 // explicitly compensate for all ancestors' nonzero scroll_deltas to keep
806 // this layer fixed correctly.
807 // Note carefully: this is Concat, not Preconcat
808 // (current_scroll_compensation * combined_transform).
809 combined_transform->ConcatTransform(scroll_compensation);
811 // For right-edge or bottom-edge anchored fixed position layers,
812 // the layer should relocate itself if the container changes its size.
813 bool fixed_to_right_edge =
814 layer->position_constraint().is_fixed_to_right_edge();
815 bool fixed_to_bottom_edge =
816 layer->position_constraint().is_fixed_to_bottom_edge();
817 gfx::Vector2dF position_offset = container->FixedContainerSizeDelta();
818 position_offset.set_x(fixed_to_right_edge ? position_offset.x() : 0);
819 position_offset.set_y(fixed_to_bottom_edge ? position_offset.y() : 0);
820 if (position_offset.IsZero())
821 return;
823 // Note: Again, this is Concat. The compensation matrix will be applied on
824 // the vector in target surface space.
825 combined_transform->ConcatTransform(
826 ComputeSizeDeltaCompensation(layer, container, position_offset));
829 gfx::Transform ComputeScrollCompensationForThisLayer(
830 LayerImpl* scrolling_layer,
831 const gfx::Transform& parent_matrix,
832 const gfx::Vector2dF& scroll_delta) {
833 // For every layer that has non-zero scroll_delta, we have to compute a
834 // transform that can undo the scroll_delta translation. In particular, we
835 // want this matrix to premultiply a fixed-position layer's parent_matrix, so
836 // we design this transform in three steps as follows. The steps described
837 // here apply from right-to-left, so Step 1 would be the right-most matrix:
839 // Step 1. transform from target surface space to the exact space where
840 // scroll_delta is actually applied.
841 // -- this is inverse of parent_matrix
842 // Step 2. undo the scroll_delta
843 // -- this is just a translation by scroll_delta.
844 // Step 3. transform back to target surface space.
845 // -- this transform is the parent_matrix
847 // These steps create a matrix that both start and end in target surface
848 // space. So this matrix can pre-multiply any fixed-position layer's
849 // draw_transform to undo the scroll_deltas -- as long as that fixed position
850 // layer is fixed onto the same render_target as this scrolling_layer.
853 gfx::Transform scroll_compensation_for_this_layer = parent_matrix; // Step 3
854 scroll_compensation_for_this_layer.Translate(
855 scroll_delta.x(),
856 scroll_delta.y()); // Step 2
858 gfx::Transform inverse_parent_matrix(gfx::Transform::kSkipInitialization);
859 if (!parent_matrix.GetInverse(&inverse_parent_matrix)) {
860 // TODO(shawnsingh): Either we need to handle uninvertible transforms
861 // here, or DCHECK that the transform is invertible.
863 scroll_compensation_for_this_layer.PreconcatTransform(
864 inverse_parent_matrix); // Step 1
865 return scroll_compensation_for_this_layer;
868 gfx::Transform ComputeScrollCompensationMatrixForChildren(
869 LayerImpl* layer,
870 const gfx::Transform& parent_matrix,
871 const gfx::Transform& current_scroll_compensation_matrix,
872 const gfx::Vector2dF& scroll_delta) {
873 // "Total scroll compensation" is the transform needed to cancel out all
874 // scroll_delta translations that occurred since the nearest container layer,
875 // even if there are render_surfaces in-between.
877 // There are some edge cases to be aware of, that are not explicit in the
878 // code:
879 // - A layer that is both a fixed-position and container should not be its
880 // own container, instead, that means it is fixed to an ancestor, and is a
881 // container for any fixed-position descendants.
882 // - A layer that is a fixed-position container and has a render_surface
883 // should behave the same as a container without a render_surface, the
884 // render_surface is irrelevant in that case.
885 // - A layer that does not have an explicit container is simply fixed to the
886 // viewport. (i.e. the root render_surface.)
887 // - If the fixed-position layer has its own render_surface, then the
888 // render_surface is the one who gets fixed.
890 // This function needs to be called AFTER layers create their own
891 // render_surfaces.
894 // Scroll compensation restarts from identity under two possible conditions:
895 // - the current layer is a container for fixed-position descendants
896 // - the current layer is fixed-position itself, so any fixed-position
897 // descendants are positioned with respect to this layer. Thus, any
898 // fixed position descendants only need to compensate for scrollDeltas
899 // that occur below this layer.
900 bool current_layer_resets_scroll_compensation_for_descendants =
901 layer->IsContainerForFixedPositionLayers() ||
902 layer->position_constraint().is_fixed_position();
904 // Avoid the overheads (including stack allocation and matrix
905 // initialization/copy) if we know that the scroll compensation doesn't need
906 // to be reset or adjusted.
907 if (!current_layer_resets_scroll_compensation_for_descendants &&
908 scroll_delta.IsZero() && !layer->render_surface())
909 return current_scroll_compensation_matrix;
911 // Start as identity matrix.
912 gfx::Transform next_scroll_compensation_matrix;
914 // If this layer does not reset scroll compensation, then it inherits the
915 // existing scroll compensations.
916 if (!current_layer_resets_scroll_compensation_for_descendants)
917 next_scroll_compensation_matrix = current_scroll_compensation_matrix;
919 // If the current layer has a non-zero scroll_delta, then we should compute
920 // its local scroll compensation and accumulate it to the
921 // next_scroll_compensation_matrix.
922 if (!scroll_delta.IsZero()) {
923 gfx::Transform scroll_compensation_for_this_layer =
924 ComputeScrollCompensationForThisLayer(
925 layer, parent_matrix, scroll_delta);
926 next_scroll_compensation_matrix.PreconcatTransform(
927 scroll_compensation_for_this_layer);
930 // If the layer created its own render_surface, we have to adjust
931 // next_scroll_compensation_matrix. The adjustment allows us to continue
932 // using the scroll compensation on the next surface.
933 // Step 1 (right-most in the math): transform from the new surface to the
934 // original ancestor surface
935 // Step 2: apply the scroll compensation
936 // Step 3: transform back to the new surface.
937 if (layer->render_surface() &&
938 !next_scroll_compensation_matrix.IsIdentity()) {
939 gfx::Transform inverse_surface_draw_transform(
940 gfx::Transform::kSkipInitialization);
941 if (!layer->render_surface()->draw_transform().GetInverse(
942 &inverse_surface_draw_transform)) {
943 // TODO(shawnsingh): Either we need to handle uninvertible transforms
944 // here, or DCHECK that the transform is invertible.
946 next_scroll_compensation_matrix =
947 inverse_surface_draw_transform * next_scroll_compensation_matrix *
948 layer->render_surface()->draw_transform();
951 return next_scroll_compensation_matrix;
954 static inline void UpdateLayerScaleDrawProperties(
955 LayerImpl* layer,
956 float maximum_animation_contents_scale,
957 float starting_animation_contents_scale) {
958 layer->draw_properties().maximum_animation_contents_scale =
959 maximum_animation_contents_scale;
960 layer->draw_properties().starting_animation_contents_scale =
961 starting_animation_contents_scale;
964 static inline void CalculateAnimationContentsScale(
965 LayerImpl* layer,
966 bool ancestor_is_animating_scale,
967 float ancestor_maximum_animation_contents_scale,
968 float ancestor_starting_animation_contents_scale,
969 const gfx::Transform& ancestor_transform,
970 const gfx::Transform& combined_transform,
971 bool* combined_is_animating_scale,
972 float* combined_maximum_animation_contents_scale,
973 float* combined_starting_animation_contents_scale) {
974 if (ancestor_is_animating_scale &&
975 ancestor_maximum_animation_contents_scale == 0.f) {
976 // We've already failed to compute a maximum animated scale at an
977 // ancestor, so we'll continue to fail.
978 *combined_maximum_animation_contents_scale = 0.f;
979 *combined_starting_animation_contents_scale = 0.f;
980 *combined_is_animating_scale = true;
981 return;
984 if (!combined_transform.IsScaleOrTranslation()) {
985 // Computing maximum animated scale in the presence of
986 // non-scale/translation transforms isn't supported.
987 *combined_maximum_animation_contents_scale = 0.f;
988 *combined_starting_animation_contents_scale = 0.f;
989 *combined_is_animating_scale = true;
990 return;
993 // We currently only support computing maximum scale for combinations of
994 // scales and translations. We treat all non-translations as potentially
995 // affecting scale. Animations that include non-translation/scale components
996 // will cause the computation of MaximumScale below to fail.
997 bool layer_is_animating_scale = !layer->HasOnlyTranslationTransforms();
999 if (!layer_is_animating_scale && !ancestor_is_animating_scale) {
1000 *combined_maximum_animation_contents_scale = 0.f;
1001 *combined_starting_animation_contents_scale = 0.f;
1002 *combined_is_animating_scale = false;
1003 return;
1006 // We don't attempt to accumulate animation scale from multiple nodes,
1007 // because of the risk of significant overestimation. For example, one node
1008 // may be increasing scale from 1 to 10 at the same time as a descendant is
1009 // decreasing scale from 10 to 1. Naively combining these scales would produce
1010 // a scale of 100.
1011 if (layer_is_animating_scale && ancestor_is_animating_scale) {
1012 *combined_maximum_animation_contents_scale = 0.f;
1013 *combined_starting_animation_contents_scale = 0.f;
1014 *combined_is_animating_scale = true;
1015 return;
1018 // At this point, we know either the layer or an ancestor, but not both,
1019 // is animating scale.
1020 *combined_is_animating_scale = true;
1021 if (!layer_is_animating_scale) {
1022 gfx::Vector2dF layer_transform_scales =
1023 MathUtil::ComputeTransform2dScaleComponents(layer->transform(), 0.f);
1024 float max_layer_scale =
1025 std::max(layer_transform_scales.x(), layer_transform_scales.y());
1026 *combined_maximum_animation_contents_scale =
1027 ancestor_maximum_animation_contents_scale * max_layer_scale;
1028 *combined_starting_animation_contents_scale =
1029 ancestor_starting_animation_contents_scale * max_layer_scale;
1030 return;
1033 float layer_maximum_animated_scale = 0.f;
1034 float layer_start_animated_scale = 0.f;
1035 if (!layer->MaximumTargetScale(&layer_maximum_animated_scale)) {
1036 *combined_maximum_animation_contents_scale = 0.f;
1037 return;
1039 if (!layer->AnimationStartScale(&layer_start_animated_scale)) {
1040 *combined_starting_animation_contents_scale = 0.f;
1041 return;
1044 gfx::Vector2dF ancestor_transform_scales =
1045 MathUtil::ComputeTransform2dScaleComponents(ancestor_transform, 0.f);
1046 float max_scale_xy =
1047 std::max(ancestor_transform_scales.x(), ancestor_transform_scales.y());
1048 *combined_maximum_animation_contents_scale =
1049 layer_maximum_animated_scale * max_scale_xy;
1050 *combined_starting_animation_contents_scale =
1051 layer_start_animated_scale * max_scale_xy;
1054 static inline void MarkLayerWithRenderSurfaceLayerListId(
1055 LayerImpl* layer,
1056 int current_render_surface_layer_list_id) {
1057 layer->draw_properties().last_drawn_render_surface_layer_list_id =
1058 current_render_surface_layer_list_id;
1059 layer->set_layer_or_descendant_is_drawn(
1060 !!current_render_surface_layer_list_id);
1063 static inline void MarkMasksWithRenderSurfaceLayerListId(
1064 LayerImpl* layer,
1065 int current_render_surface_layer_list_id) {
1066 if (layer->mask_layer()) {
1067 MarkLayerWithRenderSurfaceLayerListId(layer->mask_layer(),
1068 current_render_surface_layer_list_id);
1070 if (layer->replica_layer() && layer->replica_layer()->mask_layer()) {
1071 MarkLayerWithRenderSurfaceLayerListId(layer->replica_layer()->mask_layer(),
1072 current_render_surface_layer_list_id);
1076 static inline void MarkLayerListWithRenderSurfaceLayerListId(
1077 LayerImplList* layer_list,
1078 int current_render_surface_layer_list_id) {
1079 for (LayerImplList::iterator it = layer_list->begin();
1080 it != layer_list->end(); ++it) {
1081 MarkLayerWithRenderSurfaceLayerListId(*it,
1082 current_render_surface_layer_list_id);
1083 MarkMasksWithRenderSurfaceLayerListId(*it,
1084 current_render_surface_layer_list_id);
1088 static inline void RemoveSurfaceForEarlyExit(
1089 LayerImpl* layer_to_remove,
1090 LayerImplList* render_surface_layer_list) {
1091 DCHECK(layer_to_remove->render_surface());
1092 // Technically, we know that the layer we want to remove should be
1093 // at the back of the render_surface_layer_list. However, we have had
1094 // bugs before that added unnecessary layers here
1095 // (https://bugs.webkit.org/show_bug.cgi?id=74147), but that causes
1096 // things to crash. So here we proactively remove any additional
1097 // layers from the end of the list.
1098 while (render_surface_layer_list->back() != layer_to_remove) {
1099 MarkLayerListWithRenderSurfaceLayerListId(
1100 &render_surface_layer_list->back()->render_surface()->layer_list(), 0);
1101 MarkLayerWithRenderSurfaceLayerListId(render_surface_layer_list->back(), 0);
1103 render_surface_layer_list->back()->ClearRenderSurfaceLayerList();
1104 render_surface_layer_list->pop_back();
1106 DCHECK_EQ(render_surface_layer_list->back(), layer_to_remove);
1107 MarkLayerListWithRenderSurfaceLayerListId(
1108 &layer_to_remove->render_surface()->layer_list(), 0);
1109 MarkLayerWithRenderSurfaceLayerListId(layer_to_remove, 0);
1110 render_surface_layer_list->pop_back();
1111 layer_to_remove->ClearRenderSurfaceLayerList();
1114 struct PreCalculateMetaInformationRecursiveData {
1115 size_t num_unclipped_descendants;
1116 int num_layer_or_descendants_with_copy_request;
1117 int num_layer_or_descendants_with_input_handler;
1119 PreCalculateMetaInformationRecursiveData()
1120 : num_unclipped_descendants(0),
1121 num_layer_or_descendants_with_copy_request(0),
1122 num_layer_or_descendants_with_input_handler(0) {}
1124 void Merge(const PreCalculateMetaInformationRecursiveData& data) {
1125 num_layer_or_descendants_with_copy_request +=
1126 data.num_layer_or_descendants_with_copy_request;
1127 num_layer_or_descendants_with_input_handler +=
1128 data.num_layer_or_descendants_with_input_handler;
1129 num_unclipped_descendants += data.num_unclipped_descendants;
1133 static void ValidateRenderSurface(LayerImpl* layer) {
1134 // This test verifies that there are no cases where a LayerImpl needs
1135 // a render surface, but doesn't have one.
1136 if (layer->render_surface())
1137 return;
1139 DCHECK(layer->filters().IsEmpty()) << "layer: " << layer->id();
1140 DCHECK(layer->background_filters().IsEmpty()) << "layer: " << layer->id();
1141 DCHECK(!layer->mask_layer()) << "layer: " << layer->id();
1142 DCHECK(!layer->replica_layer()) << "layer: " << layer->id();
1143 DCHECK(!IsRootLayer(layer)) << "layer: " << layer->id();
1144 DCHECK(!layer->is_root_for_isolated_group()) << "layer: " << layer->id();
1145 DCHECK(!layer->HasCopyRequest()) << "layer: " << layer->id();
1148 static void ValidateRenderSurface(Layer* layer) {
1151 static bool IsMetaInformationRecomputationNeeded(Layer* layer) {
1152 return layer->layer_tree_host()->needs_meta_info_recomputation();
1155 static void UpdateMetaInformationSequenceNumber(Layer* root_layer) {
1156 root_layer->layer_tree_host()->IncrementMetaInformationSequenceNumber();
1159 static void UpdateMetaInformationSequenceNumber(LayerImpl* root_layer) {
1162 // Recursively walks the layer tree(if needed) to compute any information
1163 // that is needed before doing the main recursion.
1164 static void PreCalculateMetaInformationInternal(
1165 Layer* layer,
1166 PreCalculateMetaInformationRecursiveData* recursive_data) {
1167 ValidateRenderSurface(layer);
1169 if (!IsMetaInformationRecomputationNeeded(layer)) {
1170 DCHECK(IsRootLayer(layer));
1171 return;
1174 layer->set_sorted_for_recursion(false);
1175 layer->draw_properties().has_child_with_a_scroll_parent = false;
1176 layer->set_layer_or_descendant_is_drawn(false);
1177 layer->set_visited(false);
1179 if (!HasInvertibleOrAnimatedTransform(layer)) {
1180 // Layers with singular transforms should not be drawn, the whole subtree
1181 // can be skipped.
1182 return;
1185 if (layer->clip_parent())
1186 recursive_data->num_unclipped_descendants++;
1188 layer->set_num_children_with_scroll_parent(0);
1189 for (size_t i = 0; i < layer->children().size(); ++i) {
1190 Layer* child_layer = layer->child_at(i);
1192 PreCalculateMetaInformationRecursiveData data_for_child;
1193 PreCalculateMetaInformationInternal(child_layer, &data_for_child);
1195 if (child_layer->scroll_parent()) {
1196 layer->draw_properties().has_child_with_a_scroll_parent = true;
1197 layer->set_num_children_with_scroll_parent(
1198 layer->num_children_with_scroll_parent() + 1);
1200 recursive_data->Merge(data_for_child);
1203 if (layer->clip_children()) {
1204 size_t num_clip_children = layer->clip_children()->size();
1205 DCHECK_GE(recursive_data->num_unclipped_descendants, num_clip_children);
1206 recursive_data->num_unclipped_descendants -= num_clip_children;
1209 if (layer->HasCopyRequest())
1210 recursive_data->num_layer_or_descendants_with_copy_request++;
1212 if (!layer->touch_event_handler_region().IsEmpty() ||
1213 layer->have_wheel_event_handlers())
1214 recursive_data->num_layer_or_descendants_with_input_handler++;
1216 layer->draw_properties().num_unclipped_descendants =
1217 recursive_data->num_unclipped_descendants;
1218 layer->draw_properties().layer_or_descendant_has_copy_request =
1219 (recursive_data->num_layer_or_descendants_with_copy_request != 0);
1220 layer->draw_properties().layer_or_descendant_has_input_handler =
1221 (recursive_data->num_layer_or_descendants_with_input_handler != 0);
1222 layer->set_num_layer_or_descandant_with_copy_request(
1223 recursive_data->num_layer_or_descendants_with_copy_request);
1225 if (IsRootLayer(layer))
1226 layer->layer_tree_host()->SetNeedsMetaInfoRecomputation(false);
1229 static void PreCalculateMetaInformationInternal(
1230 LayerImpl* layer,
1231 PreCalculateMetaInformationRecursiveData* recursive_data) {
1232 ValidateRenderSurface(layer);
1234 layer->set_sorted_for_recursion(false);
1235 layer->draw_properties().has_child_with_a_scroll_parent = false;
1236 layer->set_layer_or_descendant_is_drawn(false);
1237 layer->set_visited(false);
1239 if (!HasInvertibleOrAnimatedTransform(layer)) {
1240 // Layers with singular transforms should not be drawn, the whole subtree
1241 // can be skipped.
1242 return;
1245 if (layer->clip_parent())
1246 recursive_data->num_unclipped_descendants++;
1248 for (size_t i = 0; i < layer->children().size(); ++i) {
1249 LayerImpl* child_layer = layer->child_at(i);
1251 PreCalculateMetaInformationRecursiveData data_for_child;
1252 PreCalculateMetaInformationInternal(child_layer, &data_for_child);
1254 if (child_layer->scroll_parent())
1255 layer->draw_properties().has_child_with_a_scroll_parent = true;
1256 recursive_data->Merge(data_for_child);
1259 if (layer->clip_children()) {
1260 size_t num_clip_children = layer->clip_children()->size();
1261 DCHECK_GE(recursive_data->num_unclipped_descendants, num_clip_children);
1262 recursive_data->num_unclipped_descendants -= num_clip_children;
1265 if (layer->HasCopyRequest())
1266 recursive_data->num_layer_or_descendants_with_copy_request++;
1268 if (!layer->touch_event_handler_region().IsEmpty() ||
1269 layer->have_wheel_event_handlers())
1270 recursive_data->num_layer_or_descendants_with_input_handler++;
1272 layer->draw_properties().num_unclipped_descendants =
1273 recursive_data->num_unclipped_descendants;
1274 layer->draw_properties().layer_or_descendant_has_copy_request =
1275 (recursive_data->num_layer_or_descendants_with_copy_request != 0);
1276 layer->draw_properties().layer_or_descendant_has_input_handler =
1277 (recursive_data->num_layer_or_descendants_with_input_handler != 0);
1280 void LayerTreeHostCommon::PreCalculateMetaInformation(Layer* root_layer) {
1281 PreCalculateMetaInformationRecursiveData recursive_data;
1282 PreCalculateMetaInformationInternal(root_layer, &recursive_data);
1285 void LayerTreeHostCommon::PreCalculateMetaInformationForTesting(
1286 LayerImpl* root_layer) {
1287 PreCalculateMetaInformationRecursiveData recursive_data;
1288 PreCalculateMetaInformationInternal(root_layer, &recursive_data);
1291 void LayerTreeHostCommon::PreCalculateMetaInformationForTesting(
1292 Layer* root_layer) {
1293 UpdateMetaInformationSequenceNumber(root_layer);
1294 PreCalculateMetaInformationRecursiveData recursive_data;
1295 PreCalculateMetaInformationInternal(root_layer, &recursive_data);
1298 struct SubtreeGlobals {
1299 int max_texture_size;
1300 float device_scale_factor;
1301 float page_scale_factor;
1302 const LayerImpl* page_scale_layer;
1303 gfx::Vector2dF elastic_overscroll;
1304 const LayerImpl* elastic_overscroll_application_layer;
1305 bool can_adjust_raster_scales;
1306 bool can_render_to_separate_surface;
1307 bool layers_always_allowed_lcd_text;
1310 struct DataForRecursion {
1311 // The accumulated sequence of transforms a layer will use to determine its
1312 // own draw transform.
1313 gfx::Transform parent_matrix;
1315 // The accumulated sequence of transforms a layer will use to determine its
1316 // own screen-space transform.
1317 gfx::Transform full_hierarchy_matrix;
1319 // The transform that removes all scrolling that may have occurred between a
1320 // fixed-position layer and its container, so that the layer actually does
1321 // remain fixed.
1322 gfx::Transform scroll_compensation_matrix;
1324 // The ancestor that would be the container for any fixed-position / sticky
1325 // layers.
1326 LayerImpl* fixed_container;
1328 // This is the normal clip rect that is propagated from parent to child.
1329 gfx::Rect clip_rect_in_target_space;
1331 // When the layer's children want to compute their visible content rect, they
1332 // want to know what their target surface's clip rect will be. BUT - they
1333 // want to know this clip rect represented in their own target space. This
1334 // requires inverse-projecting the surface's clip rect from the surface's
1335 // render target space down to the surface's own space. Instead of computing
1336 // this value redundantly for each child layer, it is computed only once
1337 // while dealing with the parent layer, and then this precomputed value is
1338 // passed down the recursion to the children that actually use it.
1339 gfx::Rect clip_rect_of_target_surface_in_target_space;
1341 // The maximum amount by which this layer will be scaled during the lifetime
1342 // of currently running animations, considering only scales at keyframes not
1343 // including the starting keyframe of each animation.
1344 float maximum_animation_contents_scale;
1346 // The maximum amout by which this layer will be scaled during the lifetime of
1347 // currently running animations, consdering only the starting scale of each
1348 // animation.
1349 float starting_animation_contents_scale;
1351 bool ancestor_is_animating_scale;
1352 bool ancestor_clips_subtree;
1353 RenderSurfaceImpl* nearest_occlusion_immune_ancestor_surface;
1354 bool in_subtree_of_page_scale_layer;
1355 bool subtree_can_use_lcd_text;
1356 bool subtree_is_visible_from_ancestor;
1359 static LayerImpl* GetChildContainingLayer(const LayerImpl& parent,
1360 LayerImpl* layer) {
1361 for (LayerImpl* ancestor = layer; ancestor; ancestor = ancestor->parent()) {
1362 if (ancestor->parent() == &parent)
1363 return ancestor;
1365 NOTREACHED();
1366 return 0;
1369 static void AddScrollParentChain(std::vector<LayerImpl*>* out,
1370 const LayerImpl& parent,
1371 LayerImpl* layer) {
1372 // At a high level, this function walks up the chain of scroll parents
1373 // recursively, and once we reach the end of the chain, we add the child
1374 // of |parent| containing each scroll ancestor as we unwind. The result is
1375 // an ordering of parent's children that ensures that scroll parents are
1376 // visited before their descendants.
1377 // Take for example this layer tree:
1379 // + stacking_context
1380 // + scroll_child (1)
1381 // + scroll_parent_graphics_layer (*)
1382 // | + scroll_parent_scrolling_layer
1383 // | + scroll_parent_scrolling_content_layer (2)
1384 // + scroll_grandparent_graphics_layer (**)
1385 // + scroll_grandparent_scrolling_layer
1386 // + scroll_grandparent_scrolling_content_layer (3)
1388 // The scroll child is (1), its scroll parent is (2) and its scroll
1389 // grandparent is (3). Note, this doesn't mean that (2)'s scroll parent is
1390 // (3), it means that (*)'s scroll parent is (3). We don't want our list to
1391 // look like [ (3), (2), (1) ], even though that does have the ancestor chain
1392 // in the right order. Instead, we want [ (**), (*), (1) ]. That is, only want
1393 // (1)'s siblings in the list, but we want them to appear in such an order
1394 // that the scroll ancestors get visited in the correct order.
1396 // So our first task at this step of the recursion is to determine the layer
1397 // that we will potentionally add to the list. That is, the child of parent
1398 // containing |layer|.
1399 LayerImpl* child = GetChildContainingLayer(parent, layer);
1400 if (child->sorted_for_recursion())
1401 return;
1403 if (LayerImpl* scroll_parent = child->scroll_parent())
1404 AddScrollParentChain(out, parent, scroll_parent);
1406 out->push_back(child);
1407 bool sorted_for_recursion = true;
1408 child->set_sorted_for_recursion(sorted_for_recursion);
1411 static bool SortChildrenForRecursion(std::vector<LayerImpl*>* out,
1412 const LayerImpl& parent) {
1413 out->reserve(parent.children().size());
1414 bool order_changed = false;
1415 for (size_t i = 0; i < parent.children().size(); ++i) {
1416 LayerImpl* current =
1417 LayerTreeHostCommon::get_layer_as_raw_ptr(parent.children(), i);
1419 if (current->sorted_for_recursion()) {
1420 order_changed = true;
1421 continue;
1424 AddScrollParentChain(out, parent, current);
1427 DCHECK_EQ(parent.children().size(), out->size());
1428 return order_changed;
1431 // Recursively walks the layer tree starting at the given node and computes all
1432 // the necessary transformations, clip rects, render surfaces, etc.
1433 static void CalculateDrawPropertiesInternal(
1434 LayerImpl* layer,
1435 const SubtreeGlobals& globals,
1436 const DataForRecursion& data_from_ancestor,
1437 std::vector<AccumulatedSurfaceState>* accumulated_surface_state) {
1438 // This function computes the new matrix transformations recursively for this
1439 // layer and all its descendants. It also computes the appropriate render
1440 // surfaces.
1441 // Some important points to remember:
1443 // 0. Here, transforms are notated in Matrix x Vector order, and in words we
1444 // describe what the transform does from left to right.
1446 // 1. In our terminology, the "layer origin" refers to the top-left corner of
1447 // a layer, and the positive Y-axis points downwards. This interpretation is
1448 // valid because the orthographic projection applied at draw time flips the Y
1449 // axis appropriately.
1451 // 2. The anchor point, when given as a PointF object, is specified in "unit
1452 // layer space", where the bounds of the layer map to [0, 1]. However, as a
1453 // Transform object, the transform to the anchor point is specified in "layer
1454 // space", where the bounds of the layer map to [bounds.width(),
1455 // bounds.height()].
1457 // 3. Definition of various transforms used:
1458 // M[parent] is the parent matrix, with respect to the nearest render
1459 // surface, passed down recursively.
1461 // M[root] is the full hierarchy, with respect to the root, passed down
1462 // recursively.
1464 // Tr[origin] is the translation matrix from the parent's origin to
1465 // this layer's origin.
1467 // Tr[origin2anchor] is the translation from the layer's origin to its
1468 // anchor point
1470 // Tr[origin2center] is the translation from the layer's origin to its
1471 // center
1473 // M[layer] is the layer's matrix (applied at the anchor point)
1475 // S[layer2content] is the ratio of a layer's content_bounds() to its
1476 // Bounds().
1478 // Some composite transforms can help in understanding the sequence of
1479 // transforms:
1480 // composite_layer_transform = Tr[origin2anchor] * M[layer] *
1481 // Tr[origin2anchor].inverse()
1483 // 4. When a layer (or render surface) is drawn, it is drawn into a "target
1484 // render surface". Therefore the draw transform does not necessarily
1485 // transform from screen space to local layer space. Instead, the draw
1486 // transform is the transform between the "target render surface space" and
1487 // local layer space. Note that render surfaces, except for the root, also
1488 // draw themselves into a different target render surface, and so their draw
1489 // transform and origin transforms are also described with respect to the
1490 // target.
1492 // Using these definitions, then:
1494 // The draw transform for the layer is:
1495 // M[draw] = M[parent] * Tr[origin] * composite_layer_transform *
1496 // S[layer2content] = M[parent] * Tr[layer->position() + anchor] *
1497 // M[layer] * Tr[anchor2origin] * S[layer2content]
1499 // Interpreting the math left-to-right, this transforms from the
1500 // layer's render surface to the origin of the layer in content space.
1502 // The screen space transform is:
1503 // M[screenspace] = M[root] * Tr[origin] * composite_layer_transform *
1504 // S[layer2content]
1505 // = M[root] * Tr[layer->position() + anchor] * M[layer]
1506 // * Tr[anchor2origin] * S[layer2content]
1508 // Interpreting the math left-to-right, this transforms from the root
1509 // render surface's content space to the origin of the layer in content
1510 // space.
1512 // The transform hierarchy that is passed on to children (i.e. the child's
1513 // parent_matrix) is:
1514 // M[parent]_for_child = M[parent] * Tr[origin] *
1515 // composite_layer_transform
1516 // = M[parent] * Tr[layer->position() + anchor] *
1517 // M[layer] * Tr[anchor2origin]
1519 // and a similar matrix for the full hierarchy with respect to the
1520 // root.
1522 // Finally, note that the final matrix used by the shader for the layer is P *
1523 // M[draw] * S . This final product is computed in drawTexturedQuad(), where:
1524 // P is the projection matrix
1525 // S is the scale adjustment (to scale up a canonical quad to the
1526 // layer's size)
1528 // When a render surface has a replica layer, that layer's transform is used
1529 // to draw a second copy of the surface. gfx::Transforms named here are
1530 // relative to the surface, unless they specify they are relative to the
1531 // replica layer.
1533 // We will denote a scale by device scale S[deviceScale]
1535 // The render surface draw transform to its target surface origin is:
1536 // M[surfaceDraw] = M[owningLayer->Draw]
1538 // The render surface origin transform to its the root (screen space) origin
1539 // is:
1540 // M[surface2root] = M[owningLayer->screenspace] *
1541 // S[deviceScale].inverse()
1543 // The replica draw transform to its target surface origin is:
1544 // M[replicaDraw] = S[deviceScale] * M[surfaceDraw] *
1545 // Tr[replica->position() + replica->anchor()] * Tr[replica] *
1546 // Tr[origin2anchor].inverse() * S[contents_scale].inverse()
1548 // The replica draw transform to the root (screen space) origin is:
1549 // M[replica2root] = M[surface2root] * Tr[replica->position()] *
1550 // Tr[replica] * Tr[origin2anchor].inverse()
1553 // It makes no sense to have a non-unit page_scale_factor without specifying
1554 // which layer roots the subtree the scale is applied to.
1555 DCHECK(globals.page_scale_layer || (globals.page_scale_factor == 1.f));
1557 CHECK(!layer->visited());
1558 bool visited = true;
1559 layer->set_visited(visited);
1561 DataForRecursion data_for_children;
1562 RenderSurfaceImpl* nearest_occlusion_immune_ancestor_surface =
1563 data_from_ancestor.nearest_occlusion_immune_ancestor_surface;
1564 data_for_children.in_subtree_of_page_scale_layer =
1565 data_from_ancestor.in_subtree_of_page_scale_layer;
1566 data_for_children.subtree_can_use_lcd_text =
1567 data_from_ancestor.subtree_can_use_lcd_text;
1569 // Layers that are marked as hidden will hide themselves and their subtree.
1570 // Exception: Layers with copy requests, whether hidden or not, must be drawn
1571 // anyway. In this case, we will inform their subtree they are visible to get
1572 // the right results.
1573 const bool layer_is_visible =
1574 data_from_ancestor.subtree_is_visible_from_ancestor &&
1575 !layer->hide_layer_and_subtree();
1576 const bool layer_is_drawn = layer_is_visible || layer->HasCopyRequest();
1578 // The root layer cannot skip CalcDrawProperties.
1579 if (!IsRootLayer(layer) && SubtreeShouldBeSkipped(layer, layer_is_drawn)) {
1580 return;
1583 // We need to circumvent the normal recursive flow of information for clip
1584 // children (they don't inherit their direct ancestor's clip information).
1585 // This is unfortunate, and would be unnecessary if we were to formally
1586 // separate the clipping hierarchy from the layer hierarchy.
1587 bool ancestor_clips_subtree = data_from_ancestor.ancestor_clips_subtree;
1588 gfx::Rect ancestor_clip_rect_in_target_space =
1589 data_from_ancestor.clip_rect_in_target_space;
1591 // Update our clipping state. If we have a clip parent we will need to pull
1592 // from the clip state cache rather than using the clip state passed from our
1593 // immediate ancestor.
1594 UpdateClipRectsForClipChild(layer, &ancestor_clip_rect_in_target_space,
1595 &ancestor_clips_subtree);
1597 // As this function proceeds, these are the properties for the current
1598 // layer that actually get computed. To avoid unnecessary copies
1599 // (particularly for matrices), we do computations directly on these values
1600 // when possible.
1601 DrawProperties<LayerImpl>& layer_draw_properties = layer->draw_properties();
1603 gfx::Rect clip_rect_in_target_space;
1604 bool layer_or_ancestor_clips_descendants = false;
1606 // This value is cached on the stack so that we don't have to inverse-project
1607 // the surface's clip rect redundantly for every layer. This value is the
1608 // same as the target surface's clip rect, except that instead of being
1609 // described in the target surface's target's space, it is described in the
1610 // current render target's space.
1611 gfx::Rect clip_rect_of_target_surface_in_target_space;
1613 float accumulated_draw_opacity = layer->opacity();
1614 if (layer->parent())
1615 accumulated_draw_opacity *= layer->parent()->draw_opacity();
1617 bool animating_transform_to_screen =
1618 layer->HasPotentiallyRunningTransformAnimation();
1619 if (layer->parent()) {
1620 animating_transform_to_screen |=
1621 layer->parent()->screen_space_transform_is_animating();
1623 gfx::Point3F transform_origin = layer->transform_origin();
1624 gfx::ScrollOffset scroll_offset = GetEffectiveCurrentScrollOffset(layer);
1625 gfx::PointF position =
1626 layer->position() - ScrollOffsetToVector2dF(scroll_offset);
1627 gfx::Transform combined_transform = data_from_ancestor.parent_matrix;
1628 if (!layer->transform().IsIdentity()) {
1629 // LT = Tr[origin] * Tr[origin2transformOrigin]
1630 combined_transform.Translate3d(position.x() + transform_origin.x(),
1631 position.y() + transform_origin.y(),
1632 transform_origin.z());
1633 // LT = Tr[origin] * Tr[origin2origin] * M[layer]
1634 combined_transform.PreconcatTransform(layer->transform());
1635 // LT = Tr[origin] * Tr[origin2origin] * M[layer] *
1636 // Tr[transformOrigin2origin]
1637 combined_transform.Translate3d(
1638 -transform_origin.x(), -transform_origin.y(), -transform_origin.z());
1639 } else {
1640 combined_transform.Translate(position.x(), position.y());
1643 gfx::Vector2dF effective_scroll_delta = GetEffectiveScrollDelta(layer);
1644 if (!animating_transform_to_screen && layer->scrollable() &&
1645 combined_transform.IsScaleOrTranslation()) {
1646 // Align the scrollable layer's position to screen space pixels to avoid
1647 // blurriness. To avoid side-effects, do this only if the transform is
1648 // simple.
1649 gfx::Vector2dF previous_translation = combined_transform.To2dTranslation();
1650 combined_transform.RoundTranslationComponents();
1651 gfx::Vector2dF current_translation = combined_transform.To2dTranslation();
1653 // This rounding changes the scroll delta, and so must be included
1654 // in the scroll compensation matrix. The scaling converts from physical
1655 // coordinates to the scroll delta's CSS coordinates (using the parent
1656 // matrix instead of combined transform since scrolling is applied before
1657 // the layer's transform). For example, if we have a total scale factor of
1658 // 3.0, then 1 physical pixel is only 1/3 of a CSS pixel.
1659 gfx::Vector2dF parent_scales = MathUtil::ComputeTransform2dScaleComponents(
1660 data_from_ancestor.parent_matrix, 1.f);
1661 effective_scroll_delta -=
1662 gfx::ScaleVector2d(current_translation - previous_translation,
1663 1.f / parent_scales.x(),
1664 1.f / parent_scales.y());
1667 // Apply adjustment from position constraints.
1668 ApplyPositionAdjustment(layer, data_from_ancestor.fixed_container,
1669 data_from_ancestor.scroll_compensation_matrix, &combined_transform);
1671 bool combined_is_animating_scale = false;
1672 float combined_maximum_animation_contents_scale = 0.f;
1673 float combined_starting_animation_contents_scale = 0.f;
1674 if (globals.can_adjust_raster_scales) {
1675 CalculateAnimationContentsScale(
1676 layer, data_from_ancestor.ancestor_is_animating_scale,
1677 data_from_ancestor.maximum_animation_contents_scale,
1678 data_from_ancestor.starting_animation_contents_scale,
1679 data_from_ancestor.parent_matrix, combined_transform,
1680 &combined_is_animating_scale,
1681 &combined_maximum_animation_contents_scale,
1682 &combined_starting_animation_contents_scale);
1684 data_for_children.ancestor_is_animating_scale = combined_is_animating_scale;
1685 data_for_children.maximum_animation_contents_scale =
1686 combined_maximum_animation_contents_scale;
1687 data_for_children.starting_animation_contents_scale =
1688 combined_starting_animation_contents_scale;
1690 // Compute the 2d scale components of the transform hierarchy up to the target
1691 // surface. From there, we can decide on a contents scale for the layer.
1692 float layer_scale_factors = globals.device_scale_factor;
1693 if (data_from_ancestor.in_subtree_of_page_scale_layer)
1694 layer_scale_factors *= globals.page_scale_factor;
1695 gfx::Vector2dF combined_transform_scales =
1696 MathUtil::ComputeTransform2dScaleComponents(
1697 combined_transform,
1698 layer_scale_factors);
1700 UpdateLayerScaleDrawProperties(layer,
1701 combined_maximum_animation_contents_scale,
1702 combined_starting_animation_contents_scale);
1704 LayerImpl* mask_layer = layer->mask_layer();
1705 if (mask_layer) {
1706 UpdateLayerScaleDrawProperties(mask_layer,
1707 combined_maximum_animation_contents_scale,
1708 combined_starting_animation_contents_scale);
1711 LayerImpl* replica_mask_layer =
1712 layer->replica_layer() ? layer->replica_layer()->mask_layer() : NULL;
1713 if (replica_mask_layer) {
1714 UpdateLayerScaleDrawProperties(replica_mask_layer,
1715 combined_maximum_animation_contents_scale,
1716 combined_starting_animation_contents_scale);
1719 if (layer == globals.page_scale_layer) {
1720 combined_transform.Scale(globals.page_scale_factor,
1721 globals.page_scale_factor);
1722 data_for_children.in_subtree_of_page_scale_layer = true;
1725 // The draw_transform that gets computed below is effectively the layer's
1726 // draw_transform, unless the layer itself creates a render_surface. In that
1727 // case, the render_surface re-parents the transforms.
1728 layer_draw_properties.target_space_transform = combined_transform;
1730 // The layer's screen_space_transform represents the transform between root
1731 // layer's "screen space" and local content space.
1732 layer_draw_properties.screen_space_transform =
1733 data_from_ancestor.full_hierarchy_matrix;
1734 layer_draw_properties.screen_space_transform.PreconcatTransform
1735 (layer_draw_properties.target_space_transform);
1737 bool layer_can_use_lcd_text = true;
1738 bool subtree_can_use_lcd_text = true;
1739 if (!globals.layers_always_allowed_lcd_text) {
1740 // To avoid color fringing, LCD text should only be used on opaque layers
1741 // with just integral translation.
1742 subtree_can_use_lcd_text = data_from_ancestor.subtree_can_use_lcd_text &&
1743 accumulated_draw_opacity == 1.f &&
1744 layer_draw_properties.target_space_transform
1745 .IsIdentityOrIntegerTranslation();
1746 // Also disable LCD text locally for non-opaque content.
1747 layer_can_use_lcd_text = subtree_can_use_lcd_text &&
1748 layer->contents_opaque();
1751 // full_hierarchy_matrix is the matrix that transforms objects between screen
1752 // space (except projection matrix) and the most recent RenderSurfaceImpl's
1753 // space. next_hierarchy_matrix will only change if this layer uses a new
1754 // RenderSurfaceImpl, otherwise remains the same.
1755 data_for_children.full_hierarchy_matrix =
1756 data_from_ancestor.full_hierarchy_matrix;
1758 bool render_to_separate_surface =
1759 IsRootLayer(layer) ||
1760 (globals.can_render_to_separate_surface && layer->render_surface());
1762 if (render_to_separate_surface) {
1763 DCHECK(layer->render_surface());
1764 // Check back-face visibility before continuing with this surface and its
1765 // subtree
1766 if (!layer->double_sided() &&
1767 IsSurfaceBackFaceVisible(layer, combined_transform)) {
1768 return;
1771 RenderSurfaceImpl* render_surface = layer->render_surface();
1773 if (IsRootLayer(layer)) {
1774 // The root layer's render surface size is predetermined and so the root
1775 // layer can't directly support non-identity transforms. It should just
1776 // forward top-level transforms to the rest of the tree.
1777 data_for_children.parent_matrix = combined_transform;
1778 } else {
1779 // The owning layer's draw transform has a scale from content to layer
1780 // space which we do not want; so here we use the combined_transform
1781 // instead of the draw_transform. However, we do need to add a different
1782 // scale factor that accounts for the surface's pixel dimensions.
1783 // Remove the combined_transform scale from the draw transform.
1784 gfx::Transform draw_transform = combined_transform;
1785 draw_transform.Scale(1.0 / combined_transform_scales.x(),
1786 1.0 / combined_transform_scales.y());
1787 render_surface->SetDrawTransform(draw_transform);
1789 // The owning layer's transform was re-parented by the surface, so the
1790 // layer's new draw_transform only needs to scale the layer to surface
1791 // space.
1792 layer_draw_properties.target_space_transform.MakeIdentity();
1793 layer_draw_properties.target_space_transform.Scale(
1794 combined_transform_scales.x(), combined_transform_scales.y());
1796 // Inside the surface's subtree, we scale everything to the owning layer's
1797 // scale. The sublayer matrix transforms layer rects into target surface
1798 // content space. Conceptually, all layers in the subtree inherit the
1799 // scale at the point of the render surface in the transform hierarchy,
1800 // but we apply it explicitly to the owning layer and the remainder of the
1801 // subtree independently.
1802 DCHECK(data_for_children.parent_matrix.IsIdentity());
1803 data_for_children.parent_matrix.Scale(combined_transform_scales.x(),
1804 combined_transform_scales.y());
1807 // The opacity value is moved from the layer to its surface, so that the
1808 // entire subtree properly inherits opacity.
1809 render_surface->SetDrawOpacity(accumulated_draw_opacity);
1810 layer_draw_properties.opacity = 1.f;
1811 DCHECK_EQ(layer->draw_blend_mode(), SkXfermode::kSrcOver_Mode);
1813 layer_draw_properties.screen_space_transform_is_animating =
1814 animating_transform_to_screen;
1816 // Update the aggregate hierarchy matrix to include the transform of the
1817 // newly created RenderSurfaceImpl.
1818 data_for_children.full_hierarchy_matrix.PreconcatTransform(
1819 render_surface->draw_transform());
1821 // A render surface inherently acts as a flattening point for the content of
1822 // its descendants.
1823 data_for_children.full_hierarchy_matrix.FlattenTo2d();
1825 if (layer->mask_layer()) {
1826 DrawProperties<LayerImpl>& mask_layer_draw_properties =
1827 layer->mask_layer()->draw_properties();
1828 mask_layer_draw_properties.visible_layer_rect =
1829 gfx::Rect(layer->bounds());
1830 // Temporarily copy the draw transform of the mask's owning layer into the
1831 // mask layer draw properties. This won't actually get used for drawing
1832 // (the render surface uses the mask texture directly), but will get used
1833 // to get the correct contents scale.
1834 // TODO(enne): do something similar for property trees.
1835 mask_layer_draw_properties.target_space_transform =
1836 layer_draw_properties.target_space_transform;
1839 if (layer->replica_layer() && layer->replica_layer()->mask_layer()) {
1840 DrawProperties<LayerImpl>& replica_mask_draw_properties =
1841 layer->replica_layer()->mask_layer()->draw_properties();
1842 replica_mask_draw_properties.visible_layer_rect =
1843 gfx::Rect(layer->bounds());
1844 replica_mask_draw_properties.target_space_transform =
1845 layer_draw_properties.target_space_transform;
1848 // Ignore occlusion from outside the surface when surface contents need to
1849 // be fully drawn. Layers with copy-request need to be complete.
1850 // We could be smarter about layers with replica and exclude regions
1851 // where both layer and the replica are occluded, but this seems like an
1852 // overkill. The same is true for layers with filters that move pixels.
1853 // TODO(senorblanco): make this smarter for the SkImageFilter case (check
1854 // for pixel-moving filters)
1855 if (layer->HasCopyRequest() ||
1856 layer->has_replica() ||
1857 layer->filters().HasReferenceFilter() ||
1858 layer->filters().HasFilterThatMovesPixels()) {
1859 nearest_occlusion_immune_ancestor_surface = render_surface;
1861 render_surface->SetNearestOcclusionImmuneAncestor(
1862 nearest_occlusion_immune_ancestor_surface);
1864 layer_or_ancestor_clips_descendants = false;
1865 bool subtree_is_clipped_by_surface_bounds = false;
1866 if (ancestor_clips_subtree) {
1867 // It may be the layer or the surface doing the clipping of the subtree,
1868 // but in either case, we'll be clipping to the projected clip rect of our
1869 // ancestor.
1870 gfx::Transform inverse_surface_draw_transform(
1871 gfx::Transform::kSkipInitialization);
1872 if (!render_surface->draw_transform().GetInverse(
1873 &inverse_surface_draw_transform)) {
1874 // TODO(shawnsingh): Either we need to handle uninvertible transforms
1875 // here, or DCHECK that the transform is invertible.
1878 gfx::Rect surface_clip_rect_in_target_space = gfx::IntersectRects(
1879 data_from_ancestor.clip_rect_of_target_surface_in_target_space,
1880 ancestor_clip_rect_in_target_space);
1881 gfx::Rect projected_surface_rect = MathUtil::ProjectEnclosingClippedRect(
1882 inverse_surface_draw_transform, surface_clip_rect_in_target_space);
1884 if (layer_draw_properties.num_unclipped_descendants > 0u) {
1885 // If we have unclipped descendants, we cannot count on the render
1886 // surface's bounds clipping our subtree: the unclipped descendants
1887 // could cause us to expand our bounds. In this case, we must rely on
1888 // layer clipping for correctess. NB: since we can only encounter
1889 // translations between a clip child and its clip parent, clipping is
1890 // guaranteed to be exact in this case.
1891 layer_or_ancestor_clips_descendants = true;
1892 clip_rect_in_target_space = projected_surface_rect;
1893 } else {
1894 // The new render_surface here will correctly clip the entire subtree.
1895 // So, we do not need to continue propagating the clipping state further
1896 // down the tree. This way, we can avoid transforming clip rects from
1897 // ancestor target surface space to current target surface space that
1898 // could cause more w < 0 headaches. The render surface clip rect is
1899 // expressed in the space where this surface draws, i.e. the same space
1900 // as clip_rect_from_ancestor_in_ancestor_target_space.
1901 render_surface->SetClipRect(ancestor_clip_rect_in_target_space);
1902 clip_rect_of_target_surface_in_target_space = projected_surface_rect;
1903 subtree_is_clipped_by_surface_bounds = true;
1907 DCHECK(layer->render_surface());
1908 DCHECK(!layer->parent() || layer->parent()->render_target() ==
1909 accumulated_surface_state->back().render_target);
1911 accumulated_surface_state->push_back(AccumulatedSurfaceState(layer));
1913 render_surface->SetIsClipped(subtree_is_clipped_by_surface_bounds);
1914 if (!subtree_is_clipped_by_surface_bounds) {
1915 render_surface->SetClipRect(gfx::Rect());
1916 clip_rect_of_target_surface_in_target_space =
1917 data_from_ancestor.clip_rect_of_target_surface_in_target_space;
1920 // If the new render surface is drawn translucent or with a non-integral
1921 // translation then the subtree that gets drawn on this render surface
1922 // cannot use LCD text.
1923 data_for_children.subtree_can_use_lcd_text = subtree_can_use_lcd_text;
1925 } else {
1926 DCHECK(layer->parent());
1928 // Note: layer_draw_properties.target_space_transform is computed above,
1929 // before this if-else statement.
1930 layer_draw_properties.screen_space_transform_is_animating =
1931 animating_transform_to_screen;
1932 layer_draw_properties.opacity = accumulated_draw_opacity;
1933 DCHECK_EQ(layer->draw_blend_mode(), layer->blend_mode());
1934 data_for_children.parent_matrix = combined_transform;
1936 // Layers without render_surfaces directly inherit the ancestor's clip
1937 // status.
1938 layer_or_ancestor_clips_descendants = ancestor_clips_subtree;
1939 if (ancestor_clips_subtree) {
1940 clip_rect_in_target_space =
1941 ancestor_clip_rect_in_target_space;
1944 // The surface's cached clip rect value propagates regardless of what
1945 // clipping goes on between layers here.
1946 clip_rect_of_target_surface_in_target_space =
1947 data_from_ancestor.clip_rect_of_target_surface_in_target_space;
1950 layer_draw_properties.can_use_lcd_text = layer_can_use_lcd_text;
1952 // The layer bounds() includes the layer's bounds_delta() which we want
1953 // for the clip rect.
1954 gfx::Rect rect_in_target_space = MathUtil::MapEnclosingClippedRect(
1955 layer->draw_transform(), gfx::Rect(layer->bounds()));
1957 if (LayerClipsSubtree(layer)) {
1958 layer_or_ancestor_clips_descendants = true;
1959 if (ancestor_clips_subtree && !render_to_separate_surface) {
1960 // A layer without render surface shares the same target as its ancestor.
1961 clip_rect_in_target_space =
1962 ancestor_clip_rect_in_target_space;
1963 clip_rect_in_target_space.Intersect(rect_in_target_space);
1964 } else {
1965 clip_rect_in_target_space = rect_in_target_space;
1969 // Tell the layer the rect that it's clipped by. In theory we could use a
1970 // tighter clip rect here (drawable_content_rect), but that actually does not
1971 // reduce how much would be drawn, and instead it would create unnecessary
1972 // changes to scissor state affecting GPU performance. Our clip information
1973 // is used in the recursion below, so we must set it beforehand.
1974 DCHECK_EQ(layer_or_ancestor_clips_descendants, layer->is_clipped());
1975 if (layer_or_ancestor_clips_descendants) {
1976 layer_draw_properties.clip_rect = clip_rect_in_target_space;
1977 } else {
1978 // Initialize the clip rect to a safe value that will not clip the
1979 // layer, just in case clipping is still accidentally used.
1980 layer_draw_properties.clip_rect = rect_in_target_space;
1983 if (!layer->children().empty()) {
1984 if (layer == globals.elastic_overscroll_application_layer) {
1985 data_for_children.parent_matrix.Translate(
1986 -globals.elastic_overscroll.x(), -globals.elastic_overscroll.y());
1989 // Flatten to 2D if the layer doesn't preserve 3D.
1990 if (layer->should_flatten_transform())
1991 data_for_children.parent_matrix.FlattenTo2d();
1993 data_for_children.scroll_compensation_matrix =
1994 ComputeScrollCompensationMatrixForChildren(
1995 layer,
1996 data_from_ancestor.parent_matrix,
1997 data_from_ancestor.scroll_compensation_matrix,
1998 effective_scroll_delta);
1999 data_for_children.fixed_container =
2000 layer->IsContainerForFixedPositionLayers() ?
2001 layer : data_from_ancestor.fixed_container;
2003 data_for_children.clip_rect_in_target_space = clip_rect_in_target_space;
2004 data_for_children.clip_rect_of_target_surface_in_target_space =
2005 clip_rect_of_target_surface_in_target_space;
2006 data_for_children.ancestor_clips_subtree =
2007 layer_or_ancestor_clips_descendants;
2008 data_for_children.nearest_occlusion_immune_ancestor_surface =
2009 nearest_occlusion_immune_ancestor_surface;
2010 data_for_children.subtree_is_visible_from_ancestor = layer_is_drawn;
2013 std::vector<LayerImpl*> sorted_children;
2014 if (layer_draw_properties.has_child_with_a_scroll_parent)
2015 SortChildrenForRecursion(&sorted_children, *layer);
2017 for (size_t i = 0; i < layer->children().size(); ++i) {
2018 // If one of layer's children has a scroll parent, then we may have to
2019 // visit the children out of order. The new order is stored in
2020 // sorted_children. Otherwise, we'll grab the child directly from the
2021 // layer's list of children.
2023 LayerImpl* child =
2024 layer_draw_properties.has_child_with_a_scroll_parent
2025 ? sorted_children[i]
2026 : LayerTreeHostCommon::get_layer_as_raw_ptr(layer->children(), i);
2028 CalculateDrawPropertiesInternal(child, globals, data_for_children,
2029 accumulated_surface_state);
2031 if (child->layer_or_descendant_is_drawn()) {
2032 bool layer_or_descendant_is_drawn = true;
2033 layer->set_layer_or_descendant_is_drawn(layer_or_descendant_is_drawn);
2037 // Compute the total drawable_content_rect for this subtree (the rect is in
2038 // target surface space).
2039 gfx::Rect local_drawable_content_rect_of_subtree =
2040 accumulated_surface_state->back().drawable_content_rect;
2041 if (render_to_separate_surface) {
2042 DCHECK(accumulated_surface_state->back().render_target == layer);
2043 accumulated_surface_state->pop_back();
2046 // Compute the layer's drawable content rect (the rect is in target surface
2047 // space).
2048 layer_draw_properties.drawable_content_rect = rect_in_target_space;
2049 if (layer_or_ancestor_clips_descendants) {
2050 layer_draw_properties.drawable_content_rect.Intersect(
2051 clip_rect_in_target_space);
2053 if (layer->DrawsContent()) {
2054 local_drawable_content_rect_of_subtree.Union(
2055 layer_draw_properties.drawable_content_rect);
2058 // Compute the layer's visible content rect (the rect is in content space).
2059 layer_draw_properties.visible_layer_rect = CalculateVisibleLayerRect(
2060 layer, clip_rect_of_target_surface_in_target_space, rect_in_target_space);
2062 // Compute the remaining properties for the render surface, if the layer has
2063 // one.
2064 if (IsRootLayer(layer)) {
2065 // The root layer's surface's content_rect is always the entire viewport.
2066 DCHECK(render_to_separate_surface);
2067 layer->render_surface()->SetContentRect(
2068 ancestor_clip_rect_in_target_space);
2069 } else if (render_to_separate_surface) {
2070 RenderSurfaceImpl* render_surface = layer->render_surface();
2071 gfx::Rect clipped_content_rect = local_drawable_content_rect_of_subtree;
2073 // Don't clip if the layer is reflected as the reflection shouldn't be
2074 // clipped.
2075 if (!layer->replica_layer()) {
2076 // Note, it is correct to use data_from_ancestor.ancestor_clips_subtree
2077 // here, because we are looking at this layer's render_surface, not the
2078 // layer itself.
2079 if (render_surface->is_clipped() && !clipped_content_rect.IsEmpty()) {
2080 gfx::Rect surface_clip_rect = LayerTreeHostCommon::CalculateVisibleRect(
2081 render_surface->clip_rect(),
2082 clipped_content_rect,
2083 render_surface->draw_transform());
2084 clipped_content_rect.Intersect(surface_clip_rect);
2088 // The RenderSurfaceImpl backing texture cannot exceed the maximum supported
2089 // texture size.
2090 clipped_content_rect.set_width(
2091 std::min(clipped_content_rect.width(), globals.max_texture_size));
2092 clipped_content_rect.set_height(
2093 std::min(clipped_content_rect.height(), globals.max_texture_size));
2095 // Layers having a non-default blend mode will blend with the content
2096 // inside its parent's render target. This render target should be
2097 // either root_for_isolated_group, or the root of the layer tree.
2098 // Otherwise, this layer will use an incomplete backdrop, limited to its
2099 // render target and the blending result will be incorrect.
2100 DCHECK(layer->uses_default_blend_mode() || IsRootLayer(layer) ||
2101 !layer->parent()->render_target() ||
2102 IsRootLayer(layer->parent()->render_target()) ||
2103 layer->parent()->render_target()->is_root_for_isolated_group());
2105 render_surface->SetContentRect(clipped_content_rect);
2107 if (clipped_content_rect.IsEmpty()) {
2108 return;
2111 // The owning layer's screen_space_transform has a scale from content to
2112 // layer space which we need to undo and replace with a scale from the
2113 // surface's subtree into layer space.
2114 gfx::Transform screen_space_transform = layer->screen_space_transform();
2115 screen_space_transform.Scale(1.0 / combined_transform_scales.x(),
2116 1.0 / combined_transform_scales.y());
2117 render_surface->SetScreenSpaceTransform(screen_space_transform);
2119 if (layer->replica_layer()) {
2120 gfx::Transform surface_origin_to_replica_origin_transform;
2121 surface_origin_to_replica_origin_transform.Scale(
2122 combined_transform_scales.x(), combined_transform_scales.y());
2123 surface_origin_to_replica_origin_transform.Translate(
2124 layer->replica_layer()->position().x() +
2125 layer->replica_layer()->transform_origin().x(),
2126 layer->replica_layer()->position().y() +
2127 layer->replica_layer()->transform_origin().y());
2128 surface_origin_to_replica_origin_transform.PreconcatTransform(
2129 layer->replica_layer()->transform());
2130 surface_origin_to_replica_origin_transform.Translate(
2131 -layer->replica_layer()->transform_origin().x(),
2132 -layer->replica_layer()->transform_origin().y());
2133 surface_origin_to_replica_origin_transform.Scale(
2134 1.0 / combined_transform_scales.x(),
2135 1.0 / combined_transform_scales.y());
2137 // Compute the replica's "originTransform" that maps from the replica's
2138 // origin space to the target surface origin space.
2139 gfx::Transform replica_origin_transform =
2140 layer->render_surface()->draw_transform() *
2141 surface_origin_to_replica_origin_transform;
2142 render_surface->SetReplicaDrawTransform(replica_origin_transform);
2144 // Compute the replica's "screen_space_transform" that maps from the
2145 // replica's origin space to the screen's origin space.
2146 gfx::Transform replica_screen_space_transform =
2147 layer->render_surface()->screen_space_transform() *
2148 surface_origin_to_replica_origin_transform;
2149 render_surface->SetReplicaScreenSpaceTransform(
2150 replica_screen_space_transform);
2154 SavePaintPropertiesLayer(layer);
2156 UpdateAccumulatedSurfaceState(layer, local_drawable_content_rect_of_subtree,
2157 accumulated_surface_state);
2158 } // NOLINT(readability/fn_size)
2160 static void ProcessCalcDrawPropsInputs(
2161 const LayerTreeHostCommon::CalcDrawPropsImplInputs& inputs,
2162 SubtreeGlobals* globals,
2163 DataForRecursion* data_for_recursion) {
2164 DCHECK(inputs.root_layer);
2165 DCHECK(IsRootLayer(inputs.root_layer));
2166 DCHECK(inputs.render_surface_layer_list);
2168 gfx::Transform identity_matrix;
2170 // The root layer's render_surface should receive the device viewport as the
2171 // initial clip rect.
2172 gfx::Rect device_viewport_rect(inputs.device_viewport_size);
2174 gfx::Vector2dF device_transform_scale_components =
2175 MathUtil::ComputeTransform2dScaleComponents(inputs.device_transform, 1.f);
2176 // Not handling the rare case of different x and y device scale.
2177 float device_transform_scale =
2178 std::max(device_transform_scale_components.x(),
2179 device_transform_scale_components.y());
2181 gfx::Transform scaled_device_transform = inputs.device_transform;
2182 scaled_device_transform.Scale(inputs.device_scale_factor,
2183 inputs.device_scale_factor);
2185 globals->max_texture_size = inputs.max_texture_size;
2186 globals->device_scale_factor =
2187 inputs.device_scale_factor * device_transform_scale;
2188 globals->page_scale_factor = inputs.page_scale_factor;
2189 globals->page_scale_layer = inputs.page_scale_layer;
2190 globals->elastic_overscroll = inputs.elastic_overscroll;
2191 globals->elastic_overscroll_application_layer =
2192 inputs.elastic_overscroll_application_layer;
2193 globals->can_render_to_separate_surface =
2194 inputs.can_render_to_separate_surface;
2195 globals->can_adjust_raster_scales = inputs.can_adjust_raster_scales;
2196 globals->layers_always_allowed_lcd_text =
2197 inputs.layers_always_allowed_lcd_text;
2199 data_for_recursion->parent_matrix = scaled_device_transform;
2200 data_for_recursion->full_hierarchy_matrix = identity_matrix;
2201 data_for_recursion->scroll_compensation_matrix = identity_matrix;
2202 data_for_recursion->fixed_container = inputs.root_layer;
2203 data_for_recursion->clip_rect_in_target_space = device_viewport_rect;
2204 data_for_recursion->clip_rect_of_target_surface_in_target_space =
2205 device_viewport_rect;
2206 data_for_recursion->maximum_animation_contents_scale = 0.f;
2207 data_for_recursion->starting_animation_contents_scale = 0.f;
2208 data_for_recursion->ancestor_is_animating_scale = false;
2209 data_for_recursion->ancestor_clips_subtree = true;
2210 data_for_recursion->nearest_occlusion_immune_ancestor_surface = NULL;
2211 data_for_recursion->in_subtree_of_page_scale_layer = false;
2212 data_for_recursion->subtree_can_use_lcd_text = inputs.can_use_lcd_text;
2213 data_for_recursion->subtree_is_visible_from_ancestor = true;
2216 void LayerTreeHostCommon::UpdateRenderSurface(
2217 Layer* layer,
2218 bool can_render_to_separate_surface,
2219 gfx::Transform* transform,
2220 bool* draw_transform_is_axis_aligned) {
2221 bool preserves_2d_axis_alignment =
2222 transform->Preserves2dAxisAlignment() && *draw_transform_is_axis_aligned;
2223 if (IsRootLayer(layer) || (can_render_to_separate_surface &&
2224 SubtreeShouldRenderToSeparateSurface(
2225 layer, preserves_2d_axis_alignment))) {
2226 // We reset the transform here so that any axis-changing transforms
2227 // will now be relative to this RenderSurface.
2228 transform->MakeIdentity();
2229 *draw_transform_is_axis_aligned = true;
2230 if (!layer->render_surface()) {
2231 layer->CreateRenderSurface();
2233 layer->SetHasRenderSurface(true);
2234 return;
2236 layer->SetHasRenderSurface(false);
2237 if (layer->render_surface())
2238 layer->ClearRenderSurface();
2241 void LayerTreeHostCommon::UpdateRenderSurfaces(
2242 Layer* layer,
2243 bool can_render_to_separate_surface,
2244 const gfx::Transform& parent_transform,
2245 bool draw_transform_is_axis_aligned) {
2246 gfx::Transform transform_for_children = layer->transform();
2247 transform_for_children *= parent_transform;
2248 draw_transform_is_axis_aligned &= layer->AnimationsPreserveAxisAlignment();
2249 UpdateRenderSurface(layer, can_render_to_separate_surface,
2250 &transform_for_children, &draw_transform_is_axis_aligned);
2252 for (size_t i = 0; i < layer->children().size(); ++i) {
2253 UpdateRenderSurfaces(layer->children()[i].get(),
2254 can_render_to_separate_surface, transform_for_children,
2255 draw_transform_is_axis_aligned);
2259 static bool ApproximatelyEqual(const gfx::Rect& r1, const gfx::Rect& r2) {
2260 // TODO(vollick): This tolerance should be lower: crbug.com/471786
2261 static const int tolerance = 3;
2263 if (r1.IsEmpty())
2264 return std::min(r2.width(), r2.height()) < tolerance;
2266 if (r2.IsEmpty())
2267 return std::min(r1.width(), r1.height()) < tolerance;
2269 return std::abs(r1.x() - r2.x()) <= tolerance &&
2270 std::abs(r1.y() - r2.y()) <= tolerance &&
2271 std::abs(r1.right() - r2.right()) <= tolerance &&
2272 std::abs(r1.bottom() - r2.bottom()) <= tolerance;
2275 static bool ApproximatelyEqual(const gfx::Transform& a,
2276 const gfx::Transform& b) {
2277 static const float component_tolerance = 0.1f;
2279 // We may have a larger discrepancy in the scroll components due to snapping
2280 // (floating point error might round the other way).
2281 static const float translation_tolerance = 1.f;
2283 for (int row = 0; row < 4; row++) {
2284 for (int col = 0; col < 4; col++) {
2285 const float delta =
2286 std::abs(a.matrix().get(row, col) - b.matrix().get(row, col));
2287 const float tolerance =
2288 col == 3 && row < 3 ? translation_tolerance : component_tolerance;
2289 if (delta > tolerance)
2290 return false;
2294 return true;
2297 void VerifyPropertyTreeValuesForSurface(RenderSurfaceImpl* render_surface,
2298 PropertyTrees* property_trees) {
2299 const bool render_surface_draw_transforms_match =
2300 ApproximatelyEqual(render_surface->draw_transform(),
2301 DrawTransformOfRenderSurfaceFromPropertyTrees(
2302 render_surface, property_trees->transform_tree));
2303 CHECK(render_surface_draw_transforms_match)
2304 << "expected: " << render_surface->draw_transform().ToString()
2305 << " actual: "
2306 << DrawTransformOfRenderSurfaceFromPropertyTrees(
2307 render_surface, property_trees->transform_tree)
2308 .ToString();
2310 const bool render_surface_screen_space_transform_match =
2311 ApproximatelyEqual(render_surface->screen_space_transform(),
2312 ScreenSpaceTransformOfRenderSurfaceFromPropertyTrees(
2313 render_surface, property_trees->transform_tree));
2314 CHECK(render_surface_screen_space_transform_match)
2315 << "expected: " << render_surface->screen_space_transform().ToString()
2316 << " actual: "
2317 << ScreenSpaceTransformOfRenderSurfaceFromPropertyTrees(
2318 render_surface, property_trees->transform_tree)
2319 .ToString();
2321 CHECK_EQ(render_surface->is_clipped(),
2322 RenderSurfaceIsClippedFromPropertyTrees(render_surface,
2323 property_trees->clip_tree));
2325 const bool render_surface_clip_rects_match =
2326 ApproximatelyEqual(render_surface->clip_rect(),
2327 ClipRectOfRenderSurfaceFromPropertyTrees(
2328 render_surface, property_trees->clip_tree));
2329 CHECK(render_surface_clip_rects_match)
2330 << "expected: " << render_surface->clip_rect().ToString() << " actual: "
2331 << ClipRectOfRenderSurfaceFromPropertyTrees(render_surface,
2332 property_trees->clip_tree)
2333 .ToString();
2335 const bool render_surface_content_rects_match =
2336 ApproximatelyEqual(render_surface->content_rect(),
2337 render_surface->content_rect_from_property_trees());
2338 CHECK(render_surface_content_rects_match)
2339 << "expected: " << render_surface->content_rect().ToString()
2340 << " actual: "
2341 << render_surface->content_rect_from_property_trees().ToString();
2343 CHECK_EQ(render_surface->draw_opacity(),
2344 DrawOpacityOfRenderSurfaceFromPropertyTrees(
2345 render_surface, property_trees->effect_tree));
2348 void VerifyPropertyTreeValuesForLayer(LayerImpl* current_layer,
2349 PropertyTrees* property_trees,
2350 bool layers_always_allowed_lcd_text,
2351 bool can_use_lcd_text) {
2352 const bool visible_rects_match =
2353 ApproximatelyEqual(current_layer->visible_layer_rect(),
2354 current_layer->visible_rect_from_property_trees());
2355 CHECK(visible_rects_match)
2356 << "expected: " << current_layer->visible_layer_rect().ToString()
2357 << " actual: "
2358 << current_layer->visible_rect_from_property_trees().ToString();
2360 const bool draw_transforms_match =
2361 ApproximatelyEqual(current_layer->draw_transform(),
2362 DrawTransformFromPropertyTrees(
2363 current_layer, property_trees->transform_tree));
2364 CHECK(draw_transforms_match)
2365 << "expected: " << current_layer->draw_transform().ToString()
2366 << " actual: "
2367 << DrawTransformFromPropertyTrees(
2368 current_layer, property_trees->transform_tree).ToString();
2370 const bool draw_opacities_match =
2371 current_layer->draw_opacity() ==
2372 DrawOpacityFromPropertyTrees(current_layer, property_trees->effect_tree);
2373 CHECK(draw_opacities_match)
2374 << "expected: " << current_layer->draw_opacity()
2375 << " actual: " << DrawOpacityFromPropertyTrees(
2376 current_layer, property_trees->effect_tree);
2378 const bool can_use_lcd_text_match =
2379 CanUseLcdTextFromPropertyTrees(
2380 current_layer, layers_always_allowed_lcd_text, can_use_lcd_text,
2381 property_trees) == current_layer->can_use_lcd_text();
2382 CHECK(can_use_lcd_text_match);
2384 CHECK_EQ(current_layer->screen_space_transform_is_animating(),
2385 ScreenSpaceTransformIsAnimatingFromPropertyTrees(
2386 current_layer, property_trees->transform_tree));
2388 const bool drawable_content_rects_match =
2389 ApproximatelyEqual(current_layer->drawable_content_rect(),
2390 DrawableContentRectFromPropertyTrees(
2391 current_layer, property_trees->transform_tree));
2392 CHECK(drawable_content_rects_match)
2393 << "expected: " << current_layer->drawable_content_rect().ToString()
2394 << " actual: "
2395 << DrawableContentRectFromPropertyTrees(current_layer,
2396 property_trees->transform_tree)
2397 .ToString();
2399 const bool clip_rects_match = ApproximatelyEqual(
2400 current_layer->clip_rect(),
2401 ClipRectFromPropertyTrees(current_layer, property_trees->transform_tree));
2402 CHECK(clip_rects_match) << "expected: "
2403 << current_layer->clip_rect().ToString()
2404 << " actual: "
2405 << ClipRectFromPropertyTrees(
2406 current_layer, property_trees->transform_tree)
2407 .ToString();
2410 void VerifyPropertyTreeValues(
2411 LayerTreeHostCommon::CalcDrawPropsImplInputs* inputs) {
2412 LayerIterator it, end;
2413 for (it = LayerIterator::Begin(inputs->render_surface_layer_list),
2414 end = LayerIterator::End(inputs->render_surface_layer_list);
2415 it != end; ++it) {
2416 LayerImpl* current_layer = *it;
2417 if (it.represents_target_render_surface())
2418 VerifyPropertyTreeValuesForSurface(current_layer->render_surface(),
2419 inputs->property_trees);
2420 if (!it.represents_itself() || !current_layer->DrawsContent())
2421 continue;
2422 VerifyPropertyTreeValuesForLayer(current_layer, inputs->property_trees,
2423 inputs->layers_always_allowed_lcd_text,
2424 inputs->can_use_lcd_text);
2428 enum PropertyTreeOption {
2429 BUILD_PROPERTY_TREES_IF_NEEDED,
2430 DONT_BUILD_PROPERTY_TREES
2433 void CalculateRenderTargetInternal(LayerImpl* layer,
2434 bool subtree_visible_from_ancestor,
2435 bool can_render_to_separate_surface) {
2436 const bool layer_is_visible =
2437 subtree_visible_from_ancestor && !layer->hide_layer_and_subtree();
2438 const bool layer_is_drawn = layer_is_visible || layer->HasCopyRequest();
2440 // The root layer cannot be skipped.
2441 if (!IsRootLayer(layer) && SubtreeShouldBeSkipped(layer, layer_is_drawn)) {
2442 layer->draw_properties().render_target = nullptr;
2443 return;
2446 bool render_to_separate_surface =
2447 IsRootLayer(layer) ||
2448 (can_render_to_separate_surface && layer->render_surface());
2450 if (render_to_separate_surface) {
2451 DCHECK(layer->render_surface());
2452 layer->draw_properties().render_target = layer;
2454 if (layer->mask_layer())
2455 layer->mask_layer()->draw_properties().render_target = layer;
2457 if (layer->replica_layer() && layer->replica_layer()->mask_layer())
2458 layer->replica_layer()->mask_layer()->draw_properties().render_target =
2459 layer;
2461 } else {
2462 DCHECK(layer->parent());
2463 layer->draw_properties().render_target = layer->parent()->render_target();
2466 for (size_t i = 0; i < layer->children().size(); ++i) {
2467 CalculateRenderTargetInternal(
2468 LayerTreeHostCommon::get_layer_as_raw_ptr(layer->children(), i),
2469 layer_is_drawn, can_render_to_separate_surface);
2473 void CalculateRenderSurfaceLayerListInternal(
2474 LayerImpl* layer,
2475 PropertyTrees* property_trees,
2476 LayerImplList* render_surface_layer_list,
2477 LayerImplList* descendants,
2478 bool subtree_visible_from_ancestor,
2479 const bool can_render_to_separate_surface,
2480 const int current_render_surface_layer_list_id,
2481 const bool verify_property_trees) {
2482 // This calculates top level Render Surface Layer List, and Layer List for all
2483 // Render Surfaces.
2485 // |layer| is current layer.
2487 // |render_surface_layer_list| is the top level RenderSurfaceLayerList.
2489 // |descendants| is used to determine what's in current layer's render
2490 // surface's layer list.
2492 // |subtree_visible_from_ancestor| is set during recursion to affect current
2493 // layer's subtree.
2495 // |can_render_to_separate_surface| and |current_render_surface_layer_list_id|
2496 // are settings that should stay the same during recursion.
2498 // Layers that are marked as hidden will hide themselves and their subtree.
2499 // Exception: Layers with copy requests, whether hidden or not, must be drawn
2500 // anyway. In this case, we will inform their subtree they are visible to get
2501 // the right results.
2502 const bool layer_is_visible =
2503 subtree_visible_from_ancestor && !layer->hide_layer_and_subtree();
2504 const bool layer_is_drawn = layer_is_visible || layer->HasCopyRequest();
2506 // The root layer cannot be skipped.
2507 if (!IsRootLayer(layer) && SubtreeShouldBeSkipped(layer, layer_is_drawn)) {
2508 if (layer->render_surface())
2509 layer->ClearRenderSurfaceLayerList();
2510 layer->draw_properties().render_target = nullptr;
2511 return;
2514 bool render_to_separate_surface =
2515 IsRootLayer(layer) ||
2516 (can_render_to_separate_surface && layer->render_surface());
2518 if (render_to_separate_surface) {
2519 DCHECK(layer->render_surface());
2520 if (!layer->double_sided() &&
2521 IsSurfaceBackFaceVisible(layer, layer->draw_transform())) {
2522 layer->ClearRenderSurfaceLayerList();
2523 layer->draw_properties().render_target = nullptr;
2524 return;
2526 if (IsRootLayer(layer)) {
2527 // The root surface does not contribute to any other surface, it has no
2528 // target.
2529 layer->render_surface()->set_contributes_to_drawn_surface(false);
2530 } else {
2531 // Even if the |layer_is_drawn|, it only contributes to a drawn surface
2532 // when the |layer_is_visible|.
2533 layer->render_surface()->set_contributes_to_drawn_surface(
2534 layer_is_visible);
2537 layer->ClearRenderSurfaceLayerList();
2539 render_surface_layer_list->push_back(layer);
2541 descendants = &(layer->render_surface()->layer_list());
2544 size_t descendants_size = descendants->size();
2546 bool layer_should_be_skipped = LayerShouldBeSkipped(layer, layer_is_drawn);
2547 if (!layer_should_be_skipped) {
2548 MarkLayerWithRenderSurfaceLayerListId(layer,
2549 current_render_surface_layer_list_id);
2550 descendants->push_back(layer);
2553 // The render surface's content rect is the union of drawable content rects
2554 // of the layers that draw into the surface. If the render surface is clipped,
2555 // it is also intersected with the render's surface clip rect.
2556 if (verify_property_trees) {
2557 if (render_to_separate_surface) {
2558 if (IsRootLayer(layer)) {
2559 // The root layer's surface content rect is always the entire viewport.
2560 gfx::Rect viewport =
2561 ViewportRectFromPropertyTrees(property_trees->clip_tree);
2562 layer->render_surface()->SetAccumulatedContentRect(viewport);
2563 } else {
2564 // If the owning layer of a render surface draws content, the content
2565 // rect of the render surface is initialized to the drawable content
2566 // rect of the layer.
2567 gfx::Rect content_rect =
2568 layer->DrawsContent() ? DrawableContentRectFromPropertyTrees(
2569 layer, property_trees->transform_tree)
2570 : gfx::Rect();
2571 layer->render_surface()->SetAccumulatedContentRect(content_rect);
2573 } else if (!layer_should_be_skipped &&
2574 !IsRootLayer(layer->render_target())) {
2575 // In this case, the layer's drawable content rect can expand the
2576 // content rect of the render surface it is drawing into.
2577 gfx::Rect surface_content_rect =
2578 layer->render_target()->render_surface()->accumulated_content_rect();
2579 surface_content_rect.Union(DrawableContentRectFromPropertyTrees(
2580 layer, property_trees->transform_tree));
2581 layer->render_target()->render_surface()->SetAccumulatedContentRect(
2582 surface_content_rect);
2586 for (auto& child_layer : layer->children()) {
2587 CalculateRenderSurfaceLayerListInternal(
2588 child_layer, property_trees, render_surface_layer_list, descendants,
2589 layer_is_drawn, can_render_to_separate_surface,
2590 current_render_surface_layer_list_id, verify_property_trees);
2592 // If the child is its own render target, then it has a render surface.
2593 if (child_layer->render_target() == child_layer &&
2594 !child_layer->render_surface()->layer_list().empty() &&
2595 !child_layer->render_surface()->content_rect().IsEmpty()) {
2596 // This child will contribute its render surface, which means
2597 // we need to mark just the mask layer (and replica mask layer)
2598 // with the id.
2599 MarkMasksWithRenderSurfaceLayerListId(
2600 child_layer, current_render_surface_layer_list_id);
2601 descendants->push_back(child_layer);
2604 if (child_layer->layer_or_descendant_is_drawn()) {
2605 bool layer_or_descendant_is_drawn = true;
2606 layer->set_layer_or_descendant_is_drawn(layer_or_descendant_is_drawn);
2610 if (render_to_separate_surface && !IsRootLayer(layer) &&
2611 layer->render_surface()->layer_list().empty()) {
2612 RemoveSurfaceForEarlyExit(layer, render_surface_layer_list);
2613 return;
2616 if (verify_property_trees && render_to_separate_surface &&
2617 !IsRootLayer(layer)) {
2618 if (!layer->replica_layer() &&
2619 RenderSurfaceIsClippedFromPropertyTrees(layer->render_surface(),
2620 property_trees->clip_tree)) {
2621 // Here, we clip the render surface's content rect with its clip rect.
2622 // As the clip rect of render surface is in the surface's target space,
2623 // we first map the content rect into the target space, intersect it with
2624 // clip rect and project back the result to the surface space.
2625 gfx::Rect surface_content_rect =
2626 layer->render_surface()->accumulated_content_rect();
2628 if (!surface_content_rect.IsEmpty()) {
2629 gfx::Rect surface_clip_rect = LayerTreeHostCommon::CalculateVisibleRect(
2630 ClipRectOfRenderSurfaceFromPropertyTrees(layer->render_surface(),
2631 property_trees->clip_tree),
2632 surface_content_rect,
2633 DrawTransformOfRenderSurfaceFromPropertyTrees(
2634 layer->render_surface(), property_trees->transform_tree));
2635 surface_content_rect.Intersect(surface_clip_rect);
2636 layer->render_surface()->SetAccumulatedContentRect(
2637 surface_content_rect);
2640 layer->render_surface()->SetContentRectFromPropertyTrees(
2641 layer->render_surface()->accumulated_content_rect());
2642 if (!IsRootLayer(layer->parent()->render_target())) {
2643 // The surface's drawable content rect may expand the content rect
2644 // of its target's surface(surface's target's surface).
2645 gfx::Rect surface_target_rect = layer->parent()
2646 ->render_target()
2647 ->render_surface()
2648 ->accumulated_content_rect();
2649 surface_target_rect.Union(DrawableContentRectOfSurfaceFromPropertyTrees(
2650 layer->render_surface(), property_trees->transform_tree));
2651 layer->parent()
2652 ->render_target()
2653 ->render_surface()
2654 ->SetAccumulatedContentRect(surface_target_rect);
2658 if (verify_property_trees && IsRootLayer(layer))
2659 layer->render_surface()->SetContentRectFromPropertyTrees(
2660 layer->render_surface()->accumulated_content_rect());
2662 if (render_to_separate_surface && !IsRootLayer(layer) &&
2663 layer->render_surface()->content_rect().IsEmpty()) {
2664 RemoveSurfaceForEarlyExit(layer, render_surface_layer_list);
2665 return;
2668 // If neither this layer nor any of its children were added, early out.
2669 if (descendants_size == descendants->size()) {
2670 DCHECK(!render_to_separate_surface || IsRootLayer(layer));
2671 return;
2674 if (layer->HasContributingDelegatedRenderPasses()) {
2675 layer->render_target()
2676 ->render_surface()
2677 ->AddContributingDelegatedRenderPassLayer(layer);
2681 void CalculateRenderTarget(
2682 LayerTreeHostCommon::CalcDrawPropsImplInputs* inputs) {
2683 CalculateRenderTargetInternal(inputs->root_layer, true,
2684 inputs->can_render_to_separate_surface);
2687 void CalculateRenderSurfaceLayerList(
2688 LayerTreeHostCommon::CalcDrawPropsImplInputs* inputs) {
2689 const bool subtree_visible_from_ancestor = true;
2690 CalculateRenderSurfaceLayerListInternal(
2691 inputs->root_layer, inputs->property_trees,
2692 inputs->render_surface_layer_list, nullptr, subtree_visible_from_ancestor,
2693 inputs->can_render_to_separate_surface,
2694 inputs->current_render_surface_layer_list_id,
2695 inputs->verify_property_trees);
2698 void CalculateDrawPropertiesAndVerify(
2699 LayerTreeHostCommon::CalcDrawPropsImplInputs* inputs,
2700 PropertyTreeOption property_tree_option) {
2701 SubtreeGlobals globals;
2702 DataForRecursion data_for_recursion;
2703 inputs->render_surface_layer_list->clear();
2705 ProcessCalcDrawPropsInputs(*inputs, &globals, &data_for_recursion);
2706 UpdateMetaInformationSequenceNumber(inputs->root_layer);
2707 PreCalculateMetaInformationRecursiveData recursive_data;
2708 PreCalculateMetaInformationInternal(inputs->root_layer, &recursive_data);
2710 const bool should_measure_property_tree_performance =
2711 inputs->verify_property_trees &&
2712 (property_tree_option == BUILD_PROPERTY_TREES_IF_NEEDED);
2714 if (inputs->verify_property_trees) {
2715 LayerImplList update_layer_list;
2717 switch (property_tree_option) {
2718 case BUILD_PROPERTY_TREES_IF_NEEDED: {
2719 // The translation from layer to property trees is an intermediate
2720 // state. We will eventually get these data passed directly to the
2721 // compositor.
2722 if (should_measure_property_tree_performance) {
2723 TRACE_EVENT_BEGIN0(
2724 TRACE_DISABLED_BY_DEFAULT("cc.debug.cdp-perf"),
2725 "LayerTreeHostCommon::ComputeVisibleRectsWithPropertyTrees");
2728 BuildPropertyTreesAndComputeVisibleRects(
2729 inputs->root_layer, inputs->page_scale_layer,
2730 inputs->inner_viewport_scroll_layer,
2731 inputs->outer_viewport_scroll_layer, inputs->page_scale_factor,
2732 inputs->device_scale_factor,
2733 gfx::Rect(inputs->device_viewport_size), inputs->device_transform,
2734 inputs->property_trees, &update_layer_list);
2736 if (should_measure_property_tree_performance) {
2737 TRACE_EVENT_END0(
2738 TRACE_DISABLED_BY_DEFAULT("cc.debug.cdp-perf"),
2739 "LayerTreeHostCommon::ComputeVisibleRectsWithPropertyTrees");
2742 break;
2744 case DONT_BUILD_PROPERTY_TREES: {
2745 TRACE_EVENT0(
2746 TRACE_DISABLED_BY_DEFAULT("cc.debug.cdp-perf"),
2747 "LayerTreeHostCommon::ComputeJustVisibleRectsWithPropertyTrees");
2748 ComputeVisibleRectsUsingPropertyTrees(
2749 inputs->root_layer, inputs->property_trees, &update_layer_list);
2750 break;
2755 if (should_measure_property_tree_performance) {
2756 TRACE_EVENT_BEGIN0(TRACE_DISABLED_BY_DEFAULT("cc.debug.cdp-perf"),
2757 "LayerTreeHostCommon::CalculateDrawProperties");
2760 std::vector<AccumulatedSurfaceState> accumulated_surface_state;
2761 CalculateRenderTarget(inputs);
2762 CalculateDrawPropertiesInternal(inputs->root_layer, globals,
2763 data_for_recursion,
2764 &accumulated_surface_state);
2765 CalculateRenderSurfaceLayerList(inputs);
2767 if (should_measure_property_tree_performance) {
2768 TRACE_EVENT_END0(TRACE_DISABLED_BY_DEFAULT("cc.debug.cdp-perf"),
2769 "LayerTreeHostCommon::CalculateDrawProperties");
2772 if (inputs->verify_property_trees)
2773 VerifyPropertyTreeValues(inputs);
2775 // A root layer render_surface should always exist after
2776 // CalculateDrawProperties.
2777 DCHECK(inputs->root_layer->render_surface());
2780 void LayerTreeHostCommon::CalculateDrawProperties(
2781 CalcDrawPropsMainInputs* inputs) {
2782 LayerList update_layer_list;
2783 bool can_render_to_separate_surface = true;
2784 UpdateRenderSurfaces(inputs->root_layer, can_render_to_separate_surface,
2785 gfx::Transform(), false);
2786 PropertyTrees* property_trees =
2787 inputs->root_layer->layer_tree_host()->property_trees();
2788 BuildPropertyTreesAndComputeVisibleRects(
2789 inputs->root_layer, inputs->page_scale_layer,
2790 inputs->inner_viewport_scroll_layer, inputs->outer_viewport_scroll_layer,
2791 inputs->page_scale_factor, inputs->device_scale_factor,
2792 gfx::Rect(inputs->device_viewport_size), inputs->device_transform,
2793 property_trees, &update_layer_list);
2796 void LayerTreeHostCommon::CalculateDrawProperties(
2797 CalcDrawPropsImplInputs* inputs) {
2798 CalculateDrawPropertiesAndVerify(inputs, DONT_BUILD_PROPERTY_TREES);
2801 void LayerTreeHostCommon::CalculateDrawProperties(
2802 CalcDrawPropsImplInputsForTesting* inputs) {
2803 CalculateDrawPropertiesAndVerify(inputs, BUILD_PROPERTY_TREES_IF_NEEDED);
2806 PropertyTrees* GetPropertyTrees(Layer* layer) {
2807 return layer->layer_tree_host()->property_trees();
2810 PropertyTrees* GetPropertyTrees(LayerImpl* layer) {
2811 return layer->layer_tree_impl()->property_trees();
2814 } // namespace cc