- add sources.
[platform/framework/web/crosswalk.git] / src / cc / trees / layer_tree_host_common.cc
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.
4
5 #include "cc/trees/layer_tree_host_common.h"
6
7 #include <algorithm>
8
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"
22
23 namespace cc {
24
25 ScrollAndScaleSet::ScrollAndScaleSet() {}
26
27 ScrollAndScaleSet::~ScrollAndScaleSet() {}
28
29 static void SortLayers(LayerList::iterator forst,
30                        LayerList::iterator end,
31                        void* layer_sorter) {
32   NOTREACHED();
33 }
34
35 static void SortLayers(LayerImplList::iterator first,
36                        LayerImplList::iterator end,
37                        LayerSorter* layer_sorter) {
38   DCHECK(layer_sorter);
39   TRACE_EVENT0("cc", "LayerTreeHostCommon::SortLayers");
40   layer_sorter->Sort(first, end);
41 }
42
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();
52   return scroll_delta;
53 }
54
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();
63   return offset;
64 }
65
66 inline gfx::Rect CalculateVisibleRectWithCachedLayerRect(
67     gfx::Rect target_surface_rect,
68     gfx::Rect layer_bound_rect,
69     gfx::Rect layer_rect_in_target_space,
70     const gfx::Transform& transform) {
71   if (layer_rect_in_target_space.IsEmpty())
72     return gfx::Rect();
73
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;
77
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);
83
84   if (minimal_surface_rect.IsEmpty())
85       return gfx::Rect();
86
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.
91
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
96     // visible.
97     return layer_bound_rect;
98   }
99
100   gfx::Rect layer_rect = gfx::ToEnclosingRect(MathUtil::ProjectClippedRect(
101       surface_to_layer, gfx::RectF(minimal_surface_rect)));
102   layer_rect.Intersect(layer_bound_rect);
103   return layer_rect;
104 }
105
106 gfx::Rect LayerTreeHostCommon::CalculateVisibleRect(
107     gfx::Rect target_surface_rect,
108     gfx::Rect layer_bound_rect,
109     const gfx::Transform& transform) {
110   gfx::Rect layer_in_surface_space =
111       MathUtil::MapClippedRect(transform, layer_bound_rect);
112   return CalculateVisibleRectWithCachedLayerRect(
113       target_surface_rect, layer_bound_rect, layer_in_surface_space, transform);
114 }
115
116 template <typename LayerType>
117 static LayerType* NextTargetSurface(LayerType* layer) {
118   return layer->parent() ? layer->parent()->render_target() : 0;
119 }
120
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);
135
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();
144   }
145
146   return translation;
147 }
148
149 enum TranslateRectDirection {
150   TranslateRectDirectionToAncestor,
151   TranslateRectDirectionToDescendant
152 };
153
154 template <typename LayerType>
155 static gfx::Rect TranslateRectToTargetSpace(const LayerType& ancestor_layer,
156                                             const LayerType& descendant_layer,
157                                             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()));
165 }
166
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();
178
179   if (!clip_parent)
180     clip_parent = layer->clip_parent();
181
182   if (!clip_parent || clip_parent == layer->parent())
183     return;
184
185   // The root layer is never a clip child.
186   DCHECK(layer->parent());
187
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();
191
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>(
200         *clip_parent,
201         *layer->parent(),
202         *clip_rect_in_parent_target_space,
203         TranslateRectDirectionToDescendant);
204   } else {
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
208     // parent).
209     *clip_rect_in_parent_target_space =
210         TranslateRectToTargetSpace<LayerType>(*layer->parent(),
211                                               *clip_parent,
212                                               *clip_rect_in_parent_target_space,
213                                               TranslateRectDirectionToAncestor);
214   }
215 }
216
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
221 // and its parent.
222 //
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) {}
228
229   // The accumulated drawable content rect for the surface associated with the
230   // given |render_target|.
231   gfx::Rect drawable_content_rect;
232
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
236   // descendants).
237   LayerType* render_target;
238 };
239
240 template <typename LayerType>
241 void UpdateAccumulatedSurfaceState(
242     LayerType* layer,
243     gfx::Rect drawable_content_rect,
244     std::vector<AccumulatedSurfaceState<LayerType> >*
245         accumulated_surface_state) {
246   if (IsRootLayer(layer))
247     return;
248
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();
259
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()) {
265     target_rect =
266         gfx::ToEnclosedRect(layer->render_surface()->DrawableContentRect());
267   }
268
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(),
276           *layer,
277           clip_rect,
278           TranslateRectDirectionToDescendant);
279     }
280     target_rect.Intersect(clip_rect);
281   }
282
283   // We must have at least one entry in the vector for the root.
284   DCHECK_LT(0ul, accumulated_surface_state->size());
285
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();
292
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);
298
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;
302       break;
303     }
304
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();
310
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());
314
315     target_rect = gfx::ToEnclosingRect(
316         MathUtil::MapClippedRect(current_draw_transform, target_rect));
317   }
318
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);
323 }
324
325 template <typename LayerType> static inline bool IsRootLayer(LayerType* layer) {
326   return !layer->parent();
327 }
328
329 template <typename LayerType>
330 static inline bool LayerIsInExisting3DRenderingContext(LayerType* layer) {
331   // According to current W3C spec on CSS transforms, a layer is part of an
332   // established 3d rendering context if its parent has transform-style of
333   // preserves-3d.
334   return layer->parent() && layer->parent()->preserves_3d();
335 }
336
337 template <typename LayerType>
338 static bool IsRootLayerOfNewRenderingContext(LayerType* layer) {
339   // According to current W3C spec on CSS transforms (Section 6.1), a layer is
340   // the beginning of 3d rendering context if its parent does not have
341   // transform-style: preserve-3d, but this layer itself does.
342   if (layer->parent())
343     return !layer->parent()->preserves_3d() && layer->preserves_3d();
344
345   return layer->preserves_3d();
346 }
347
348 template <typename LayerType>
349 static bool IsLayerBackFaceVisible(LayerType* layer) {
350   // The current W3C spec on CSS transforms says that backface visibility should
351   // be determined differently depending on whether the layer is in a "3d
352   // rendering context" or not. For Chromium code, we can determine whether we
353   // are in a 3d rendering context by checking if the parent preserves 3d.
354
355   if (LayerIsInExisting3DRenderingContext(layer))
356     return layer->draw_transform().IsBackFaceVisible();
357
358   // In this case, either the layer establishes a new 3d rendering context, or
359   // is not in a 3d rendering context at all.
360   return layer->transform().IsBackFaceVisible();
361 }
362
363 template <typename LayerType>
364 static bool IsSurfaceBackFaceVisible(LayerType* layer,
365                                      const gfx::Transform& draw_transform) {
366   if (LayerIsInExisting3DRenderingContext(layer))
367     return draw_transform.IsBackFaceVisible();
368
369   if (IsRootLayerOfNewRenderingContext(layer))
370     return layer->transform().IsBackFaceVisible();
371
372   // If the render_surface is not part of a new or existing rendering context,
373   // then the layers that contribute to this surface will decide back-face
374   // visibility for themselves.
375   return false;
376 }
377
378 template <typename LayerType>
379 static inline bool LayerClipsSubtree(LayerType* layer) {
380   return layer->masks_to_bounds() || layer->mask_layer();
381 }
382
383 template <typename LayerType>
384 static gfx::Rect CalculateVisibleContentRect(
385     LayerType* layer,
386     gfx::Rect clip_rect_of_target_surface_in_target_space,
387     gfx::Rect layer_rect_in_target_space) {
388   DCHECK(layer->render_target());
389
390   // Nothing is visible if the layer bounds are empty.
391   if (!layer->DrawsContent() || layer->content_bounds().IsEmpty() ||
392       layer->drawable_content_rect().IsEmpty())
393     return gfx::Rect();
394
395   // Compute visible bounds in target surface space.
396   gfx::Rect visible_rect_in_target_surface_space =
397       layer->drawable_content_rect();
398
399   if (!layer->render_target()->render_surface()->clip_rect().IsEmpty()) {
400     // The |layer| L has a target T which owns a surface Ts. The surface Ts
401     // has a target TsT.
402     //
403     // In this case the target surface Ts does clip the layer L that contributes
404     // to it. So, we have to convert the clip rect of Ts from the target space
405     // of Ts (that is the space of TsT), to the current render target's space
406     // (that is the space of T). This conversion is done outside this function
407     // so that it can be cached instead of computing it redundantly for every
408     // layer.
409     visible_rect_in_target_surface_space.Intersect(
410         clip_rect_of_target_surface_in_target_space);
411   }
412
413   if (visible_rect_in_target_surface_space.IsEmpty())
414     return gfx::Rect();
415
416   return CalculateVisibleRectWithCachedLayerRect(
417       visible_rect_in_target_surface_space,
418       gfx::Rect(layer->content_bounds()),
419       layer_rect_in_target_space,
420       layer->draw_transform());
421 }
422
423 static inline bool TransformToParentIsKnown(LayerImpl* layer) { return true; }
424
425 static inline bool TransformToParentIsKnown(Layer* layer) {
426   return !layer->TransformIsAnimating();
427 }
428
429 static inline bool TransformToScreenIsKnown(LayerImpl* layer) { return true; }
430
431 static inline bool TransformToScreenIsKnown(Layer* layer) {
432   return !layer->screen_space_transform_is_animating();
433 }
434
435 template <typename LayerType>
436 static bool LayerShouldBeSkipped(LayerType* layer,
437                                  bool layer_is_visible) {
438   // Layers can be skipped if any of these conditions are met.
439   //   - is not visible due to it or one of its ancestors being hidden.
440   //   - has empty bounds
441   //   - the layer is not double-sided, but its back face is visible.
442   //   - is transparent
443   //   - does not draw content and does not participate in hit testing.
444   //
445   // Some additional conditions need to be computed at a later point after the
446   // recursion is finished.
447   //   - the intersection of render_surface content and layer clip_rect is empty
448   //   - the visible_content_rect is empty
449   //
450   // Note, if the layer should not have been drawn due to being fully
451   // transparent, we would have skipped the entire subtree and never made it
452   // into this function, so it is safe to omit this check here.
453
454   if (!layer_is_visible)
455     return true;
456
457   if (layer->bounds().IsEmpty())
458     return true;
459
460   LayerType* backface_test_layer = layer;
461   if (layer->use_parent_backface_visibility()) {
462     DCHECK(layer->parent());
463     DCHECK(!layer->parent()->use_parent_backface_visibility());
464     backface_test_layer = layer->parent();
465   }
466
467   // The layer should not be drawn if (1) it is not double-sided and (2) the
468   // back of the layer is known to be facing the screen.
469   if (!backface_test_layer->double_sided() &&
470       TransformToScreenIsKnown(backface_test_layer) &&
471       IsLayerBackFaceVisible(backface_test_layer))
472     return true;
473
474   // The layer is visible to events.  If it's subject to hit testing, then
475   // we can't skip it.
476   bool can_accept_input = !layer->touch_event_handler_region().IsEmpty() ||
477       layer->have_wheel_event_handlers();
478   if (!layer->DrawsContent() && !can_accept_input)
479     return true;
480
481   return false;
482 }
483
484 static inline bool SubtreeShouldBeSkipped(LayerImpl* layer,
485                                           bool layer_is_visible) {
486   // When we need to do a readback/copy of a layer's output, we can not skip
487   // it or any of its ancestors.
488   if (layer->draw_properties().layer_or_descendant_has_copy_request)
489     return false;
490
491   // If the layer is not visible, then skip it and its subtree.
492   if (!layer_is_visible)
493     return true;
494
495   // If layer is on the pending tree and opacity is being animated then
496   // this subtree can't be skipped as we need to create, prioritize and
497   // include tiles for this layer when deciding if tree can be activated.
498   if (layer->layer_tree_impl()->IsPendingTree() && layer->OpacityIsAnimating())
499     return false;
500
501   // The opacity of a layer always applies to its children (either implicitly
502   // via a render surface or explicitly if the parent preserves 3D), so the
503   // entire subtree can be skipped if this layer is fully transparent.
504   // TODO(sad): Don't skip layers used for hit testing crbug.com/295295.
505   return !layer->opacity();
506 }
507
508 static inline bool SubtreeShouldBeSkipped(Layer* layer,
509                                           bool layer_is_visible) {
510   // When we need to do a readback/copy of a layer's output, we can not skip
511   // it or any of its ancestors.
512   if (layer->draw_properties().layer_or_descendant_has_copy_request)
513     return false;
514
515   // If the layer is not visible, then skip it and its subtree.
516   if (!layer_is_visible)
517     return true;
518
519   // If the opacity is being animated then the opacity on the main thread is
520   // unreliable (since the impl thread may be using a different opacity), so it
521   // should not be trusted.
522   // In particular, it should not cause the subtree to be skipped.
523   // Similarly, for layers that might animate opacity using an impl-only
524   // animation, their subtree should also not be skipped.
525   // TODO(sad): Don't skip layers used for hit testing crbug.com/295295.
526   return !layer->opacity() && !layer->OpacityIsAnimating() &&
527          !layer->OpacityCanAnimateOnImplThread();
528 }
529
530 static inline void SavePaintPropertiesLayer(LayerImpl* layer) {}
531
532 static inline void SavePaintPropertiesLayer(Layer* layer) {
533   layer->SavePaintProperties();
534
535   if (layer->mask_layer())
536     layer->mask_layer()->SavePaintProperties();
537   if (layer->replica_layer() && layer->replica_layer()->mask_layer())
538     layer->replica_layer()->mask_layer()->SavePaintProperties();
539 }
540
541 template <typename LayerType>
542 static bool SubtreeShouldRenderToSeparateSurface(
543     LayerType* layer,
544     bool axis_aligned_with_respect_to_parent) {
545   //
546   // A layer and its descendants should render onto a new RenderSurfaceImpl if
547   // any of these rules hold:
548   //
549
550   // The root layer owns a render surface, but it never acts as a contributing
551   // surface to another render target. Compositor features that are applied via
552   // a contributing surface can not be applied to the root layer. In order to
553   // use these effects, another child of the root would need to be introduced
554   // in order to act as a contributing surface to the root layer's surface.
555   bool is_root = IsRootLayer(layer);
556
557   // If the layer uses a mask.
558   if (layer->mask_layer()) {
559     DCHECK(!is_root);
560     return true;
561   }
562
563   // If the layer has a reflection.
564   if (layer->replica_layer()) {
565     DCHECK(!is_root);
566     return true;
567   }
568
569   // If the layer uses a CSS filter.
570   if (!layer->filters().IsEmpty() || !layer->background_filters().IsEmpty()) {
571     DCHECK(!is_root);
572     return true;
573   }
574
575   int num_descendants_that_draw_content =
576       layer->draw_properties().num_descendants_that_draw_content;
577
578   // If the layer flattens its subtree (i.e. the layer doesn't preserve-3d), but
579   // it is treated as a 3D object by its parent (i.e. parent does preserve-3d).
580   if (LayerIsInExisting3DRenderingContext(layer) && !layer->preserves_3d() &&
581       num_descendants_that_draw_content > 0) {
582     TRACE_EVENT_INSTANT0(
583         "cc",
584         "LayerTreeHostCommon::SubtreeShouldRenderToSeparateSurface flattening",
585         TRACE_EVENT_SCOPE_THREAD);
586     DCHECK(!is_root);
587     return true;
588   }
589
590   // If the layer clips its descendants but it is not axis-aligned with respect
591   // to its parent.
592   bool layer_clips_external_content =
593       LayerClipsSubtree(layer) || layer->HasDelegatedContent();
594   if (layer_clips_external_content && !axis_aligned_with_respect_to_parent &&
595       num_descendants_that_draw_content > 0) {
596     TRACE_EVENT_INSTANT0(
597         "cc",
598         "LayerTreeHostCommon::SubtreeShouldRenderToSeparateSurface clipping",
599         TRACE_EVENT_SCOPE_THREAD);
600     DCHECK(!is_root);
601     return true;
602   }
603
604   // If the layer has some translucency and does not have a preserves-3d
605   // transform style.  This condition only needs a render surface if two or more
606   // layers in the subtree overlap. But checking layer overlaps is unnecessarily
607   // costly so instead we conservatively create a surface whenever at least two
608   // layers draw content for this subtree.
609   bool at_least_two_layers_in_subtree_draw_content =
610       num_descendants_that_draw_content > 0 &&
611       (layer->DrawsContent() || num_descendants_that_draw_content > 1);
612
613   if (layer->opacity() != 1.f && !layer->preserves_3d() &&
614       at_least_two_layers_in_subtree_draw_content) {
615     TRACE_EVENT_INSTANT0(
616         "cc",
617         "LayerTreeHostCommon::SubtreeShouldRenderToSeparateSurface opacity",
618         TRACE_EVENT_SCOPE_THREAD);
619     DCHECK(!is_root);
620     return true;
621   }
622
623   // The root layer should always have a render_surface.
624   if (is_root)
625     return true;
626
627   //
628   // These are allowed on the root surface, as they don't require the surface to
629   // be used as a contributing surface in order to apply correctly.
630   //
631
632   // If we force it.
633   if (layer->force_render_surface())
634     return true;
635
636   // If we'll make a copy of the layer's contents.
637   if (layer->HasCopyRequest())
638     return true;
639
640   return false;
641 }
642
643 // This function returns a translation matrix that can be applied on a vector
644 // that's in the layer's target surface coordinate, while the position offset is
645 // specified in some ancestor layer's coordinate.
646 gfx::Transform ComputeSizeDeltaCompensation(
647     LayerImpl* layer,
648     LayerImpl* container,
649     gfx::Vector2dF position_offset) {
650   gfx::Transform result_transform;
651
652   // To apply a translate in the container's layer space,
653   // the following steps need to be done:
654   //     Step 1a. transform from target surface space to the container's target
655   //              surface space
656   //     Step 1b. transform from container's target surface space to the
657   //              container's layer space
658   //     Step 2. apply the compensation
659   //     Step 3. transform back to target surface space
660
661   gfx::Transform target_surface_space_to_container_layer_space;
662   // Calculate step 1a
663   LayerImpl* container_target_surface = container->render_target();
664   for (LayerImpl* current_target_surface = NextTargetSurface(layer);
665       current_target_surface &&
666           current_target_surface != container_target_surface;
667       current_target_surface = NextTargetSurface(current_target_surface)) {
668     // Note: Concat is used here to convert the result coordinate space from
669     //       current render surface to the next render surface.
670     target_surface_space_to_container_layer_space.ConcatTransform(
671         current_target_surface->render_surface()->draw_transform());
672   }
673   // Calculate step 1b
674   gfx::Transform container_layer_space_to_container_target_surface_space =
675       container->draw_transform();
676   container_layer_space_to_container_target_surface_space.Scale(
677       container->contents_scale_x(), container->contents_scale_y());
678
679   gfx::Transform container_target_surface_space_to_container_layer_space;
680   if (container_layer_space_to_container_target_surface_space.GetInverse(
681       &container_target_surface_space_to_container_layer_space)) {
682     // Note: Again, Concat is used to conver the result coordinate space from
683     //       the container render surface to the container layer.
684     target_surface_space_to_container_layer_space.ConcatTransform(
685         container_target_surface_space_to_container_layer_space);
686   }
687
688   // Apply step 3
689   gfx::Transform container_layer_space_to_target_surface_space;
690   if (target_surface_space_to_container_layer_space.GetInverse(
691           &container_layer_space_to_target_surface_space)) {
692     result_transform.PreconcatTransform(
693         container_layer_space_to_target_surface_space);
694   } else {
695     // TODO(shawnsingh): A non-invertible matrix could still make meaningful
696     // projection.  For example ScaleZ(0) is non-invertible but the layer is
697     // still visible.
698     return gfx::Transform();
699   }
700
701   // Apply step 2
702   result_transform.Translate(position_offset.x(), position_offset.y());
703
704   // Apply step 1
705   result_transform.PreconcatTransform(
706       target_surface_space_to_container_layer_space);
707
708   return result_transform;
709 }
710
711 void ApplyPositionAdjustment(
712     Layer* layer,
713     Layer* container,
714     const gfx::Transform& scroll_compensation,
715     gfx::Transform* combined_transform) {}
716 void ApplyPositionAdjustment(
717     LayerImpl* layer,
718     LayerImpl* container,
719     const gfx::Transform& scroll_compensation,
720     gfx::Transform* combined_transform) {
721   if (!layer->position_constraint().is_fixed_position())
722     return;
723
724   // Special case: this layer is a composited fixed-position layer; we need to
725   // explicitly compensate for all ancestors' nonzero scroll_deltas to keep
726   // this layer fixed correctly.
727   // Note carefully: this is Concat, not Preconcat
728   // (current_scroll_compensation * combined_transform).
729   combined_transform->ConcatTransform(scroll_compensation);
730
731   // For right-edge or bottom-edge anchored fixed position layers,
732   // the layer should relocate itself if the container changes its size.
733   bool fixed_to_right_edge =
734       layer->position_constraint().is_fixed_to_right_edge();
735   bool fixed_to_bottom_edge =
736       layer->position_constraint().is_fixed_to_bottom_edge();
737   gfx::Vector2dF position_offset = container->fixed_container_size_delta();
738   position_offset.set_x(fixed_to_right_edge ? position_offset.x() : 0);
739   position_offset.set_y(fixed_to_bottom_edge ? position_offset.y() : 0);
740   if (position_offset.IsZero())
741     return;
742
743   // Note: Again, this is Concat. The compensation matrix will be applied on
744   //       the vector in target surface space.
745   combined_transform->ConcatTransform(
746       ComputeSizeDeltaCompensation(layer, container, position_offset));
747 }
748
749 gfx::Transform ComputeScrollCompensationForThisLayer(
750     LayerImpl* scrolling_layer,
751     const gfx::Transform& parent_matrix,
752     gfx::Vector2dF scroll_delta) {
753   // For every layer that has non-zero scroll_delta, we have to compute a
754   // transform that can undo the scroll_delta translation. In particular, we
755   // want this matrix to premultiply a fixed-position layer's parent_matrix, so
756   // we design this transform in three steps as follows. The steps described
757   // here apply from right-to-left, so Step 1 would be the right-most matrix:
758   //
759   //     Step 1. transform from target surface space to the exact space where
760   //           scroll_delta is actually applied.
761   //           -- this is inverse of parent_matrix
762   //     Step 2. undo the scroll_delta
763   //           -- this is just a translation by scroll_delta.
764   //     Step 3. transform back to target surface space.
765   //           -- this transform is the parent_matrix
766   //
767   // These steps create a matrix that both start and end in target surface
768   // space. So this matrix can pre-multiply any fixed-position layer's
769   // draw_transform to undo the scroll_deltas -- as long as that fixed position
770   // layer is fixed onto the same render_target as this scrolling_layer.
771   //
772
773   gfx::Transform scroll_compensation_for_this_layer = parent_matrix;  // Step 3
774   scroll_compensation_for_this_layer.Translate(
775       scroll_delta.x(),
776       scroll_delta.y());  // Step 2
777
778   gfx::Transform inverse_parent_matrix(gfx::Transform::kSkipInitialization);
779   if (!parent_matrix.GetInverse(&inverse_parent_matrix)) {
780     // TODO(shawnsingh): Either we need to handle uninvertible transforms
781     // here, or DCHECK that the transform is invertible.
782   }
783   scroll_compensation_for_this_layer.PreconcatTransform(
784       inverse_parent_matrix);  // Step 1
785   return scroll_compensation_for_this_layer;
786 }
787
788 gfx::Transform ComputeScrollCompensationMatrixForChildren(
789     Layer* current_layer,
790     const gfx::Transform& current_parent_matrix,
791     const gfx::Transform& current_scroll_compensation,
792     gfx::Vector2dF scroll_delta) {
793   // The main thread (i.e. Layer) does not need to worry about scroll
794   // compensation.  So we can just return an identity matrix here.
795   return gfx::Transform();
796 }
797
798 gfx::Transform ComputeScrollCompensationMatrixForChildren(
799     LayerImpl* layer,
800     const gfx::Transform& parent_matrix,
801     const gfx::Transform& current_scroll_compensation_matrix,
802     gfx::Vector2dF scroll_delta) {
803   // "Total scroll compensation" is the transform needed to cancel out all
804   // scroll_delta translations that occurred since the nearest container layer,
805   // even if there are render_surfaces in-between.
806   //
807   // There are some edge cases to be aware of, that are not explicit in the
808   // code:
809   //  - A layer that is both a fixed-position and container should not be its
810   //  own container, instead, that means it is fixed to an ancestor, and is a
811   //  container for any fixed-position descendants.
812   //  - A layer that is a fixed-position container and has a render_surface
813   //  should behave the same as a container without a render_surface, the
814   //  render_surface is irrelevant in that case.
815   //  - A layer that does not have an explicit container is simply fixed to the
816   //  viewport.  (i.e. the root render_surface.)
817   //  - If the fixed-position layer has its own render_surface, then the
818   //  render_surface is the one who gets fixed.
819   //
820   // This function needs to be called AFTER layers create their own
821   // render_surfaces.
822   //
823
824   // Scroll compensation restarts from identity under two possible conditions:
825   //  - the current layer is a container for fixed-position descendants
826   //  - the current layer is fixed-position itself, so any fixed-position
827   //    descendants are positioned with respect to this layer. Thus, any
828   //    fixed position descendants only need to compensate for scrollDeltas
829   //    that occur below this layer.
830   bool current_layer_resets_scroll_compensation_for_descendants =
831       layer->IsContainerForFixedPositionLayers() ||
832       layer->position_constraint().is_fixed_position();
833
834   // Avoid the overheads (including stack allocation and matrix
835   // initialization/copy) if we know that the scroll compensation doesn't need
836   // to be reset or adjusted.
837   if (!current_layer_resets_scroll_compensation_for_descendants &&
838       scroll_delta.IsZero() && !layer->render_surface())
839     return current_scroll_compensation_matrix;
840
841   // Start as identity matrix.
842   gfx::Transform next_scroll_compensation_matrix;
843
844   // If this layer does not reset scroll compensation, then it inherits the
845   // existing scroll compensations.
846   if (!current_layer_resets_scroll_compensation_for_descendants)
847     next_scroll_compensation_matrix = current_scroll_compensation_matrix;
848
849   // If the current layer has a non-zero scroll_delta, then we should compute
850   // its local scroll compensation and accumulate it to the
851   // next_scroll_compensation_matrix.
852   if (!scroll_delta.IsZero()) {
853     gfx::Transform scroll_compensation_for_this_layer =
854         ComputeScrollCompensationForThisLayer(
855             layer, parent_matrix, scroll_delta);
856     next_scroll_compensation_matrix.PreconcatTransform(
857         scroll_compensation_for_this_layer);
858   }
859
860   // If the layer created its own render_surface, we have to adjust
861   // next_scroll_compensation_matrix.  The adjustment allows us to continue
862   // using the scroll compensation on the next surface.
863   //  Step 1 (right-most in the math): transform from the new surface to the
864   //  original ancestor surface
865   //  Step 2: apply the scroll compensation
866   //  Step 3: transform back to the new surface.
867   if (layer->render_surface() &&
868       !next_scroll_compensation_matrix.IsIdentity()) {
869     gfx::Transform inverse_surface_draw_transform(
870         gfx::Transform::kSkipInitialization);
871     if (!layer->render_surface()->draw_transform().GetInverse(
872             &inverse_surface_draw_transform)) {
873       // TODO(shawnsingh): Either we need to handle uninvertible transforms
874       // here, or DCHECK that the transform is invertible.
875     }
876     next_scroll_compensation_matrix =
877         inverse_surface_draw_transform * next_scroll_compensation_matrix *
878         layer->render_surface()->draw_transform();
879   }
880
881   return next_scroll_compensation_matrix;
882 }
883
884 template <typename LayerType>
885 static inline void CalculateContentsScale(LayerType* layer,
886                                           float contents_scale,
887                                           float device_scale_factor,
888                                           float page_scale_factor,
889                                           bool animating_transform_to_screen) {
890   layer->CalculateContentsScale(contents_scale,
891                                 device_scale_factor,
892                                 page_scale_factor,
893                                 animating_transform_to_screen,
894                                 &layer->draw_properties().contents_scale_x,
895                                 &layer->draw_properties().contents_scale_y,
896                                 &layer->draw_properties().content_bounds);
897
898   LayerType* mask_layer = layer->mask_layer();
899   if (mask_layer) {
900     mask_layer->CalculateContentsScale(
901         contents_scale,
902         device_scale_factor,
903         page_scale_factor,
904         animating_transform_to_screen,
905         &mask_layer->draw_properties().contents_scale_x,
906         &mask_layer->draw_properties().contents_scale_y,
907         &mask_layer->draw_properties().content_bounds);
908   }
909
910   LayerType* replica_mask_layer =
911       layer->replica_layer() ? layer->replica_layer()->mask_layer() : NULL;
912   if (replica_mask_layer) {
913     replica_mask_layer->CalculateContentsScale(
914         contents_scale,
915         device_scale_factor,
916         page_scale_factor,
917         animating_transform_to_screen,
918         &replica_mask_layer->draw_properties().contents_scale_x,
919         &replica_mask_layer->draw_properties().contents_scale_y,
920         &replica_mask_layer->draw_properties().content_bounds);
921   }
922 }
923
924 static inline void UpdateLayerContentsScale(
925     LayerImpl* layer,
926     bool can_adjust_raster_scale,
927     float ideal_contents_scale,
928     float device_scale_factor,
929     float page_scale_factor,
930     bool animating_transform_to_screen) {
931   CalculateContentsScale(layer,
932                          ideal_contents_scale,
933                          device_scale_factor,
934                          page_scale_factor,
935                          animating_transform_to_screen);
936 }
937
938 static inline void UpdateLayerContentsScale(
939     Layer* layer,
940     bool can_adjust_raster_scale,
941     float ideal_contents_scale,
942     float device_scale_factor,
943     float page_scale_factor,
944     bool animating_transform_to_screen) {
945   if (can_adjust_raster_scale) {
946     float ideal_raster_scale =
947         ideal_contents_scale / (device_scale_factor * page_scale_factor);
948
949     bool need_to_set_raster_scale = layer->raster_scale_is_unknown();
950
951     // If we've previously saved a raster_scale but the ideal changes, things
952     // are unpredictable and we should just use 1.
953     if (!need_to_set_raster_scale && layer->raster_scale() != 1.f &&
954         ideal_raster_scale != layer->raster_scale()) {
955       ideal_raster_scale = 1.f;
956       need_to_set_raster_scale = true;
957     }
958
959     if (need_to_set_raster_scale) {
960       bool use_and_save_ideal_scale =
961           ideal_raster_scale >= 1.f && !animating_transform_to_screen;
962       if (use_and_save_ideal_scale)
963         layer->set_raster_scale(ideal_raster_scale);
964     }
965   }
966
967   float raster_scale = 1.f;
968   if (!layer->raster_scale_is_unknown())
969     raster_scale = layer->raster_scale();
970
971
972   float contents_scale = raster_scale * device_scale_factor * page_scale_factor;
973   CalculateContentsScale(layer,
974                          contents_scale,
975                          device_scale_factor,
976                          page_scale_factor,
977                          animating_transform_to_screen);
978 }
979
980 static inline RenderSurface* CreateOrReuseRenderSurface(Layer* layer) {
981   // The render surface should always be new on the main thread, as the
982   // RenderSurfaceLayerList should be a new empty list when given to
983   // CalculateDrawProperties.
984   DCHECK(!layer->render_surface());
985   layer->CreateRenderSurface();
986   return layer->render_surface();
987 }
988
989 static inline RenderSurfaceImpl* CreateOrReuseRenderSurface(LayerImpl* layer) {
990   if (!layer->render_surface()) {
991     layer->CreateRenderSurface();
992     return layer->render_surface();
993   }
994
995   layer->render_surface()->ClearLayerLists();
996   return layer->render_surface();
997 }
998
999 template <typename LayerType>
1000 static inline void RemoveSurfaceForEarlyExit(
1001     LayerType* layer_to_remove,
1002     typename LayerType::RenderSurfaceListType* render_surface_layer_list) {
1003   DCHECK(layer_to_remove->render_surface());
1004   // Technically, we know that the layer we want to remove should be
1005   // at the back of the render_surface_layer_list. However, we have had
1006   // bugs before that added unnecessary layers here
1007   // (https://bugs.webkit.org/show_bug.cgi?id=74147), but that causes
1008   // things to crash. So here we proactively remove any additional
1009   // layers from the end of the list.
1010   while (render_surface_layer_list->back() != layer_to_remove) {
1011     render_surface_layer_list->back()->ClearRenderSurface();
1012     render_surface_layer_list->pop_back();
1013   }
1014   DCHECK_EQ(render_surface_layer_list->back(), layer_to_remove);
1015   render_surface_layer_list->pop_back();
1016   layer_to_remove->ClearRenderSurface();
1017 }
1018
1019 struct PreCalculateMetaInformationRecursiveData {
1020   bool layer_or_descendant_has_copy_request;
1021   int num_unclipped_descendants;
1022
1023   PreCalculateMetaInformationRecursiveData()
1024       : layer_or_descendant_has_copy_request(false),
1025         num_unclipped_descendants(0) {}
1026
1027   void Merge(const PreCalculateMetaInformationRecursiveData& data) {
1028     layer_or_descendant_has_copy_request |=
1029         data.layer_or_descendant_has_copy_request;
1030     num_unclipped_descendants +=
1031         data.num_unclipped_descendants;
1032   }
1033 };
1034
1035 // Recursively walks the layer tree to compute any information that is needed
1036 // before doing the main recursion.
1037 template <typename LayerType>
1038 static void PreCalculateMetaInformation(
1039     LayerType* layer,
1040     PreCalculateMetaInformationRecursiveData* recursive_data) {
1041   bool has_delegated_content = layer->HasDelegatedContent();
1042   int num_descendants_that_draw_content = 0;
1043
1044   if (has_delegated_content) {
1045     // Layers with delegated content need to be treated as if they have as
1046     // many children as the number of layers they own delegated quads for.
1047     // Since we don't know this number right now, we choose one that acts like
1048     // infinity for our purposes.
1049     num_descendants_that_draw_content = 1000;
1050   }
1051
1052   layer->draw_properties().sorted_for_recursion = false;
1053   layer->draw_properties().has_child_with_a_scroll_parent = false;
1054
1055   if (layer->clip_parent())
1056     recursive_data->num_unclipped_descendants++;
1057
1058   for (size_t i = 0; i < layer->children().size(); ++i) {
1059     LayerType* child_layer =
1060         LayerTreeHostCommon::get_child_as_raw_ptr(layer->children(), i);
1061
1062     PreCalculateMetaInformationRecursiveData data_for_child;
1063     PreCalculateMetaInformation(child_layer, &data_for_child);
1064
1065     num_descendants_that_draw_content += child_layer->DrawsContent() ? 1 : 0;
1066     num_descendants_that_draw_content +=
1067         child_layer->draw_properties().num_descendants_that_draw_content;
1068
1069     if (child_layer->scroll_parent())
1070       layer->draw_properties().has_child_with_a_scroll_parent = true;
1071     recursive_data->Merge(data_for_child);
1072   }
1073
1074   if (layer->clip_children()) {
1075     int num_clip_children = layer->clip_children()->size();
1076     DCHECK_GE(recursive_data->num_unclipped_descendants, num_clip_children);
1077     recursive_data->num_unclipped_descendants -= num_clip_children;
1078   }
1079
1080   if (layer->HasCopyRequest())
1081     recursive_data->layer_or_descendant_has_copy_request = true;
1082
1083   layer->draw_properties().num_descendants_that_draw_content =
1084       num_descendants_that_draw_content;
1085   layer->draw_properties().num_unclipped_descendants =
1086       recursive_data->num_unclipped_descendants;
1087   layer->draw_properties().layer_or_descendant_has_copy_request =
1088       recursive_data->layer_or_descendant_has_copy_request;
1089 }
1090
1091 static void RoundTranslationComponents(gfx::Transform* transform) {
1092   transform->matrix().set(0, 3, MathUtil::Round(transform->matrix().get(0, 3)));
1093   transform->matrix().set(1, 3, MathUtil::Round(transform->matrix().get(1, 3)));
1094 }
1095
1096 template <typename LayerType>
1097 struct SubtreeGlobals {
1098   LayerSorter* layer_sorter;
1099   int max_texture_size;
1100   float device_scale_factor;
1101   float page_scale_factor;
1102   const LayerType* page_scale_application_layer;
1103   bool can_adjust_raster_scales;
1104   bool can_render_to_separate_surface;
1105 };
1106
1107 template<typename LayerType>
1108 struct DataForRecursion {
1109   // The accumulated sequence of transforms a layer will use to determine its
1110   // own draw transform.
1111   gfx::Transform parent_matrix;
1112
1113   // The accumulated sequence of transforms a layer will use to determine its
1114   // own screen-space transform.
1115   gfx::Transform full_hierarchy_matrix;
1116
1117   // The transform that removes all scrolling that may have occurred between a
1118   // fixed-position layer and its container, so that the layer actually does
1119   // remain fixed.
1120   gfx::Transform scroll_compensation_matrix;
1121
1122   // The ancestor that would be the container for any fixed-position / sticky
1123   // layers.
1124   LayerType* fixed_container;
1125
1126   // This is the normal clip rect that is propagated from parent to child.
1127   gfx::Rect clip_rect_in_target_space;
1128
1129   // When the layer's children want to compute their visible content rect, they
1130   // want to know what their target surface's clip rect will be. BUT - they
1131   // want to know this clip rect represented in their own target space. This
1132   // requires inverse-projecting the surface's clip rect from the surface's
1133   // render target space down to the surface's own space. Instead of computing
1134   // this value redundantly for each child layer, it is computed only once
1135   // while dealing with the parent layer, and then this precomputed value is
1136   // passed down the recursion to the children that actually use it.
1137   gfx::Rect clip_rect_of_target_surface_in_target_space;
1138
1139   bool ancestor_clips_subtree;
1140   typename LayerType::RenderSurfaceType*
1141       nearest_ancestor_surface_that_moves_pixels;
1142   bool in_subtree_of_page_scale_application_layer;
1143   bool subtree_can_use_lcd_text;
1144   bool subtree_is_visible_from_ancestor;
1145 };
1146
1147 template <typename LayerType>
1148 static LayerType* GetChildContainingLayer(const LayerType& parent,
1149                                           LayerType* layer) {
1150   for (LayerType* ancestor = layer; ancestor; ancestor = ancestor->parent()) {
1151     if (ancestor->parent() == &parent)
1152       return ancestor;
1153   }
1154   NOTREACHED();
1155   return 0;
1156 }
1157
1158 template <typename LayerType>
1159 static void AddScrollParentChain(std::vector<LayerType*>* out,
1160                                  const LayerType& parent,
1161                                  LayerType* layer) {
1162   // At a high level, this function walks up the chain of scroll parents
1163   // recursively, and once we reach the end of the chain, we add the child
1164   // of |parent| containing each scroll ancestor as we unwind. The result is
1165   // an ordering of parent's children that ensures that scroll parents are
1166   // visited before their descendants.
1167   // Take for example this layer tree:
1168   //
1169   // + stacking_context
1170   //   + scroll_child (1)
1171   //   + scroll_parent_graphics_layer (*)
1172   //   | + scroll_parent_scrolling_layer
1173   //   |   + scroll_parent_scrolling_content_layer (2)
1174   //   + scroll_grandparent_graphics_layer (**)
1175   //     + scroll_grandparent_scrolling_layer
1176   //       + scroll_grandparent_scrolling_content_layer (3)
1177   //
1178   // The scroll child is (1), its scroll parent is (2) and its scroll
1179   // grandparent is (3). Note, this doesn't mean that (2)'s scroll parent is
1180   // (3), it means that (*)'s scroll parent is (3). We don't want our list to
1181   // look like [ (3), (2), (1) ], even though that does have the ancestor chain
1182   // in the right order. Instead, we want [ (**), (*), (1) ]. That is, only want
1183   // (1)'s siblings in the list, but we want them to appear in such an order
1184   // that the scroll ancestors get visited in the correct order.
1185   //
1186   // So our first task at this step of the recursion is to determine the layer
1187   // that we will potentionally add to the list. That is, the child of parent
1188   // containing |layer|.
1189   LayerType* child = GetChildContainingLayer(parent, layer);
1190   if (child->draw_properties().sorted_for_recursion)
1191     return;
1192
1193   if (LayerType* scroll_parent = child->scroll_parent())
1194     AddScrollParentChain(out, parent, scroll_parent);
1195
1196   out->push_back(child);
1197   child->draw_properties().sorted_for_recursion = true;
1198 }
1199
1200 template <typename LayerType>
1201 static bool SortChildrenForRecursion(std::vector<LayerType*>* out,
1202                                      const LayerType& parent) {
1203   out->reserve(parent.children().size());
1204   bool order_changed = false;
1205   for (size_t i = 0; i < parent.children().size(); ++i) {
1206     LayerType* current =
1207         LayerTreeHostCommon::get_child_as_raw_ptr(parent.children(), i);
1208
1209     if (current->draw_properties().sorted_for_recursion) {
1210       order_changed = true;
1211       continue;
1212     }
1213
1214     AddScrollParentChain(out, parent, current);
1215   }
1216
1217   DCHECK_EQ(parent.children().size(), out->size());
1218   return order_changed;
1219 }
1220
1221 template <typename LayerType>
1222 static void GetNewDescendantsStartIndexAndCount(LayerType* layer,
1223                                                 size_t* start_index,
1224                                                 size_t* count) {
1225   *start_index = layer->draw_properties().index_of_first_descendants_addition;
1226   *count = layer->draw_properties().num_descendants_added;
1227 }
1228
1229 template <typename LayerType>
1230 static void GetNewRenderSurfacesStartIndexAndCount(LayerType* layer,
1231                                                    size_t* start_index,
1232                                                    size_t* count) {
1233   *start_index = layer->draw_properties()
1234                      .index_of_first_render_surface_layer_list_addition;
1235   *count = layer->draw_properties().num_render_surfaces_added;
1236 }
1237
1238 template <typename LayerType,
1239           typename GetIndexAndCountType>
1240 static void SortLayerListContributions(
1241     const LayerType& parent,
1242     typename LayerType::RenderSurfaceListType* unsorted,
1243     size_t start_index_for_all_contributions,
1244     GetIndexAndCountType get_index_and_count) {
1245
1246   typename LayerType::LayerListType buffer;
1247   for (size_t i = 0; i < parent.children().size(); ++i) {
1248     LayerType* child =
1249         LayerTreeHostCommon::get_child_as_raw_ptr(parent.children(), i);
1250
1251     size_t start_index = 0;
1252     size_t count = 0;
1253     get_index_and_count(child, &start_index, &count);
1254     for (size_t j = start_index; j < start_index + count; ++j)
1255       buffer.push_back(unsorted->at(j));
1256   }
1257
1258   DCHECK_EQ(buffer.size(),
1259             unsorted->size() - start_index_for_all_contributions);
1260
1261   for (size_t i = 0; i < buffer.size(); ++i)
1262     (*unsorted)[i + start_index_for_all_contributions] = buffer[i];
1263 }
1264
1265 // Recursively walks the layer tree starting at the given node and computes all
1266 // the necessary transformations, clip rects, render surfaces, etc.
1267 template <typename LayerType>
1268 static void CalculateDrawPropertiesInternal(
1269     LayerType* layer,
1270     const SubtreeGlobals<LayerType>& globals,
1271     const DataForRecursion<LayerType>& data_from_ancestor,
1272     typename LayerType::RenderSurfaceListType* render_surface_layer_list,
1273     typename LayerType::RenderSurfaceListType* layer_list,
1274     std::vector<AccumulatedSurfaceState<LayerType> >*
1275         accumulated_surface_state) {
1276   // This function computes the new matrix transformations recursively for this
1277   // layer and all its descendants. It also computes the appropriate render
1278   // surfaces.
1279   // Some important points to remember:
1280   //
1281   // 0. Here, transforms are notated in Matrix x Vector order, and in words we
1282   // describe what the transform does from left to right.
1283   //
1284   // 1. In our terminology, the "layer origin" refers to the top-left corner of
1285   // a layer, and the positive Y-axis points downwards. This interpretation is
1286   // valid because the orthographic projection applied at draw time flips the Y
1287   // axis appropriately.
1288   //
1289   // 2. The anchor point, when given as a PointF object, is specified in "unit
1290   // layer space", where the bounds of the layer map to [0, 1]. However, as a
1291   // Transform object, the transform to the anchor point is specified in "layer
1292   // space", where the bounds of the layer map to [bounds.width(),
1293   // bounds.height()].
1294   //
1295   // 3. Definition of various transforms used:
1296   //        M[parent] is the parent matrix, with respect to the nearest render
1297   //        surface, passed down recursively.
1298   //
1299   //        M[root] is the full hierarchy, with respect to the root, passed down
1300   //        recursively.
1301   //
1302   //        Tr[origin] is the translation matrix from the parent's origin to
1303   //        this layer's origin.
1304   //
1305   //        Tr[origin2anchor] is the translation from the layer's origin to its
1306   //        anchor point
1307   //
1308   //        Tr[origin2center] is the translation from the layer's origin to its
1309   //        center
1310   //
1311   //        M[layer] is the layer's matrix (applied at the anchor point)
1312   //
1313   //        M[sublayer] is the layer's sublayer transform (also applied at the
1314   //        layer's anchor point)
1315   //
1316   //        S[layer2content] is the ratio of a layer's content_bounds() to its
1317   //        Bounds().
1318   //
1319   //    Some composite transforms can help in understanding the sequence of
1320   //    transforms:
1321   //        composite_layer_transform = Tr[origin2anchor] * M[layer] *
1322   //        Tr[origin2anchor].inverse()
1323   //
1324   //        composite_sublayer_transform = Tr[origin2anchor] * M[sublayer] *
1325   //        Tr[origin2anchor].inverse()
1326   //
1327   // 4. When a layer (or render surface) is drawn, it is drawn into a "target
1328   // render surface". Therefore the draw transform does not necessarily
1329   // transform from screen space to local layer space. Instead, the draw
1330   // transform is the transform between the "target render surface space" and
1331   // local layer space. Note that render surfaces, except for the root, also
1332   // draw themselves into a different target render surface, and so their draw
1333   // transform and origin transforms are also described with respect to the
1334   // target.
1335   //
1336   // Using these definitions, then:
1337   //
1338   // The draw transform for the layer is:
1339   //        M[draw] = M[parent] * Tr[origin] * composite_layer_transform *
1340   //            S[layer2content] = M[parent] * Tr[layer->position() + anchor] *
1341   //            M[layer] * Tr[anchor2origin] * S[layer2content]
1342   //
1343   //        Interpreting the math left-to-right, this transforms from the
1344   //        layer's render surface to the origin of the layer in content space.
1345   //
1346   // The screen space transform is:
1347   //        M[screenspace] = M[root] * Tr[origin] * composite_layer_transform *
1348   //            S[layer2content]
1349   //                       = M[root] * Tr[layer->position() + anchor] * M[layer]
1350   //                           * Tr[anchor2origin] * S[layer2content]
1351   //
1352   //        Interpreting the math left-to-right, this transforms from the root
1353   //        render surface's content space to the origin of the layer in content
1354   //        space.
1355   //
1356   // The transform hierarchy that is passed on to children (i.e. the child's
1357   // parent_matrix) is:
1358   //        M[parent]_for_child = M[parent] * Tr[origin] *
1359   //            composite_layer_transform * composite_sublayer_transform
1360   //                            = M[parent] * Tr[layer->position() + anchor] *
1361   //                              M[layer] * Tr[anchor2origin] *
1362   //                              composite_sublayer_transform
1363   //
1364   //        and a similar matrix for the full hierarchy with respect to the
1365   //        root.
1366   //
1367   // Finally, note that the final matrix used by the shader for the layer is P *
1368   // M[draw] * S . This final product is computed in drawTexturedQuad(), where:
1369   //        P is the projection matrix
1370   //        S is the scale adjustment (to scale up a canonical quad to the
1371   //            layer's size)
1372   //
1373   // When a render surface has a replica layer, that layer's transform is used
1374   // to draw a second copy of the surface.  gfx::Transforms named here are
1375   // relative to the surface, unless they specify they are relative to the
1376   // replica layer.
1377   //
1378   // We will denote a scale by device scale S[deviceScale]
1379   //
1380   // The render surface draw transform to its target surface origin is:
1381   //        M[surfaceDraw] = M[owningLayer->Draw]
1382   //
1383   // The render surface origin transform to its the root (screen space) origin
1384   // is:
1385   //        M[surface2root] =  M[owningLayer->screenspace] *
1386   //            S[deviceScale].inverse()
1387   //
1388   // The replica draw transform to its target surface origin is:
1389   //        M[replicaDraw] = S[deviceScale] * M[surfaceDraw] *
1390   //            Tr[replica->position() + replica->anchor()] * Tr[replica] *
1391   //            Tr[origin2anchor].inverse() * S[contents_scale].inverse()
1392   //
1393   // The replica draw transform to the root (screen space) origin is:
1394   //        M[replica2root] = M[surface2root] * Tr[replica->position()] *
1395   //            Tr[replica] * Tr[origin2anchor].inverse()
1396   //
1397
1398   // It makes no sense to have a non-unit page_scale_factor without specifying
1399   // which layer roots the subtree the scale is applied to.
1400   DCHECK(globals.page_scale_application_layer ||
1401          (globals.page_scale_factor == 1.f));
1402
1403   DataForRecursion<LayerType> data_for_children;
1404   typename LayerType::RenderSurfaceType*
1405       nearest_ancestor_surface_that_moves_pixels =
1406           data_from_ancestor.nearest_ancestor_surface_that_moves_pixels;
1407   data_for_children.in_subtree_of_page_scale_application_layer =
1408       data_from_ancestor.in_subtree_of_page_scale_application_layer;
1409   data_for_children.subtree_can_use_lcd_text =
1410       data_from_ancestor.subtree_can_use_lcd_text;
1411
1412   // Layers with a copy request are always visible, as well as un-hiding their
1413   // subtree. Otherise, layers that are marked as hidden will hide themselves
1414   // and their subtree.
1415   bool layer_is_visible =
1416       data_from_ancestor.subtree_is_visible_from_ancestor &&
1417       !layer->hide_layer_and_subtree();
1418   if (layer->HasCopyRequest())
1419     layer_is_visible = true;
1420
1421   // The root layer cannot skip CalcDrawProperties.
1422   if (!IsRootLayer(layer) && SubtreeShouldBeSkipped(layer, layer_is_visible)) {
1423     if (layer->render_surface())
1424       layer->ClearRenderSurface();
1425     return;
1426   }
1427
1428   // We need to circumvent the normal recursive flow of information for clip
1429   // children (they don't inherit their direct ancestor's clip information).
1430   // This is unfortunate, and would be unnecessary if we were to formally
1431   // separate the clipping hierarchy from the layer hierarchy.
1432   bool ancestor_clips_subtree = data_from_ancestor.ancestor_clips_subtree;
1433   gfx::Rect ancestor_clip_rect_in_target_space =
1434       data_from_ancestor.clip_rect_in_target_space;
1435
1436   // Update our clipping state. If we have a clip parent we will need to pull
1437   // from the clip state cache rather than using the clip state passed from our
1438   // immediate ancestor.
1439   UpdateClipRectsForClipChild<LayerType>(
1440       layer, &ancestor_clip_rect_in_target_space, &ancestor_clips_subtree);
1441
1442   // As this function proceeds, these are the properties for the current
1443   // layer that actually get computed. To avoid unnecessary copies
1444   // (particularly for matrices), we do computations directly on these values
1445   // when possible.
1446   DrawProperties<LayerType>& layer_draw_properties = layer->draw_properties();
1447
1448   gfx::Rect clip_rect_in_target_space;
1449   bool layer_or_ancestor_clips_descendants = false;
1450
1451   // This value is cached on the stack so that we don't have to inverse-project
1452   // the surface's clip rect redundantly for every layer. This value is the
1453   // same as the target surface's clip rect, except that instead of being
1454   // described in the target surface's target's space, it is described in the
1455   // current render target's space.
1456   gfx::Rect clip_rect_of_target_surface_in_target_space;
1457
1458   float accumulated_draw_opacity = layer->opacity();
1459   bool animating_opacity_to_target = layer->OpacityIsAnimating();
1460   bool animating_opacity_to_screen = animating_opacity_to_target;
1461   if (layer->parent()) {
1462     accumulated_draw_opacity *= layer->parent()->draw_opacity();
1463     animating_opacity_to_target |= layer->parent()->draw_opacity_is_animating();
1464     animating_opacity_to_screen |=
1465         layer->parent()->screen_space_opacity_is_animating();
1466   }
1467
1468   bool animating_transform_to_target = layer->TransformIsAnimating();
1469   bool animating_transform_to_screen = animating_transform_to_target;
1470   if (layer->parent()) {
1471     animating_transform_to_target |=
1472         layer->parent()->draw_transform_is_animating();
1473     animating_transform_to_screen |=
1474         layer->parent()->screen_space_transform_is_animating();
1475   }
1476
1477   gfx::Size bounds = layer->bounds();
1478   gfx::PointF anchor_point = layer->anchor_point();
1479   gfx::Vector2dF scroll_offset = GetEffectiveTotalScrollOffset(layer);
1480   gfx::PointF position = layer->position() - scroll_offset;
1481
1482   gfx::Transform combined_transform = data_from_ancestor.parent_matrix;
1483   if (!layer->transform().IsIdentity()) {
1484     // LT = Tr[origin] * Tr[origin2anchor]
1485     combined_transform.Translate3d(
1486         position.x() + anchor_point.x() * bounds.width(),
1487         position.y() + anchor_point.y() * bounds.height(),
1488         layer->anchor_point_z());
1489     // LT = Tr[origin] * Tr[origin2anchor] * M[layer]
1490     combined_transform.PreconcatTransform(layer->transform());
1491     // LT = Tr[origin] * Tr[origin2anchor] * M[layer] * Tr[anchor2origin]
1492     combined_transform.Translate3d(-anchor_point.x() * bounds.width(),
1493                                    -anchor_point.y() * bounds.height(),
1494                                    -layer->anchor_point_z());
1495   } else {
1496     combined_transform.Translate(position.x(), position.y());
1497   }
1498
1499   gfx::Vector2dF effective_scroll_delta = GetEffectiveScrollDelta(layer);
1500   if (!animating_transform_to_target && layer->scrollable() &&
1501       combined_transform.IsScaleOrTranslation()) {
1502     // Align the scrollable layer's position to screen space pixels to avoid
1503     // blurriness.  To avoid side-effects, do this only if the transform is
1504     // simple.
1505     gfx::Vector2dF previous_translation = combined_transform.To2dTranslation();
1506     RoundTranslationComponents(&combined_transform);
1507     gfx::Vector2dF current_translation = combined_transform.To2dTranslation();
1508
1509     // This rounding changes the scroll delta, and so must be included
1510     // in the scroll compensation matrix.
1511     effective_scroll_delta -= current_translation - previous_translation;
1512   }
1513
1514   // Apply adjustment from position constraints.
1515   ApplyPositionAdjustment(layer, data_from_ancestor.fixed_container,
1516       data_from_ancestor.scroll_compensation_matrix, &combined_transform);
1517
1518   // Compute the 2d scale components of the transform hierarchy up to the target
1519   // surface. From there, we can decide on a contents scale for the layer.
1520   float layer_scale_factors = globals.device_scale_factor;
1521   if (data_from_ancestor.in_subtree_of_page_scale_application_layer)
1522     layer_scale_factors *= globals.page_scale_factor;
1523   gfx::Vector2dF combined_transform_scales =
1524       MathUtil::ComputeTransform2dScaleComponents(
1525           combined_transform,
1526           layer_scale_factors);
1527
1528   float ideal_contents_scale =
1529       globals.can_adjust_raster_scales
1530       ? std::max(combined_transform_scales.x(),
1531                  combined_transform_scales.y())
1532       : layer_scale_factors;
1533   UpdateLayerContentsScale(
1534       layer,
1535       globals.can_adjust_raster_scales,
1536       ideal_contents_scale,
1537       globals.device_scale_factor,
1538       data_from_ancestor.in_subtree_of_page_scale_application_layer ?
1539           globals.page_scale_factor : 1.f,
1540       animating_transform_to_screen);
1541
1542   // The draw_transform that gets computed below is effectively the layer's
1543   // draw_transform, unless the layer itself creates a render_surface. In that
1544   // case, the render_surface re-parents the transforms.
1545   layer_draw_properties.target_space_transform = combined_transform;
1546   // M[draw] = M[parent] * LT * S[layer2content]
1547   layer_draw_properties.target_space_transform.Scale(
1548       SK_MScalar1 / layer->contents_scale_x(),
1549       SK_MScalar1 / layer->contents_scale_y());
1550
1551   // The layer's screen_space_transform represents the transform between root
1552   // layer's "screen space" and local content space.
1553   layer_draw_properties.screen_space_transform =
1554       data_from_ancestor.full_hierarchy_matrix;
1555   if (!layer->preserves_3d())
1556     layer_draw_properties.screen_space_transform.FlattenTo2d();
1557   layer_draw_properties.screen_space_transform.PreconcatTransform
1558       (layer_draw_properties.target_space_transform);
1559
1560   // Adjusting text AA method during animation may cause repaints, which in-turn
1561   // causes jank.
1562   bool adjust_text_aa =
1563       !animating_opacity_to_screen && !animating_transform_to_screen;
1564   // To avoid color fringing, LCD text should only be used on opaque layers with
1565   // just integral translation.
1566   bool layer_can_use_lcd_text =
1567       data_from_ancestor.subtree_can_use_lcd_text &&
1568       accumulated_draw_opacity == 1.f &&
1569       layer_draw_properties.target_space_transform.
1570           IsIdentityOrIntegerTranslation();
1571
1572   gfx::RectF content_rect(layer->content_bounds());
1573
1574   // full_hierarchy_matrix is the matrix that transforms objects between screen
1575   // space (except projection matrix) and the most recent RenderSurfaceImpl's
1576   // space.  next_hierarchy_matrix will only change if this layer uses a new
1577   // RenderSurfaceImpl, otherwise remains the same.
1578   data_for_children.full_hierarchy_matrix =
1579       data_from_ancestor.full_hierarchy_matrix;
1580
1581   // If the subtree will scale layer contents by the transform hierarchy, then
1582   // we should scale things into the render surface by the transform hierarchy
1583   // to take advantage of that.
1584   gfx::Vector2dF render_surface_sublayer_scale =
1585       globals.can_adjust_raster_scales
1586       ? combined_transform_scales
1587       : gfx::Vector2dF(layer_scale_factors, layer_scale_factors);
1588
1589   bool render_to_separate_surface;
1590   if (globals.can_render_to_separate_surface) {
1591     render_to_separate_surface = SubtreeShouldRenderToSeparateSurface(
1592           layer, combined_transform.Preserves2dAxisAlignment());
1593   } else {
1594     render_to_separate_surface = IsRootLayer(layer);
1595   }
1596   if (render_to_separate_surface) {
1597     // Check back-face visibility before continuing with this surface and its
1598     // subtree
1599     if (!layer->double_sided() && TransformToParentIsKnown(layer) &&
1600         IsSurfaceBackFaceVisible(layer, combined_transform)) {
1601       layer->ClearRenderSurface();
1602       return;
1603     }
1604
1605     typename LayerType::RenderSurfaceType* render_surface =
1606         CreateOrReuseRenderSurface(layer);
1607
1608     if (IsRootLayer(layer)) {
1609       // The root layer's render surface size is predetermined and so the root
1610       // layer can't directly support non-identity transforms.  It should just
1611       // forward top-level transforms to the rest of the tree.
1612       data_for_children.parent_matrix = combined_transform;
1613
1614       // The root surface does not contribute to any other surface, it has no
1615       // target.
1616       layer->render_surface()->set_contributes_to_drawn_surface(false);
1617     } else {
1618       // The owning layer's draw transform has a scale from content to layer
1619       // space which we do not want; so here we use the combined_transform
1620       // instead of the draw_transform. However, we do need to add a different
1621       // scale factor that accounts for the surface's pixel dimensions.
1622       combined_transform.Scale(1.0 / render_surface_sublayer_scale.x(),
1623                                1.0 / render_surface_sublayer_scale.y());
1624       render_surface->SetDrawTransform(combined_transform);
1625
1626       // The owning layer's transform was re-parented by the surface, so the
1627       // layer's new draw_transform only needs to scale the layer to surface
1628       // space.
1629       layer_draw_properties.target_space_transform.MakeIdentity();
1630       layer_draw_properties.target_space_transform.
1631           Scale(render_surface_sublayer_scale.x() / layer->contents_scale_x(),
1632                 render_surface_sublayer_scale.y() / layer->contents_scale_y());
1633
1634       // Inside the surface's subtree, we scale everything to the owning layer's
1635       // scale.  The sublayer matrix transforms layer rects into target surface
1636       // content space.  Conceptually, all layers in the subtree inherit the
1637       // scale at the point of the render surface in the transform hierarchy,
1638       // but we apply it explicitly to the owning layer and the remainder of the
1639       // subtree independently.
1640       DCHECK(data_for_children.parent_matrix.IsIdentity());
1641       data_for_children.parent_matrix.Scale(render_surface_sublayer_scale.x(),
1642                             render_surface_sublayer_scale.y());
1643
1644       layer->render_surface()->set_contributes_to_drawn_surface(
1645           data_from_ancestor.subtree_is_visible_from_ancestor &&
1646           layer_is_visible);
1647     }
1648
1649     // The opacity value is moved from the layer to its surface, so that the
1650     // entire subtree properly inherits opacity.
1651     render_surface->SetDrawOpacity(accumulated_draw_opacity);
1652     render_surface->SetDrawOpacityIsAnimating(animating_opacity_to_target);
1653     animating_opacity_to_target = false;
1654     layer_draw_properties.opacity = 1.f;
1655     layer_draw_properties.opacity_is_animating = animating_opacity_to_target;
1656     layer_draw_properties.screen_space_opacity_is_animating =
1657         animating_opacity_to_screen;
1658
1659     render_surface->SetTargetSurfaceTransformsAreAnimating(
1660         animating_transform_to_target);
1661     render_surface->SetScreenSpaceTransformsAreAnimating(
1662         animating_transform_to_screen);
1663     animating_transform_to_target = false;
1664     layer_draw_properties.target_space_transform_is_animating =
1665         animating_transform_to_target;
1666     layer_draw_properties.screen_space_transform_is_animating =
1667         animating_transform_to_screen;
1668
1669     // Update the aggregate hierarchy matrix to include the transform of the
1670     // newly created RenderSurfaceImpl.
1671     data_for_children.full_hierarchy_matrix.PreconcatTransform(
1672         render_surface->draw_transform());
1673
1674     if (layer->mask_layer()) {
1675       DrawProperties<LayerType>& mask_layer_draw_properties =
1676           layer->mask_layer()->draw_properties();
1677       mask_layer_draw_properties.render_target = layer;
1678       mask_layer_draw_properties.visible_content_rect =
1679           gfx::Rect(layer->content_bounds());
1680     }
1681
1682     if (layer->replica_layer() && layer->replica_layer()->mask_layer()) {
1683       DrawProperties<LayerType>& replica_mask_draw_properties =
1684           layer->replica_layer()->mask_layer()->draw_properties();
1685       replica_mask_draw_properties.render_target = layer;
1686       replica_mask_draw_properties.visible_content_rect =
1687           gfx::Rect(layer->content_bounds());
1688     }
1689
1690     // TODO(senorblanco): make this smarter for the SkImageFilter case (check
1691     // for pixel-moving filters)
1692     if (layer->filters().HasReferenceFilter() ||
1693         layer->filters().HasFilterThatMovesPixels())
1694       nearest_ancestor_surface_that_moves_pixels = render_surface;
1695
1696     render_surface->SetNearestAncestorThatMovesPixels(
1697         nearest_ancestor_surface_that_moves_pixels);
1698
1699     layer_or_ancestor_clips_descendants = false;
1700     bool subtree_is_clipped_by_surface_bounds = false;
1701     if (ancestor_clips_subtree) {
1702       // It may be the layer or the surface doing the clipping of the subtree,
1703       // but in either case, we'll be clipping to the projected clip rect of our
1704       // ancestor.
1705       gfx::Transform inverse_surface_draw_transform(
1706           gfx::Transform::kSkipInitialization);
1707       if (!render_surface->draw_transform().GetInverse(
1708               &inverse_surface_draw_transform)) {
1709         // TODO(shawnsingh): Either we need to handle uninvertible transforms
1710         // here, or DCHECK that the transform is invertible.
1711       }
1712
1713       gfx::Rect projected_surface_rect = gfx::ToEnclosingRect(
1714           MathUtil::ProjectClippedRect(inverse_surface_draw_transform,
1715                                        ancestor_clip_rect_in_target_space));
1716
1717       if (layer_draw_properties.num_unclipped_descendants > 0) {
1718         // If we have unclipped descendants, we cannot count on the render
1719         // surface's bounds clipping our subtree: the unclipped descendants
1720         // could cause us to expand our bounds. In this case, we must rely on
1721         // layer clipping for correctess. NB: since we can only encounter
1722         // translations between a clip child and its clip parent, clipping is
1723         // guaranteed to be exact in this case.
1724         layer_or_ancestor_clips_descendants = true;
1725         clip_rect_in_target_space = projected_surface_rect;
1726       } else {
1727         // The new render_surface here will correctly clip the entire subtree.
1728         // So, we do not need to continue propagating the clipping state further
1729         // down the tree. This way, we can avoid transforming clip rects from
1730         // ancestor target surface space to current target surface space that
1731         // could cause more w < 0 headaches. The render surface clip rect is
1732         // expressed in the space where this surface draws, i.e. the same space
1733         // as clip_rect_from_ancestor_in_ancestor_target_space.
1734         render_surface->SetClipRect(ancestor_clip_rect_in_target_space);
1735         clip_rect_of_target_surface_in_target_space = projected_surface_rect;
1736         subtree_is_clipped_by_surface_bounds = true;
1737       }
1738     }
1739
1740     DCHECK(layer->render_surface());
1741     DCHECK(!layer->parent() || layer->parent()->render_target() ==
1742            accumulated_surface_state->back().render_target);
1743
1744     accumulated_surface_state->push_back(
1745         AccumulatedSurfaceState<LayerType>(layer));
1746
1747     render_surface->SetIsClipped(subtree_is_clipped_by_surface_bounds);
1748     if (!subtree_is_clipped_by_surface_bounds) {
1749       render_surface->SetClipRect(gfx::Rect());
1750       clip_rect_of_target_surface_in_target_space =
1751           data_from_ancestor.clip_rect_of_target_surface_in_target_space;
1752     }
1753
1754     // If the new render surface is drawn translucent or with a non-integral
1755     // translation then the subtree that gets drawn on this render surface
1756     // cannot use LCD text.
1757     data_for_children.subtree_can_use_lcd_text = layer_can_use_lcd_text;
1758
1759     render_surface_layer_list->push_back(layer);
1760   } else {
1761     DCHECK(layer->parent());
1762
1763     // Note: layer_draw_properties.target_space_transform is computed above,
1764     // before this if-else statement.
1765     layer_draw_properties.target_space_transform_is_animating =
1766         animating_transform_to_target;
1767     layer_draw_properties.screen_space_transform_is_animating =
1768         animating_transform_to_screen;
1769     layer_draw_properties.opacity = accumulated_draw_opacity;
1770     layer_draw_properties.opacity_is_animating = animating_opacity_to_target;
1771     layer_draw_properties.screen_space_opacity_is_animating =
1772         animating_opacity_to_screen;
1773     data_for_children.parent_matrix = combined_transform;
1774
1775     layer->ClearRenderSurface();
1776
1777     // Layers without render_surfaces directly inherit the ancestor's clip
1778     // status.
1779     layer_or_ancestor_clips_descendants = ancestor_clips_subtree;
1780     if (ancestor_clips_subtree) {
1781       clip_rect_in_target_space =
1782           ancestor_clip_rect_in_target_space;
1783     }
1784
1785     // The surface's cached clip rect value propagates regardless of what
1786     // clipping goes on between layers here.
1787     clip_rect_of_target_surface_in_target_space =
1788         data_from_ancestor.clip_rect_of_target_surface_in_target_space;
1789
1790     // Layers that are not their own render_target will render into the target
1791     // of their nearest ancestor.
1792     layer_draw_properties.render_target = layer->parent()->render_target();
1793   }
1794
1795   // Mark whether a layer could be drawn directly to the back buffer, for
1796   // example when it could use LCD text even though it's in a non-contents
1797   // opaque layer.  This means that it can't be drawn to an intermediate
1798   // render target and also that no blending is applied to the layer as a whole
1799   // (meaning that its contents don't have to be pre-composited into a bitmap or
1800   // a render target).
1801   //
1802   // Ignoring animations is an optimization,
1803   // as it means that we're going to need some retained resources for this
1804   // layer in the near future even if its opacity is 1 now.
1805   layer_draw_properties.can_draw_directly_to_backbuffer =
1806       IsRootLayer(layer_draw_properties.render_target) &&
1807       layer->draw_properties().opacity == 1.f &&
1808       !animating_opacity_to_screen;
1809
1810   if (adjust_text_aa)
1811     layer_draw_properties.can_use_lcd_text = layer_can_use_lcd_text;
1812
1813   gfx::Rect rect_in_target_space = ToEnclosingRect(
1814       MathUtil::MapClippedRect(layer->draw_transform(), content_rect));
1815
1816   if (LayerClipsSubtree(layer)) {
1817     layer_or_ancestor_clips_descendants = true;
1818     if (ancestor_clips_subtree && !layer->render_surface()) {
1819       // A layer without render surface shares the same target as its ancestor.
1820       clip_rect_in_target_space =
1821           ancestor_clip_rect_in_target_space;
1822       clip_rect_in_target_space.Intersect(rect_in_target_space);
1823     } else {
1824       clip_rect_in_target_space = rect_in_target_space;
1825     }
1826   }
1827
1828   // Tell the layer the rect that it's clipped by. In theory we could use a
1829   // tighter clip rect here (drawable_content_rect), but that actually does not
1830   // reduce how much would be drawn, and instead it would create unnecessary
1831   // changes to scissor state affecting GPU performance. Our clip information
1832   // is used in the recursion below, so we must set it beforehand.
1833   layer_draw_properties.is_clipped = layer_or_ancestor_clips_descendants;
1834   if (layer_or_ancestor_clips_descendants) {
1835     layer_draw_properties.clip_rect = clip_rect_in_target_space;
1836   } else {
1837     // Initialize the clip rect to a safe value that will not clip the
1838     // layer, just in case clipping is still accidentally used.
1839     layer_draw_properties.clip_rect = rect_in_target_space;
1840   }
1841
1842   typename LayerType::RenderSurfaceListType& descendants =
1843       (layer->render_surface() ? layer->render_surface()->layer_list()
1844                                : *layer_list);
1845
1846   // Any layers that are appended after this point are in the layer's subtree
1847   // and should be included in the sorting process.
1848   size_t sorting_start_index = descendants.size();
1849
1850   if (!LayerShouldBeSkipped(layer, layer_is_visible))
1851     descendants.push_back(layer);
1852
1853   // Any layers that are appended after this point may need to be sorted if we
1854   // visit the children out of order.
1855   size_t render_surface_layer_list_child_sorting_start_index =
1856       render_surface_layer_list->size();
1857   size_t layer_list_child_sorting_start_index = descendants.size();
1858
1859   if (!layer->children().empty()) {
1860     if (layer == globals.page_scale_application_layer) {
1861       data_for_children.parent_matrix.Scale(
1862           globals.page_scale_factor,
1863           globals.page_scale_factor);
1864       data_for_children.in_subtree_of_page_scale_application_layer = true;
1865     }
1866
1867     // Flatten to 2D if the layer doesn't preserve 3D.
1868     if (!layer->preserves_3d())
1869       data_for_children.parent_matrix.FlattenTo2d();
1870
1871     // Apply the sublayer transform at the anchor point of the layer.
1872     if (!layer->sublayer_transform().IsIdentity()) {
1873       data_for_children.parent_matrix.Translate(
1874           layer->anchor_point().x() * bounds.width(),
1875           layer->anchor_point().y() * bounds.height());
1876       data_for_children.parent_matrix.PreconcatTransform(
1877           layer->sublayer_transform());
1878       data_for_children.parent_matrix.Translate(
1879           -layer->anchor_point().x() * bounds.width(),
1880           -layer->anchor_point().y() * bounds.height());
1881     }
1882
1883     data_for_children.scroll_compensation_matrix =
1884         ComputeScrollCompensationMatrixForChildren(
1885             layer,
1886             data_from_ancestor.parent_matrix,
1887             data_from_ancestor.scroll_compensation_matrix,
1888             effective_scroll_delta);
1889     data_for_children.fixed_container =
1890         layer->IsContainerForFixedPositionLayers() ?
1891             layer : data_from_ancestor.fixed_container;
1892
1893     data_for_children.clip_rect_in_target_space = clip_rect_in_target_space;
1894     data_for_children.clip_rect_of_target_surface_in_target_space =
1895         clip_rect_of_target_surface_in_target_space;
1896     data_for_children.ancestor_clips_subtree =
1897         layer_or_ancestor_clips_descendants;
1898     data_for_children.nearest_ancestor_surface_that_moves_pixels =
1899         nearest_ancestor_surface_that_moves_pixels;
1900     data_for_children.subtree_is_visible_from_ancestor = layer_is_visible;
1901   }
1902
1903   std::vector<LayerType*> sorted_children;
1904   bool child_order_changed = false;
1905   if (layer_draw_properties.has_child_with_a_scroll_parent)
1906     child_order_changed = SortChildrenForRecursion(&sorted_children, *layer);
1907
1908   for (size_t i = 0; i < layer->children().size(); ++i) {
1909     // If one of layer's children has a scroll parent, then we may have to
1910     // visit the children out of order. The new order is stored in
1911     // sorted_children. Otherwise, we'll grab the child directly from the
1912     // layer's list of children.
1913     LayerType* child =
1914         layer_draw_properties.has_child_with_a_scroll_parent
1915             ? sorted_children[i]
1916             : LayerTreeHostCommon::get_child_as_raw_ptr(layer->children(), i);
1917
1918     child->draw_properties().index_of_first_descendants_addition =
1919         descendants.size();
1920     child->draw_properties().index_of_first_render_surface_layer_list_addition =
1921         render_surface_layer_list->size();
1922
1923     CalculateDrawPropertiesInternal<LayerType>(child,
1924                                                globals,
1925                                                data_for_children,
1926                                                render_surface_layer_list,
1927                                                &descendants,
1928                                                accumulated_surface_state);
1929     if (child->render_surface() &&
1930         !child->render_surface()->content_rect().IsEmpty()) {
1931       descendants.push_back(child);
1932     }
1933
1934     child->draw_properties().num_descendants_added =
1935         descendants.size() -
1936         child->draw_properties().index_of_first_descendants_addition;
1937     child->draw_properties().num_render_surfaces_added =
1938         render_surface_layer_list->size() -
1939         child->draw_properties()
1940             .index_of_first_render_surface_layer_list_addition;
1941   }
1942
1943   // Add the unsorted layer list contributions, if necessary.
1944   if (child_order_changed) {
1945     SortLayerListContributions(
1946         *layer,
1947         render_surface_layer_list,
1948         render_surface_layer_list_child_sorting_start_index,
1949         &GetNewRenderSurfacesStartIndexAndCount<LayerType>);
1950
1951     SortLayerListContributions(
1952         *layer,
1953         &descendants,
1954         layer_list_child_sorting_start_index,
1955         &GetNewDescendantsStartIndexAndCount<LayerType>);
1956   }
1957
1958   // Compute the total drawable_content_rect for this subtree (the rect is in
1959   // target surface space).
1960   gfx::Rect local_drawable_content_rect_of_subtree =
1961       accumulated_surface_state->back().drawable_content_rect;
1962   if (layer->render_surface()) {
1963     DCHECK(accumulated_surface_state->back().render_target == layer);
1964     accumulated_surface_state->pop_back();
1965   }
1966
1967   if (layer->render_surface() && !IsRootLayer(layer) &&
1968       layer->render_surface()->layer_list().empty()) {
1969     RemoveSurfaceForEarlyExit(layer, render_surface_layer_list);
1970     return;
1971   }
1972
1973   if (layer->DrawsContent()) {
1974     gfx::Rect local_drawable_content_rect = rect_in_target_space;
1975     if (layer_or_ancestor_clips_descendants)
1976       local_drawable_content_rect.Intersect(clip_rect_in_target_space);
1977     local_drawable_content_rect_of_subtree.Union(local_drawable_content_rect);
1978   }
1979
1980   // Compute the layer's drawable content rect (the rect is in target surface
1981   // space).
1982   layer_draw_properties.drawable_content_rect = rect_in_target_space;
1983   if (layer_or_ancestor_clips_descendants) {
1984     layer_draw_properties.drawable_content_rect.
1985         Intersect(clip_rect_in_target_space);
1986   }
1987
1988   // Compute the layer's visible content rect (the rect is in content space).
1989   layer_draw_properties.visible_content_rect = CalculateVisibleContentRect(
1990       layer, clip_rect_of_target_surface_in_target_space, rect_in_target_space);
1991
1992   // Compute the remaining properties for the render surface, if the layer has
1993   // one.
1994   if (IsRootLayer(layer)) {
1995     // The root layer's surface's content_rect is always the entire viewport.
1996     DCHECK(layer->render_surface());
1997     layer->render_surface()->SetContentRect(
1998         ancestor_clip_rect_in_target_space);
1999   } else if (layer->render_surface()) {
2000     typename LayerType::RenderSurfaceType* render_surface =
2001         layer->render_surface();
2002     gfx::Rect clipped_content_rect = local_drawable_content_rect_of_subtree;
2003
2004     // Don't clip if the layer is reflected as the reflection shouldn't be
2005     // clipped. If the layer is animating, then the surface's transform to
2006     // its target is not known on the main thread, and we should not use it
2007     // to clip.
2008     if (!layer->replica_layer() && TransformToParentIsKnown(layer)) {
2009       // Note, it is correct to use data_from_ancestor.ancestor_clips_subtree
2010       // here, because we are looking at this layer's render_surface, not the
2011       // layer itself.
2012       if (render_surface->is_clipped() && !clipped_content_rect.IsEmpty()) {
2013         gfx::Rect surface_clip_rect = LayerTreeHostCommon::CalculateVisibleRect(
2014             render_surface->clip_rect(),
2015             clipped_content_rect,
2016             render_surface->draw_transform());
2017         clipped_content_rect.Intersect(surface_clip_rect);
2018       }
2019     }
2020
2021     // The RenderSurfaceImpl backing texture cannot exceed the maximum supported
2022     // texture size.
2023     clipped_content_rect.set_width(
2024         std::min(clipped_content_rect.width(), globals.max_texture_size));
2025     clipped_content_rect.set_height(
2026         std::min(clipped_content_rect.height(), globals.max_texture_size));
2027
2028     if (clipped_content_rect.IsEmpty()) {
2029       RemoveSurfaceForEarlyExit(layer, render_surface_layer_list);
2030       return;
2031     }
2032
2033     render_surface->SetContentRect(clipped_content_rect);
2034
2035     // The owning layer's screen_space_transform has a scale from content to
2036     // layer space which we need to undo and replace with a scale from the
2037     // surface's subtree into layer space.
2038     gfx::Transform screen_space_transform = layer->screen_space_transform();
2039     screen_space_transform.Scale(
2040         layer->contents_scale_x() / render_surface_sublayer_scale.x(),
2041         layer->contents_scale_y() / render_surface_sublayer_scale.y());
2042     render_surface->SetScreenSpaceTransform(screen_space_transform);
2043
2044     if (layer->replica_layer()) {
2045       gfx::Transform surface_origin_to_replica_origin_transform;
2046       surface_origin_to_replica_origin_transform.Scale(
2047           render_surface_sublayer_scale.x(), render_surface_sublayer_scale.y());
2048       surface_origin_to_replica_origin_transform.Translate(
2049           layer->replica_layer()->position().x() +
2050           layer->replica_layer()->anchor_point().x() * bounds.width(),
2051           layer->replica_layer()->position().y() +
2052           layer->replica_layer()->anchor_point().y() * bounds.height());
2053       surface_origin_to_replica_origin_transform.PreconcatTransform(
2054           layer->replica_layer()->transform());
2055       surface_origin_to_replica_origin_transform.Translate(
2056           -layer->replica_layer()->anchor_point().x() * bounds.width(),
2057           -layer->replica_layer()->anchor_point().y() * bounds.height());
2058       surface_origin_to_replica_origin_transform.Scale(
2059           1.0 / render_surface_sublayer_scale.x(),
2060           1.0 / render_surface_sublayer_scale.y());
2061
2062       // Compute the replica's "originTransform" that maps from the replica's
2063       // origin space to the target surface origin space.
2064       gfx::Transform replica_origin_transform =
2065           layer->render_surface()->draw_transform() *
2066           surface_origin_to_replica_origin_transform;
2067       render_surface->SetReplicaDrawTransform(replica_origin_transform);
2068
2069       // Compute the replica's "screen_space_transform" that maps from the
2070       // replica's origin space to the screen's origin space.
2071       gfx::Transform replica_screen_space_transform =
2072           layer->render_surface()->screen_space_transform() *
2073           surface_origin_to_replica_origin_transform;
2074       render_surface->SetReplicaScreenSpaceTransform(
2075           replica_screen_space_transform);
2076     }
2077   }
2078
2079   SavePaintPropertiesLayer(layer);
2080
2081   // If neither this layer nor any of its children were added, early out.
2082   if (sorting_start_index == descendants.size()) {
2083     DCHECK(!layer->render_surface() || IsRootLayer(layer));
2084     return;
2085   }
2086
2087   // If preserves-3d then sort all the descendants in 3D so that they can be
2088   // drawn from back to front. If the preserves-3d property is also set on the
2089   // parent then skip the sorting as the parent will sort all the descendants
2090   // anyway.
2091   if (globals.layer_sorter && descendants.size() && layer->preserves_3d() &&
2092       (!layer->parent() || !layer->parent()->preserves_3d())) {
2093     SortLayers(descendants.begin() + sorting_start_index,
2094                descendants.end(),
2095                globals.layer_sorter);
2096   }
2097
2098   UpdateAccumulatedSurfaceState<LayerType>(
2099       layer, local_drawable_content_rect_of_subtree, accumulated_surface_state);
2100
2101   if (layer->HasContributingDelegatedRenderPasses()) {
2102     layer->render_target()->render_surface()->
2103         AddContributingDelegatedRenderPassLayer(layer);
2104   }
2105 }
2106
2107 void LayerTreeHostCommon::CalculateDrawProperties(
2108     CalcDrawPropsMainInputs* inputs) {
2109   DCHECK(inputs->root_layer);
2110   DCHECK(IsRootLayer(inputs->root_layer));
2111   DCHECK(inputs->render_surface_layer_list);
2112   gfx::Transform identity_matrix;
2113   gfx::Transform scaled_device_transform = inputs->device_transform;
2114   scaled_device_transform.Scale(inputs->device_scale_factor,
2115                                 inputs->device_scale_factor);
2116   RenderSurfaceLayerList dummy_layer_list;
2117
2118   // The root layer's render_surface should receive the device viewport as the
2119   // initial clip rect.
2120   gfx::Rect device_viewport_rect(inputs->device_viewport_size);
2121
2122   SubtreeGlobals<Layer> globals;
2123   globals.layer_sorter = NULL;
2124   globals.max_texture_size = inputs->max_texture_size;
2125   globals.device_scale_factor = inputs->device_scale_factor;
2126   globals.page_scale_factor = inputs->page_scale_factor;
2127   globals.page_scale_application_layer = inputs->page_scale_application_layer;
2128   globals.can_render_to_separate_surface =
2129       inputs->can_render_to_separate_surface;
2130   globals.can_adjust_raster_scales = inputs->can_adjust_raster_scales;
2131
2132   DataForRecursion<Layer> data_for_recursion;
2133   data_for_recursion.parent_matrix = scaled_device_transform;
2134   data_for_recursion.full_hierarchy_matrix = identity_matrix;
2135   data_for_recursion.scroll_compensation_matrix = identity_matrix;
2136   data_for_recursion.fixed_container = inputs->root_layer;
2137   data_for_recursion.clip_rect_in_target_space = device_viewport_rect;
2138   data_for_recursion.clip_rect_of_target_surface_in_target_space =
2139       device_viewport_rect;
2140   data_for_recursion.ancestor_clips_subtree = true;
2141   data_for_recursion.nearest_ancestor_surface_that_moves_pixels = NULL;
2142   data_for_recursion.in_subtree_of_page_scale_application_layer = false;
2143   data_for_recursion.subtree_can_use_lcd_text = inputs->can_use_lcd_text;
2144   data_for_recursion.subtree_is_visible_from_ancestor = true;
2145
2146   PreCalculateMetaInformationRecursiveData recursive_data;
2147   PreCalculateMetaInformation(inputs->root_layer, &recursive_data);
2148   std::vector<AccumulatedSurfaceState<Layer> > accumulated_surface_state;
2149   CalculateDrawPropertiesInternal<Layer>(inputs->root_layer,
2150                                          globals,
2151                                          data_for_recursion,
2152                                          inputs->render_surface_layer_list,
2153                                          &dummy_layer_list,
2154                                          &accumulated_surface_state);
2155
2156   // The dummy layer list should not have been used.
2157   DCHECK_EQ(0u, dummy_layer_list.size());
2158   // A root layer render_surface should always exist after
2159   // CalculateDrawProperties.
2160   DCHECK(inputs->root_layer->render_surface());
2161 }
2162
2163 void LayerTreeHostCommon::CalculateDrawProperties(
2164     CalcDrawPropsImplInputs* inputs) {
2165   DCHECK(inputs->root_layer);
2166   DCHECK(IsRootLayer(inputs->root_layer));
2167   DCHECK(inputs->render_surface_layer_list);
2168
2169   gfx::Transform identity_matrix;
2170   gfx::Transform scaled_device_transform = inputs->device_transform;
2171   scaled_device_transform.Scale(inputs->device_scale_factor,
2172                                 inputs->device_scale_factor);
2173   LayerImplList dummy_layer_list;
2174   LayerSorter layer_sorter;
2175
2176   // The root layer's render_surface should receive the device viewport as the
2177   // initial clip rect.
2178   gfx::Rect device_viewport_rect(inputs->device_viewport_size);
2179
2180   SubtreeGlobals<LayerImpl> globals;
2181   globals.layer_sorter = &layer_sorter;
2182   globals.max_texture_size = inputs->max_texture_size;
2183   globals.device_scale_factor = inputs->device_scale_factor;
2184   globals.page_scale_factor = inputs->page_scale_factor;
2185   globals.page_scale_application_layer = inputs->page_scale_application_layer;
2186   globals.can_render_to_separate_surface =
2187       inputs->can_render_to_separate_surface;
2188   globals.can_adjust_raster_scales = inputs->can_adjust_raster_scales;
2189
2190   DataForRecursion<LayerImpl> data_for_recursion;
2191   data_for_recursion.parent_matrix = scaled_device_transform;
2192   data_for_recursion.full_hierarchy_matrix = identity_matrix;
2193   data_for_recursion.scroll_compensation_matrix = identity_matrix;
2194   data_for_recursion.fixed_container = inputs->root_layer;
2195   data_for_recursion.clip_rect_in_target_space = device_viewport_rect;
2196   data_for_recursion.clip_rect_of_target_surface_in_target_space =
2197       device_viewport_rect;
2198   data_for_recursion.ancestor_clips_subtree = true;
2199   data_for_recursion.nearest_ancestor_surface_that_moves_pixels = NULL;
2200   data_for_recursion.in_subtree_of_page_scale_application_layer = false;
2201   data_for_recursion.subtree_can_use_lcd_text = inputs->can_use_lcd_text;
2202   data_for_recursion.subtree_is_visible_from_ancestor = true;
2203
2204   PreCalculateMetaInformationRecursiveData recursive_data;
2205   PreCalculateMetaInformation(inputs->root_layer, &recursive_data);
2206   std::vector<AccumulatedSurfaceState<LayerImpl> >
2207       accumulated_surface_state;
2208   CalculateDrawPropertiesInternal<LayerImpl>(inputs->root_layer,
2209                                              globals,
2210                                              data_for_recursion,
2211                                              inputs->render_surface_layer_list,
2212                                              &dummy_layer_list,
2213                                              &accumulated_surface_state);
2214
2215   // The dummy layer list should not have been used.
2216   DCHECK_EQ(0u, dummy_layer_list.size());
2217   // A root layer render_surface should always exist after
2218   // CalculateDrawProperties.
2219   DCHECK(inputs->root_layer->render_surface());
2220 }
2221
2222 static bool PointHitsRect(
2223     gfx::PointF screen_space_point,
2224     const gfx::Transform& local_space_to_screen_space_transform,
2225     gfx::RectF local_space_rect) {
2226   // If the transform is not invertible, then assume that this point doesn't hit
2227   // this rect.
2228   gfx::Transform inverse_local_space_to_screen_space(
2229       gfx::Transform::kSkipInitialization);
2230   if (!local_space_to_screen_space_transform.GetInverse(
2231           &inverse_local_space_to_screen_space))
2232     return false;
2233
2234   // Transform the hit test point from screen space to the local space of the
2235   // given rect.
2236   bool clipped = false;
2237   gfx::PointF hit_test_point_in_local_space = MathUtil::ProjectPoint(
2238       inverse_local_space_to_screen_space, screen_space_point, &clipped);
2239
2240   // If ProjectPoint could not project to a valid value, then we assume that
2241   // this point doesn't hit this rect.
2242   if (clipped)
2243     return false;
2244
2245   return local_space_rect.Contains(hit_test_point_in_local_space);
2246 }
2247
2248 static bool PointHitsRegion(gfx::PointF screen_space_point,
2249                             const gfx::Transform& screen_space_transform,
2250                             const Region& layer_space_region,
2251                             float layer_content_scale_x,
2252                             float layer_content_scale_y) {
2253   // If the transform is not invertible, then assume that this point doesn't hit
2254   // this region.
2255   gfx::Transform inverse_screen_space_transform(
2256       gfx::Transform::kSkipInitialization);
2257   if (!screen_space_transform.GetInverse(&inverse_screen_space_transform))
2258     return false;
2259
2260   // Transform the hit test point from screen space to the local space of the
2261   // given region.
2262   bool clipped = false;
2263   gfx::PointF hit_test_point_in_content_space = MathUtil::ProjectPoint(
2264       inverse_screen_space_transform, screen_space_point, &clipped);
2265   gfx::PointF hit_test_point_in_layer_space =
2266       gfx::ScalePoint(hit_test_point_in_content_space,
2267                       1.f / layer_content_scale_x,
2268                       1.f / layer_content_scale_y);
2269
2270   // If ProjectPoint could not project to a valid value, then we assume that
2271   // this point doesn't hit this region.
2272   if (clipped)
2273     return false;
2274
2275   return layer_space_region.Contains(
2276       gfx::ToRoundedPoint(hit_test_point_in_layer_space));
2277 }
2278
2279 static bool PointIsClippedBySurfaceOrClipRect(gfx::PointF screen_space_point,
2280                                               LayerImpl* layer) {
2281   LayerImpl* current_layer = layer;
2282
2283   // Walk up the layer tree and hit-test any render_surfaces and any layer
2284   // clip rects that are active.
2285   while (current_layer) {
2286     if (current_layer->render_surface() &&
2287         !PointHitsRect(
2288             screen_space_point,
2289             current_layer->render_surface()->screen_space_transform(),
2290             current_layer->render_surface()->content_rect()))
2291       return true;
2292
2293     // Note that drawable content rects are actually in target surface space, so
2294     // the transform we have to provide is the target surface's
2295     // screen_space_transform.
2296     LayerImpl* render_target = current_layer->render_target();
2297     if (LayerClipsSubtree(current_layer) &&
2298         !PointHitsRect(
2299             screen_space_point,
2300             render_target->render_surface()->screen_space_transform(),
2301             current_layer->drawable_content_rect()))
2302       return true;
2303
2304     current_layer = current_layer->parent();
2305   }
2306
2307   // If we have finished walking all ancestors without having already exited,
2308   // then the point is not clipped by any ancestors.
2309   return false;
2310 }
2311
2312 LayerImpl* LayerTreeHostCommon::FindLayerThatIsHitByPoint(
2313     gfx::PointF screen_space_point,
2314     const LayerImplList& render_surface_layer_list) {
2315   LayerImpl* found_layer = NULL;
2316
2317   typedef LayerIterator<LayerImpl,
2318                         LayerImplList,
2319                         RenderSurfaceImpl,
2320                         LayerIteratorActions::FrontToBack> LayerIteratorType;
2321   LayerIteratorType end = LayerIteratorType::End(&render_surface_layer_list);
2322
2323   for (LayerIteratorType
2324            it = LayerIteratorType::Begin(&render_surface_layer_list);
2325        it != end;
2326        ++it) {
2327     // We don't want to consider render_surfaces for hit testing.
2328     if (!it.represents_itself())
2329       continue;
2330
2331     LayerImpl* current_layer = (*it);
2332
2333     gfx::RectF content_rect(current_layer->content_bounds());
2334     if (!PointHitsRect(screen_space_point,
2335                        current_layer->screen_space_transform(),
2336                        content_rect))
2337       continue;
2338
2339     // At this point, we think the point does hit the layer, but we need to walk
2340     // up the parents to ensure that the layer was not clipped in such a way
2341     // that the hit point actually should not hit the layer.
2342     if (PointIsClippedBySurfaceOrClipRect(screen_space_point, current_layer))
2343       continue;
2344
2345     // Skip the HUD layer.
2346     if (current_layer == current_layer->layer_tree_impl()->hud_layer())
2347       continue;
2348
2349     found_layer = current_layer;
2350     break;
2351   }
2352
2353   // This can potentially return NULL, which means the screen_space_point did
2354   // not successfully hit test any layers, not even the root layer.
2355   return found_layer;
2356 }
2357
2358 LayerImpl* LayerTreeHostCommon::FindLayerThatIsHitByPointInTouchHandlerRegion(
2359     gfx::PointF screen_space_point,
2360     const LayerImplList& render_surface_layer_list) {
2361   // First find out which layer was hit from the saved list of visible layers
2362   // in the most recent frame.
2363   LayerImpl* layer_impl = LayerTreeHostCommon::FindLayerThatIsHitByPoint(
2364       screen_space_point,
2365       render_surface_layer_list);
2366
2367   // Walk up the hierarchy and look for a layer with a touch event handler
2368   // region that the given point hits.
2369   // This walk may not be necessary anymore: http://crbug.com/310817
2370   for (; layer_impl; layer_impl = layer_impl->parent()) {
2371     if (LayerTreeHostCommon::LayerHasTouchEventHandlersAt(screen_space_point,
2372                                                           layer_impl))
2373       break;
2374   }
2375   return layer_impl;
2376 }
2377
2378 bool LayerTreeHostCommon::LayerHasTouchEventHandlersAt(
2379     gfx::PointF screen_space_point,
2380     LayerImpl* layer_impl) {
2381   if (layer_impl->touch_event_handler_region().IsEmpty())
2382     return false;
2383
2384   if (!PointHitsRegion(screen_space_point,
2385                        layer_impl->screen_space_transform(),
2386                        layer_impl->touch_event_handler_region(),
2387                        layer_impl->contents_scale_x(),
2388                        layer_impl->contents_scale_y()))
2389     return false;
2390
2391   // At this point, we think the point does hit the touch event handler region
2392   // on the layer, but we need to walk up the parents to ensure that the layer
2393   // was not clipped in such a way that the hit point actually should not hit
2394   // the layer.
2395   if (PointIsClippedBySurfaceOrClipRect(screen_space_point, layer_impl))
2396     return false;
2397
2398   return true;
2399 }
2400 }  // namespace cc