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