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