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"
9 #include "base/debug/trace_event.h"
10 #include "cc/base/math_util.h"
11 #include "cc/layers/heads_up_display_layer_impl.h"
12 #include "cc/layers/layer.h"
13 #include "cc/layers/layer_impl.h"
14 #include "cc/layers/layer_iterator.h"
15 #include "cc/layers/render_surface.h"
16 #include "cc/layers/render_surface_impl.h"
17 #include "cc/trees/layer_sorter.h"
18 #include "cc/trees/layer_tree_impl.h"
19 #include "ui/gfx/point_conversions.h"
20 #include "ui/gfx/rect_conversions.h"
21 #include "ui/gfx/transform.h"
25 ScrollAndScaleSet::ScrollAndScaleSet() {}
27 ScrollAndScaleSet::~ScrollAndScaleSet() {}
29 static void SortLayers(LayerList::iterator forst,
30 LayerList::iterator end,
35 static void SortLayers(LayerImplList::iterator first,
36 LayerImplList::iterator end,
37 LayerSorter* layer_sorter) {
39 TRACE_EVENT0("cc", "LayerTreeHostCommon::SortLayers");
40 layer_sorter->Sort(first, end);
43 template <typename LayerType>
44 static gfx::Vector2dF GetEffectiveScrollDelta(LayerType* layer) {
45 gfx::Vector2dF scroll_delta = layer->ScrollDelta();
46 // The scroll parent's scroll delta is the amount we've scrolled on the
47 // compositor thread since the commit for this layer tree's source frame.
48 // we last reported to the main thread. I.e., it's the discrepancy between
49 // a scroll parent's scroll delta and offset, so we must add it here.
50 if (layer->scroll_parent())
51 scroll_delta += layer->scroll_parent()->ScrollDelta();
55 template <typename LayerType>
56 static gfx::Vector2dF GetEffectiveTotalScrollOffset(LayerType* layer) {
57 gfx::Vector2dF offset = layer->TotalScrollOffset();
58 // The scroll parent's total scroll offset (scroll offset + scroll delta)
59 // can't be used because its scroll offset has already been applied to the
60 // scroll children's positions by the main thread layer positioning code.
61 if (layer->scroll_parent())
62 offset += layer->scroll_parent()->ScrollDelta();
66 inline gfx::Rect CalculateVisibleRectWithCachedLayerRect(
67 const gfx::Rect& target_surface_rect,
68 const gfx::Rect& layer_bound_rect,
69 const gfx::Rect& layer_rect_in_target_space,
70 const gfx::Transform& transform) {
71 if (layer_rect_in_target_space.IsEmpty())
74 // Is this layer fully contained within the target surface?
75 if (target_surface_rect.Contains(layer_rect_in_target_space))
76 return layer_bound_rect;
78 // If the layer doesn't fill up the entire surface, then find the part of
79 // the surface rect where the layer could be visible. This avoids trying to
80 // project surface rect points that are behind the projection point.
81 gfx::Rect minimal_surface_rect = target_surface_rect;
82 minimal_surface_rect.Intersect(layer_rect_in_target_space);
84 if (minimal_surface_rect.IsEmpty())
87 // Project the corners of the target surface rect into the layer space.
88 // This bounding rectangle may be larger than it needs to be (being
89 // axis-aligned), but is a reasonable filter on the space to consider.
90 // Non-invertible transforms will create an empty rect here.
92 gfx::Transform surface_to_layer(gfx::Transform::kSkipInitialization);
93 if (!transform.GetInverse(&surface_to_layer)) {
94 // Because we cannot use the surface bounds to determine what portion of
95 // the layer is visible, we must conservatively assume the full layer is
97 return layer_bound_rect;
100 gfx::Rect layer_rect = MathUtil::ProjectEnclosingClippedRect(
101 surface_to_layer, minimal_surface_rect);
102 layer_rect.Intersect(layer_bound_rect);
106 gfx::Rect LayerTreeHostCommon::CalculateVisibleRect(
107 const gfx::Rect& target_surface_rect,
108 const gfx::Rect& layer_bound_rect,
109 const gfx::Transform& transform) {
110 gfx::Rect layer_in_surface_space =
111 MathUtil::MapEnclosingClippedRect(transform, layer_bound_rect);
112 return CalculateVisibleRectWithCachedLayerRect(
113 target_surface_rect, layer_bound_rect, layer_in_surface_space, transform);
116 template <typename LayerType>
117 static LayerType* NextTargetSurface(LayerType* layer) {
118 return layer->parent() ? layer->parent()->render_target() : 0;
121 // Given two layers, this function finds their respective render targets and,
122 // computes a change of basis translation. It does this by accumulating the
123 // translation components of the draw transforms of each target between the
124 // ancestor and descendant. These transforms must be 2D translations, and this
125 // requirement is enforced at every step.
126 template <typename LayerType>
127 static gfx::Vector2dF ComputeChangeOfBasisTranslation(
128 const LayerType& ancestor_layer,
129 const LayerType& descendant_layer) {
130 DCHECK(descendant_layer.HasAncestor(&ancestor_layer));
131 const LayerType* descendant_target = descendant_layer.render_target();
132 DCHECK(descendant_target);
133 const LayerType* ancestor_target = ancestor_layer.render_target();
134 DCHECK(ancestor_target);
136 gfx::Vector2dF translation;
137 for (const LayerType* target = descendant_target; target != ancestor_target;
138 target = NextTargetSurface(target)) {
139 const gfx::Transform& trans = target->render_surface()->draw_transform();
140 // Ensure that this translation is truly 2d.
141 DCHECK(trans.IsIdentityOrTranslation());
142 DCHECK_EQ(0.f, trans.matrix().get(2, 3));
143 translation += trans.To2dTranslation();
149 enum TranslateRectDirection {
150 TranslateRectDirectionToAncestor,
151 TranslateRectDirectionToDescendant
154 template <typename LayerType>
155 static gfx::Rect TranslateRectToTargetSpace(const LayerType& ancestor_layer,
156 const LayerType& descendant_layer,
157 const gfx::Rect& rect,
158 TranslateRectDirection direction) {
159 gfx::Vector2dF translation = ComputeChangeOfBasisTranslation<LayerType>(
160 ancestor_layer, descendant_layer);
161 if (direction == TranslateRectDirectionToDescendant)
162 translation.Scale(-1.f);
163 return gfx::ToEnclosingRect(
164 gfx::RectF(rect.origin() + translation, rect.size()));
167 // Attempts to update the clip rects for the given layer. If the layer has a
168 // clip_parent, it may not inherit its immediate ancestor's clip.
169 template <typename LayerType>
170 static void UpdateClipRectsForClipChild(
171 const LayerType* layer,
172 gfx::Rect* clip_rect_in_parent_target_space,
173 bool* subtree_should_be_clipped) {
174 // If the layer has no clip_parent, or the ancestor is the same as its actual
175 // parent, then we don't need special clip rects. Bail now and leave the out
176 // parameters untouched.
177 const LayerType* clip_parent = layer->scroll_parent();
180 clip_parent = layer->clip_parent();
182 if (!clip_parent || clip_parent == layer->parent())
185 // The root layer is never a clip child.
186 DCHECK(layer->parent());
188 // Grab the cached values.
189 *clip_rect_in_parent_target_space = clip_parent->clip_rect();
190 *subtree_should_be_clipped = clip_parent->is_clipped();
192 // We may have to project the clip rect into our parent's target space. Note,
193 // it must be our parent's target space, not ours. For one, we haven't
194 // computed our transforms, so we couldn't put it in our space yet even if we
195 // wanted to. But more importantly, this matches the expectations of
196 // CalculateDrawPropertiesInternal. If we, say, create a render surface, these
197 // clip rects will want to be in its target space, not ours.
198 if (clip_parent == layer->clip_parent()) {
199 *clip_rect_in_parent_target_space = TranslateRectToTargetSpace<LayerType>(
202 *clip_rect_in_parent_target_space,
203 TranslateRectDirectionToDescendant);
205 // If we're being clipped by our scroll parent, we must translate through
206 // our common ancestor. This happens to be our parent, so it is sufficent to
207 // translate from our clip parent's space to the space of its ancestor (our
209 *clip_rect_in_parent_target_space =
210 TranslateRectToTargetSpace<LayerType>(*layer->parent(),
212 *clip_rect_in_parent_target_space,
213 TranslateRectDirectionToAncestor);
217 // We collect an accumulated drawable content rect per render surface.
218 // Typically, a layer will contribute to only one surface, the surface
219 // associated with its render target. Clip children, however, may affect
220 // several surfaces since there may be several surfaces between the clip child
223 // NB: we accumulate the layer's *clipped* drawable content rect.
224 template <typename LayerType>
225 struct AccumulatedSurfaceState {
226 explicit AccumulatedSurfaceState(LayerType* render_target)
227 : render_target(render_target) {}
229 // The accumulated drawable content rect for the surface associated with the
230 // given |render_target|.
231 gfx::Rect drawable_content_rect;
233 // The target owning the surface. (We hang onto the target rather than the
234 // surface so that we can DCHECK that the surface's draw transform is simply
235 // a translation when |render_target| reports that it has no unclipped
237 LayerType* render_target;
240 template <typename LayerType>
241 void UpdateAccumulatedSurfaceState(
243 const gfx::Rect& drawable_content_rect,
244 std::vector<AccumulatedSurfaceState<LayerType> >*
245 accumulated_surface_state) {
246 if (IsRootLayer(layer))
249 // We will apply our drawable content rect to the accumulated rects for all
250 // surfaces between us and |render_target| (inclusive). This is either our
251 // clip parent's target if we are a clip child, or else simply our parent's
252 // target. We use our parent's target because we're either the owner of a
253 // render surface and we'll want to add our rect to our *surface's* target, or
254 // we're not and our target is the same as our parent's. In both cases, the
255 // parent's target gives us what we want.
256 LayerType* render_target = layer->clip_parent()
257 ? layer->clip_parent()->render_target()
258 : layer->parent()->render_target();
260 // If the layer owns a surface, then the content rect is in the wrong space.
261 // Instead, we will use the surface's DrawableContentRect which is in target
262 // space as required.
263 gfx::Rect target_rect = drawable_content_rect;
264 if (layer->render_surface()) {
266 gfx::ToEnclosedRect(layer->render_surface()->DrawableContentRect());
269 if (render_target->is_clipped()) {
270 gfx::Rect clip_rect = render_target->clip_rect();
271 // If the layer has a clip parent, the clip rect may be in the wrong space,
272 // so we'll need to transform it before it is applied.
273 if (layer->clip_parent()) {
274 clip_rect = TranslateRectToTargetSpace<LayerType>(
275 *layer->clip_parent(),
278 TranslateRectDirectionToDescendant);
280 target_rect.Intersect(clip_rect);
283 // We must have at least one entry in the vector for the root.
284 DCHECK_LT(0ul, accumulated_surface_state->size());
286 typedef typename std::vector<AccumulatedSurfaceState<LayerType> >
287 AccumulatedSurfaceStateVector;
288 typedef typename AccumulatedSurfaceStateVector::reverse_iterator
289 AccumulatedSurfaceStateIterator;
290 AccumulatedSurfaceStateIterator current_state =
291 accumulated_surface_state->rbegin();
293 // Add this rect to the accumulated content rect for all surfaces until we
294 // reach the target surface.
295 bool found_render_target = false;
296 for (; current_state != accumulated_surface_state->rend(); ++current_state) {
297 current_state->drawable_content_rect.Union(target_rect);
299 // If we've reached |render_target| our work is done and we can bail.
300 if (current_state->render_target == render_target) {
301 found_render_target = true;
305 // Transform rect from the current target's space to the next.
306 LayerType* current_target = current_state->render_target;
307 DCHECK(current_target->render_surface());
308 const gfx::Transform& current_draw_transform =
309 current_target->render_surface()->draw_transform();
311 // If we have unclipped descendants, the draw transform is a translation.
312 DCHECK(current_target->num_unclipped_descendants() == 0 ||
313 current_draw_transform.IsIdentityOrTranslation());
315 target_rect = gfx::ToEnclosingRect(
316 MathUtil::MapClippedRect(current_draw_transform, target_rect));
319 // It is an error to not reach |render_target|. If this happens, it means that
320 // either the clip parent is not an ancestor of the clip child or the surface
321 // state vector is empty, both of which should be impossible.
322 DCHECK(found_render_target);
325 template <typename LayerType> static inline bool IsRootLayer(LayerType* layer) {
326 return !layer->parent();
329 template <typename LayerType>
330 static inline bool LayerIsInExisting3DRenderingContext(LayerType* layer) {
331 return layer->is_3d_sorted() && layer->parent() &&
332 layer->parent()->is_3d_sorted();
335 template <typename LayerType>
336 static bool IsRootLayerOfNewRenderingContext(LayerType* layer) {
338 return !layer->parent()->is_3d_sorted() && layer->is_3d_sorted();
340 return layer->is_3d_sorted();
343 template <typename LayerType>
344 static bool IsLayerBackFaceVisible(LayerType* layer) {
345 // The current W3C spec on CSS transforms says that backface visibility should
346 // be determined differently depending on whether the layer is in a "3d
347 // rendering context" or not. For Chromium code, we can determine whether we
348 // are in a 3d rendering context by checking if the parent preserves 3d.
350 if (LayerIsInExisting3DRenderingContext(layer))
351 return layer->draw_transform().IsBackFaceVisible();
353 // In this case, either the layer establishes a new 3d rendering context, or
354 // is not in a 3d rendering context at all.
355 return layer->transform().IsBackFaceVisible();
358 template <typename LayerType>
359 static bool IsSurfaceBackFaceVisible(LayerType* layer,
360 const gfx::Transform& draw_transform) {
361 if (LayerIsInExisting3DRenderingContext(layer))
362 return draw_transform.IsBackFaceVisible();
364 if (IsRootLayerOfNewRenderingContext(layer))
365 return layer->transform().IsBackFaceVisible();
367 // If the render_surface is not part of a new or existing rendering context,
368 // then the layers that contribute to this surface will decide back-face
369 // visibility for themselves.
373 template <typename LayerType>
374 static inline bool LayerClipsSubtree(LayerType* layer) {
375 return layer->masks_to_bounds() || layer->mask_layer();
378 template <typename LayerType>
379 static gfx::Rect CalculateVisibleContentRect(
381 const gfx::Rect& clip_rect_of_target_surface_in_target_space,
382 const gfx::Rect& layer_rect_in_target_space) {
383 DCHECK(layer->render_target());
385 // Nothing is visible if the layer bounds are empty.
386 if (!layer->DrawsContent() || layer->content_bounds().IsEmpty() ||
387 layer->drawable_content_rect().IsEmpty())
390 // Compute visible bounds in target surface space.
391 gfx::Rect visible_rect_in_target_surface_space =
392 layer->drawable_content_rect();
394 if (!layer->render_target()->render_surface()->clip_rect().IsEmpty()) {
395 // The |layer| L has a target T which owns a surface Ts. The surface Ts
398 // In this case the target surface Ts does clip the layer L that contributes
399 // to it. So, we have to convert the clip rect of Ts from the target space
400 // of Ts (that is the space of TsT), to the current render target's space
401 // (that is the space of T). This conversion is done outside this function
402 // so that it can be cached instead of computing it redundantly for every
404 visible_rect_in_target_surface_space.Intersect(
405 clip_rect_of_target_surface_in_target_space);
408 if (visible_rect_in_target_surface_space.IsEmpty())
411 return CalculateVisibleRectWithCachedLayerRect(
412 visible_rect_in_target_surface_space,
413 gfx::Rect(layer->content_bounds()),
414 layer_rect_in_target_space,
415 layer->draw_transform());
418 static inline bool TransformToParentIsKnown(LayerImpl* layer) { return true; }
420 static inline bool TransformToParentIsKnown(Layer* layer) {
421 return !layer->TransformIsAnimating();
424 static inline bool TransformToScreenIsKnown(LayerImpl* layer) { return true; }
426 static inline bool TransformToScreenIsKnown(Layer* layer) {
427 return !layer->screen_space_transform_is_animating();
430 template <typename LayerType>
431 static bool LayerShouldBeSkipped(LayerType* layer, bool layer_is_drawn) {
432 // Layers can be skipped if any of these conditions are met.
433 // - is not drawn due to it or one of its ancestors being hidden (or having
434 // no copy requests).
435 // - has empty bounds
436 // - the layer is not double-sided, but its back face is visible.
438 // - does not draw content and does not participate in hit testing.
440 // Some additional conditions need to be computed at a later point after the
441 // recursion is finished.
442 // - the intersection of render_surface content and layer clip_rect is empty
443 // - the visible_content_rect is empty
445 // Note, if the layer should not have been drawn due to being fully
446 // transparent, we would have skipped the entire subtree and never made it
447 // into this function, so it is safe to omit this check here.
452 if (layer->bounds().IsEmpty())
455 LayerType* backface_test_layer = layer;
456 if (layer->use_parent_backface_visibility()) {
457 DCHECK(layer->parent());
458 DCHECK(!layer->parent()->use_parent_backface_visibility());
459 backface_test_layer = layer->parent();
462 // The layer should not be drawn if (1) it is not double-sided and (2) the
463 // back of the layer is known to be facing the screen.
464 if (!backface_test_layer->double_sided() &&
465 TransformToScreenIsKnown(backface_test_layer) &&
466 IsLayerBackFaceVisible(backface_test_layer))
469 // The layer is visible to events. If it's subject to hit testing, then
471 bool can_accept_input = !layer->touch_event_handler_region().IsEmpty() ||
472 layer->have_wheel_event_handlers();
473 if (!layer->DrawsContent() && !can_accept_input)
479 template <typename LayerType>
480 static bool HasInvertibleOrAnimatedTransform(LayerType* layer) {
481 return layer->transform_is_invertible() || layer->TransformIsAnimating();
484 static inline bool SubtreeShouldBeSkipped(LayerImpl* layer,
485 bool layer_is_drawn) {
486 // If the layer transform is not invertible, it should not be drawn.
487 // TODO(ajuma): Correctly process subtrees with singular transform for the
488 // case where we may animate to a non-singular transform and wish to
490 if (!HasInvertibleOrAnimatedTransform(layer))
493 // When we need to do a readback/copy of a layer's output, we can not skip
494 // it or any of its ancestors.
495 if (layer->draw_properties().layer_or_descendant_has_copy_request)
498 // If the layer is not drawn, then skip it and its subtree.
502 // If layer is on the pending tree and opacity is being animated then
503 // this subtree can't be skipped as we need to create, prioritize and
504 // include tiles for this layer when deciding if tree can be activated.
505 if (layer->layer_tree_impl()->IsPendingTree() && layer->OpacityIsAnimating())
508 // The opacity of a layer always applies to its children (either implicitly
509 // via a render surface or explicitly if the parent preserves 3D), so the
510 // entire subtree can be skipped if this layer is fully transparent.
511 // TODO(sad): Don't skip layers used for hit testing crbug.com/295295.
512 return !layer->opacity();
515 static inline bool SubtreeShouldBeSkipped(Layer* layer, bool layer_is_drawn) {
516 // If the layer transform is not invertible, it should not be drawn.
517 if (!layer->transform_is_invertible() && !layer->TransformIsAnimating())
520 // When we need to do a readback/copy of a layer's output, we can not skip
521 // it or any of its ancestors.
522 if (layer->draw_properties().layer_or_descendant_has_copy_request)
525 // If the layer is not drawn, then skip it and its subtree.
529 // If the opacity is being animated then the opacity on the main thread is
530 // unreliable (since the impl thread may be using a different opacity), so it
531 // should not be trusted.
532 // In particular, it should not cause the subtree to be skipped.
533 // Similarly, for layers that might animate opacity using an impl-only
534 // animation, their subtree should also not be skipped.
535 // TODO(sad): Don't skip layers used for hit testing crbug.com/295295.
536 return !layer->opacity() && !layer->OpacityIsAnimating() &&
537 !layer->OpacityCanAnimateOnImplThread();
540 static inline void SavePaintPropertiesLayer(LayerImpl* layer) {}
542 static inline void SavePaintPropertiesLayer(Layer* layer) {
543 layer->SavePaintProperties();
545 if (layer->mask_layer())
546 layer->mask_layer()->SavePaintProperties();
547 if (layer->replica_layer() && layer->replica_layer()->mask_layer())
548 layer->replica_layer()->mask_layer()->SavePaintProperties();
551 template <typename LayerType>
552 static bool SubtreeShouldRenderToSeparateSurface(
554 bool axis_aligned_with_respect_to_parent) {
556 // A layer and its descendants should render onto a new RenderSurfaceImpl if
557 // any of these rules hold:
560 // The root layer owns a render surface, but it never acts as a contributing
561 // surface to another render target. Compositor features that are applied via
562 // a contributing surface can not be applied to the root layer. In order to
563 // use these effects, another child of the root would need to be introduced
564 // in order to act as a contributing surface to the root layer's surface.
565 bool is_root = IsRootLayer(layer);
567 // If the layer uses a mask.
568 if (layer->mask_layer()) {
573 // If the layer has a reflection.
574 if (layer->replica_layer()) {
579 // If the layer uses a CSS filter.
580 if (!layer->filters().IsEmpty() || !layer->background_filters().IsEmpty()) {
585 int num_descendants_that_draw_content =
586 layer->draw_properties().num_descendants_that_draw_content;
588 // If the layer flattens its subtree, but it is treated as a 3D object by its
589 // parent (i.e. parent participates in a 3D rendering context).
590 if (LayerIsInExisting3DRenderingContext(layer) &&
591 layer->should_flatten_transform() &&
592 num_descendants_that_draw_content > 0) {
593 TRACE_EVENT_INSTANT0(
595 "LayerTreeHostCommon::SubtreeShouldRenderToSeparateSurface flattening",
596 TRACE_EVENT_SCOPE_THREAD);
601 // If the layer has blending.
602 // TODO(rosca): this is temporary, until blending is implemented for other
603 // types of quads than RenderPassDrawQuad. Layers having descendants that draw
604 // content will still create a separate rendering surface.
605 if (!layer->uses_default_blend_mode()) {
606 TRACE_EVENT_INSTANT0(
608 "LayerTreeHostCommon::SubtreeShouldRenderToSeparateSurface blending",
609 TRACE_EVENT_SCOPE_THREAD);
614 // If the layer clips its descendants but it is not axis-aligned with respect
616 bool layer_clips_external_content =
617 LayerClipsSubtree(layer) || layer->HasDelegatedContent();
618 if (layer_clips_external_content && !axis_aligned_with_respect_to_parent &&
619 num_descendants_that_draw_content > 0) {
620 TRACE_EVENT_INSTANT0(
622 "LayerTreeHostCommon::SubtreeShouldRenderToSeparateSurface clipping",
623 TRACE_EVENT_SCOPE_THREAD);
628 // If the layer has some translucency and does not have a preserves-3d
629 // transform style. This condition only needs a render surface if two or more
630 // layers in the subtree overlap. But checking layer overlaps is unnecessarily
631 // costly so instead we conservatively create a surface whenever at least two
632 // layers draw content for this subtree.
633 bool at_least_two_layers_in_subtree_draw_content =
634 num_descendants_that_draw_content > 0 &&
635 (layer->DrawsContent() || num_descendants_that_draw_content > 1);
637 if (layer->opacity() != 1.f && layer->should_flatten_transform() &&
638 at_least_two_layers_in_subtree_draw_content) {
639 TRACE_EVENT_INSTANT0(
641 "LayerTreeHostCommon::SubtreeShouldRenderToSeparateSurface opacity",
642 TRACE_EVENT_SCOPE_THREAD);
647 // The root layer should always have a render_surface.
652 // These are allowed on the root surface, as they don't require the surface to
653 // be used as a contributing surface in order to apply correctly.
656 // If the layer has isolation.
657 // TODO(rosca): to be optimized - create separate rendering surface only when
658 // the blending descendants might have access to the content behind this layer
659 // (layer has transparent background or descendants overflow).
660 // https://code.google.com/p/chromium/issues/detail?id=301738
661 if (layer->is_root_for_isolated_group()) {
662 TRACE_EVENT_INSTANT0(
664 "LayerTreeHostCommon::SubtreeShouldRenderToSeparateSurface isolation",
665 TRACE_EVENT_SCOPE_THREAD);
670 if (layer->force_render_surface())
673 // If we'll make a copy of the layer's contents.
674 if (layer->HasCopyRequest())
680 // This function returns a translation matrix that can be applied on a vector
681 // that's in the layer's target surface coordinate, while the position offset is
682 // specified in some ancestor layer's coordinate.
683 gfx::Transform ComputeSizeDeltaCompensation(
685 LayerImpl* container,
686 const gfx::Vector2dF& position_offset) {
687 gfx::Transform result_transform;
689 // To apply a translate in the container's layer space,
690 // the following steps need to be done:
691 // Step 1a. transform from target surface space to the container's target
693 // Step 1b. transform from container's target surface space to the
694 // container's layer space
695 // Step 2. apply the compensation
696 // Step 3. transform back to target surface space
698 gfx::Transform target_surface_space_to_container_layer_space;
700 LayerImpl* container_target_surface = container->render_target();
701 for (LayerImpl* current_target_surface = NextTargetSurface(layer);
702 current_target_surface &&
703 current_target_surface != container_target_surface;
704 current_target_surface = NextTargetSurface(current_target_surface)) {
705 // Note: Concat is used here to convert the result coordinate space from
706 // current render surface to the next render surface.
707 target_surface_space_to_container_layer_space.ConcatTransform(
708 current_target_surface->render_surface()->draw_transform());
711 gfx::Transform container_layer_space_to_container_target_surface_space =
712 container->draw_transform();
713 container_layer_space_to_container_target_surface_space.Scale(
714 container->contents_scale_x(), container->contents_scale_y());
716 gfx::Transform container_target_surface_space_to_container_layer_space;
717 if (container_layer_space_to_container_target_surface_space.GetInverse(
718 &container_target_surface_space_to_container_layer_space)) {
719 // Note: Again, Concat is used to conver the result coordinate space from
720 // the container render surface to the container layer.
721 target_surface_space_to_container_layer_space.ConcatTransform(
722 container_target_surface_space_to_container_layer_space);
726 gfx::Transform container_layer_space_to_target_surface_space;
727 if (target_surface_space_to_container_layer_space.GetInverse(
728 &container_layer_space_to_target_surface_space)) {
729 result_transform.PreconcatTransform(
730 container_layer_space_to_target_surface_space);
732 // TODO(shawnsingh): A non-invertible matrix could still make meaningful
733 // projection. For example ScaleZ(0) is non-invertible but the layer is
735 return gfx::Transform();
739 result_transform.Translate(position_offset.x(), position_offset.y());
742 result_transform.PreconcatTransform(
743 target_surface_space_to_container_layer_space);
745 return result_transform;
748 void ApplyPositionAdjustment(
751 const gfx::Transform& scroll_compensation,
752 gfx::Transform* combined_transform) {}
753 void ApplyPositionAdjustment(
755 LayerImpl* container,
756 const gfx::Transform& scroll_compensation,
757 gfx::Transform* combined_transform) {
758 if (!layer->position_constraint().is_fixed_position())
761 // Special case: this layer is a composited fixed-position layer; we need to
762 // explicitly compensate for all ancestors' nonzero scroll_deltas to keep
763 // this layer fixed correctly.
764 // Note carefully: this is Concat, not Preconcat
765 // (current_scroll_compensation * combined_transform).
766 combined_transform->ConcatTransform(scroll_compensation);
768 // For right-edge or bottom-edge anchored fixed position layers,
769 // the layer should relocate itself if the container changes its size.
770 bool fixed_to_right_edge =
771 layer->position_constraint().is_fixed_to_right_edge();
772 bool fixed_to_bottom_edge =
773 layer->position_constraint().is_fixed_to_bottom_edge();
774 gfx::Vector2dF position_offset = container->FixedContainerSizeDelta();
775 position_offset.set_x(fixed_to_right_edge ? position_offset.x() : 0);
776 position_offset.set_y(fixed_to_bottom_edge ? position_offset.y() : 0);
777 if (position_offset.IsZero())
780 // Note: Again, this is Concat. The compensation matrix will be applied on
781 // the vector in target surface space.
782 combined_transform->ConcatTransform(
783 ComputeSizeDeltaCompensation(layer, container, position_offset));
786 gfx::Transform ComputeScrollCompensationForThisLayer(
787 LayerImpl* scrolling_layer,
788 const gfx::Transform& parent_matrix,
789 const gfx::Vector2dF& scroll_delta) {
790 // For every layer that has non-zero scroll_delta, we have to compute a
791 // transform that can undo the scroll_delta translation. In particular, we
792 // want this matrix to premultiply a fixed-position layer's parent_matrix, so
793 // we design this transform in three steps as follows. The steps described
794 // here apply from right-to-left, so Step 1 would be the right-most matrix:
796 // Step 1. transform from target surface space to the exact space where
797 // scroll_delta is actually applied.
798 // -- this is inverse of parent_matrix
799 // Step 2. undo the scroll_delta
800 // -- this is just a translation by scroll_delta.
801 // Step 3. transform back to target surface space.
802 // -- this transform is the parent_matrix
804 // These steps create a matrix that both start and end in target surface
805 // space. So this matrix can pre-multiply any fixed-position layer's
806 // draw_transform to undo the scroll_deltas -- as long as that fixed position
807 // layer is fixed onto the same render_target as this scrolling_layer.
810 gfx::Transform scroll_compensation_for_this_layer = parent_matrix; // Step 3
811 scroll_compensation_for_this_layer.Translate(
813 scroll_delta.y()); // Step 2
815 gfx::Transform inverse_parent_matrix(gfx::Transform::kSkipInitialization);
816 if (!parent_matrix.GetInverse(&inverse_parent_matrix)) {
817 // TODO(shawnsingh): Either we need to handle uninvertible transforms
818 // here, or DCHECK that the transform is invertible.
820 scroll_compensation_for_this_layer.PreconcatTransform(
821 inverse_parent_matrix); // Step 1
822 return scroll_compensation_for_this_layer;
825 gfx::Transform ComputeScrollCompensationMatrixForChildren(
826 Layer* current_layer,
827 const gfx::Transform& current_parent_matrix,
828 const gfx::Transform& current_scroll_compensation,
829 const gfx::Vector2dF& scroll_delta) {
830 // The main thread (i.e. Layer) does not need to worry about scroll
831 // compensation. So we can just return an identity matrix here.
832 return gfx::Transform();
835 gfx::Transform ComputeScrollCompensationMatrixForChildren(
837 const gfx::Transform& parent_matrix,
838 const gfx::Transform& current_scroll_compensation_matrix,
839 const gfx::Vector2dF& scroll_delta) {
840 // "Total scroll compensation" is the transform needed to cancel out all
841 // scroll_delta translations that occurred since the nearest container layer,
842 // even if there are render_surfaces in-between.
844 // There are some edge cases to be aware of, that are not explicit in the
846 // - A layer that is both a fixed-position and container should not be its
847 // own container, instead, that means it is fixed to an ancestor, and is a
848 // container for any fixed-position descendants.
849 // - A layer that is a fixed-position container and has a render_surface
850 // should behave the same as a container without a render_surface, the
851 // render_surface is irrelevant in that case.
852 // - A layer that does not have an explicit container is simply fixed to the
853 // viewport. (i.e. the root render_surface.)
854 // - If the fixed-position layer has its own render_surface, then the
855 // render_surface is the one who gets fixed.
857 // This function needs to be called AFTER layers create their own
861 // Scroll compensation restarts from identity under two possible conditions:
862 // - the current layer is a container for fixed-position descendants
863 // - the current layer is fixed-position itself, so any fixed-position
864 // descendants are positioned with respect to this layer. Thus, any
865 // fixed position descendants only need to compensate for scrollDeltas
866 // that occur below this layer.
867 bool current_layer_resets_scroll_compensation_for_descendants =
868 layer->IsContainerForFixedPositionLayers() ||
869 layer->position_constraint().is_fixed_position();
871 // Avoid the overheads (including stack allocation and matrix
872 // initialization/copy) if we know that the scroll compensation doesn't need
873 // to be reset or adjusted.
874 if (!current_layer_resets_scroll_compensation_for_descendants &&
875 scroll_delta.IsZero() && !layer->render_surface())
876 return current_scroll_compensation_matrix;
878 // Start as identity matrix.
879 gfx::Transform next_scroll_compensation_matrix;
881 // If this layer does not reset scroll compensation, then it inherits the
882 // existing scroll compensations.
883 if (!current_layer_resets_scroll_compensation_for_descendants)
884 next_scroll_compensation_matrix = current_scroll_compensation_matrix;
886 // If the current layer has a non-zero scroll_delta, then we should compute
887 // its local scroll compensation and accumulate it to the
888 // next_scroll_compensation_matrix.
889 if (!scroll_delta.IsZero()) {
890 gfx::Transform scroll_compensation_for_this_layer =
891 ComputeScrollCompensationForThisLayer(
892 layer, parent_matrix, scroll_delta);
893 next_scroll_compensation_matrix.PreconcatTransform(
894 scroll_compensation_for_this_layer);
897 // If the layer created its own render_surface, we have to adjust
898 // next_scroll_compensation_matrix. The adjustment allows us to continue
899 // using the scroll compensation on the next surface.
900 // Step 1 (right-most in the math): transform from the new surface to the
901 // original ancestor surface
902 // Step 2: apply the scroll compensation
903 // Step 3: transform back to the new surface.
904 if (layer->render_surface() &&
905 !next_scroll_compensation_matrix.IsIdentity()) {
906 gfx::Transform inverse_surface_draw_transform(
907 gfx::Transform::kSkipInitialization);
908 if (!layer->render_surface()->draw_transform().GetInverse(
909 &inverse_surface_draw_transform)) {
910 // TODO(shawnsingh): Either we need to handle uninvertible transforms
911 // here, or DCHECK that the transform is invertible.
913 next_scroll_compensation_matrix =
914 inverse_surface_draw_transform * next_scroll_compensation_matrix *
915 layer->render_surface()->draw_transform();
918 return next_scroll_compensation_matrix;
921 template <typename LayerType>
922 static inline void CalculateContentsScale(
924 float contents_scale,
925 float device_scale_factor,
926 float page_scale_factor,
927 float maximum_animation_contents_scale,
928 bool animating_transform_to_screen) {
929 layer->CalculateContentsScale(contents_scale,
932 maximum_animation_contents_scale,
933 animating_transform_to_screen,
934 &layer->draw_properties().contents_scale_x,
935 &layer->draw_properties().contents_scale_y,
936 &layer->draw_properties().content_bounds);
938 LayerType* mask_layer = layer->mask_layer();
940 mask_layer->CalculateContentsScale(
944 maximum_animation_contents_scale,
945 animating_transform_to_screen,
946 &mask_layer->draw_properties().contents_scale_x,
947 &mask_layer->draw_properties().contents_scale_y,
948 &mask_layer->draw_properties().content_bounds);
951 LayerType* replica_mask_layer =
952 layer->replica_layer() ? layer->replica_layer()->mask_layer() : NULL;
953 if (replica_mask_layer) {
954 replica_mask_layer->CalculateContentsScale(
958 maximum_animation_contents_scale,
959 animating_transform_to_screen,
960 &replica_mask_layer->draw_properties().contents_scale_x,
961 &replica_mask_layer->draw_properties().contents_scale_y,
962 &replica_mask_layer->draw_properties().content_bounds);
966 static inline void UpdateLayerContentsScale(
968 bool can_adjust_raster_scale,
969 float ideal_contents_scale,
970 float device_scale_factor,
971 float page_scale_factor,
972 float maximum_animation_contents_scale,
973 bool animating_transform_to_screen) {
974 CalculateContentsScale(layer,
975 ideal_contents_scale,
978 maximum_animation_contents_scale,
979 animating_transform_to_screen);
982 static inline void UpdateLayerContentsScale(
984 bool can_adjust_raster_scale,
985 float ideal_contents_scale,
986 float device_scale_factor,
987 float page_scale_factor,
988 float maximum_animation_contents_scale,
989 bool animating_transform_to_screen) {
990 if (can_adjust_raster_scale) {
991 float ideal_raster_scale =
992 ideal_contents_scale / (device_scale_factor * page_scale_factor);
994 bool need_to_set_raster_scale = layer->raster_scale_is_unknown();
996 // If we've previously saved a raster_scale but the ideal changes, things
997 // are unpredictable and we should just use 1.
998 if (!need_to_set_raster_scale && layer->raster_scale() != 1.f &&
999 ideal_raster_scale != layer->raster_scale()) {
1000 ideal_raster_scale = 1.f;
1001 need_to_set_raster_scale = true;
1004 if (need_to_set_raster_scale) {
1005 bool use_and_save_ideal_scale =
1006 ideal_raster_scale >= 1.f && !animating_transform_to_screen;
1007 if (use_and_save_ideal_scale)
1008 layer->set_raster_scale(ideal_raster_scale);
1012 float raster_scale = 1.f;
1013 if (!layer->raster_scale_is_unknown())
1014 raster_scale = layer->raster_scale();
1016 gfx::Size old_content_bounds = layer->content_bounds();
1017 float old_contents_scale_x = layer->contents_scale_x();
1018 float old_contents_scale_y = layer->contents_scale_y();
1020 float contents_scale = raster_scale * device_scale_factor * page_scale_factor;
1021 CalculateContentsScale(layer,
1023 device_scale_factor,
1025 maximum_animation_contents_scale,
1026 animating_transform_to_screen);
1028 if (layer->content_bounds() != old_content_bounds ||
1029 layer->contents_scale_x() != old_contents_scale_x ||
1030 layer->contents_scale_y() != old_contents_scale_y)
1031 layer->SetNeedsPushProperties();
1034 static inline void CalculateAnimationContentsScale(
1036 bool ancestor_is_animating_scale,
1037 float ancestor_maximum_animation_contents_scale,
1038 const gfx::Transform& parent_transform,
1039 const gfx::Transform& combined_transform,
1040 bool* combined_is_animating_scale,
1041 float* combined_maximum_animation_contents_scale) {
1042 *combined_is_animating_scale = false;
1043 *combined_maximum_animation_contents_scale = 0.f;
1046 static inline void CalculateAnimationContentsScale(
1048 bool ancestor_is_animating_scale,
1049 float ancestor_maximum_animation_contents_scale,
1050 const gfx::Transform& ancestor_transform,
1051 const gfx::Transform& combined_transform,
1052 bool* combined_is_animating_scale,
1053 float* combined_maximum_animation_contents_scale) {
1054 if (ancestor_is_animating_scale &&
1055 ancestor_maximum_animation_contents_scale == 0.f) {
1056 // We've already failed to compute a maximum animated scale at an
1057 // ancestor, so we'll continue to fail.
1058 *combined_maximum_animation_contents_scale = 0.f;
1059 *combined_is_animating_scale = true;
1063 if (!combined_transform.IsScaleOrTranslation()) {
1064 // Computing maximum animated scale in the presence of
1065 // non-scale/translation transforms isn't supported.
1066 *combined_maximum_animation_contents_scale = 0.f;
1067 *combined_is_animating_scale = true;
1071 // We currently only support computing maximum scale for combinations of
1072 // scales and translations. We treat all non-translations as potentially
1073 // affecting scale. Animations that include non-translation/scale components
1074 // will cause the computation of MaximumScale below to fail.
1075 bool layer_is_animating_scale =
1076 !layer->layer_animation_controller()->HasOnlyTranslationTransforms();
1078 if (!layer_is_animating_scale && !ancestor_is_animating_scale) {
1079 *combined_maximum_animation_contents_scale = 0.f;
1080 *combined_is_animating_scale = false;
1084 // We don't attempt to accumulate animation scale from multiple nodes,
1085 // because of the risk of significant overestimation. For example, one node
1086 // may be increasing scale from 1 to 10 at the same time as a descendant is
1087 // decreasing scale from 10 to 1. Naively combining these scales would produce
1089 if (layer_is_animating_scale && ancestor_is_animating_scale) {
1090 *combined_maximum_animation_contents_scale = 0.f;
1091 *combined_is_animating_scale = true;
1095 // At this point, we know either the layer or an ancestor, but not both,
1096 // is animating scale.
1097 *combined_is_animating_scale = true;
1098 if (!layer_is_animating_scale) {
1099 gfx::Vector2dF layer_transform_scales =
1100 MathUtil::ComputeTransform2dScaleComponents(layer->transform(), 0.f);
1101 *combined_maximum_animation_contents_scale =
1102 ancestor_maximum_animation_contents_scale *
1103 std::max(layer_transform_scales.x(), layer_transform_scales.y());
1107 float layer_maximum_animated_scale = 0.f;
1108 if (!layer->layer_animation_controller()->MaximumScale(
1109 &layer_maximum_animated_scale)) {
1110 *combined_maximum_animation_contents_scale = 0.f;
1113 gfx::Vector2dF ancestor_transform_scales =
1114 MathUtil::ComputeTransform2dScaleComponents(ancestor_transform, 0.f);
1115 *combined_maximum_animation_contents_scale =
1116 layer_maximum_animated_scale *
1117 std::max(ancestor_transform_scales.x(), ancestor_transform_scales.y());
1120 template <typename LayerType>
1121 static inline typename LayerType::RenderSurfaceType* CreateOrReuseRenderSurface(
1123 if (!layer->render_surface()) {
1124 layer->CreateRenderSurface();
1125 return layer->render_surface();
1128 layer->render_surface()->ClearLayerLists();
1129 return layer->render_surface();
1132 template <typename LayerTypePtr>
1133 static inline void MarkLayerWithRenderSurfaceLayerListId(
1135 int current_render_surface_layer_list_id) {
1136 layer->draw_properties().last_drawn_render_surface_layer_list_id =
1137 current_render_surface_layer_list_id;
1140 template <typename LayerTypePtr>
1141 static inline void MarkMasksWithRenderSurfaceLayerListId(
1143 int current_render_surface_layer_list_id) {
1144 if (layer->mask_layer()) {
1145 MarkLayerWithRenderSurfaceLayerListId(layer->mask_layer(),
1146 current_render_surface_layer_list_id);
1148 if (layer->replica_layer() && layer->replica_layer()->mask_layer()) {
1149 MarkLayerWithRenderSurfaceLayerListId(layer->replica_layer()->mask_layer(),
1150 current_render_surface_layer_list_id);
1154 template <typename LayerListType>
1155 static inline void MarkLayerListWithRenderSurfaceLayerListId(
1156 LayerListType* layer_list,
1157 int current_render_surface_layer_list_id) {
1158 for (typename LayerListType::iterator it = layer_list->begin();
1159 it != layer_list->end();
1161 MarkLayerWithRenderSurfaceLayerListId(*it,
1162 current_render_surface_layer_list_id);
1163 MarkMasksWithRenderSurfaceLayerListId(*it,
1164 current_render_surface_layer_list_id);
1168 template <typename LayerType>
1169 static inline void RemoveSurfaceForEarlyExit(
1170 LayerType* layer_to_remove,
1171 typename LayerType::RenderSurfaceListType* render_surface_layer_list) {
1172 DCHECK(layer_to_remove->render_surface());
1173 // Technically, we know that the layer we want to remove should be
1174 // at the back of the render_surface_layer_list. However, we have had
1175 // bugs before that added unnecessary layers here
1176 // (https://bugs.webkit.org/show_bug.cgi?id=74147), but that causes
1177 // things to crash. So here we proactively remove any additional
1178 // layers from the end of the list.
1179 while (render_surface_layer_list->back() != layer_to_remove) {
1180 MarkLayerListWithRenderSurfaceLayerListId(
1181 &render_surface_layer_list->back()->render_surface()->layer_list(), 0);
1182 MarkLayerWithRenderSurfaceLayerListId(render_surface_layer_list->back(), 0);
1184 render_surface_layer_list->back()->ClearRenderSurfaceLayerList();
1185 render_surface_layer_list->pop_back();
1187 DCHECK_EQ(render_surface_layer_list->back(), layer_to_remove);
1188 MarkLayerListWithRenderSurfaceLayerListId(
1189 &layer_to_remove->render_surface()->layer_list(), 0);
1190 MarkLayerWithRenderSurfaceLayerListId(layer_to_remove, 0);
1191 render_surface_layer_list->pop_back();
1192 layer_to_remove->ClearRenderSurfaceLayerList();
1195 struct PreCalculateMetaInformationRecursiveData {
1196 bool layer_or_descendant_has_copy_request;
1197 int num_unclipped_descendants;
1199 PreCalculateMetaInformationRecursiveData()
1200 : layer_or_descendant_has_copy_request(false),
1201 num_unclipped_descendants(0) {}
1203 void Merge(const PreCalculateMetaInformationRecursiveData& data) {
1204 layer_or_descendant_has_copy_request |=
1205 data.layer_or_descendant_has_copy_request;
1206 num_unclipped_descendants +=
1207 data.num_unclipped_descendants;
1211 // Recursively walks the layer tree to compute any information that is needed
1212 // before doing the main recursion.
1213 template <typename LayerType>
1214 static void PreCalculateMetaInformation(
1216 PreCalculateMetaInformationRecursiveData* recursive_data) {
1217 bool has_delegated_content = layer->HasDelegatedContent();
1218 int num_descendants_that_draw_content = 0;
1220 layer->draw_properties().sorted_for_recursion = false;
1221 layer->draw_properties().has_child_with_a_scroll_parent = false;
1223 if (!HasInvertibleOrAnimatedTransform(layer)) {
1224 // Layers with singular transforms should not be drawn, the whole subtree
1229 if (has_delegated_content) {
1230 // Layers with delegated content need to be treated as if they have as
1231 // many children as the number of layers they own delegated quads for.
1232 // Since we don't know this number right now, we choose one that acts like
1233 // infinity for our purposes.
1234 num_descendants_that_draw_content = 1000;
1237 if (layer->clip_parent())
1238 recursive_data->num_unclipped_descendants++;
1240 for (size_t i = 0; i < layer->children().size(); ++i) {
1241 LayerType* child_layer =
1242 LayerTreeHostCommon::get_layer_as_raw_ptr(layer->children(), i);
1244 PreCalculateMetaInformationRecursiveData data_for_child;
1245 PreCalculateMetaInformation(child_layer, &data_for_child);
1247 num_descendants_that_draw_content += child_layer->DrawsContent() ? 1 : 0;
1248 num_descendants_that_draw_content +=
1249 child_layer->draw_properties().num_descendants_that_draw_content;
1251 if (child_layer->scroll_parent())
1252 layer->draw_properties().has_child_with_a_scroll_parent = true;
1253 recursive_data->Merge(data_for_child);
1256 if (layer->clip_children()) {
1257 int num_clip_children = layer->clip_children()->size();
1258 DCHECK_GE(recursive_data->num_unclipped_descendants, num_clip_children);
1259 recursive_data->num_unclipped_descendants -= num_clip_children;
1262 if (layer->HasCopyRequest())
1263 recursive_data->layer_or_descendant_has_copy_request = true;
1265 layer->draw_properties().num_descendants_that_draw_content =
1266 num_descendants_that_draw_content;
1267 layer->draw_properties().num_unclipped_descendants =
1268 recursive_data->num_unclipped_descendants;
1269 layer->draw_properties().layer_or_descendant_has_copy_request =
1270 recursive_data->layer_or_descendant_has_copy_request;
1273 static void RoundTranslationComponents(gfx::Transform* transform) {
1274 transform->matrix().set(0, 3, MathUtil::Round(transform->matrix().get(0, 3)));
1275 transform->matrix().set(1, 3, MathUtil::Round(transform->matrix().get(1, 3)));
1278 template <typename LayerType>
1279 struct SubtreeGlobals {
1280 LayerSorter* layer_sorter;
1281 int max_texture_size;
1282 float device_scale_factor;
1283 float page_scale_factor;
1284 const LayerType* page_scale_application_layer;
1285 bool can_adjust_raster_scales;
1286 bool can_render_to_separate_surface;
1289 template<typename LayerType>
1290 struct DataForRecursion {
1291 // The accumulated sequence of transforms a layer will use to determine its
1292 // own draw transform.
1293 gfx::Transform parent_matrix;
1295 // The accumulated sequence of transforms a layer will use to determine its
1296 // own screen-space transform.
1297 gfx::Transform full_hierarchy_matrix;
1299 // The transform that removes all scrolling that may have occurred between a
1300 // fixed-position layer and its container, so that the layer actually does
1302 gfx::Transform scroll_compensation_matrix;
1304 // The ancestor that would be the container for any fixed-position / sticky
1306 LayerType* fixed_container;
1308 // This is the normal clip rect that is propagated from parent to child.
1309 gfx::Rect clip_rect_in_target_space;
1311 // When the layer's children want to compute their visible content rect, they
1312 // want to know what their target surface's clip rect will be. BUT - they
1313 // want to know this clip rect represented in their own target space. This
1314 // requires inverse-projecting the surface's clip rect from the surface's
1315 // render target space down to the surface's own space. Instead of computing
1316 // this value redundantly for each child layer, it is computed only once
1317 // while dealing with the parent layer, and then this precomputed value is
1318 // passed down the recursion to the children that actually use it.
1319 gfx::Rect clip_rect_of_target_surface_in_target_space;
1321 // The maximum amount by which this layer will be scaled during the lifetime
1322 // of currently running animations.
1323 float maximum_animation_contents_scale;
1325 bool ancestor_is_animating_scale;
1326 bool ancestor_clips_subtree;
1327 typename LayerType::RenderSurfaceType*
1328 nearest_occlusion_immune_ancestor_surface;
1329 bool in_subtree_of_page_scale_application_layer;
1330 bool subtree_can_use_lcd_text;
1331 bool subtree_is_visible_from_ancestor;
1334 template <typename LayerType>
1335 static LayerType* GetChildContainingLayer(const LayerType& parent,
1337 for (LayerType* ancestor = layer; ancestor; ancestor = ancestor->parent()) {
1338 if (ancestor->parent() == &parent)
1345 template <typename LayerType>
1346 static void AddScrollParentChain(std::vector<LayerType*>* out,
1347 const LayerType& parent,
1349 // At a high level, this function walks up the chain of scroll parents
1350 // recursively, and once we reach the end of the chain, we add the child
1351 // of |parent| containing each scroll ancestor as we unwind. The result is
1352 // an ordering of parent's children that ensures that scroll parents are
1353 // visited before their descendants.
1354 // Take for example this layer tree:
1356 // + stacking_context
1357 // + scroll_child (1)
1358 // + scroll_parent_graphics_layer (*)
1359 // | + scroll_parent_scrolling_layer
1360 // | + scroll_parent_scrolling_content_layer (2)
1361 // + scroll_grandparent_graphics_layer (**)
1362 // + scroll_grandparent_scrolling_layer
1363 // + scroll_grandparent_scrolling_content_layer (3)
1365 // The scroll child is (1), its scroll parent is (2) and its scroll
1366 // grandparent is (3). Note, this doesn't mean that (2)'s scroll parent is
1367 // (3), it means that (*)'s scroll parent is (3). We don't want our list to
1368 // look like [ (3), (2), (1) ], even though that does have the ancestor chain
1369 // in the right order. Instead, we want [ (**), (*), (1) ]. That is, only want
1370 // (1)'s siblings in the list, but we want them to appear in such an order
1371 // that the scroll ancestors get visited in the correct order.
1373 // So our first task at this step of the recursion is to determine the layer
1374 // that we will potentionally add to the list. That is, the child of parent
1375 // containing |layer|.
1376 LayerType* child = GetChildContainingLayer(parent, layer);
1377 if (child->draw_properties().sorted_for_recursion)
1380 if (LayerType* scroll_parent = child->scroll_parent())
1381 AddScrollParentChain(out, parent, scroll_parent);
1383 out->push_back(child);
1384 child->draw_properties().sorted_for_recursion = true;
1387 template <typename LayerType>
1388 static bool SortChildrenForRecursion(std::vector<LayerType*>* out,
1389 const LayerType& parent) {
1390 out->reserve(parent.children().size());
1391 bool order_changed = false;
1392 for (size_t i = 0; i < parent.children().size(); ++i) {
1393 LayerType* current =
1394 LayerTreeHostCommon::get_layer_as_raw_ptr(parent.children(), i);
1396 if (current->draw_properties().sorted_for_recursion) {
1397 order_changed = true;
1401 AddScrollParentChain(out, parent, current);
1404 DCHECK_EQ(parent.children().size(), out->size());
1405 return order_changed;
1408 template <typename LayerType>
1409 static void GetNewDescendantsStartIndexAndCount(LayerType* layer,
1410 size_t* start_index,
1412 *start_index = layer->draw_properties().index_of_first_descendants_addition;
1413 *count = layer->draw_properties().num_descendants_added;
1416 template <typename LayerType>
1417 static void GetNewRenderSurfacesStartIndexAndCount(LayerType* layer,
1418 size_t* start_index,
1420 *start_index = layer->draw_properties()
1421 .index_of_first_render_surface_layer_list_addition;
1422 *count = layer->draw_properties().num_render_surfaces_added;
1425 // We need to extract a list from the the two flavors of RenderSurfaceListType
1426 // for use in the sorting function below.
1427 static LayerList* GetLayerListForSorting(RenderSurfaceLayerList* rsll) {
1428 return &rsll->AsLayerList();
1431 static LayerImplList* GetLayerListForSorting(LayerImplList* layer_list) {
1435 template <typename LayerType, typename GetIndexAndCountType>
1436 static void SortLayerListContributions(
1437 const LayerType& parent,
1438 typename LayerType::LayerListType* unsorted,
1439 size_t start_index_for_all_contributions,
1440 GetIndexAndCountType get_index_and_count) {
1441 typename LayerType::LayerListType buffer;
1442 for (size_t i = 0; i < parent.children().size(); ++i) {
1444 LayerTreeHostCommon::get_layer_as_raw_ptr(parent.children(), i);
1446 size_t start_index = 0;
1448 get_index_and_count(child, &start_index, &count);
1449 for (size_t j = start_index; j < start_index + count; ++j)
1450 buffer.push_back(unsorted->at(j));
1453 DCHECK_EQ(buffer.size(),
1454 unsorted->size() - start_index_for_all_contributions);
1456 for (size_t i = 0; i < buffer.size(); ++i)
1457 (*unsorted)[i + start_index_for_all_contributions] = buffer[i];
1460 // Recursively walks the layer tree starting at the given node and computes all
1461 // the necessary transformations, clip rects, render surfaces, etc.
1462 template <typename LayerType>
1463 static void CalculateDrawPropertiesInternal(
1465 const SubtreeGlobals<LayerType>& globals,
1466 const DataForRecursion<LayerType>& data_from_ancestor,
1467 typename LayerType::RenderSurfaceListType* render_surface_layer_list,
1468 typename LayerType::LayerListType* layer_list,
1469 std::vector<AccumulatedSurfaceState<LayerType> >* accumulated_surface_state,
1470 int current_render_surface_layer_list_id) {
1471 // This function computes the new matrix transformations recursively for this
1472 // layer and all its descendants. It also computes the appropriate render
1474 // Some important points to remember:
1476 // 0. Here, transforms are notated in Matrix x Vector order, and in words we
1477 // describe what the transform does from left to right.
1479 // 1. In our terminology, the "layer origin" refers to the top-left corner of
1480 // a layer, and the positive Y-axis points downwards. This interpretation is
1481 // valid because the orthographic projection applied at draw time flips the Y
1482 // axis appropriately.
1484 // 2. The anchor point, when given as a PointF object, is specified in "unit
1485 // layer space", where the bounds of the layer map to [0, 1]. However, as a
1486 // Transform object, the transform to the anchor point is specified in "layer
1487 // space", where the bounds of the layer map to [bounds.width(),
1488 // bounds.height()].
1490 // 3. Definition of various transforms used:
1491 // M[parent] is the parent matrix, with respect to the nearest render
1492 // surface, passed down recursively.
1494 // M[root] is the full hierarchy, with respect to the root, passed down
1497 // Tr[origin] is the translation matrix from the parent's origin to
1498 // this layer's origin.
1500 // Tr[origin2anchor] is the translation from the layer's origin to its
1503 // Tr[origin2center] is the translation from the layer's origin to its
1506 // M[layer] is the layer's matrix (applied at the anchor point)
1508 // S[layer2content] is the ratio of a layer's content_bounds() to its
1511 // Some composite transforms can help in understanding the sequence of
1513 // composite_layer_transform = Tr[origin2anchor] * M[layer] *
1514 // Tr[origin2anchor].inverse()
1516 // 4. When a layer (or render surface) is drawn, it is drawn into a "target
1517 // render surface". Therefore the draw transform does not necessarily
1518 // transform from screen space to local layer space. Instead, the draw
1519 // transform is the transform between the "target render surface space" and
1520 // local layer space. Note that render surfaces, except for the root, also
1521 // draw themselves into a different target render surface, and so their draw
1522 // transform and origin transforms are also described with respect to the
1525 // Using these definitions, then:
1527 // The draw transform for the layer is:
1528 // M[draw] = M[parent] * Tr[origin] * composite_layer_transform *
1529 // S[layer2content] = M[parent] * Tr[layer->position() + anchor] *
1530 // M[layer] * Tr[anchor2origin] * S[layer2content]
1532 // Interpreting the math left-to-right, this transforms from the
1533 // layer's render surface to the origin of the layer in content space.
1535 // The screen space transform is:
1536 // M[screenspace] = M[root] * Tr[origin] * composite_layer_transform *
1538 // = M[root] * Tr[layer->position() + anchor] * M[layer]
1539 // * Tr[anchor2origin] * S[layer2content]
1541 // Interpreting the math left-to-right, this transforms from the root
1542 // render surface's content space to the origin of the layer in content
1545 // The transform hierarchy that is passed on to children (i.e. the child's
1546 // parent_matrix) is:
1547 // M[parent]_for_child = M[parent] * Tr[origin] *
1548 // composite_layer_transform
1549 // = M[parent] * Tr[layer->position() + anchor] *
1550 // M[layer] * Tr[anchor2origin]
1552 // and a similar matrix for the full hierarchy with respect to the
1555 // Finally, note that the final matrix used by the shader for the layer is P *
1556 // M[draw] * S . This final product is computed in drawTexturedQuad(), where:
1557 // P is the projection matrix
1558 // S is the scale adjustment (to scale up a canonical quad to the
1561 // When a render surface has a replica layer, that layer's transform is used
1562 // to draw a second copy of the surface. gfx::Transforms named here are
1563 // relative to the surface, unless they specify they are relative to the
1566 // We will denote a scale by device scale S[deviceScale]
1568 // The render surface draw transform to its target surface origin is:
1569 // M[surfaceDraw] = M[owningLayer->Draw]
1571 // The render surface origin transform to its the root (screen space) origin
1573 // M[surface2root] = M[owningLayer->screenspace] *
1574 // S[deviceScale].inverse()
1576 // The replica draw transform to its target surface origin is:
1577 // M[replicaDraw] = S[deviceScale] * M[surfaceDraw] *
1578 // Tr[replica->position() + replica->anchor()] * Tr[replica] *
1579 // Tr[origin2anchor].inverse() * S[contents_scale].inverse()
1581 // The replica draw transform to the root (screen space) origin is:
1582 // M[replica2root] = M[surface2root] * Tr[replica->position()] *
1583 // Tr[replica] * Tr[origin2anchor].inverse()
1586 // It makes no sense to have a non-unit page_scale_factor without specifying
1587 // which layer roots the subtree the scale is applied to.
1588 DCHECK(globals.page_scale_application_layer ||
1589 (globals.page_scale_factor == 1.f));
1591 DataForRecursion<LayerType> data_for_children;
1592 typename LayerType::RenderSurfaceType*
1593 nearest_occlusion_immune_ancestor_surface =
1594 data_from_ancestor.nearest_occlusion_immune_ancestor_surface;
1595 data_for_children.in_subtree_of_page_scale_application_layer =
1596 data_from_ancestor.in_subtree_of_page_scale_application_layer;
1597 data_for_children.subtree_can_use_lcd_text =
1598 data_from_ancestor.subtree_can_use_lcd_text;
1600 // Layers that are marked as hidden will hide themselves and their subtree.
1601 // Exception: Layers with copy requests, whether hidden or not, must be drawn
1602 // anyway. In this case, we will inform their subtree they are visible to get
1603 // the right results.
1604 const bool layer_is_visible =
1605 data_from_ancestor.subtree_is_visible_from_ancestor &&
1606 !layer->hide_layer_and_subtree();
1607 const bool layer_is_drawn = layer_is_visible || layer->HasCopyRequest();
1609 // The root layer cannot skip CalcDrawProperties.
1610 if (!IsRootLayer(layer) && SubtreeShouldBeSkipped(layer, layer_is_drawn)) {
1611 if (layer->render_surface())
1612 layer->ClearRenderSurfaceLayerList();
1616 // We need to circumvent the normal recursive flow of information for clip
1617 // children (they don't inherit their direct ancestor's clip information).
1618 // This is unfortunate, and would be unnecessary if we were to formally
1619 // separate the clipping hierarchy from the layer hierarchy.
1620 bool ancestor_clips_subtree = data_from_ancestor.ancestor_clips_subtree;
1621 gfx::Rect ancestor_clip_rect_in_target_space =
1622 data_from_ancestor.clip_rect_in_target_space;
1624 // Update our clipping state. If we have a clip parent we will need to pull
1625 // from the clip state cache rather than using the clip state passed from our
1626 // immediate ancestor.
1627 UpdateClipRectsForClipChild<LayerType>(
1628 layer, &ancestor_clip_rect_in_target_space, &ancestor_clips_subtree);
1630 // As this function proceeds, these are the properties for the current
1631 // layer that actually get computed. To avoid unnecessary copies
1632 // (particularly for matrices), we do computations directly on these values
1634 DrawProperties<LayerType>& layer_draw_properties = layer->draw_properties();
1636 gfx::Rect clip_rect_in_target_space;
1637 bool layer_or_ancestor_clips_descendants = false;
1639 // This value is cached on the stack so that we don't have to inverse-project
1640 // the surface's clip rect redundantly for every layer. This value is the
1641 // same as the target surface's clip rect, except that instead of being
1642 // described in the target surface's target's space, it is described in the
1643 // current render target's space.
1644 gfx::Rect clip_rect_of_target_surface_in_target_space;
1646 float accumulated_draw_opacity = layer->opacity();
1647 bool animating_opacity_to_target = layer->OpacityIsAnimating();
1648 bool animating_opacity_to_screen = animating_opacity_to_target;
1649 if (layer->parent()) {
1650 accumulated_draw_opacity *= layer->parent()->draw_opacity();
1651 animating_opacity_to_target |= layer->parent()->draw_opacity_is_animating();
1652 animating_opacity_to_screen |=
1653 layer->parent()->screen_space_opacity_is_animating();
1656 bool animating_transform_to_target = layer->TransformIsAnimating();
1657 bool animating_transform_to_screen = animating_transform_to_target;
1658 if (layer->parent()) {
1659 animating_transform_to_target |=
1660 layer->parent()->draw_transform_is_animating();
1661 animating_transform_to_screen |=
1662 layer->parent()->screen_space_transform_is_animating();
1665 gfx::Size bounds = layer->bounds();
1666 gfx::PointF anchor_point = layer->anchor_point();
1667 gfx::Vector2dF scroll_offset = GetEffectiveTotalScrollOffset(layer);
1668 gfx::PointF position = layer->position() - scroll_offset;
1670 gfx::Transform combined_transform = data_from_ancestor.parent_matrix;
1671 if (!layer->transform().IsIdentity()) {
1672 // LT = Tr[origin] * Tr[origin2anchor]
1673 combined_transform.Translate3d(
1674 position.x() + anchor_point.x() * bounds.width(),
1675 position.y() + anchor_point.y() * bounds.height(),
1676 layer->anchor_point_z());
1677 // LT = Tr[origin] * Tr[origin2anchor] * M[layer]
1678 combined_transform.PreconcatTransform(layer->transform());
1679 // LT = Tr[origin] * Tr[origin2anchor] * M[layer] * Tr[anchor2origin]
1680 combined_transform.Translate3d(-anchor_point.x() * bounds.width(),
1681 -anchor_point.y() * bounds.height(),
1682 -layer->anchor_point_z());
1684 combined_transform.Translate(position.x(), position.y());
1687 gfx::Vector2dF effective_scroll_delta = GetEffectiveScrollDelta(layer);
1688 if (!animating_transform_to_target && layer->scrollable() &&
1689 combined_transform.IsScaleOrTranslation()) {
1690 // Align the scrollable layer's position to screen space pixels to avoid
1691 // blurriness. To avoid side-effects, do this only if the transform is
1693 gfx::Vector2dF previous_translation = combined_transform.To2dTranslation();
1694 RoundTranslationComponents(&combined_transform);
1695 gfx::Vector2dF current_translation = combined_transform.To2dTranslation();
1697 // This rounding changes the scroll delta, and so must be included
1698 // in the scroll compensation matrix. The scaling converts from physical
1699 // coordinates to the scroll delta's CSS coordinates (using the parent
1700 // matrix instead of combined transform since scrolling is applied before
1701 // the layer's transform). For example, if we have a total scale factor of
1702 // 3.0, then 1 physical pixel is only 1/3 of a CSS pixel.
1703 gfx::Vector2dF parent_scales = MathUtil::ComputeTransform2dScaleComponents(
1704 data_from_ancestor.parent_matrix, 1.f);
1705 effective_scroll_delta -=
1706 gfx::ScaleVector2d(current_translation - previous_translation,
1707 1.f / parent_scales.x(),
1708 1.f / parent_scales.y());
1711 // Apply adjustment from position constraints.
1712 ApplyPositionAdjustment(layer, data_from_ancestor.fixed_container,
1713 data_from_ancestor.scroll_compensation_matrix, &combined_transform);
1715 bool combined_is_animating_scale = false;
1716 float combined_maximum_animation_contents_scale = 0.f;
1717 if (globals.can_adjust_raster_scales) {
1718 CalculateAnimationContentsScale(
1720 data_from_ancestor.ancestor_is_animating_scale,
1721 data_from_ancestor.maximum_animation_contents_scale,
1722 data_from_ancestor.parent_matrix,
1724 &combined_is_animating_scale,
1725 &combined_maximum_animation_contents_scale);
1727 data_for_children.ancestor_is_animating_scale = combined_is_animating_scale;
1728 data_for_children.maximum_animation_contents_scale =
1729 combined_maximum_animation_contents_scale;
1731 // Compute the 2d scale components of the transform hierarchy up to the target
1732 // surface. From there, we can decide on a contents scale for the layer.
1733 float layer_scale_factors = globals.device_scale_factor;
1734 if (data_from_ancestor.in_subtree_of_page_scale_application_layer)
1735 layer_scale_factors *= globals.page_scale_factor;
1736 gfx::Vector2dF combined_transform_scales =
1737 MathUtil::ComputeTransform2dScaleComponents(
1739 layer_scale_factors);
1741 float ideal_contents_scale =
1742 globals.can_adjust_raster_scales
1743 ? std::max(combined_transform_scales.x(),
1744 combined_transform_scales.y())
1745 : layer_scale_factors;
1746 UpdateLayerContentsScale(
1748 globals.can_adjust_raster_scales,
1749 ideal_contents_scale,
1750 globals.device_scale_factor,
1751 data_from_ancestor.in_subtree_of_page_scale_application_layer
1752 ? globals.page_scale_factor
1754 combined_maximum_animation_contents_scale,
1755 animating_transform_to_screen);
1757 // The draw_transform that gets computed below is effectively the layer's
1758 // draw_transform, unless the layer itself creates a render_surface. In that
1759 // case, the render_surface re-parents the transforms.
1760 layer_draw_properties.target_space_transform = combined_transform;
1761 // M[draw] = M[parent] * LT * S[layer2content]
1762 layer_draw_properties.target_space_transform.Scale(
1763 SK_MScalar1 / layer->contents_scale_x(),
1764 SK_MScalar1 / layer->contents_scale_y());
1766 // The layer's screen_space_transform represents the transform between root
1767 // layer's "screen space" and local content space.
1768 layer_draw_properties.screen_space_transform =
1769 data_from_ancestor.full_hierarchy_matrix;
1770 if (layer->should_flatten_transform())
1771 layer_draw_properties.screen_space_transform.FlattenTo2d();
1772 layer_draw_properties.screen_space_transform.PreconcatTransform
1773 (layer_draw_properties.target_space_transform);
1775 // Adjusting text AA method during animation may cause repaints, which in-turn
1777 bool adjust_text_aa =
1778 !animating_opacity_to_screen && !animating_transform_to_screen;
1779 // To avoid color fringing, LCD text should only be used on opaque layers with
1780 // just integral translation.
1781 bool layer_can_use_lcd_text =
1782 data_from_ancestor.subtree_can_use_lcd_text &&
1783 accumulated_draw_opacity == 1.f &&
1784 layer_draw_properties.target_space_transform.
1785 IsIdentityOrIntegerTranslation();
1787 gfx::RectF content_rect(layer->content_bounds());
1789 // full_hierarchy_matrix is the matrix that transforms objects between screen
1790 // space (except projection matrix) and the most recent RenderSurfaceImpl's
1791 // space. next_hierarchy_matrix will only change if this layer uses a new
1792 // RenderSurfaceImpl, otherwise remains the same.
1793 data_for_children.full_hierarchy_matrix =
1794 data_from_ancestor.full_hierarchy_matrix;
1796 // If the subtree will scale layer contents by the transform hierarchy, then
1797 // we should scale things into the render surface by the transform hierarchy
1798 // to take advantage of that.
1799 gfx::Vector2dF render_surface_sublayer_scale =
1800 globals.can_adjust_raster_scales
1801 ? combined_transform_scales
1802 : gfx::Vector2dF(layer_scale_factors, layer_scale_factors);
1804 bool render_to_separate_surface;
1805 if (globals.can_render_to_separate_surface) {
1806 render_to_separate_surface = SubtreeShouldRenderToSeparateSurface(
1807 layer, combined_transform.Preserves2dAxisAlignment());
1809 render_to_separate_surface = IsRootLayer(layer);
1811 if (render_to_separate_surface) {
1812 // Check back-face visibility before continuing with this surface and its
1814 if (!layer->double_sided() && TransformToParentIsKnown(layer) &&
1815 IsSurfaceBackFaceVisible(layer, combined_transform)) {
1816 layer->ClearRenderSurfaceLayerList();
1820 typename LayerType::RenderSurfaceType* render_surface =
1821 CreateOrReuseRenderSurface(layer);
1823 if (IsRootLayer(layer)) {
1824 // The root layer's render surface size is predetermined and so the root
1825 // layer can't directly support non-identity transforms. It should just
1826 // forward top-level transforms to the rest of the tree.
1827 data_for_children.parent_matrix = combined_transform;
1829 // The root surface does not contribute to any other surface, it has no
1831 layer->render_surface()->set_contributes_to_drawn_surface(false);
1833 // The owning layer's draw transform has a scale from content to layer
1834 // space which we do not want; so here we use the combined_transform
1835 // instead of the draw_transform. However, we do need to add a different
1836 // scale factor that accounts for the surface's pixel dimensions.
1837 combined_transform.Scale(1.0 / render_surface_sublayer_scale.x(),
1838 1.0 / render_surface_sublayer_scale.y());
1839 render_surface->SetDrawTransform(combined_transform);
1841 // The owning layer's transform was re-parented by the surface, so the
1842 // layer's new draw_transform only needs to scale the layer to surface
1844 layer_draw_properties.target_space_transform.MakeIdentity();
1845 layer_draw_properties.target_space_transform.
1846 Scale(render_surface_sublayer_scale.x() / layer->contents_scale_x(),
1847 render_surface_sublayer_scale.y() / layer->contents_scale_y());
1849 // Inside the surface's subtree, we scale everything to the owning layer's
1850 // scale. The sublayer matrix transforms layer rects into target surface
1851 // content space. Conceptually, all layers in the subtree inherit the
1852 // scale at the point of the render surface in the transform hierarchy,
1853 // but we apply it explicitly to the owning layer and the remainder of the
1854 // subtree independently.
1855 DCHECK(data_for_children.parent_matrix.IsIdentity());
1856 data_for_children.parent_matrix.Scale(render_surface_sublayer_scale.x(),
1857 render_surface_sublayer_scale.y());
1859 // Even if the |layer_is_drawn|, it only contributes to a drawn surface
1860 // when the |layer_is_visible|.
1861 layer->render_surface()->set_contributes_to_drawn_surface(
1865 // The opacity value is moved from the layer to its surface, so that the
1866 // entire subtree properly inherits opacity.
1867 render_surface->SetDrawOpacity(accumulated_draw_opacity);
1868 render_surface->SetDrawOpacityIsAnimating(animating_opacity_to_target);
1869 animating_opacity_to_target = false;
1870 layer_draw_properties.opacity = 1.f;
1871 layer_draw_properties.opacity_is_animating = animating_opacity_to_target;
1872 layer_draw_properties.screen_space_opacity_is_animating =
1873 animating_opacity_to_screen;
1875 render_surface->SetTargetSurfaceTransformsAreAnimating(
1876 animating_transform_to_target);
1877 render_surface->SetScreenSpaceTransformsAreAnimating(
1878 animating_transform_to_screen);
1879 animating_transform_to_target = false;
1880 layer_draw_properties.target_space_transform_is_animating =
1881 animating_transform_to_target;
1882 layer_draw_properties.screen_space_transform_is_animating =
1883 animating_transform_to_screen;
1885 // Update the aggregate hierarchy matrix to include the transform of the
1886 // newly created RenderSurfaceImpl.
1887 data_for_children.full_hierarchy_matrix.PreconcatTransform(
1888 render_surface->draw_transform());
1890 if (layer->mask_layer()) {
1891 DrawProperties<LayerType>& mask_layer_draw_properties =
1892 layer->mask_layer()->draw_properties();
1893 mask_layer_draw_properties.render_target = layer;
1894 mask_layer_draw_properties.visible_content_rect =
1895 gfx::Rect(layer->content_bounds());
1898 if (layer->replica_layer() && layer->replica_layer()->mask_layer()) {
1899 DrawProperties<LayerType>& replica_mask_draw_properties =
1900 layer->replica_layer()->mask_layer()->draw_properties();
1901 replica_mask_draw_properties.render_target = layer;
1902 replica_mask_draw_properties.visible_content_rect =
1903 gfx::Rect(layer->content_bounds());
1906 // Ignore occlusion from outside the surface when surface contents need to
1907 // be fully drawn. Layers with copy-request need to be complete.
1908 // We could be smarter about layers with replica and exclude regions
1909 // where both layer and the replica are occluded, but this seems like an
1910 // overkill. The same is true for layers with filters that move pixels.
1911 // TODO(senorblanco): make this smarter for the SkImageFilter case (check
1912 // for pixel-moving filters)
1913 if (layer->HasCopyRequest() ||
1914 layer->has_replica() ||
1915 layer->filters().HasReferenceFilter() ||
1916 layer->filters().HasFilterThatMovesPixels()) {
1917 nearest_occlusion_immune_ancestor_surface = render_surface;
1919 render_surface->SetNearestOcclusionImmuneAncestor(
1920 nearest_occlusion_immune_ancestor_surface);
1922 layer_or_ancestor_clips_descendants = false;
1923 bool subtree_is_clipped_by_surface_bounds = false;
1924 if (ancestor_clips_subtree) {
1925 // It may be the layer or the surface doing the clipping of the subtree,
1926 // but in either case, we'll be clipping to the projected clip rect of our
1928 gfx::Transform inverse_surface_draw_transform(
1929 gfx::Transform::kSkipInitialization);
1930 if (!render_surface->draw_transform().GetInverse(
1931 &inverse_surface_draw_transform)) {
1932 // TODO(shawnsingh): Either we need to handle uninvertible transforms
1933 // here, or DCHECK that the transform is invertible.
1936 gfx::Rect projected_surface_rect = MathUtil::ProjectEnclosingClippedRect(
1937 inverse_surface_draw_transform, ancestor_clip_rect_in_target_space);
1939 if (layer_draw_properties.num_unclipped_descendants > 0) {
1940 // If we have unclipped descendants, we cannot count on the render
1941 // surface's bounds clipping our subtree: the unclipped descendants
1942 // could cause us to expand our bounds. In this case, we must rely on
1943 // layer clipping for correctess. NB: since we can only encounter
1944 // translations between a clip child and its clip parent, clipping is
1945 // guaranteed to be exact in this case.
1946 layer_or_ancestor_clips_descendants = true;
1947 clip_rect_in_target_space = projected_surface_rect;
1949 // The new render_surface here will correctly clip the entire subtree.
1950 // So, we do not need to continue propagating the clipping state further
1951 // down the tree. This way, we can avoid transforming clip rects from
1952 // ancestor target surface space to current target surface space that
1953 // could cause more w < 0 headaches. The render surface clip rect is
1954 // expressed in the space where this surface draws, i.e. the same space
1955 // as clip_rect_from_ancestor_in_ancestor_target_space.
1956 render_surface->SetClipRect(ancestor_clip_rect_in_target_space);
1957 clip_rect_of_target_surface_in_target_space = projected_surface_rect;
1958 subtree_is_clipped_by_surface_bounds = true;
1962 DCHECK(layer->render_surface());
1963 DCHECK(!layer->parent() || layer->parent()->render_target() ==
1964 accumulated_surface_state->back().render_target);
1966 accumulated_surface_state->push_back(
1967 AccumulatedSurfaceState<LayerType>(layer));
1969 render_surface->SetIsClipped(subtree_is_clipped_by_surface_bounds);
1970 if (!subtree_is_clipped_by_surface_bounds) {
1971 render_surface->SetClipRect(gfx::Rect());
1972 clip_rect_of_target_surface_in_target_space =
1973 data_from_ancestor.clip_rect_of_target_surface_in_target_space;
1976 // If the new render surface is drawn translucent or with a non-integral
1977 // translation then the subtree that gets drawn on this render surface
1978 // cannot use LCD text.
1979 data_for_children.subtree_can_use_lcd_text = layer_can_use_lcd_text;
1981 render_surface_layer_list->push_back(layer);
1983 DCHECK(layer->parent());
1985 // Note: layer_draw_properties.target_space_transform is computed above,
1986 // before this if-else statement.
1987 layer_draw_properties.target_space_transform_is_animating =
1988 animating_transform_to_target;
1989 layer_draw_properties.screen_space_transform_is_animating =
1990 animating_transform_to_screen;
1991 layer_draw_properties.opacity = accumulated_draw_opacity;
1992 layer_draw_properties.opacity_is_animating = animating_opacity_to_target;
1993 layer_draw_properties.screen_space_opacity_is_animating =
1994 animating_opacity_to_screen;
1995 data_for_children.parent_matrix = combined_transform;
1997 layer->ClearRenderSurface();
1999 // Layers without render_surfaces directly inherit the ancestor's clip
2001 layer_or_ancestor_clips_descendants = ancestor_clips_subtree;
2002 if (ancestor_clips_subtree) {
2003 clip_rect_in_target_space =
2004 ancestor_clip_rect_in_target_space;
2007 // The surface's cached clip rect value propagates regardless of what
2008 // clipping goes on between layers here.
2009 clip_rect_of_target_surface_in_target_space =
2010 data_from_ancestor.clip_rect_of_target_surface_in_target_space;
2012 // Layers that are not their own render_target will render into the target
2013 // of their nearest ancestor.
2014 layer_draw_properties.render_target = layer->parent()->render_target();
2018 layer_draw_properties.can_use_lcd_text = layer_can_use_lcd_text;
2020 gfx::Rect rect_in_target_space = ToEnclosingRect(
2021 MathUtil::MapClippedRect(layer->draw_transform(), content_rect));
2023 if (LayerClipsSubtree(layer)) {
2024 layer_or_ancestor_clips_descendants = true;
2025 if (ancestor_clips_subtree && !layer->render_surface()) {
2026 // A layer without render surface shares the same target as its ancestor.
2027 clip_rect_in_target_space =
2028 ancestor_clip_rect_in_target_space;
2029 clip_rect_in_target_space.Intersect(rect_in_target_space);
2031 clip_rect_in_target_space = rect_in_target_space;
2035 // Tell the layer the rect that it's clipped by. In theory we could use a
2036 // tighter clip rect here (drawable_content_rect), but that actually does not
2037 // reduce how much would be drawn, and instead it would create unnecessary
2038 // changes to scissor state affecting GPU performance. Our clip information
2039 // is used in the recursion below, so we must set it beforehand.
2040 layer_draw_properties.is_clipped = layer_or_ancestor_clips_descendants;
2041 if (layer_or_ancestor_clips_descendants) {
2042 layer_draw_properties.clip_rect = clip_rect_in_target_space;
2044 // Initialize the clip rect to a safe value that will not clip the
2045 // layer, just in case clipping is still accidentally used.
2046 layer_draw_properties.clip_rect = rect_in_target_space;
2049 typename LayerType::LayerListType& descendants =
2050 (layer->render_surface() ? layer->render_surface()->layer_list()
2053 // Any layers that are appended after this point are in the layer's subtree
2054 // and should be included in the sorting process.
2055 size_t sorting_start_index = descendants.size();
2057 if (!LayerShouldBeSkipped(layer, layer_is_drawn)) {
2058 MarkLayerWithRenderSurfaceLayerListId(layer,
2059 current_render_surface_layer_list_id);
2060 descendants.push_back(layer);
2063 // Any layers that are appended after this point may need to be sorted if we
2064 // visit the children out of order.
2065 size_t render_surface_layer_list_child_sorting_start_index =
2066 render_surface_layer_list->size();
2067 size_t layer_list_child_sorting_start_index = descendants.size();
2069 if (!layer->children().empty()) {
2070 if (layer == globals.page_scale_application_layer) {
2071 data_for_children.parent_matrix.Scale(
2072 globals.page_scale_factor,
2073 globals.page_scale_factor);
2074 data_for_children.in_subtree_of_page_scale_application_layer = true;
2077 // Flatten to 2D if the layer doesn't preserve 3D.
2078 if (layer->should_flatten_transform())
2079 data_for_children.parent_matrix.FlattenTo2d();
2081 data_for_children.scroll_compensation_matrix =
2082 ComputeScrollCompensationMatrixForChildren(
2084 data_from_ancestor.parent_matrix,
2085 data_from_ancestor.scroll_compensation_matrix,
2086 effective_scroll_delta);
2087 data_for_children.fixed_container =
2088 layer->IsContainerForFixedPositionLayers() ?
2089 layer : data_from_ancestor.fixed_container;
2091 data_for_children.clip_rect_in_target_space = clip_rect_in_target_space;
2092 data_for_children.clip_rect_of_target_surface_in_target_space =
2093 clip_rect_of_target_surface_in_target_space;
2094 data_for_children.ancestor_clips_subtree =
2095 layer_or_ancestor_clips_descendants;
2096 data_for_children.nearest_occlusion_immune_ancestor_surface =
2097 nearest_occlusion_immune_ancestor_surface;
2098 data_for_children.subtree_is_visible_from_ancestor = layer_is_drawn;
2101 std::vector<LayerType*> sorted_children;
2102 bool child_order_changed = false;
2103 if (layer_draw_properties.has_child_with_a_scroll_parent)
2104 child_order_changed = SortChildrenForRecursion(&sorted_children, *layer);
2106 for (size_t i = 0; i < layer->children().size(); ++i) {
2107 // If one of layer's children has a scroll parent, then we may have to
2108 // visit the children out of order. The new order is stored in
2109 // sorted_children. Otherwise, we'll grab the child directly from the
2110 // layer's list of children.
2112 layer_draw_properties.has_child_with_a_scroll_parent
2113 ? sorted_children[i]
2114 : LayerTreeHostCommon::get_layer_as_raw_ptr(layer->children(), i);
2116 child->draw_properties().index_of_first_descendants_addition =
2118 child->draw_properties().index_of_first_render_surface_layer_list_addition =
2119 render_surface_layer_list->size();
2121 CalculateDrawPropertiesInternal<LayerType>(
2125 render_surface_layer_list,
2127 accumulated_surface_state,
2128 current_render_surface_layer_list_id);
2129 if (child->render_surface() &&
2130 !child->render_surface()->layer_list().empty() &&
2131 !child->render_surface()->content_rect().IsEmpty()) {
2132 // This child will contribute its render surface, which means
2133 // we need to mark just the mask layer (and replica mask layer)
2135 MarkMasksWithRenderSurfaceLayerListId(
2136 child, current_render_surface_layer_list_id);
2137 descendants.push_back(child);
2140 child->draw_properties().num_descendants_added =
2141 descendants.size() -
2142 child->draw_properties().index_of_first_descendants_addition;
2143 child->draw_properties().num_render_surfaces_added =
2144 render_surface_layer_list->size() -
2145 child->draw_properties()
2146 .index_of_first_render_surface_layer_list_addition;
2149 // Add the unsorted layer list contributions, if necessary.
2150 if (child_order_changed) {
2151 SortLayerListContributions(
2153 GetLayerListForSorting(render_surface_layer_list),
2154 render_surface_layer_list_child_sorting_start_index,
2155 &GetNewRenderSurfacesStartIndexAndCount<LayerType>);
2157 SortLayerListContributions(
2160 layer_list_child_sorting_start_index,
2161 &GetNewDescendantsStartIndexAndCount<LayerType>);
2164 // Compute the total drawable_content_rect for this subtree (the rect is in
2165 // target surface space).
2166 gfx::Rect local_drawable_content_rect_of_subtree =
2167 accumulated_surface_state->back().drawable_content_rect;
2168 if (layer->render_surface()) {
2169 DCHECK(accumulated_surface_state->back().render_target == layer);
2170 accumulated_surface_state->pop_back();
2173 if (layer->render_surface() && !IsRootLayer(layer) &&
2174 layer->render_surface()->layer_list().empty()) {
2175 RemoveSurfaceForEarlyExit(layer, render_surface_layer_list);
2179 // Compute the layer's drawable content rect (the rect is in target surface
2181 layer_draw_properties.drawable_content_rect = rect_in_target_space;
2182 if (layer_or_ancestor_clips_descendants) {
2183 layer_draw_properties.drawable_content_rect.Intersect(
2184 clip_rect_in_target_space);
2186 if (layer->DrawsContent()) {
2187 local_drawable_content_rect_of_subtree.Union(
2188 layer_draw_properties.drawable_content_rect);
2191 // Compute the layer's visible content rect (the rect is in content space).
2192 layer_draw_properties.visible_content_rect = CalculateVisibleContentRect(
2193 layer, clip_rect_of_target_surface_in_target_space, rect_in_target_space);
2195 // Compute the remaining properties for the render surface, if the layer has
2197 if (IsRootLayer(layer)) {
2198 // The root layer's surface's content_rect is always the entire viewport.
2199 DCHECK(layer->render_surface());
2200 layer->render_surface()->SetContentRect(
2201 ancestor_clip_rect_in_target_space);
2202 } else if (layer->render_surface()) {
2203 typename LayerType::RenderSurfaceType* render_surface =
2204 layer->render_surface();
2205 gfx::Rect clipped_content_rect = local_drawable_content_rect_of_subtree;
2207 // Don't clip if the layer is reflected as the reflection shouldn't be
2208 // clipped. If the layer is animating, then the surface's transform to
2209 // its target is not known on the main thread, and we should not use it
2211 if (!layer->replica_layer() && TransformToParentIsKnown(layer)) {
2212 // Note, it is correct to use data_from_ancestor.ancestor_clips_subtree
2213 // here, because we are looking at this layer's render_surface, not the
2215 if (render_surface->is_clipped() && !clipped_content_rect.IsEmpty()) {
2216 gfx::Rect surface_clip_rect = LayerTreeHostCommon::CalculateVisibleRect(
2217 render_surface->clip_rect(),
2218 clipped_content_rect,
2219 render_surface->draw_transform());
2220 clipped_content_rect.Intersect(surface_clip_rect);
2224 // The RenderSurfaceImpl backing texture cannot exceed the maximum supported
2226 clipped_content_rect.set_width(
2227 std::min(clipped_content_rect.width(), globals.max_texture_size));
2228 clipped_content_rect.set_height(
2229 std::min(clipped_content_rect.height(), globals.max_texture_size));
2231 if (clipped_content_rect.IsEmpty()) {
2232 RemoveSurfaceForEarlyExit(layer, render_surface_layer_list);
2236 // Layers having a non-default blend mode will blend with the content
2237 // inside its parent's render target. This render target should be
2238 // either root_for_isolated_group, or the root of the layer tree.
2239 // Otherwise, this layer will use an incomplete backdrop, limited to its
2240 // render target and the blending result will be incorrect.
2241 DCHECK(layer->uses_default_blend_mode() || IsRootLayer(layer) ||
2242 !layer->parent()->render_target() ||
2243 IsRootLayer(layer->parent()->render_target()) ||
2244 layer->parent()->render_target()->is_root_for_isolated_group());
2246 render_surface->SetContentRect(clipped_content_rect);
2248 // The owning layer's screen_space_transform has a scale from content to
2249 // layer space which we need to undo and replace with a scale from the
2250 // surface's subtree into layer space.
2251 gfx::Transform screen_space_transform = layer->screen_space_transform();
2252 screen_space_transform.Scale(
2253 layer->contents_scale_x() / render_surface_sublayer_scale.x(),
2254 layer->contents_scale_y() / render_surface_sublayer_scale.y());
2255 render_surface->SetScreenSpaceTransform(screen_space_transform);
2257 if (layer->replica_layer()) {
2258 gfx::Transform surface_origin_to_replica_origin_transform;
2259 surface_origin_to_replica_origin_transform.Scale(
2260 render_surface_sublayer_scale.x(), render_surface_sublayer_scale.y());
2261 surface_origin_to_replica_origin_transform.Translate(
2262 layer->replica_layer()->position().x() +
2263 layer->replica_layer()->anchor_point().x() * bounds.width(),
2264 layer->replica_layer()->position().y() +
2265 layer->replica_layer()->anchor_point().y() * bounds.height());
2266 surface_origin_to_replica_origin_transform.PreconcatTransform(
2267 layer->replica_layer()->transform());
2268 surface_origin_to_replica_origin_transform.Translate(
2269 -layer->replica_layer()->anchor_point().x() * bounds.width(),
2270 -layer->replica_layer()->anchor_point().y() * bounds.height());
2271 surface_origin_to_replica_origin_transform.Scale(
2272 1.0 / render_surface_sublayer_scale.x(),
2273 1.0 / render_surface_sublayer_scale.y());
2275 // Compute the replica's "originTransform" that maps from the replica's
2276 // origin space to the target surface origin space.
2277 gfx::Transform replica_origin_transform =
2278 layer->render_surface()->draw_transform() *
2279 surface_origin_to_replica_origin_transform;
2280 render_surface->SetReplicaDrawTransform(replica_origin_transform);
2282 // Compute the replica's "screen_space_transform" that maps from the
2283 // replica's origin space to the screen's origin space.
2284 gfx::Transform replica_screen_space_transform =
2285 layer->render_surface()->screen_space_transform() *
2286 surface_origin_to_replica_origin_transform;
2287 render_surface->SetReplicaScreenSpaceTransform(
2288 replica_screen_space_transform);
2292 SavePaintPropertiesLayer(layer);
2294 // If neither this layer nor any of its children were added, early out.
2295 if (sorting_start_index == descendants.size()) {
2296 DCHECK(!layer->render_surface() || IsRootLayer(layer));
2300 // If preserves-3d then sort all the descendants in 3D so that they can be
2301 // drawn from back to front. If the preserves-3d property is also set on the
2302 // parent then skip the sorting as the parent will sort all the descendants
2304 if (globals.layer_sorter && descendants.size() && layer->is_3d_sorted() &&
2305 !LayerIsInExisting3DRenderingContext(layer)) {
2306 SortLayers(descendants.begin() + sorting_start_index,
2308 globals.layer_sorter);
2311 UpdateAccumulatedSurfaceState<LayerType>(
2312 layer, local_drawable_content_rect_of_subtree, accumulated_surface_state);
2314 if (layer->HasContributingDelegatedRenderPasses()) {
2315 layer->render_target()->render_surface()->
2316 AddContributingDelegatedRenderPassLayer(layer);
2320 template <typename LayerType, typename RenderSurfaceLayerListType>
2321 static void ProcessCalcDrawPropsInputs(
2322 const LayerTreeHostCommon::CalcDrawPropsInputs<LayerType,
2323 RenderSurfaceLayerListType>&
2325 SubtreeGlobals<LayerType>* globals,
2326 DataForRecursion<LayerType>* data_for_recursion) {
2327 DCHECK(inputs.root_layer);
2328 DCHECK(IsRootLayer(inputs.root_layer));
2329 DCHECK(inputs.render_surface_layer_list);
2331 gfx::Transform identity_matrix;
2333 // The root layer's render_surface should receive the device viewport as the
2334 // initial clip rect.
2335 gfx::Rect device_viewport_rect(inputs.device_viewport_size);
2337 gfx::Vector2dF device_transform_scale_components =
2338 MathUtil::ComputeTransform2dScaleComponents(inputs.device_transform, 1.f);
2339 // Not handling the rare case of different x and y device scale.
2340 float device_transform_scale =
2341 std::max(device_transform_scale_components.x(),
2342 device_transform_scale_components.y());
2344 gfx::Transform scaled_device_transform = inputs.device_transform;
2345 scaled_device_transform.Scale(inputs.device_scale_factor,
2346 inputs.device_scale_factor);
2348 globals->layer_sorter = NULL;
2349 globals->max_texture_size = inputs.max_texture_size;
2350 globals->device_scale_factor =
2351 inputs.device_scale_factor * device_transform_scale;
2352 globals->page_scale_factor = inputs.page_scale_factor;
2353 globals->page_scale_application_layer = inputs.page_scale_application_layer;
2354 globals->can_render_to_separate_surface =
2355 inputs.can_render_to_separate_surface;
2356 globals->can_adjust_raster_scales = inputs.can_adjust_raster_scales;
2358 data_for_recursion->parent_matrix = scaled_device_transform;
2359 data_for_recursion->full_hierarchy_matrix = identity_matrix;
2360 data_for_recursion->scroll_compensation_matrix = identity_matrix;
2361 data_for_recursion->fixed_container = inputs.root_layer;
2362 data_for_recursion->clip_rect_in_target_space = device_viewport_rect;
2363 data_for_recursion->clip_rect_of_target_surface_in_target_space =
2364 device_viewport_rect;
2365 data_for_recursion->maximum_animation_contents_scale = 0.f;
2366 data_for_recursion->ancestor_is_animating_scale = false;
2367 data_for_recursion->ancestor_clips_subtree = true;
2368 data_for_recursion->nearest_occlusion_immune_ancestor_surface = NULL;
2369 data_for_recursion->in_subtree_of_page_scale_application_layer = false;
2370 data_for_recursion->subtree_can_use_lcd_text = inputs.can_use_lcd_text;
2371 data_for_recursion->subtree_is_visible_from_ancestor = true;
2374 void LayerTreeHostCommon::CalculateDrawProperties(
2375 CalcDrawPropsMainInputs* inputs) {
2376 LayerList dummy_layer_list;
2377 SubtreeGlobals<Layer> globals;
2378 DataForRecursion<Layer> data_for_recursion;
2379 ProcessCalcDrawPropsInputs(*inputs, &globals, &data_for_recursion);
2381 PreCalculateMetaInformationRecursiveData recursive_data;
2382 PreCalculateMetaInformation(inputs->root_layer, &recursive_data);
2383 std::vector<AccumulatedSurfaceState<Layer> > accumulated_surface_state;
2384 CalculateDrawPropertiesInternal<Layer>(
2388 inputs->render_surface_layer_list,
2390 &accumulated_surface_state,
2391 inputs->current_render_surface_layer_list_id);
2393 // The dummy layer list should not have been used.
2394 DCHECK_EQ(0u, dummy_layer_list.size());
2395 // A root layer render_surface should always exist after
2396 // CalculateDrawProperties.
2397 DCHECK(inputs->root_layer->render_surface());
2400 void LayerTreeHostCommon::CalculateDrawProperties(
2401 CalcDrawPropsImplInputs* inputs) {
2402 LayerImplList dummy_layer_list;
2403 SubtreeGlobals<LayerImpl> globals;
2404 DataForRecursion<LayerImpl> data_for_recursion;
2405 ProcessCalcDrawPropsInputs(*inputs, &globals, &data_for_recursion);
2407 LayerSorter layer_sorter;
2408 globals.layer_sorter = &layer_sorter;
2410 PreCalculateMetaInformationRecursiveData recursive_data;
2411 PreCalculateMetaInformation(inputs->root_layer, &recursive_data);
2412 std::vector<AccumulatedSurfaceState<LayerImpl> >
2413 accumulated_surface_state;
2414 CalculateDrawPropertiesInternal<LayerImpl>(
2418 inputs->render_surface_layer_list,
2420 &accumulated_surface_state,
2421 inputs->current_render_surface_layer_list_id);
2423 // The dummy layer list should not have been used.
2424 DCHECK_EQ(0u, dummy_layer_list.size());
2425 // A root layer render_surface should always exist after
2426 // CalculateDrawProperties.
2427 DCHECK(inputs->root_layer->render_surface());
2430 static bool PointHitsRect(
2431 const gfx::PointF& screen_space_point,
2432 const gfx::Transform& local_space_to_screen_space_transform,
2433 const gfx::RectF& local_space_rect) {
2434 // If the transform is not invertible, then assume that this point doesn't hit
2436 gfx::Transform inverse_local_space_to_screen_space(
2437 gfx::Transform::kSkipInitialization);
2438 if (!local_space_to_screen_space_transform.GetInverse(
2439 &inverse_local_space_to_screen_space))
2442 // Transform the hit test point from screen space to the local space of the
2444 bool clipped = false;
2445 gfx::PointF hit_test_point_in_local_space = MathUtil::ProjectPoint(
2446 inverse_local_space_to_screen_space, screen_space_point, &clipped);
2448 // If ProjectPoint could not project to a valid value, then we assume that
2449 // this point doesn't hit this rect.
2453 return local_space_rect.Contains(hit_test_point_in_local_space);
2456 static bool PointHitsRegion(const gfx::PointF& screen_space_point,
2457 const gfx::Transform& screen_space_transform,
2458 const Region& layer_space_region,
2459 float layer_content_scale_x,
2460 float layer_content_scale_y) {
2461 // If the transform is not invertible, then assume that this point doesn't hit
2463 gfx::Transform inverse_screen_space_transform(
2464 gfx::Transform::kSkipInitialization);
2465 if (!screen_space_transform.GetInverse(&inverse_screen_space_transform))
2468 // Transform the hit test point from screen space to the local space of the
2470 bool clipped = false;
2471 gfx::PointF hit_test_point_in_content_space = MathUtil::ProjectPoint(
2472 inverse_screen_space_transform, screen_space_point, &clipped);
2473 gfx::PointF hit_test_point_in_layer_space =
2474 gfx::ScalePoint(hit_test_point_in_content_space,
2475 1.f / layer_content_scale_x,
2476 1.f / layer_content_scale_y);
2478 // If ProjectPoint could not project to a valid value, then we assume that
2479 // this point doesn't hit this region.
2483 return layer_space_region.Contains(
2484 gfx::ToRoundedPoint(hit_test_point_in_layer_space));
2487 static bool PointIsClippedBySurfaceOrClipRect(
2488 const gfx::PointF& screen_space_point,
2490 LayerImpl* current_layer = layer;
2492 // Walk up the layer tree and hit-test any render_surfaces and any layer
2493 // clip rects that are active.
2494 while (current_layer) {
2495 if (current_layer->render_surface() &&
2498 current_layer->render_surface()->screen_space_transform(),
2499 current_layer->render_surface()->content_rect()))
2502 // Note that drawable content rects are actually in target surface space, so
2503 // the transform we have to provide is the target surface's
2504 // screen_space_transform.
2505 LayerImpl* render_target = current_layer->render_target();
2506 if (LayerClipsSubtree(current_layer) &&
2509 render_target->render_surface()->screen_space_transform(),
2510 current_layer->drawable_content_rect()))
2513 current_layer = current_layer->parent();
2516 // If we have finished walking all ancestors without having already exited,
2517 // then the point is not clipped by any ancestors.
2521 static bool PointHitsLayer(LayerImpl* layer,
2522 const gfx::PointF& screen_space_point) {
2523 gfx::RectF content_rect(layer->content_bounds());
2525 screen_space_point, layer->screen_space_transform(), content_rect))
2528 // At this point, we think the point does hit the layer, but we need to walk
2529 // up the parents to ensure that the layer was not clipped in such a way
2530 // that the hit point actually should not hit the layer.
2531 if (PointIsClippedBySurfaceOrClipRect(screen_space_point, layer))
2534 // Skip the HUD layer.
2535 if (layer == layer->layer_tree_impl()->hud_layer())
2541 LayerImpl* LayerTreeHostCommon::FindFirstScrollingLayerThatIsHitByPoint(
2542 const gfx::PointF& screen_space_point,
2543 const LayerImplList& render_surface_layer_list) {
2544 typedef LayerIterator<LayerImpl> LayerIteratorType;
2545 LayerIteratorType end = LayerIteratorType::End(&render_surface_layer_list);
2546 for (LayerIteratorType it =
2547 LayerIteratorType::Begin(&render_surface_layer_list);
2550 // We don't want to consider render_surfaces for hit testing.
2551 if (!it.represents_itself())
2554 LayerImpl* current_layer = (*it);
2555 if (!PointHitsLayer(current_layer, screen_space_point))
2558 if (current_layer->scrollable())
2559 return current_layer;
2565 LayerImpl* LayerTreeHostCommon::FindLayerThatIsHitByPoint(
2566 const gfx::PointF& screen_space_point,
2567 const LayerImplList& render_surface_layer_list) {
2568 LayerImpl* found_layer = NULL;
2570 typedef LayerIterator<LayerImpl> LayerIteratorType;
2571 LayerIteratorType end = LayerIteratorType::End(&render_surface_layer_list);
2572 for (LayerIteratorType
2573 it = LayerIteratorType::Begin(&render_surface_layer_list);
2576 // We don't want to consider render_surfaces for hit testing.
2577 if (!it.represents_itself())
2580 LayerImpl* current_layer = (*it);
2581 if (!PointHitsLayer(current_layer, screen_space_point))
2584 found_layer = current_layer;
2588 // This can potentially return NULL, which means the screen_space_point did
2589 // not successfully hit test any layers, not even the root layer.
2593 LayerImpl* LayerTreeHostCommon::FindLayerThatIsHitByPointInTouchHandlerRegion(
2594 const gfx::PointF& screen_space_point,
2595 const LayerImplList& render_surface_layer_list) {
2596 typedef LayerIterator<LayerImpl> LayerIteratorType;
2597 LayerIteratorType end = LayerIteratorType::End(&render_surface_layer_list);
2598 for (LayerIteratorType it =
2599 LayerIteratorType::Begin(&render_surface_layer_list);
2602 // We don't want to consider render_surfaces for hit testing.
2603 if (!it.represents_itself())
2606 LayerImpl* current_layer = (*it);
2607 if (!PointHitsLayer(current_layer, screen_space_point))
2610 if (LayerTreeHostCommon::LayerHasTouchEventHandlersAt(screen_space_point,
2612 return current_layer;
2614 // Note that we could stop searching if we hit a layer we know to be
2615 // opaque to hit-testing, but knowing that reliably is tricky (eg. due to
2616 // CSS pointer-events: none). Also blink has an optimization for the
2617 // common case of an entire document having handlers where it doesn't
2618 // report any rects for child layers (since it knows they can't exceed
2619 // the document bounds).
2624 bool LayerTreeHostCommon::LayerHasTouchEventHandlersAt(
2625 const gfx::PointF& screen_space_point,
2626 LayerImpl* layer_impl) {
2627 if (layer_impl->touch_event_handler_region().IsEmpty())
2630 if (!PointHitsRegion(screen_space_point,
2631 layer_impl->screen_space_transform(),
2632 layer_impl->touch_event_handler_region(),
2633 layer_impl->contents_scale_x(),
2634 layer_impl->contents_scale_y()))
2637 // At this point, we think the point does hit the touch event handler region
2638 // on the layer, but we need to walk up the parents to ensure that the layer
2639 // was not clipped in such a way that the hit point actually should not hit
2641 if (PointIsClippedBySurfaceOrClipRect(screen_space_point, layer_impl))