Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(510)

Side by Side Diff: cc/trees/layer_tree_host_common.cc

Issue 12760011: cc: Chromify LayerTreeHostCommon (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: Rebase Created 7 years, 9 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
« no previous file with comments | « cc/trees/layer_tree_host_common.h ('k') | cc/trees/layer_tree_host_common_unittest.cc » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 // Copyright 2011 The Chromium Authors. All rights reserved. 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 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "cc/trees/layer_tree_host_common.h" 5 #include "cc/trees/layer_tree_host_common.h"
6 6
7 #include <algorithm> 7 #include <algorithm>
8 8
9 #include "base/debug/trace_event.h" 9 #include "base/debug/trace_event.h"
10 #include "cc/base/math_util.h" 10 #include "cc/base/math_util.h"
11 #include "cc/layers/heads_up_display_layer_impl.h" 11 #include "cc/layers/heads_up_display_layer_impl.h"
12 #include "cc/layers/layer.h" 12 #include "cc/layers/layer.h"
13 #include "cc/layers/layer_impl.h" 13 #include "cc/layers/layer_impl.h"
14 #include "cc/layers/layer_iterator.h" 14 #include "cc/layers/layer_iterator.h"
15 #include "cc/layers/render_surface.h" 15 #include "cc/layers/render_surface.h"
16 #include "cc/layers/render_surface_impl.h" 16 #include "cc/layers/render_surface_impl.h"
17 #include "cc/trees/layer_sorter.h" 17 #include "cc/trees/layer_sorter.h"
18 #include "cc/trees/layer_tree_impl.h" 18 #include "cc/trees/layer_tree_impl.h"
19 #include "ui/gfx/point_conversions.h" 19 #include "ui/gfx/point_conversions.h"
20 #include "ui/gfx/rect_conversions.h" 20 #include "ui/gfx/rect_conversions.h"
21 #include "ui/gfx/transform.h" 21 #include "ui/gfx/transform.h"
22 22
23 namespace cc { 23 namespace cc {
24 24
25 ScrollAndScaleSet::ScrollAndScaleSet() 25 ScrollAndScaleSet::ScrollAndScaleSet() {}
26 { 26
27 } 27 ScrollAndScaleSet::~ScrollAndScaleSet() {}
28 28
29 ScrollAndScaleSet::~ScrollAndScaleSet() 29 static void SortLayers(std::vector<scoped_refptr<Layer> >::iterator forst,
30 { 30 std::vector<scoped_refptr<Layer> >::iterator end,
31 } 31 void* layer_sorter) {
32 32 NOTREACHED();
33 static void sortLayers(std::vector<scoped_refptr<Layer> >::iterator forst, std:: vector<scoped_refptr<Layer> >::iterator end, void* layerSorter) 33 }
34 { 34
35 NOTREACHED(); 35 static void SortLayers(std::vector<LayerImpl*>::iterator first,
36 } 36 std::vector<LayerImpl*>::iterator end,
37 37 LayerSorter* layer_sorter) {
38 static void sortLayers(std::vector<LayerImpl*>::iterator first, std::vector<Laye rImpl*>::iterator end, LayerSorter* layerSorter) 38 DCHECK(layer_sorter);
39 { 39 TRACE_EVENT0("cc", "LayerTreeHostCommon::SortLayers");
40 DCHECK(layerSorter); 40 layer_sorter->Sort(first, end);
41 TRACE_EVENT0("cc", "layer_tree_host_common::sortLayers"); 41 }
42 layerSorter->Sort(first, end); 42
43 } 43 inline gfx::Rect CalculateVisibleRectWithCachedLayerRect(
44 44 gfx::Rect target_surface_rect,
45 inline gfx::Rect calculateVisibleRectWithCachedLayerRect(const gfx::Rect& target SurfaceRect, const gfx::Rect& layerBoundRect, const gfx::Rect& layerRectInTarget Space, const gfx::Transform& transform) 45 gfx::Rect layer_bound_rect,
46 { 46 gfx::Rect layer_rect_in_target_space,
47 // Is this layer fully contained within the target surface? 47 const gfx::Transform& transform) {
48 if (targetSurfaceRect.Contains(layerRectInTargetSpace)) 48 // Is this layer fully contained within the target surface?
49 return layerBoundRect; 49 if (target_surface_rect.Contains(layer_rect_in_target_space))
50 50 return layer_bound_rect;
51 // If the layer doesn't fill up the entire surface, then find the part of 51
52 // the surface rect where the layer could be visible. This avoids trying to 52 // If the layer doesn't fill up the entire surface, then find the part of
53 // project surface rect points that are behind the projection point. 53 // the surface rect where the layer could be visible. This avoids trying to
54 gfx::Rect minimalSurfaceRect = targetSurfaceRect; 54 // project surface rect points that are behind the projection point.
55 minimalSurfaceRect.Intersect(layerRectInTargetSpace); 55 gfx::Rect minimal_surface_rect = target_surface_rect;
56 56 minimal_surface_rect.Intersect(layer_rect_in_target_space);
57 // Project the corners of the target surface rect into the layer space. 57
58 // This bounding rectangle may be larger than it needs to be (being 58 // Project the corners of the target surface rect into the layer space.
59 // axis-aligned), but is a reasonable filter on the space to consider. 59 // This bounding rectangle may be larger than it needs to be (being
60 // Non-invertible transforms will create an empty rect here. 60 // axis-aligned), but is a reasonable filter on the space to consider.
61 61 // Non-invertible transforms will create an empty rect here.
62 gfx::Transform surfaceToLayer(gfx::Transform::kSkipInitialization); 62
63 if (!transform.GetInverse(&surfaceToLayer)) { 63 gfx::Transform surface_to_layer(gfx::Transform::kSkipInitialization);
64 // TODO(shawnsingh): Either we need to handle uninvertible transforms 64 if (!transform.GetInverse(&surface_to_layer)) {
65 // here, or DCHECK that the transform is invertible. 65 // TODO(shawnsingh): Either we need to handle uninvertible transforms
66 } 66 // here, or DCHECK that the transform is invertible.
67 gfx::Rect layerRect = gfx::ToEnclosingRect(MathUtil::ProjectClippedRect(surf aceToLayer, gfx::RectF(minimalSurfaceRect))); 67 }
68 layerRect.Intersect(layerBoundRect); 68 gfx::Rect layer_rect = gfx::ToEnclosingRect(MathUtil::ProjectClippedRect(
69 return layerRect; 69 surface_to_layer, gfx::RectF(minimal_surface_rect)));
70 } 70 layer_rect.Intersect(layer_bound_rect);
71 71 return layer_rect;
72 gfx::Rect LayerTreeHostCommon::calculateVisibleRect(const gfx::Rect& targetSurfa ceRect, const gfx::Rect& layerBoundRect, const gfx::Transform& transform) 72 }
73 { 73
74 gfx::Rect layerInSurfaceSpace = MathUtil::MapClippedRect(transform, layerBou ndRect); 74 gfx::Rect LayerTreeHostCommon::CalculateVisibleRect(
75 return calculateVisibleRectWithCachedLayerRect(targetSurfaceRect, layerBound Rect, layerInSurfaceSpace, transform); 75 gfx::Rect target_surface_rect,
76 gfx::Rect layer_bound_rect,
77 const gfx::Transform& transform) {
78 gfx::Rect layer_in_surface_space =
79 MathUtil::MapClippedRect(transform, layer_bound_rect);
80 return CalculateVisibleRectWithCachedLayerRect(
81 target_surface_rect, layer_bound_rect, layer_in_surface_space, transform);
82 }
83
84 template <typename LayerType> static inline bool IsRootLayer(LayerType* layer) {
85 return !layer->parent();
76 } 86 }
77 87
78 template <typename LayerType> 88 template <typename LayerType>
79 static inline bool isRootLayer(LayerType* layer) 89 static inline bool LayerIsInExisting3DRenderingContext(LayerType* layer) {
80 { 90 // According to current W3C spec on CSS transforms, a layer is part of an
81 return !layer->parent(); 91 // established 3d rendering context if its parent has transform-style of
82 } 92 // preserves-3d.
83 93 return layer->parent() && layer->parent()->preserves_3d();
84 template<typename LayerType> 94 }
85 static inline bool layerIsInExisting3DRenderingContext(LayerType* layer) 95
86 { 96 template <typename LayerType>
87 // According to current W3C spec on CSS transforms, a layer is part of an es tablished 97 static bool IsRootLayerOfNewRenderingContext(LayerType* layer) {
88 // 3d rendering context if its parent has transform-style of preserves-3d. 98 // According to current W3C spec on CSS transforms (Section 6.1), a layer is
89 return layer->parent() && layer->parent()->preserves_3d(); 99 // the beginning of 3d rendering context if its parent does not have
90 } 100 // transform-style: preserve-3d, but this layer itself does.
91 101 if (layer->parent())
92 template<typename LayerType> 102 return !layer->parent()->preserves_3d() && layer->preserves_3d();
93 static bool isRootLayerOfNewRenderingContext(LayerType* layer) 103
94 { 104 return layer->preserves_3d();
95 // According to current W3C spec on CSS transforms (Section 6.1), a layer is the 105 }
96 // beginning of 3d rendering context if its parent does not have transform-s tyle: 106
97 // preserve-3d, but this layer itself does. 107 template <typename LayerType>
98 if (layer->parent()) 108 static bool IsLayerBackFaceVisible(LayerType* layer) {
99 return !layer->parent()->preserves_3d() && layer->preserves_3d(); 109 // The current W3C spec on CSS transforms says that backface visibility should
100 110 // be determined differently depending on whether the layer is in a "3d
101 return layer->preserves_3d(); 111 // rendering context" or not. For Chromium code, we can determine whether we
102 } 112 // are in a 3d rendering context by checking if the parent preserves 3d.
103 113
104 template<typename LayerType> 114 if (LayerIsInExisting3DRenderingContext(layer))
105 static bool isLayerBackFaceVisible(LayerType* layer) 115 return layer->draw_transform().IsBackFaceVisible();
106 { 116
107 // The current W3C spec on CSS transforms says that backface visibility shou ld be 117 // In this case, either the layer establishes a new 3d rendering context, or
108 // determined differently depending on whether the layer is in a "3d renderi ng 118 // is not in a 3d rendering context at all.
109 // context" or not. For Chromium code, we can determine whether we are in a 3d 119 return layer->transform().IsBackFaceVisible();
110 // rendering context by checking if the parent preserves 3d. 120 }
111 121
112 if (layerIsInExisting3DRenderingContext(layer)) 122 template <typename LayerType>
113 return layer->draw_transform().IsBackFaceVisible(); 123 static bool IsSurfaceBackFaceVisible(LayerType* layer,
114 124 const gfx::Transform& draw_transform) {
115 // In this case, either the layer establishes a new 3d rendering context, or is not in 125 if (LayerIsInExisting3DRenderingContext(layer))
116 // a 3d rendering context at all. 126 return draw_transform.IsBackFaceVisible();
127
128 if (IsRootLayerOfNewRenderingContext(layer))
117 return layer->transform().IsBackFaceVisible(); 129 return layer->transform().IsBackFaceVisible();
118 } 130
119 131 // If the render_surface is not part of a new or existing rendering context,
120 template<typename LayerType> 132 // then the layers that contribute to this surface will decide back-face
121 static bool isSurfaceBackFaceVisible(LayerType* layer, const gfx::Transform& dra wTransform) 133 // visibility for themselves.
122 { 134 return false;
123 if (layerIsInExisting3DRenderingContext(layer)) 135 }
124 return drawTransform.IsBackFaceVisible(); 136
125 137 template <typename LayerType>
126 if (isRootLayerOfNewRenderingContext(layer)) 138 static inline bool LayerClipsSubtree(LayerType* layer) {
127 return layer->transform().IsBackFaceVisible(); 139 return layer->masks_to_bounds() || layer->mask_layer();
128 140 }
129 // If the renderSurface is not part of a new or existing rendering context, then the 141
130 // layers that contribute to this surface will decide back-face visibility f or themselves. 142 template <typename LayerType>
131 return false; 143 static gfx::Rect CalculateVisibleContentRect(
132 } 144 LayerType* layer,
133 145 gfx::Rect ancestor_clip_rect_in_descendant_surface_space,
134 template<typename LayerType> 146 gfx::Rect layer_rect_in_target_space) {
135 static inline bool layerClipsSubtree(LayerType* layer) 147 DCHECK(layer->render_target());
136 { 148
137 return layer->masks_to_bounds() || layer->mask_layer(); 149 // Nothing is visible if the layer bounds are empty.
138 } 150 if (!layer->DrawsContent() || layer->content_bounds().IsEmpty() ||
139 151 layer->drawable_content_rect().IsEmpty())
140 template<typename LayerType> 152 return gfx::Rect();
141 static gfx::Rect calculateVisibleContentRect(LayerType* layer, const gfx::Rect& ancestorClipRectInDescendantSurfaceSpace, const gfx::Rect& layerRectInTargetSpac e) 153
142 { 154 // Compute visible bounds in target surface space.
143 DCHECK(layer->render_target()); 155 gfx::Rect visible_rect_in_target_surface_space =
144 156 layer->drawable_content_rect();
145 // Nothing is visible if the layer bounds are empty. 157
146 if (!layer->DrawsContent() || layer->content_bounds().IsEmpty() || layer->dr awable_content_rect().IsEmpty()) 158 if (!layer->render_target()->render_surface()->clip_rect().IsEmpty()) {
147 return gfx::Rect(); 159 // In this case the target surface does clip layers that contribute to
148 160 // it. So, we have to convert the current surface's clipRect from its
149 // Compute visible bounds in target surface space. 161 // ancestor surface space to the current (descendant) surface
150 gfx::Rect visibleRectInTargetSurfaceSpace = layer->drawable_content_rect(); 162 // space. This conversion is done outside this function so that it can
151 163 // be cached instead of computing it redundantly for every layer.
152 if (!layer->render_target()->render_surface()->clip_rect().IsEmpty()) { 164 visible_rect_in_target_surface_space.Intersect(
153 // In this case the target surface does clip layers that contribute to 165 ancestor_clip_rect_in_descendant_surface_space);
154 // it. So, we have to convert the current surface's clipRect from its 166 }
155 // ancestor surface space to the current (descendant) surface 167
156 // space. This conversion is done outside this function so that it can 168 if (visible_rect_in_target_surface_space.IsEmpty())
157 // be cached instead of computing it redundantly for every layer. 169 return gfx::Rect();
158 visibleRectInTargetSurfaceSpace.Intersect(ancestorClipRectInDescendantSu rfaceSpace); 170
159 } 171 return CalculateVisibleRectWithCachedLayerRect(
160 172 visible_rect_in_target_surface_space,
161 if (visibleRectInTargetSurfaceSpace.IsEmpty()) 173 gfx::Rect(gfx::Point(), layer->content_bounds()),
162 return gfx::Rect(); 174 layer_rect_in_target_space,
163 175 layer->draw_transform());
164 return calculateVisibleRectWithCachedLayerRect(visibleRectInTargetSurfaceSpa ce, gfx::Rect(gfx::Point(), layer->content_bounds()), layerRectInTargetSpace, la yer->draw_transform()); 176 }
165 } 177
166 178 static inline bool TransformToParentIsKnown(LayerImpl* layer) { return true; }
167 static inline bool transformToParentIsKnown(LayerImpl*) 179
168 { 180 static inline bool TransformToParentIsKnown(Layer* layer) {
181
182 return !layer->TransformIsAnimating();
183 }
184
185 static inline bool TransformToScreenIsKnown(LayerImpl* layer) { return true; }
186
187 static inline bool TransformToScreenIsKnown(Layer* layer) {
188 return !layer->screen_space_transform_is_animating();
189 }
190
191 template <typename LayerType>
192 static bool LayerShouldBeSkipped(LayerType* layer) {
193 // Layers can be skipped if any of these conditions are met.
194 // - does not draw content.
195 // - is transparent
196 // - has empty bounds
197 // - the layer is not double-sided, but its back face is visible.
198 //
199 // Some additional conditions need to be computed at a later point after the
200 // recursion is finished.
201 // - the intersection of render surface content and layer clipRect is empty
202 // - the visibleContentRect is empty
203 //
204 // Note, if the layer should not have been drawn due to being fully
205 // transparent, we would have skipped the entire subtree and never made it
206 // into this function, so it is safe to omit this check here.
207
208 if (!layer->DrawsContent() || layer->bounds().IsEmpty())
169 return true; 209 return true;
170 } 210
171 211 LayerType* backface_test_layer = layer;
172 static inline bool transformToParentIsKnown(Layer* layer) 212 if (layer->use_parent_backface_visibility()) {
173 { 213 DCHECK(layer->parent());
174 214 DCHECK(!layer->parent()->use_parent_backface_visibility());
175 return !layer->TransformIsAnimating(); 215 backface_test_layer = layer->parent();
176 } 216 }
177 217
178 static inline bool transformToScreenIsKnown(LayerImpl*) 218 // The layer should not be drawn if (1) it is not double-sided and (2) the
179 { 219 // back of the layer is known to be facing the screen.
220 if (!backface_test_layer->double_sided() &&
221 TransformToScreenIsKnown(backface_test_layer) &&
222 IsLayerBackFaceVisible(backface_test_layer))
180 return true; 223 return true;
181 } 224
182 225 return false;
183 static inline bool transformToScreenIsKnown(Layer* layer) 226 }
184 { 227
185 return !layer->screen_space_transform_is_animating(); 228 static inline bool SubtreeShouldBeSkipped(LayerImpl* layer) {
186 } 229 // The opacity of a layer always applies to its children (either implicitly
187 230 // via a render surface or explicitly if the parent preserves 3D), so the
188 template<typename LayerType> 231 // entire subtree can be skipped if this layer is fully transparent.
189 static bool layerShouldBeSkipped(LayerType* layer) 232 return !layer->opacity();
190 { 233 }
191 // Layers can be skipped if any of these conditions are met. 234
192 // - does not draw content. 235 static inline bool SubtreeShouldBeSkipped(Layer* layer) {
193 // - is transparent 236 // If the opacity is being animated then the opacity on the main thread is
194 // - has empty bounds 237 // unreliable (since the impl thread may be using a different opacity), so it
195 // - the layer is not double-sided, but its back face is visible. 238 // should not be trusted.
196 // 239 // In particular, it should not cause the subtree to be skipped.
197 // Some additional conditions need to be computed at a later point after the recursion is finished. 240 // Similarly, for layers that might animate opacity using an impl-only
198 // - the intersection of render surface content and layer clipRect is empt y 241 // animation, their subtree should also not be skipped.
199 // - the visibleContentRect is empty 242 return !layer->opacity() && !layer->OpacityIsAnimating() &&
200 // 243 !layer->OpacityCanAnimateOnImplThread();
201 // Note, if the layer should not have been drawn due to being fully transpar ent,
202 // we would have skipped the entire subtree and never made it into this func tion,
203 // so it is safe to omit this check here.
204
205 if (!layer->DrawsContent() || layer->bounds().IsEmpty())
206 return true;
207
208 LayerType* backfaceTestLayer = layer;
209 if (layer->use_parent_backface_visibility()) {
210 DCHECK(layer->parent());
211 DCHECK(!layer->parent()->use_parent_backface_visibility());
212 backfaceTestLayer = layer->parent();
213 }
214
215 // The layer should not be drawn if (1) it is not double-sided and (2) the b ack of the layer is known to be facing the screen.
216 if (!backfaceTestLayer->double_sided() && transformToScreenIsKnown(backfaceT estLayer) && isLayerBackFaceVisible(backfaceTestLayer))
217 return true;
218
219 return false;
220 }
221
222 static inline bool subtreeShouldBeSkipped(LayerImpl* layer)
223 {
224 // The opacity of a layer always applies to its children (either implicitly
225 // via a render surface or explicitly if the parent preserves 3D), so the
226 // entire subtree can be skipped if this layer is fully transparent.
227 return !layer->opacity();
228 }
229
230 static inline bool subtreeShouldBeSkipped(Layer* layer)
231 {
232 // If the opacity is being animated then the opacity on the main thread is u nreliable
233 // (since the impl thread may be using a different opacity), so it should no t be trusted.
234 // In particular, it should not cause the subtree to be skipped.
235 // Similarly, for layers that might animate opacity using an impl-only
236 // animation, their subtree should also not be skipped.
237 return !layer->opacity() && !layer->OpacityIsAnimating() &&
238 !layer->OpacityCanAnimateOnImplThread();
239 } 244 }
240 245
241 // Called on each layer that could be drawn after all information from 246 // Called on each layer that could be drawn after all information from
242 // calcDrawProperties has been updated on that layer. May have some false 247 // calcDrawProperties has been updated on that layer. May have some false
243 // positives (e.g. layers get this called on them but don't actually get drawn). 248 // positives (e.g. layers get this called on them but don't actually get drawn).
244 static inline void updateTilePrioritiesForLayer(LayerImpl* layer) 249 static inline void UpdateTilePrioritiesForLayer(LayerImpl* layer) {
245 { 250 layer->UpdateTilePriorities();
246 layer->UpdateTilePriorities(); 251
247 252 // Mask layers don't get this call, so explicitly update them so they can
248 // Mask layers don't get this call, so explicitly update them so they can 253 // kick off tile rasterization.
249 // kick off tile rasterization. 254 if (layer->mask_layer())
250 if (layer->mask_layer()) 255 layer->mask_layer()->UpdateTilePriorities();
251 layer->mask_layer()->UpdateTilePriorities(); 256 if (layer->replica_layer() && layer->replica_layer()->mask_layer())
252 if (layer->replica_layer() && layer->replica_layer()->mask_layer()) 257 layer->replica_layer()->mask_layer()->UpdateTilePriorities();
253 layer->replica_layer()->mask_layer()->UpdateTilePriorities(); 258 }
254 } 259
255 260 static inline void UpdateTilePrioritiesForLayer(Layer* layer) {}
256 static inline void updateTilePrioritiesForLayer(Layer* layer) 261
257 { 262 template <typename LayerType>
258 } 263 static bool SubtreeShouldRenderToSeparateSurface(
259 264 LayerType* layer,
260 template<typename LayerType> 265 bool axis_aligned_with_respect_to_parent) {
261 static bool subtreeShouldRenderToSeparateSurface(LayerType* layer, bool axisAlig nedWithRespectToParent) 266 //
262 { 267 // A layer and its descendants should render onto a new RenderSurfaceImpl if
263 // 268 // any of these rules hold:
264 // A layer and its descendants should render onto a new RenderSurfaceImpl if any of these rules hold: 269 //
265 // 270
266 271 // The root layer should always have a render_surface.
267 // The root layer should always have a renderSurface. 272 if (IsRootLayer(layer))
268 if (isRootLayer(layer)) 273 return true;
269 return true; 274
270 275 // If we force it.
271 // If we force it. 276 if (layer->force_render_surface())
272 if (layer->force_render_surface()) 277 return true;
273 return true; 278
274 279 // If the layer uses a mask.
275 // If the layer uses a mask. 280 if (layer->mask_layer())
276 if (layer->mask_layer()) 281 return true;
277 return true; 282
278 283 // If the layer has a reflection.
279 // If the layer has a reflection. 284 if (layer->replica_layer())
280 if (layer->replica_layer()) 285 return true;
281 return true; 286
282 287 // If the layer uses a CSS filter.
283 // If the layer uses a CSS filter. 288 if (!layer->filters().isEmpty() || !layer->background_filters().isEmpty() ||
284 if (!layer->filters().isEmpty() || !layer->background_filters().isEmpty() || layer->filter()) 289 layer->filter())
285 return true; 290 return true;
286 291
287 int numDescendantsThatDrawContent = layer->draw_properties().num_descendants _that_draw_content; 292 int num_descendants_that_draw_content =
288 293 layer->draw_properties().num_descendants_that_draw_content;
289 // If the layer flattens its subtree (i.e. the layer doesn't preserve-3d), b ut it is 294
290 // treated as a 3D object by its parent (i.e. parent does preserve-3d). 295 // If the layer flattens its subtree (i.e. the layer doesn't preserve-3d), but
291 if (layerIsInExisting3DRenderingContext(layer) && !layer->preserves_3d() && numDescendantsThatDrawContent > 0) { 296 // it is treated as a 3D object by its parent (i.e. parent does preserve-3d).
292 TRACE_EVENT_INSTANT0("cc", "LayerTreeHostCommon::requireSurface flatteni ng"); 297 if (LayerIsInExisting3DRenderingContext(layer) && !layer->preserves_3d() &&
293 return true; 298 num_descendants_that_draw_content > 0) {
299 TRACE_EVENT_INSTANT0(
300 "cc",
301 "LayerTreeHostCommon::SubtreeShouldRenderToSeparateSurface flattening");
302 return true;
303 }
304
305 // If the layer clips its descendants but it is not axis-aligned with respect
306 // to its parent.
307 bool layer_clips_external_content =
308 LayerClipsSubtree(layer) || layer->HasDelegatedContent();
309 if (layer_clips_external_content && !axis_aligned_with_respect_to_parent &&
310 !layer->draw_properties().descendants_can_clip_selves) {
311 TRACE_EVENT_INSTANT0(
312 "cc",
313 "LayerTreeHostCommon::SubtreeShouldRenderToSeparateSurface clipping");
314 return true;
315 }
316
317 // If the layer has some translucency and does not have a preserves-3d
318 // transform style. This condition only needs a render surface if two or more
319 // layers in the subtree overlap. But checking layer overlaps is unnecessarily
320 // costly so instead we conservatively create a surface whenever at least two
321 // layers draw content for this subtree.
322 bool at_least_two_layers_in_subtree_draw_content =
323 num_descendants_that_draw_content > 0 &&
324 (layer->DrawsContent() || num_descendants_that_draw_content > 1);
325
326 if (layer->opacity() != 1.f && !layer->preserves_3d() &&
327 at_least_two_layers_in_subtree_draw_content) {
328 TRACE_EVENT_INSTANT0(
329 "cc",
330 "LayerTreeHostCommon::SubtreeShouldRenderToSeparateSurface opacity");
331 return true;
332 }
333
334 return false;
335 }
336
337 gfx::Transform ComputeScrollCompensationForThisLayer(
338 LayerImpl* scrolling_layer,
339 const gfx::Transform& parent_matrix) {
340 // For every layer that has non-zero scroll_delta, we have to compute a
341 // transform that can undo the scroll_delta translation. In particular, we
342 // want this matrix to premultiply a fixed-position layer's parent_matrix, so
343 // we design this transform in three steps as follows. The steps described
344 // here apply from right-to-left, so Step 1 would be the right-most matrix:
345 //
346 // Step 1. transform from target surface space to the exact space where
347 // scroll_delta is actually applied.
348 // -- this is inverse of the matrix in step 3
349 // Step 2. undo the scroll_delta
350 // -- this is just a translation by scroll_delta.
351 // Step 3. transform back to target surface space.
352 // -- this transform is the "partial_layer_origin_transform" =
353 // (parent_matrix * scale(layer->pageScaleDelta()));
354 //
355 // These steps create a matrix that both start and end in targetSurfaceSpace.
356 // So this matrix can pre-multiply any fixed-position layer's draw_transform
357 // to undo the scroll_deltas -- as long as that fixed position layer is fixed
358 // onto the same render_target as this scrolling_layer.
359 //
360
361 gfx::Transform partial_layer_origin_transform = parent_matrix;
362 partial_layer_origin_transform.PreconcatTransform(
363 scrolling_layer->impl_transform());
364
365 gfx::Transform scroll_compensation_for_this_layer =
366 partial_layer_origin_transform; // Step 3
367 scroll_compensation_for_this_layer.Translate(
368 scrolling_layer->scroll_delta().x(),
369 scrolling_layer->scroll_delta().y()); // Step 2
370
371 gfx::Transform inverse_partial_layer_origin_transform(
372 gfx::Transform::kSkipInitialization);
373 if (!partial_layer_origin_transform.GetInverse(
374 &inverse_partial_layer_origin_transform)) {
375 // TODO(shawnsingh): Either we need to handle uninvertible transforms
376 // here, or DCHECK that the transform is invertible.
377 }
378 scroll_compensation_for_this_layer.PreconcatTransform(
379 inverse_partial_layer_origin_transform); // Step 1
380 return scroll_compensation_for_this_layer;
381 }
382
383 gfx::Transform ComputeScrollCompensationMatrixForChildren(
384 Layer* current_layer,
385 const gfx::Transform& current_parent_matrix,
386 const gfx::Transform& current_scroll_compensation) {
387 // The main thread (i.e. Layer) does not need to worry about scroll
388 // compensation. So we can just return an identity matrix here.
389 return gfx::Transform();
390 }
391
392 gfx::Transform ComputeScrollCompensationMatrixForChildren(
393 LayerImpl* layer,
394 const gfx::Transform& parent_matrix,
395 const gfx::Transform& current_scroll_compensation_matrix) {
396 // "Total scroll compensation" is the transform needed to cancel out all
397 // scroll_delta translations that occurred since the nearest container layer,
398 // even if there are render_surfaces in-between.
399 //
400 // There are some edge cases to be aware of, that are not explicit in the
401 // code:
402 // - A layer that is both a fixed-position and container should not be its
403 // own container, instead, that means it is fixed to an ancestor, and is a
404 // container for any fixed-position descendants.
405 // - A layer that is a fixed-position container and has a render_surface
406 // should behave the same as a container without a render_surface, the
407 // render_surface is irrelevant in that case.
408 // - A layer that does not have an explicit container is simply fixed to the
409 // viewport. (i.e. the root render_surface.)
410 // - If the fixed-position layer has its own render_surface, then the
411 // render_surface is the one who gets fixed.
412 //
413 // This function needs to be called AFTER layers create their own
414 // render_surfaces.
415 //
416
417 // Avoid the overheads (including stack allocation and matrix
418 // initialization/copy) if we know that the scroll compensation doesn't need
419 // to be reset or adjusted.
420 if (!layer->is_container_for_fixed_position_layers() &&
421 layer->scroll_delta().IsZero() && !layer->render_surface())
422 return current_scroll_compensation_matrix;
423
424 // Start as identity matrix.
425 gfx::Transform next_scroll_compensation_matrix;
426
427 // If this layer is not a container, then it inherits the existing scroll
428 // compensations.
429 if (!layer->is_container_for_fixed_position_layers())
430 next_scroll_compensation_matrix = current_scroll_compensation_matrix;
431
432 // If the current layer has a non-zero scroll_delta, then we should compute
433 // its local scrollCompensation and accumulate it to the
434 // next_scroll_compensation_matrix.
435 if (!layer->scroll_delta().IsZero()) {
436 gfx::Transform scroll_compensation_for_this_layer =
437 ComputeScrollCompensationForThisLayer(layer, parent_matrix);
438 next_scroll_compensation_matrix.PreconcatTransform(
439 scroll_compensation_for_this_layer);
440 }
441
442 // If the layer created its own render_surface, we have to adjust
443 // next_scroll_compensation_matrix. The adjustment allows us to continue
444 // using the scrollCompensation on the next surface.
445 // Step 1 (right-most in the math): transform from the new surface to the
446 // original ancestor surface
447 // Step 2: apply the scroll compensation
448 // Step 3: transform back to the new surface.
449 if (layer->render_surface() &&
450 !next_scroll_compensation_matrix.IsIdentity()) {
451 gfx::Transform inverse_surface_draw_transform(
452 gfx::Transform::kSkipInitialization);
453 if (!layer->render_surface()->draw_transform().GetInverse(
454 &inverse_surface_draw_transform)) {
455 // TODO(shawnsingh): Either we need to handle uninvertible transforms
456 // here, or DCHECK that the transform is invertible.
294 } 457 }
295 458 next_scroll_compensation_matrix =
296 // If the layer clips its descendants but it is not axis-aligned with respec t to its parent. 459 inverse_surface_draw_transform * next_scroll_compensation_matrix *
297 bool layerClipsExternalContent = layerClipsSubtree(layer) || layer->HasDeleg atedContent(); 460 layer->render_surface()->draw_transform();
298 if (layerClipsExternalContent && !axisAlignedWithRespectToParent && !layer-> draw_properties().descendants_can_clip_selves) 461 }
299 { 462
300 TRACE_EVENT_INSTANT0("cc", "LayerTreeHostCommon::requireSurface clipping "); 463 return next_scroll_compensation_matrix;
301 return true; 464 }
465
466 template <typename LayerType>
467 static inline void CalculateContentsScale(LayerType* layer,
468 float contents_scale,
469 bool animating_transform_to_screen) {
470 layer->CalculateContentsScale(contents_scale,
471 animating_transform_to_screen,
472 &layer->draw_properties().contents_scale_x,
473 &layer->draw_properties().contents_scale_y,
474 &layer->draw_properties().content_bounds);
475
476 LayerType* mask_layer = layer->mask_layer();
477 if (mask_layer) {
478 mask_layer->CalculateContentsScale(
479 contents_scale,
480 animating_transform_to_screen,
481 &mask_layer->draw_properties().contents_scale_x,
482 &mask_layer->draw_properties().contents_scale_y,
483 &mask_layer->draw_properties().content_bounds);
484 }
485
486 LayerType* replica_mask_layer =
487 layer->replica_layer() ? layer->replica_layer()->mask_layer() : NULL;
488 if (replica_mask_layer) {
489 replica_mask_layer->CalculateContentsScale(
490 contents_scale,
491 animating_transform_to_screen,
492 &replica_mask_layer->draw_properties().contents_scale_x,
493 &replica_mask_layer->draw_properties().contents_scale_y,
494 &replica_mask_layer->draw_properties().content_bounds);
495 }
496 }
497
498 static inline void UpdateLayerContentsScale(
499 LayerImpl* layer,
500 const gfx::Transform& combined_transform,
501 float device_scale_factor,
502 float page_scale_factor,
503 bool animating_transform_to_screen) {
504 gfx::Vector2dF transform_scale = MathUtil::ComputeTransform2dScaleComponents(
505 combined_transform, device_scale_factor * page_scale_factor);
506 float contents_scale = std::max(transform_scale.x(), transform_scale.y());
507 CalculateContentsScale(layer, contents_scale, animating_transform_to_screen);
508 }
509
510 static inline void UpdateLayerContentsScale(
511 Layer* layer,
512 const gfx::Transform& combined_transform,
513 float device_scale_factor,
514 float page_scale_factor,
515 bool animating_transform_to_screen) {
516 float raster_scale = layer->raster_scale();
517
518 if (layer->automatically_compute_raster_scale()) {
519 gfx::Vector2dF transform_scale =
520 MathUtil::ComputeTransform2dScaleComponents(combined_transform, 0.f);
521 float combined_scale = std::max(transform_scale.x(), transform_scale.y());
522 float ideal_raster_scale = combined_scale / device_scale_factor;
523 if (!layer->bounds_contain_page_scale())
524 ideal_raster_scale /= page_scale_factor;
525
526 bool need_to_set_raster_scale = !raster_scale;
527
528 // If we've previously saved a raster_scale but the ideal changes, things
529 // are unpredictable and we should just use 1.
530 if (raster_scale && raster_scale != 1.f &&
531 ideal_raster_scale != raster_scale) {
532 ideal_raster_scale = 1.f;
533 need_to_set_raster_scale = true;
302 } 534 }
303 535
304 // If the layer has some translucency and does not have a preserves-3d trans form style. 536 if (need_to_set_raster_scale) {
305 // This condition only needs a render surface if two or more layers in the 537 bool use_and_save_ideal_scale =
306 // subtree overlap. But checking layer overlaps is unnecessarily costly so 538 ideal_raster_scale >= 1.f && !animating_transform_to_screen;
307 // instead we conservatively create a surface whenever at least two layers 539 if (use_and_save_ideal_scale) {
308 // draw content for this subtree. 540 raster_scale = ideal_raster_scale;
309 bool atLeastTwoLayersInSubtreeDrawContent = numDescendantsThatDrawContent > 0 && (layer->DrawsContent() || numDescendantsThatDrawContent > 1); 541 layer->SetRasterScale(raster_scale);
310 542 }
311 if (layer->opacity() != 1.f && !layer->preserves_3d() && atLeastTwoLayersInS ubtreeDrawContent) {
312 TRACE_EVENT_INSTANT0("cc", "LayerTreeHostCommon::requireSurface opacity" );
313 return true;
314 } 543 }
315 544 }
316 return false; 545
317 } 546 if (!raster_scale)
318 547 raster_scale = 1.f;
319 gfx::Transform computeScrollCompensationForThisLayer(LayerImpl* scrollingLayer, const gfx::Transform& parentMatrix) 548
320 { 549 float contents_scale = raster_scale * device_scale_factor;
321 // For every layer that has non-zero scrollDelta, we have to compute a trans form that can undo the 550 if (!layer->bounds_contain_page_scale())
322 // scrollDelta translation. In particular, we want this matrix to premultipl y a fixed-position layer's 551 contents_scale *= page_scale_factor;
323 // parentMatrix, so we design this transform in three steps as follows. The steps described here apply 552
324 // from right-to-left, so Step 1 would be the right-most matrix: 553 CalculateContentsScale(layer, contents_scale, animating_transform_to_screen);
325 // 554 }
326 // Step 1. transform from target surface space to the exact space where scrollDelta is actually applied. 555
327 // -- this is inverse of the matrix in step 3 556 template <typename LayerType, typename LayerList>
328 // Step 2. undo the scrollDelta 557 static inline void RemoveSurfaceForEarlyExit(
329 // -- this is just a translation by scrollDelta. 558 LayerType* layer_to_remove,
330 // Step 3. transform back to target surface space. 559 LayerList& render_surface_layer_list) {
331 // -- this transform is the "partialLayerOriginTransform" = (paren tMatrix * scale(layer->pageScaleDelta())); 560 DCHECK(layer_to_remove->render_surface());
332 // 561 // Technically, we know that the layer we want to remove should be
333 // These steps create a matrix that both start and end in targetSurfaceSpace . So this matrix can 562 // at the back of the render_surface_layer_list. However, we have had
334 // pre-multiply any fixed-position layer's drawTransform to undo the scrollD eltas -- as long as 563 // bugs before that added unnecessary layers here
335 // that fixed position layer is fixed onto the same renderTarget as this scr ollingLayer. 564 // (https://bugs.webkit.org/show_bug.cgi?id=74147), but that causes
336 // 565 // things to crash. So here we proactively remove any additional
337 566 // layers from the end of the list.
338 gfx::Transform partialLayerOriginTransform = parentMatrix; 567 while (render_surface_layer_list->back() != layer_to_remove) {
339 partialLayerOriginTransform.PreconcatTransform(scrollingLayer->impl_transfor m()); 568 render_surface_layer_list->back()->ClearRenderSurface();
340 569 render_surface_layer_list->pop_back();
341 gfx::Transform scrollCompensationForThisLayer = partialLayerOriginTransform; // Step 3 570 }
342 scrollCompensationForThisLayer.Translate(scrollingLayer->scroll_delta().x(), scrollingLayer->scroll_delta().y()); // Step 2 571 DCHECK_EQ(render_surface_layer_list->back(), layer_to_remove);
343 572 render_surface_layer_list->pop_back();
344 gfx::Transform inversePartialLayerOriginTransform(gfx::Transform::kSkipIniti alization); 573 layer_to_remove->ClearRenderSurface();
345 if (!partialLayerOriginTransform.GetInverse(&inversePartialLayerOriginTransf orm)) { 574 }
575
576 // Recursively walks the layer tree to compute any information that is needed
577 // before doing the main recursion.
578 template <typename LayerType>
579 static void PreCalculateMetaInformation(LayerType* layer) {
580 if (layer->HasDelegatedContent()) {
581 // Layers with delegated content need to be treated as if they have as many
582 // children as the number of layers they own delegated quads for. Since we
583 // don't know this number right now, we choose one that acts like infinity
584 // for our purposes.
585 layer->draw_properties().num_descendants_that_draw_content = 1000;
586 layer->draw_properties().descendants_can_clip_selves = false;
587 return;
588 }
589
590 int num_descendants_that_draw_content = 0;
591 bool descendants_can_clip_selves = true;
592 bool sublayer_transform_prevents_clip =
593 !layer->sublayer_transform().IsPositiveScaleOrTranslation();
594
595 for (size_t i = 0; i < layer->children().size(); ++i) {
596 LayerType* child_layer = layer->children()[i];
597 PreCalculateMetaInformation<LayerType>(child_layer);
598
599 num_descendants_that_draw_content += child_layer->DrawsContent() ? 1 : 0;
600 num_descendants_that_draw_content +=
601 child_layer->draw_properties().num_descendants_that_draw_content;
602
603 if ((child_layer->DrawsContent() && !child_layer->CanClipSelf()) ||
604 !child_layer->draw_properties().descendants_can_clip_selves ||
605 sublayer_transform_prevents_clip ||
606 !child_layer->transform().IsPositiveScaleOrTranslation())
607 descendants_can_clip_selves = false;
608 }
609
610 layer->draw_properties().num_descendants_that_draw_content =
611 num_descendants_that_draw_content;
612 layer->draw_properties().descendants_can_clip_selves =
613 descendants_can_clip_selves;
614 }
615
616 static void RoundTranslationComponents(gfx::Transform* transform) {
617 transform->matrix().
618 setDouble(0, 3, MathUtil::Round(transform->matrix().getDouble(0, 3)));
619 transform->matrix().
620 setDouble(1, 3, MathUtil::Round(transform->matrix().getDouble(1, 3)));
621 }
622
623 // Recursively walks the layer tree starting at the given node and computes all
624 // the necessary transformations, clipRects, render surfaces, etc.
625 template <typename LayerType, typename LayerList, typename RenderSurfaceType>
626 static void CalculateDrawPropertiesInternal(
627 LayerType* layer,
628 const gfx::Transform& parent_matrix,
629 const gfx::Transform& full_hierarchy_matrix,
630 const gfx::Transform& current_scroll_compensation_matrix,
631 gfx::Rect clip_rect_from_ancestor,
632 gfx::Rect clip_rect_from_ancestor_in_descendant_space,
633 bool ancestor_clips_subtree,
634 RenderSurfaceType* nearest_ancestor_that_moves_pixels,
635 LayerList* render_surface_layer_list,
636 LayerList* layer_list,
637 LayerSorter* layer_sorter,
638 int max_texture_size,
639 float device_scale_factor,
640 float page_scale_factor,
641 bool subtree_can_use_lcd_text,
642 gfx::Rect* drawable_content_rect_of_subtree,
643 bool update_tile_priorities) {
644 // This function computes the new matrix transformations recursively for this
645 // layer and all its descendants. It also computes the appropriate render
646 // surfaces.
647 // Some important points to remember:
648 //
649 // 0. Here, transforms are notated in Matrix x Vector order, and in words we
650 // describe what the transform does from left to right.
651 //
652 // 1. In our terminology, the "layer origin" refers to the top-left corner of
653 // a layer, and the positive Y-axis points downwards. This interpretation is
654 // valid because the orthographic projection applied at draw time flips the Y
655 // axis appropriately.
656 //
657 // 2. The anchor point, when given as a PointF object, is specified in "unit
658 // layer space", where the bounds of the layer map to [0, 1]. However, as a
659 // Transform object, the transform to the anchor point is specified in "layer
660 // space", where the bounds of the layer map to [bounds.width(),
661 // bounds.height()].
662 //
663 // 3. Definition of various transforms used:
664 // M[parent] is the parent matrix, with respect to the nearest render
665 // surface, passed down recursively.
666 //
667 // M[root] is the full hierarchy, with respect to the root, passed down
668 // recursively.
669 //
670 // Tr[origin] is the translation matrix from the parent's origin to
671 // this layer's origin.
672 //
673 // Tr[origin2anchor] is the translation from the layer's origin to its
674 // anchor point
675 //
676 // Tr[origin2center] is the translation from the layer's origin to its
677 // center
678 //
679 // M[layer] is the layer's matrix (applied at the anchor point)
680 //
681 // M[sublayer] is the layer's sublayer transform (also applied at the
682 // layer's anchor point)
683 //
684 // S[layer2content] is the ratio of a layer's ContentBounds() to its
685 // Bounds().
686 //
687 // Some composite transforms can help in understanding the sequence of
688 // transforms:
689 // compositeLayerTransform = Tr[origin2anchor] * M[layer] *
690 // Tr[origin2anchor].inverse()
691 //
692 // compositeSublayerTransform = Tr[origin2anchor] * M[sublayer] *
693 // Tr[origin2anchor].inverse()
694 //
695 // 4. When a layer (or render surface) is drawn, it is drawn into a "target
696 // render surface". Therefore the draw transform does not necessarily
697 // transform from screen space to local layer space. Instead, the draw
698 // transform is the transform between the "target render surface space" and
699 // local layer space. Note that render surfaces, except for the root, also
700 // draw themselves into a different target render surface, and so their draw
701 // transform and origin transforms are also described with respect to the
702 // target.
703 //
704 // Using these definitions, then:
705 //
706 // The draw transform for the layer is:
707 // M[draw] = M[parent] * Tr[origin] * compositeLayerTransform *
708 // S[layer2content] = M[parent] * Tr[layer->Position() + anchor] *
709 // M[layer] * Tr[anchor2origin] * S[layer2content]
710 //
711 // Interpreting the math left-to-right, this transforms from the
712 // layer's render surface to the origin of the layer in content space.
713 //
714 // The screen space transform is:
715 // M[screenspace] = M[root] * Tr[origin] * compositeLayerTransform *
716 // S[layer2content]
717 // = M[root] * Tr[layer->Position() + anchor] * M[layer]
718 // * Tr[anchor2origin] * S[layer2content]
719 //
720 // Interpreting the math left-to-right, this transforms from the root
721 // render surface's content space to the origin of the layer in content
722 // space.
723 //
724 // The transform hierarchy that is passed on to children (i.e. the child's
725 // parent_matrix) is:
726 // M[parent]_for_child = M[parent] * Tr[origin] *
727 // compositeLayerTransform * compositeSublayerTransform
728 // = M[parent] * Tr[layer->Position() + anchor] *
729 // M[layer] * Tr[anchor2origin] *
730 // compositeSublayerTransform
731 //
732 // and a similar matrix for the full hierarchy with respect to the
733 // root.
734 //
735 // Finally, note that the final matrix used by the shader for the layer is P *
736 // M[draw] * S . This final product is computed in drawTexturedQuad(), where:
737 // P is the projection matrix
738 // S is the scale adjustment (to scale up a canonical quad to the
739 // layer's size)
740 //
741 // When a render surface has a replica layer, that layer's transform is used
742 // to draw a second copy of the surface. gfx::Transforms named here are
743 // relative to the surface, unless they specify they are relative to the
744 // replica layer.
745 //
746 // We will denote a scale by device scale S[deviceScale]
747 //
748 // The render surface draw transform to its target surface origin is:
749 // M[surfaceDraw] = M[owningLayer->Draw]
750 //
751 // The render surface origin transform to its the root (screen space) origin
752 // is:
753 // M[surface2root] = M[owningLayer->screenspace] *
754 // S[deviceScale].inverse()
755 //
756 // The replica draw transform to its target surface origin is:
757 // M[replicaDraw] = S[deviceScale] * M[surfaceDraw] *
758 // Tr[replica->Position() + replica->anchor()] * Tr[replica] *
759 // Tr[origin2anchor].inverse() * S[contents_scale].inverse()
760 //
761 // The replica draw transform to the root (screen space) origin is:
762 // M[replica2root] = M[surface2root] * Tr[replica->Position()] *
763 // Tr[replica] * Tr[origin2anchor].inverse()
764 //
765
766 // If we early-exit anywhere in this function, the drawableContentRect of this
767 // subtree should be considered empty.
768 *drawable_content_rect_of_subtree = gfx::Rect();
769
770 // The root layer cannot skip calcDrawProperties.
771 if (!IsRootLayer(layer) && SubtreeShouldBeSkipped(layer))
772 return;
773
774 // As this function proceeds, these are the properties for the current
775 // layer that actually get computed. To avoid unnecessary copies
776 // (particularly for matrices), we do computations directly on these values
777 // when possible.
778 DrawProperties<LayerType, RenderSurfaceType>& layer_draw_properties =
779 layer->draw_properties();
780
781 gfx::Rect clip_rect_for_subtree;
782 bool subtree_should_be_clipped = false;
783
784 // This value is cached on the stack so that we don't have to inverse-project
785 // the surface's clipRect redundantly for every layer. This value is the
786 // same as the surface's clipRect, except that instead of being described
787 // in the target surface space (i.e. the ancestor surface space), it is
788 // described in the current surface space.
789 gfx::Rect clip_rect_for_subtree_in_descendant_space;
790
791 float accumulated_draw_opacity = layer->opacity();
792 bool animating_opacity_to_target = layer->OpacityIsAnimating();
793 bool animating_opacity_to_screen = animating_opacity_to_target;
794 if (layer->parent()) {
795 accumulated_draw_opacity *= layer->parent()->draw_opacity();
796 animating_opacity_to_target |= layer->parent()->draw_opacity_is_animating();
797 animating_opacity_to_screen |=
798 layer->parent()->screen_space_opacity_is_animating();
799 }
800
801 bool animating_transform_to_target = layer->TransformIsAnimating();
802 bool animating_transform_to_screen = animating_transform_to_target;
803 if (layer->parent()) {
804 animating_transform_to_target |=
805 layer->parent()->draw_transform_is_animating();
806 animating_transform_to_screen |=
807 layer->parent()->screen_space_transform_is_animating();
808 }
809
810 gfx::Size bounds = layer->bounds();
811 gfx::PointF anchor_point = layer->anchor_point();
812 gfx::PointF position = layer->position() - layer->scroll_delta();
813
814 gfx::Transform combined_transform = parent_matrix;
815 if (!layer->transform().IsIdentity()) {
816 // LT = Tr[origin] * Tr[origin2anchor]
817 combined_transform.Translate3d(
818 position.x() + anchor_point.x() * bounds.width(),
819 position.y() + anchor_point.y() * bounds.height(),
820 layer->anchor_point_z());
821 // LT = Tr[origin] * Tr[origin2anchor] * M[layer]
822 combined_transform.PreconcatTransform(layer->transform());
823 // LT = Tr[origin] * Tr[origin2anchor] * M[layer] * Tr[anchor2origin]
824 combined_transform.Translate3d(-anchor_point.x() * bounds.width(),
825 -anchor_point.y() * bounds.height(),
826 -layer->anchor_point_z());
827 } else {
828 combined_transform.Translate(position.x(), position.y());
829 }
830
831 // The layer's contentsSize is determined from the combined_transform, which
832 // then informs the layer's draw_transform.
833 UpdateLayerContentsScale(layer,
834 combined_transform,
835 device_scale_factor,
836 page_scale_factor,
837 animating_transform_to_screen);
838
839 // If there is a transformation from the impl thread then it should be at
840 // the start of the combined_transform, but we don't want it to affect the
841 // computation of contents_scale above.
842 // Note carefully: this is Concat, not Preconcat (implTransform *
843 // combined_transform).
844 combined_transform.ConcatTransform(layer->impl_transform());
845
846 if (!animating_transform_to_target && layer->scrollable() &&
847 combined_transform.IsScaleOrTranslation()) {
848 // Align the scrollable layer's position to screen space pixels to avoid
849 // blurriness. To avoid side-effects, do this only if the transform is
850 // simple.
851 RoundTranslationComponents(&combined_transform);
852 }
853
854 if (layer->fixed_to_container_layer()) {
855 // Special case: this layer is a composited fixed-position layer; we need to
856 // explicitly compensate for all ancestors' nonzero scroll_deltas to keep
857 // this layer fixed correctly.
858 // Note carefully: this is Concat, not Preconcat
859 // (current_scroll_compensation * combined_transform).
860 combined_transform.ConcatTransform(current_scroll_compensation_matrix);
861 }
862
863 // The draw_transform that gets computed below is effectively the layer's
864 // draw_transform, unless the layer itself creates a render_surface. In that
865 // case, the render_surface re-parents the transforms.
866 layer_draw_properties.target_space_transform = combined_transform;
867 // M[draw] = M[parent] * LT * S[layer2content]
868 layer_draw_properties.target_space_transform.Scale
869 (1.f / layer->contents_scale_x(), 1.f / layer->contents_scale_y());
870
871 // layerScreenSpaceTransform represents the transform between root layer's
872 // "screen space" and local content space.
873 layer_draw_properties.screen_space_transform = full_hierarchy_matrix;
874 if (!layer->preserves_3d())
875 layer_draw_properties.screen_space_transform.FlattenTo2d();
876 layer_draw_properties.screen_space_transform.PreconcatTransform
877 (layer_draw_properties.target_space_transform);
878
879 // Adjusting text AA method during animation may cause repaints, which in-turn
880 // causes jank.
881 bool adjust_text_aa =
882 !animating_opacity_to_screen && !animating_transform_to_screen;
883 // To avoid color fringing, LCD text should only be used on opaque layers with
884 // just integral translation.
885 bool layer_can_use_lcd_text =
886 subtree_can_use_lcd_text && (accumulated_draw_opacity == 1.f) &&
887 layer_draw_properties.target_space_transform.
888 IsIdentityOrIntegerTranslation();
889
890 gfx::RectF content_rect(gfx::PointF(), layer->content_bounds());
891
892 // full_hierarchy_matrix is the matrix that transforms objects between screen
893 // space (except projection matrix) and the most recent RenderSurfaceImpl's
894 // space. next_hierarchy_matrix will only change if this layer uses a new
895 // RenderSurfaceImpl, otherwise remains the same.
896 gfx::Transform next_hierarchy_matrix = full_hierarchy_matrix;
897 gfx::Transform sublayer_matrix;
898
899 gfx::Vector2dF render_surface_sublayer_scale =
900 MathUtil::ComputeTransform2dScaleComponents(
901 combined_transform, device_scale_factor * page_scale_factor);
902
903 if (SubtreeShouldRenderToSeparateSurface(
904 layer, combined_transform.IsScaleOrTranslation())) {
905 // Check back-face visibility before continuing with this surface and its
906 // subtree
907 if (!layer->double_sided() && TransformToParentIsKnown(layer) &&
908 IsSurfaceBackFaceVisible(layer, combined_transform))
909 return;
910
911 if (!layer->render_surface())
912 layer->CreateRenderSurface();
913
914 RenderSurfaceType* render_surface = layer->render_surface();
915 render_surface->ClearLayerLists();
916
917 // The owning layer's draw transform has a scale from content to layer
918 // space which we do not want; so here we use the combined_transform
919 // instead of the draw_transform. However, we do need to add a different
920 // scale factor that accounts for the surface's pixel dimensions.
921 combined_transform.Scale(1.0 / render_surface_sublayer_scale.x(),
922 1.0 / render_surface_sublayer_scale.y());
923 render_surface->SetDrawTransform(combined_transform);
924
925 // The owning layer's transform was re-parented by the surface, so the
926 // layer's new draw_transform only needs to scale the layer to surface
927 // space.
928 layer_draw_properties.target_space_transform.MakeIdentity();
929 layer_draw_properties.target_space_transform.
930 Scale(render_surface_sublayer_scale.x() / layer->contents_scale_x(),
931 render_surface_sublayer_scale.y() / layer->contents_scale_y());
932
933 // Inside the surface's subtree, we scale everything to the owning layer's
934 // scale. The sublayer matrix transforms layer rects into target surface
935 // content space.
936 DCHECK(sublayer_matrix.IsIdentity());
937 sublayer_matrix.Scale(render_surface_sublayer_scale.x(),
938 render_surface_sublayer_scale.y());
939
940 // The opacity value is moved from the layer to its surface, so that the
941 // entire subtree properly inherits opacity.
942 render_surface->SetDrawOpacity(accumulated_draw_opacity);
943 render_surface->SetDrawOpacityIsAnimating(animating_opacity_to_target);
944 animating_opacity_to_target = false;
945 layer_draw_properties.opacity = 1.f;
946 layer_draw_properties.opacity_is_animating = animating_opacity_to_target;
947 layer_draw_properties.screen_space_opacity_is_animating =
948 animating_opacity_to_screen;
949
950 render_surface->SetTargetSurfaceTransformsAreAnimating(
951 animating_transform_to_target);
952 render_surface->SetScreenSpaceTransformsAreAnimating(
953 animating_transform_to_screen);
954 animating_transform_to_target = false;
955 layer_draw_properties.target_space_transform_is_animating =
956 animating_transform_to_target;
957 layer_draw_properties.screen_space_transform_is_animating =
958 animating_transform_to_screen;
959
960 // Update the aggregate hierarchy matrix to include the transform of the
961 // newly created RenderSurfaceImpl.
962 next_hierarchy_matrix.PreconcatTransform(render_surface->draw_transform());
963
964 // The new render_surface here will correctly clip the entire subtree. So,
965 // we do not need to continue propagating the clipping state further down
966 // the tree. This way, we can avoid transforming clipRects from ancestor
967 // target surface space to current target surface space that could cause
968 // more w < 0 headaches.
969 subtree_should_be_clipped = false;
970
971 if (layer->mask_layer()) {
972 DrawProperties<LayerType, RenderSurfaceType>& mask_layer_draw_properties =
973 layer->mask_layer()->draw_properties();
974 mask_layer_draw_properties.render_target = layer;
975 mask_layer_draw_properties.visible_content_rect =
976 gfx::Rect(gfx::Point(), layer->content_bounds());
977 }
978
979 if (layer->replica_layer() && layer->replica_layer()->mask_layer()) {
980 DrawProperties<LayerType, RenderSurfaceType>&
981 replica_mask_draw_properties =
982 layer->replica_layer()->mask_layer()->draw_properties();
983 replica_mask_draw_properties.render_target = layer;
984 replica_mask_draw_properties.visible_content_rect =
985 gfx::Rect(gfx::Point(), layer->content_bounds());
986 }
987
988 // TODO(senorblanco): make this smarter for the SkImageFilter case (check
989 // for pixel-moving filters)
990 if (layer->filters().hasFilterThatMovesPixels() || layer->filter())
991 nearest_ancestor_that_moves_pixels = render_surface;
992
993 // The render surface clipRect is expressed in the space where this surface
994 // draws, i.e. the same space as clip_rect_from_ancestor.
995 render_surface->SetIsClipped(ancestor_clips_subtree);
996 if (ancestor_clips_subtree) {
997 render_surface->SetClipRect(clip_rect_from_ancestor);
998
999 gfx::Transform inverse_surface_draw_transform(
1000 gfx::Transform::kSkipInitialization);
1001 if (!render_surface->draw_transform().GetInverse(
1002 &inverse_surface_draw_transform)) {
346 // TODO(shawnsingh): Either we need to handle uninvertible transforms 1003 // TODO(shawnsingh): Either we need to handle uninvertible transforms
347 // here, or DCHECK that the transform is invertible. 1004 // here, or DCHECK that the transform is invertible.
1005 }
1006 clip_rect_for_subtree_in_descendant_space =
1007 gfx::ToEnclosingRect(MathUtil::ProjectClippedRect(
1008 inverse_surface_draw_transform, render_surface->clip_rect()));
1009 } else {
1010 render_surface->SetClipRect(gfx::Rect());
1011 clip_rect_for_subtree_in_descendant_space =
1012 clip_rect_from_ancestor_in_descendant_space;
348 } 1013 }
349 scrollCompensationForThisLayer.PreconcatTransform(inversePartialLayerOriginT ransform); // Step 1 1014
350 return scrollCompensationForThisLayer; 1015 render_surface->SetNearestAncestorThatMovesPixels(
351 } 1016 nearest_ancestor_that_moves_pixels);
352 1017
353 gfx::Transform computeScrollCompensationMatrixForChildren(Layer* current_layer, const gfx::Transform& currentParentMatrix, const gfx::Transform& currentScrollCo mpensation) 1018 // If the new render surface is drawn translucent or with a non-integral
354 { 1019 // translation then the subtree that gets drawn on this render surface
355 // The main thread (i.e. Layer) does not need to worry about scroll compensa tion. 1020 // cannot use LCD text.
356 // So we can just return an identity matrix here. 1021 subtree_can_use_lcd_text = layer_can_use_lcd_text;
357 return gfx::Transform(); 1022
358 } 1023 render_surface_layer_list->push_back(layer);
359 1024 } else {
360 gfx::Transform computeScrollCompensationMatrixForChildren(LayerImpl* layer, cons t gfx::Transform& parentMatrix, const gfx::Transform& currentScrollCompensationM atrix) 1025 DCHECK(layer->parent());
361 { 1026
362 // "Total scroll compensation" is the transform needed to cancel out all scr ollDelta translations that 1027 // Note: layer_draw_properties.target_space_transform is computed above,
363 // occurred since the nearest container layer, even if there are renderSurfa ces in-between. 1028 // before this if-else statement.
364 // 1029 layer_draw_properties.target_space_transform_is_animating =
365 // There are some edge cases to be aware of, that are not explicit in the co de: 1030 animating_transform_to_target;
366 // - A layer that is both a fixed-position and container should not be its own container, instead, that means 1031 layer_draw_properties.screen_space_transform_is_animating =
367 // it is fixed to an ancestor, and is a container for any fixed-position descendants. 1032 animating_transform_to_screen;
368 // - A layer that is a fixed-position container and has a renderSurface sho uld behave the same as a container 1033 layer_draw_properties.opacity = accumulated_draw_opacity;
369 // without a renderSurface, the renderSurface is irrelevant in that case. 1034 layer_draw_properties.opacity_is_animating = animating_opacity_to_target;
370 // - A layer that does not have an explicit container is simply fixed to th e viewport. 1035 layer_draw_properties.screen_space_opacity_is_animating =
371 // (i.e. the root renderSurface.) 1036 animating_opacity_to_screen;
372 // - If the fixed-position layer has its own renderSurface, then the render Surface is 1037 sublayer_matrix = combined_transform;
373 // the one who gets fixed. 1038
374 // 1039 layer->ClearRenderSurface();
375 // This function needs to be called AFTER layers create their own renderSurf aces. 1040
376 // 1041 // Layers without render_surfaces directly inherit the ancestor's clip
377 1042 // status.
378 // Avoid the overheads (including stack allocation and matrix initialization /copy) if we know that the scroll compensation doesn't need to be reset or adjus ted. 1043 subtree_should_be_clipped = ancestor_clips_subtree;
379 if (!layer->is_container_for_fixed_position_layers() && layer->scroll_delta( ).IsZero() && !layer->render_surface()) 1044 if (ancestor_clips_subtree)
380 return currentScrollCompensationMatrix; 1045 clip_rect_for_subtree = clip_rect_from_ancestor;
381 1046
382 // Start as identity matrix. 1047 // The surface's cached clipRect value propagates regardless of what
383 gfx::Transform nextScrollCompensationMatrix; 1048 // clipping goes on between layers here.
384 1049 clip_rect_for_subtree_in_descendant_space =
385 // If this layer is not a container, then it inherits the existing scroll co mpensations. 1050 clip_rect_from_ancestor_in_descendant_space;
386 if (!layer->is_container_for_fixed_position_layers()) 1051
387 nextScrollCompensationMatrix = currentScrollCompensationMatrix; 1052 // Layers that are not their own render_target will render into the target
388 1053 // of their nearest ancestor.
389 // If the current layer has a non-zero scrollDelta, then we should compute i ts local scrollCompensation 1054 layer_draw_properties.render_target = layer->parent()->render_target();
390 // and accumulate it to the nextScrollCompensationMatrix. 1055 }
391 if (!layer->scroll_delta().IsZero()) { 1056
392 gfx::Transform scrollCompensationForThisLayer = computeScrollCompensatio nForThisLayer(layer, parentMatrix); 1057 if (adjust_text_aa)
393 nextScrollCompensationMatrix.PreconcatTransform(scrollCompensationForThi sLayer); 1058 layer_draw_properties.can_use_lcd_text = layer_can_use_lcd_text;
1059
1060 gfx::Rect rect_in_target_space = ToEnclosingRect(
1061 MathUtil::MapClippedRect(layer->draw_transform(), content_rect));
1062
1063 if (LayerClipsSubtree(layer)) {
1064 subtree_should_be_clipped = true;
1065 if (ancestor_clips_subtree && !layer->render_surface()) {
1066 clip_rect_for_subtree = clip_rect_from_ancestor;
1067 clip_rect_for_subtree.Intersect(rect_in_target_space);
1068 } else {
1069 clip_rect_for_subtree = rect_in_target_space;
394 } 1070 }
395 1071 }
396 // If the layer created its own renderSurface, we have to adjust nextScrollC ompensationMatrix. 1072
397 // The adjustment allows us to continue using the scrollCompensation on the next surface. 1073 // Flatten to 2D if the layer doesn't preserve 3D.
398 // Step 1 (right-most in the math): transform from the new surface to the o riginal ancestor surface 1074 if (!layer->preserves_3d())
399 // Step 2: apply the scroll compensation 1075 sublayer_matrix.FlattenTo2d();
400 // Step 3: transform back to the new surface. 1076
401 if (layer->render_surface() && !nextScrollCompensationMatrix.IsIdentity()) { 1077 // Apply the sublayer transform at the anchor point of the layer.
402 gfx::Transform inverseSurfaceDrawTransform(gfx::Transform::kSkipInitiali zation); 1078 if (!layer->sublayer_transform().IsIdentity()) {
403 if (!layer->render_surface()->draw_transform().GetInverse(&inverseSurfac eDrawTransform)) { 1079 sublayer_matrix.Translate(layer->anchor_point().x() * bounds.width(),
404 // TODO(shawnsingh): Either we need to handle uninvertible transform s 1080 layer->anchor_point().y() * bounds.height());
405 // here, or DCHECK that the transform is invertible. 1081 sublayer_matrix.PreconcatTransform(layer->sublayer_transform());
406 } 1082 sublayer_matrix.Translate(-layer->anchor_point().x() * bounds.width(),
407 nextScrollCompensationMatrix = inverseSurfaceDrawTransform * nextScrollC ompensationMatrix * layer->render_surface()->draw_transform(); 1083 -layer->anchor_point().y() * bounds.height());
1084 }
1085
1086 LayerList& descendants =
1087 (layer->render_surface() ? layer->render_surface()->layer_list()
1088 : *layer_list);
1089
1090 // Any layers that are appended after this point are in the layer's subtree
1091 // and should be included in the sorting process.
1092 size_t sorting_start_index = descendants.size();
1093
1094 if (!LayerShouldBeSkipped(layer))
1095 descendants.push_back(layer);
1096
1097 gfx::Transform next_scroll_compensation_matrix =
1098 ComputeScrollCompensationMatrixForChildren(
1099 layer, parent_matrix, current_scroll_compensation_matrix);
1100
1101 gfx::Rect accumulated_drawable_content_rect_of_children;
1102 for (size_t i = 0; i < layer->children().size(); ++i) {
1103 LayerType* child =
1104 LayerTreeHostCommon::get_child_as_raw_ptr(layer->children(), i);
1105 gfx::Rect drawable_content_rect_of_child_subtree;
1106 CalculateDrawPropertiesInternal<LayerType, LayerList, RenderSurfaceType>(
1107 child,
1108 sublayer_matrix,
1109 next_hierarchy_matrix,
1110 next_scroll_compensation_matrix,
1111 clip_rect_for_subtree,
1112 clip_rect_for_subtree_in_descendant_space,
1113 subtree_should_be_clipped,
1114 nearest_ancestor_that_moves_pixels,
1115 render_surface_layer_list,
1116 &descendants,
1117 layer_sorter,
1118 max_texture_size,
1119 device_scale_factor,
1120 page_scale_factor,
1121 subtree_can_use_lcd_text,
1122 &drawable_content_rect_of_child_subtree,
1123 update_tile_priorities);
1124 if (!drawable_content_rect_of_child_subtree.IsEmpty()) {
1125 accumulated_drawable_content_rect_of_children.Union(
1126 drawable_content_rect_of_child_subtree);
1127 if (child->render_surface())
1128 descendants.push_back(child);
408 } 1129 }
409 1130 }
410 return nextScrollCompensationMatrix; 1131
411 } 1132 if (layer->render_surface() && !IsRootLayer(layer) &&
412 1133 layer->render_surface()->layer_list().empty()) {
413 template<typename LayerType> 1134 RemoveSurfaceForEarlyExit(layer, render_surface_layer_list);
414 static inline void CalculateContentsScale(LayerType* layer, float contentsScale, bool animating_transform_to_screen) 1135 return;
415 { 1136 }
416 layer->CalculateContentsScale( 1137
417 contentsScale, 1138 // Compute the total drawableContentRect for this subtree (the rect is in
418 animating_transform_to_screen, 1139 // targetSurface space).
419 &layer->draw_properties().contents_scale_x, 1140 gfx::Rect local_drawable_content_rect_of_subtree =
420 &layer->draw_properties().contents_scale_y, 1141 accumulated_drawable_content_rect_of_children;
421 &layer->draw_properties().content_bounds); 1142 if (layer->DrawsContent())
422 1143 local_drawable_content_rect_of_subtree.Union(rect_in_target_space);
423 LayerType* maskLayer = layer->mask_layer(); 1144 if (subtree_should_be_clipped)
424 if (maskLayer) 1145 local_drawable_content_rect_of_subtree.Intersect(clip_rect_for_subtree);
425 { 1146
426 maskLayer->CalculateContentsScale( 1147 // Compute the layer's drawable content rect (the rect is in targetSurface
427 contentsScale, 1148 // space).
428 animating_transform_to_screen, 1149 layer_draw_properties.drawable_content_rect = rect_in_target_space;
429 &maskLayer->draw_properties().contents_scale_x, 1150 if (subtree_should_be_clipped) {
430 &maskLayer->draw_properties().contents_scale_y, 1151 layer_draw_properties.drawable_content_rect.
431 &maskLayer->draw_properties().content_bounds); 1152 Intersect(clip_rect_for_subtree);
1153 }
1154
1155 // Tell the layer the rect that is clipped by. In theory we could use a
1156 // tighter clipRect here (drawableContentRect), but that actually does not
1157 // reduce how much would be drawn, and instead it would create unnecessary
1158 // changes to scissor state affecting GPU performance.
1159 layer_draw_properties.is_clipped = subtree_should_be_clipped;
1160 if (subtree_should_be_clipped) {
1161 layer_draw_properties.clip_rect = clip_rect_for_subtree;
1162 } else {
1163 // Initialize the clipRect to a safe value that will not clip the
1164 // layer, just in case clipping is still accidentally used.
1165 layer_draw_properties.clip_rect = rect_in_target_space;
1166 }
1167
1168 // Compute the layer's visible content rect (the rect is in content space)
1169 layer_draw_properties.visible_content_rect = CalculateVisibleContentRect(
1170 layer, clip_rect_for_subtree_in_descendant_space, rect_in_target_space);
1171
1172 // Compute the remaining properties for the render surface, if the layer has
1173 // one.
1174 if (IsRootLayer(layer)) {
1175 // The root layer's surface's content_rect is always the entire viewport.
1176 DCHECK(layer->render_surface());
1177 layer->render_surface()->SetContentRect(clip_rect_from_ancestor);
1178 } else if (layer->render_surface() && !IsRootLayer(layer)) {
1179 RenderSurfaceType* render_surface = layer->render_surface();
1180 gfx::Rect clipped_content_rect = local_drawable_content_rect_of_subtree;
1181
1182 // Don't clip if the layer is reflected as the reflection shouldn't be
1183 // clipped. If the layer is animating, then the surface's transform to
1184 // its target is not known on the main thread, and we should not use it
1185 // to clip.
1186 if (!layer->replica_layer() && TransformToParentIsKnown(layer)) {
1187 // Note, it is correct to use ancestor_clips_subtree here, because we are
1188 // looking at this layer's render_surface, not the layer itself.
1189 if (ancestor_clips_subtree && !clipped_content_rect.IsEmpty()) {
1190 gfx::Rect surface_clip_rect = LayerTreeHostCommon::CalculateVisibleRect(
1191 render_surface->clip_rect(),
1192 clipped_content_rect,
1193 render_surface->draw_transform());
1194 clipped_content_rect.Intersect(surface_clip_rect);
1195 }
432 } 1196 }
433 1197
434 LayerType* replicaMaskLayer = layer->replica_layer() ? layer->replica_layer( )->mask_layer() : 0; 1198 // The RenderSurfaceImpl backing texture cannot exceed the maximum supported
435 if (replicaMaskLayer) 1199 // texture size.
436 { 1200 clipped_content_rect.set_width(
437 replicaMaskLayer->CalculateContentsScale( 1201 std::min(clipped_content_rect.width(), max_texture_size));
438 contentsScale, 1202 clipped_content_rect.set_height(
439 animating_transform_to_screen, 1203 std::min(clipped_content_rect.height(), max_texture_size));
440 &replicaMaskLayer->draw_properties().contents_scale_x, 1204
441 &replicaMaskLayer->draw_properties().contents_scale_y, 1205 if (clipped_content_rect.IsEmpty()) {
442 &replicaMaskLayer->draw_properties().content_bounds); 1206 render_surface->ClearLayerLists();
1207 RemoveSurfaceForEarlyExit(layer, render_surface_layer_list);
1208 return;
443 } 1209 }
444 } 1210
445 1211 render_surface->SetContentRect(clipped_content_rect);
446 static inline void updateLayerContentsScale(LayerImpl* layer, const gfx::Transfo rm& combinedTransform, float deviceScaleFactor, float pageScaleFactor, bool anim ating_transform_to_screen) 1212
447 { 1213 // The owning layer's screen_space_transform has a scale from content to
448 gfx::Vector2dF transformScale = MathUtil::ComputeTransform2dScaleComponents( combinedTransform, deviceScaleFactor * pageScaleFactor); 1214 // layer space which we need to undo and replace with a scale from the
449 float contentsScale = std::max(transformScale.x(), transformScale.y()); 1215 // surface's subtree into layer space.
450 CalculateContentsScale(layer, contentsScale, animating_transform_to_screen); 1216 gfx::Transform screen_space_transform = layer->screen_space_transform();
451 } 1217 screen_space_transform.Scale(
452 1218 layer->contents_scale_x() / render_surface_sublayer_scale.x(),
453 static inline void updateLayerContentsScale(Layer* layer, const gfx::Transform& combinedTransform, float deviceScaleFactor, float pageScaleFactor, bool animatin g_transform_to_screen) 1219 layer->contents_scale_y() / render_surface_sublayer_scale.y());
454 { 1220 render_surface->SetScreenSpaceTransform(screen_space_transform);
455 float rasterScale = layer->raster_scale(); 1221
456 1222 if (layer->replica_layer()) {
457 if (layer->automatically_compute_raster_scale()) { 1223 gfx::Transform surface_origin_to_replica_origin_transform;
458 gfx::Vector2dF transformScale = MathUtil::ComputeTransform2dScaleCompone nts(combinedTransform, 0.f); 1224 surface_origin_to_replica_origin_transform.Scale(
459 float combinedScale = std::max(transformScale.x(), transformScale.y()); 1225 render_surface_sublayer_scale.x(), render_surface_sublayer_scale.y());
460 float idealRasterScale = combinedScale / deviceScaleFactor; 1226 surface_origin_to_replica_origin_transform.Translate(
461 if (!layer->bounds_contain_page_scale()) 1227 layer->replica_layer()->position().x() +
462 idealRasterScale /= pageScaleFactor; 1228 layer->replica_layer()->anchor_point().x() * bounds.width(),
463 1229 layer->replica_layer()->position().y() +
464 bool needToSetRasterScale = !rasterScale; 1230 layer->replica_layer()->anchor_point().y() * bounds.height());
465 1231 surface_origin_to_replica_origin_transform.PreconcatTransform(
466 // If we've previously saved a rasterScale but the ideal changes, things are unpredictable and we should just use 1. 1232 layer->replica_layer()->transform());
467 if (rasterScale && rasterScale != 1.f && idealRasterScale != rasterScale ) { 1233 surface_origin_to_replica_origin_transform.Translate(
468 idealRasterScale = 1.f; 1234 -layer->replica_layer()->anchor_point().x() * bounds.width(),
469 needToSetRasterScale = true; 1235 -layer->replica_layer()->anchor_point().y() * bounds.height());
470 } 1236 surface_origin_to_replica_origin_transform.Scale(
471 1237 1.0 / render_surface_sublayer_scale.x(),
472 if (needToSetRasterScale) { 1238 1.0 / render_surface_sublayer_scale.y());
473 bool useAndSaveIdealScale = idealRasterScale >= 1.f && !animating_tr ansform_to_screen; 1239
474 if (useAndSaveIdealScale) { 1240 // Compute the replica's "originTransform" that maps from the replica's
475 rasterScale = idealRasterScale; 1241 // origin space to the target surface origin space.
476 layer->SetRasterScale(rasterScale); 1242 gfx::Transform replica_origin_transform =
477 } 1243 layer->render_surface()->draw_transform() *
478 } 1244 surface_origin_to_replica_origin_transform;
1245 render_surface->SetReplicaDrawTransform(replica_origin_transform);
1246
1247 // Compute the replica's "screen_space_transform" that maps from the
1248 // replica's origin space to the screen's origin space.
1249 gfx::Transform replica_screen_space_transform =
1250 layer->render_surface()->screen_space_transform() *
1251 surface_origin_to_replica_origin_transform;
1252 render_surface->SetReplicaScreenSpaceTransform(
1253 replica_screen_space_transform);
479 } 1254 }
480 1255 }
481 if (!rasterScale) 1256
482 rasterScale = 1.f; 1257 if (update_tile_priorities)
483 1258 UpdateTilePrioritiesForLayer(layer);
484 float contentsScale = rasterScale * deviceScaleFactor; 1259
485 if (!layer->bounds_contain_page_scale()) 1260 // If neither this layer nor any of its children were added, early out.
486 contentsScale *= pageScaleFactor; 1261 if (sorting_start_index == descendants.size())
487 1262 return;
488 CalculateContentsScale(layer, contentsScale, animating_transform_to_screen); 1263
489 } 1264 // If preserves-3d then sort all the descendants in 3D so that they can be
490 1265 // drawn from back to front. If the preserves-3d property is also set on the
491 template<typename LayerType, typename LayerList> 1266 // parent then skip the sorting as the parent will sort all the descendants
492 static inline void removeSurfaceForEarlyExit(LayerType* layerToRemove, LayerList & renderSurfaceLayerList) 1267 // anyway.
493 { 1268 if (layer_sorter && descendants.size() && layer->preserves_3d() &&
494 DCHECK(layerToRemove->render_surface()); 1269 (!layer->parent() || !layer->parent()->preserves_3d())) {
495 // Technically, we know that the layer we want to remove should be 1270 SortLayers(descendants.begin() + sorting_start_index,
496 // at the back of the renderSurfaceLayerList. However, we have had 1271 descendants.end(),
497 // bugs before that added unnecessary layers here 1272 layer_sorter);
498 // (https://bugs.webkit.org/show_bug.cgi?id=74147), but that causes 1273 }
499 // things to crash. So here we proactively remove any additional 1274
500 // layers from the end of the list. 1275 if (layer->render_surface()) {
501 while (renderSurfaceLayerList.back() != layerToRemove) { 1276 *drawable_content_rect_of_subtree =
502 renderSurfaceLayerList.back()->ClearRenderSurface(); 1277 gfx::ToEnclosingRect(layer->render_surface()->DrawableContentRect());
503 renderSurfaceLayerList.pop_back(); 1278 } else {
504 } 1279 *drawable_content_rect_of_subtree = local_drawable_content_rect_of_subtree;
505 DCHECK(renderSurfaceLayerList.back() == layerToRemove); 1280 }
506 renderSurfaceLayerList.pop_back(); 1281
507 layerToRemove->ClearRenderSurface(); 1282 if (layer->HasContributingDelegatedRenderPasses()) {
508 } 1283 layer->render_target()->render_surface()->
509 1284 AddContributingDelegatedRenderPassLayer(layer);
510 // Recursively walks the layer tree to compute any information that is needed 1285 }
511 // before doing the main recursion. 1286 }
512 template<typename LayerType> 1287
513 static void preCalculateMetaInformation(LayerType* layer) 1288 void LayerTreeHostCommon::CalculateDrawProperties(
514 { 1289 Layer* root_layer,
515 if (layer->HasDelegatedContent()) { 1290 gfx::Size device_viewport_size,
516 // Layers with delegated content need to be treated as if they have as m any children as the number 1291 float device_scale_factor,
517 // of layers they own delegated quads for. Since we don't know this numb er right now, we choose 1292 float page_scale_factor,
518 // one that acts like infinity for our purposes. 1293 int max_texture_size,
519 layer->draw_properties().num_descendants_that_draw_content = 1000; 1294 bool can_use_lcd_text,
520 layer->draw_properties().descendants_can_clip_selves = false; 1295 std::vector<scoped_refptr<Layer> >* render_surface_layer_list) {
521 return; 1296 gfx::Rect total_drawable_content_rect;
522 } 1297 gfx::Transform identity_matrix;
523 1298 gfx::Transform device_scale_transform;
524 int numDescendantsThatDrawContent = 0; 1299 device_scale_transform.Scale(device_scale_factor, device_scale_factor);
525 bool descendantsCanClipSelves = true; 1300 std::vector<scoped_refptr<Layer> > dummy_layer_list;
526 bool sublayerTransformPreventsClip = !layer->sublayer_transform().IsPositive ScaleOrTranslation(); 1301
527 1302 // The root layer's render_surface should receive the deviceViewport as the
528 for (size_t i = 0; i < layer->children().size(); ++i) { 1303 // initial clipRect.
529 LayerType* childLayer = layer->children()[i]; 1304 bool subtree_should_be_clipped = true;
530 preCalculateMetaInformation<LayerType>(childLayer); 1305 gfx::Rect device_viewport_rect(gfx::Point(), device_viewport_size);
531 1306 bool update_tile_priorities = false;
532 numDescendantsThatDrawContent += childLayer->DrawsContent() ? 1 : 0; 1307
533 numDescendantsThatDrawContent += childLayer->draw_properties().num_desce ndants_that_draw_content; 1308 // This function should have received a root layer.
534 1309 DCHECK(IsRootLayer(root_layer));
535 if ((childLayer->DrawsContent() && !childLayer->CanClipSelf()) || 1310
536 !childLayer->draw_properties().descendants_can_clip_selves || 1311 PreCalculateMetaInformation<Layer>(root_layer);
537 sublayerTransformPreventsClip || 1312 CalculateDrawPropertiesInternal<Layer,
538 !childLayer->transform().IsPositiveScaleOrTranslation()) 1313 std::vector<scoped_refptr<Layer> >,
539 descendantsCanClipSelves = false; 1314 RenderSurface>(root_layer,
540 } 1315 device_scale_transform,
541 1316 identity_matrix,
542 layer->draw_properties().num_descendants_that_draw_content = numDescendantsT hatDrawContent; 1317 identity_matrix,
543 layer->draw_properties().descendants_can_clip_selves = descendantsCanClipSel ves; 1318 device_viewport_rect,
544 } 1319 device_viewport_rect,
545 1320 subtree_should_be_clipped,
546 static void roundTranslationComponents(gfx::Transform* transform) 1321 NULL,
547 { 1322 render_surface_layer_list,
548 transform->matrix().setDouble(0, 3, MathUtil::Round(transform->matrix().getD ouble(0, 3))); 1323 &dummy_layer_list,
549 transform->matrix().setDouble(1, 3, MathUtil::Round(transform->matrix().getD ouble(1, 3))); 1324 NULL,
550 } 1325 max_texture_size,
551 1326 device_scale_factor,
552 // Recursively walks the layer tree starting at the given node and computes all the 1327 page_scale_factor,
553 // necessary transformations, clipRects, render surfaces, etc. 1328 can_use_lcd_text,
554 template<typename LayerType, typename LayerList, typename RenderSurfaceType> 1329 &total_drawable_content_rect,
555 static void calculateDrawPropertiesInternal(LayerType* layer, const gfx::Transfo rm& parentMatrix, 1330 update_tile_priorities);
556 const gfx::Transform& fullHierarchyMatrix, const gfx::Transform& currentScro llCompensationMatrix, 1331
557 const gfx::Rect& clipRectFromAncestor, const gfx::Rect& clipRectFromAncestor InDescendantSpace, bool ancestorClipsSubtree, 1332 // The dummy layer list should not have been used.
558 RenderSurfaceType* nearestAncestorThatMovesPixels, LayerList& renderSurfaceL ayerList, LayerList& layerList, 1333 DCHECK_EQ(dummy_layer_list.size(), 0);
559 LayerSorter* layerSorter, int maxTextureSize, float deviceScaleFactor, float pageScaleFactor, bool subtreeCanUseLCDText, 1334 // A root layer render_surface should always exist after
560 gfx::Rect& drawableContentRectOfSubtree, bool updateTilePriorities) 1335 // calculateDrawProperties.
561 { 1336 DCHECK(root_layer->render_surface());
562 // This function computes the new matrix transformations recursively for thi s 1337 }
563 // layer and all its descendants. It also computes the appropriate render su rfaces. 1338
564 // Some important points to remember: 1339 void LayerTreeHostCommon::CalculateDrawProperties(
565 // 1340 LayerImpl* root_layer,
566 // 0. Here, transforms are notated in Matrix x Vector order, and in words we describe what 1341 gfx::Size device_viewport_size,
567 // the transform does from left to right. 1342 float device_scale_factor,
568 // 1343 float page_scale_factor,
569 // 1. In our terminology, the "layer origin" refers to the top-left corner o f a layer, and the 1344 int max_texture_size,
570 // positive Y-axis points downwards. This interpretation is valid because the orthographic 1345 bool can_use_lcd_text,
571 // projection applied at draw time flips the Y axis appropriately. 1346 std::vector<LayerImpl*>* render_surface_layer_list,
572 // 1347 bool update_tile_priorities) {
573 // 2. The anchor point, when given as a PointF object, is specified in "unit layer space", 1348 gfx::Rect total_drawable_content_rect;
574 // where the bounds of the layer map to [0, 1]. However, as a Transform o bject, 1349 gfx::Transform identity_matrix;
575 // the transform to the anchor point is specified in "layer space", where the bounds 1350 gfx::Transform device_scale_transform;
576 // of the layer map to [bounds.width(), bounds.height()]. 1351 device_scale_transform.Scale(device_scale_factor, device_scale_factor);
577 // 1352 std::vector<LayerImpl*> dummy_layer_list;
578 // 3. Definition of various transforms used: 1353 LayerSorter layer_sorter;
579 // M[parent] is the parent matrix, with respect to the nearest render surface, passed down recursively. 1354
580 // M[root] is the full hierarchy, with respect to the root, passed do wn recursively. 1355 // The root layer's render_surface should receive the deviceViewport as the
581 // Tr[origin] is the translation matrix from the parent's origin to t his layer's origin. 1356 // initial clipRect.
582 // Tr[origin2anchor] is the translation from the layer's origin to it s anchor point 1357 bool subtree_should_be_clipped = true;
583 // Tr[origin2center] is the translation from the layer's origin to it s center 1358 gfx::Rect device_viewport_rect(gfx::Point(), device_viewport_size);
584 // M[layer] is the layer's matrix (applied at the anchor point) 1359
585 // M[sublayer] is the layer's sublayer transform (also applied at the layer's anchor point) 1360 // This function should have received a root layer.
586 // S[layer2content] is the ratio of a layer's ContentBounds() to its Bounds(). 1361 DCHECK(IsRootLayer(root_layer));
587 // 1362
588 // Some composite transforms can help in understanding the sequence of tr ansforms: 1363 PreCalculateMetaInformation<LayerImpl>(root_layer);
589 // compositeLayerTransform = Tr[origin2anchor] * M[layer] * Tr[origin 2anchor].inverse() 1364 CalculateDrawPropertiesInternal<LayerImpl,
590 // compositeSublayerTransform = Tr[origin2anchor] * M[sublayer] * Tr[ origin2anchor].inverse() 1365 std::vector<LayerImpl*>,
591 // 1366 RenderSurfaceImpl>(
592 // 4. When a layer (or render surface) is drawn, it is drawn into a "target render surface". Therefore the draw 1367 root_layer,
593 // transform does not necessarily transform from screen space to local la yer space. Instead, the draw transform 1368 device_scale_transform,
594 // is the transform between the "target render surface space" and local l ayer space. Note that render surfaces, 1369 identity_matrix,
595 // except for the root, also draw themselves into a different target rend er surface, and so their draw 1370 identity_matrix,
596 // transform and origin transforms are also described with respect to the target. 1371 device_viewport_rect,
597 // 1372 device_viewport_rect,
598 // Using these definitions, then: 1373 subtree_should_be_clipped,
599 // 1374 NULL,
600 // The draw transform for the layer is: 1375 render_surface_layer_list,
601 // M[draw] = M[parent] * Tr[origin] * compositeLayerTransform * S[lay er2content] 1376 &dummy_layer_list,
602 // = M[parent] * Tr[layer->Position() + anchor] * M[layer] * Tr[anchor2origin] * S[layer2content] 1377 &layer_sorter,
603 // 1378 max_texture_size,
604 // Interpreting the math left-to-right, this transforms from the laye r's render surface to the origin of the layer in content space. 1379 device_scale_factor,
605 // 1380 page_scale_factor,
606 // The screen space transform is: 1381 can_use_lcd_text,
607 // M[screenspace] = M[root] * Tr[origin] * compositeLayerTransform * S[layer2content] 1382 &total_drawable_content_rect,
608 // = M[root] * Tr[layer->Position() + anchor] * M[laye r] * Tr[anchor2origin] * S[layer2content] 1383 update_tile_priorities);
609 // 1384
610 // Interpreting the math left-to-right, this transforms from the root render surface's content space to the origin of the layer in content space. 1385 // The dummy layer list should not have been used.
611 // 1386 DCHECK_EQ(dummy_layer_list.size(), 0);
612 // The transform hierarchy that is passed on to children (i.e. the child's p arentMatrix) is: 1387 // A root layer render_surface should always exist after
613 // M[parent]_for_child = M[parent] * Tr[origin] * compositeLayerTrans form * compositeSublayerTransform 1388 // calculateDrawProperties.
614 // = M[parent] * Tr[layer->Position() + anchor] * M[layer] * Tr[anchor2origin] * compositeSublayerTransform 1389 DCHECK(root_layer->render_surface());
615 // 1390 }
616 // and a similar matrix for the full hierarchy with respect to the ro ot. 1391
617 // 1392 static bool PointHitsRect(
618 // Finally, note that the final matrix used by the shader for the layer is P * M[draw] * S . This final product 1393 gfx::PointF screen_space_point,
619 // is computed in drawTexturedQuad(), where: 1394 const gfx::Transform& local_space_to_screen_space_transform,
620 // P is the projection matrix 1395 gfx::RectF local_space_rect) {
621 // S is the scale adjustment (to scale up a canonical quad to the lay er's size) 1396 // If the transform is not invertible, then assume that this point doesn't hit
622 // 1397 // this rect.
623 // When a render surface has a replica layer, that layer's transform is used to draw a second copy of the surface. 1398 gfx::Transform inverse_local_space_to_screen_space(
624 // gfx::Transforms named here are relative to the surface, unless they speci fy they are relative to the replica layer. 1399 gfx::Transform::kSkipInitialization);
625 // 1400 if (!local_space_to_screen_space_transform.GetInverse(
626 // We will denote a scale by device scale S[deviceScale] 1401 &inverse_local_space_to_screen_space))
627 //
628 // The render surface draw transform to its target surface origin is:
629 // M[surfaceDraw] = M[owningLayer->Draw]
630 //
631 // The render surface origin transform to its the root (screen space) origin is:
632 // M[surface2root] = M[owningLayer->screenspace] * S[deviceScale].in verse()
633 //
634 // The replica draw transform to its target surface origin is:
635 // M[replicaDraw] = S[deviceScale] * M[surfaceDraw] * Tr[replica->Pos ition() + replica->anchor()] * Tr[replica] * Tr[origin2anchor].inverse() * S[con tentsScale].inverse()
636 //
637 // The replica draw transform to the root (screen space) origin is:
638 // M[replica2root] = M[surface2root] * Tr[replica->Position()] * Tr[r eplica] * Tr[origin2anchor].inverse()
639 //
640
641 // If we early-exit anywhere in this function, the drawableContentRect of th is subtree should be considered empty.
642 drawableContentRectOfSubtree = gfx::Rect();
643
644 // The root layer cannot skip calcDrawProperties.
645 if (!isRootLayer(layer) && subtreeShouldBeSkipped(layer))
646 return;
647
648 // As this function proceeds, these are the properties for the current
649 // layer that actually get computed. To avoid unnecessary copies
650 // (particularly for matrices), we do computations directly on these values
651 // when possible.
652 DrawProperties<LayerType, RenderSurfaceType>& layerDrawProperties = layer->d raw_properties();
653
654 gfx::Rect clipRectForSubtree;
655 bool subtreeShouldBeClipped = false;
656
657 // This value is cached on the stack so that we don't have to inverse-projec t
658 // the surface's clipRect redundantly for every layer. This value is the
659 // same as the surface's clipRect, except that instead of being described
660 // in the target surface space (i.e. the ancestor surface space), it is
661 // described in the current surface space.
662 gfx::Rect clipRectForSubtreeInDescendantSpace;
663
664 float accumulatedDrawOpacity = layer->opacity();
665 bool animatingOpacityToTarget = layer->OpacityIsAnimating();
666 bool animatingOpacityToScreen = animatingOpacityToTarget;
667 if (layer->parent()) {
668 accumulatedDrawOpacity *= layer->parent()->draw_opacity();
669 animatingOpacityToTarget |= layer->parent()->draw_opacity_is_animating() ;
670 animatingOpacityToScreen |= layer->parent()->screen_space_opacity_is_ani mating();
671 }
672
673 bool animatingTransformToTarget = layer->TransformIsAnimating();
674 bool animating_transform_to_screen = animatingTransformToTarget;
675 if (layer->parent()) {
676 animatingTransformToTarget |= layer->parent()->draw_transform_is_animati ng();
677 animating_transform_to_screen |= layer->parent()->screen_space_transform _is_animating();
678 }
679
680 gfx::Size bounds = layer->bounds();
681 gfx::PointF anchorPoint = layer->anchor_point();
682 gfx::PointF position = layer->position() - layer->scroll_delta();
683
684 gfx::Transform combinedTransform = parentMatrix;
685 if (!layer->transform().IsIdentity()) {
686 // LT = Tr[origin] * Tr[origin2anchor]
687 combinedTransform.Translate3d(position.x() + anchorPoint.x() * bounds.wi dth(), position.y() + anchorPoint.y() * bounds.height(), layer->anchor_point_z() );
688 // LT = Tr[origin] * Tr[origin2anchor] * M[layer]
689 combinedTransform.PreconcatTransform(layer->transform());
690 // LT = Tr[origin] * Tr[origin2anchor] * M[layer] * Tr[anchor2origin]
691 combinedTransform.Translate3d(-anchorPoint.x() * bounds.width(), -anchor Point.y() * bounds.height(), -layer->anchor_point_z());
692 } else {
693 combinedTransform.Translate(position.x(), position.y());
694 }
695
696 // The layer's contentsSize is determined from the combinedTransform, which then informs the
697 // layer's drawTransform.
698 updateLayerContentsScale(layer, combinedTransform, deviceScaleFactor, pageSc aleFactor, animating_transform_to_screen);
699
700 // If there is a transformation from the impl thread then it should be at
701 // the start of the combinedTransform, but we don't want it to affect the
702 // computation of contentsScale above.
703 // Note carefully: this is Concat, not Preconcat (implTransform * combinedTr ansform).
704 combinedTransform.ConcatTransform(layer->impl_transform());
705
706 if (!animatingTransformToTarget && layer->scrollable() && combinedTransform. IsScaleOrTranslation()) {
707 // Align the scrollable layer's position to screen space pixels to avoid blurriness.
708 // To avoid side-effects, do this only if the transform is simple.
709 roundTranslationComponents(&combinedTransform);
710 }
711
712 if (layer->fixed_to_container_layer()) {
713 // Special case: this layer is a composited fixed-position layer; we nee d to
714 // explicitly compensate for all ancestors' nonzero scrollDeltas to keep this layer
715 // fixed correctly.
716 // Note carefully: this is Concat, not Preconcat (currentScrollCompensat ion * combinedTransform).
717 combinedTransform.ConcatTransform(currentScrollCompensationMatrix);
718 }
719
720 // The drawTransform that gets computed below is effectively the layer's dra wTransform, unless
721 // the layer itself creates a renderSurface. In that case, the renderSurface re-parents the transforms.
722 layerDrawProperties.target_space_transform = combinedTransform;
723 // M[draw] = M[parent] * LT * S[layer2content]
724 layerDrawProperties.target_space_transform.Scale(1.0 / layer->contents_scale _x(), 1.0 / layer->contents_scale_y());
725
726 // layerScreenSpaceTransform represents the transform between root layer's " screen space" and local content space.
727 layerDrawProperties.screen_space_transform = fullHierarchyMatrix;
728 if (!layer->preserves_3d())
729 layerDrawProperties.screen_space_transform.FlattenTo2d();
730 layerDrawProperties.screen_space_transform.PreconcatTransform(layerDrawPrope rties.target_space_transform);
731
732 // Adjusting text AA method during animation may cause repaints, which in-tu rn causes jank.
733 bool adjustTextAA = !animatingOpacityToScreen && !animating_transform_to_scr een;
734 // To avoid color fringing, LCD text should only be used on opaque layers wi th just integral translation.
735 bool layerCanUseLCDText = subtreeCanUseLCDText &&
736 (accumulatedDrawOpacity == 1.0) &&
737 layerDrawProperties.target_space_transform.IsIdent ityOrIntegerTranslation();
738
739 gfx::RectF contentRect(gfx::PointF(), layer->content_bounds());
740
741 // fullHierarchyMatrix is the matrix that transforms objects between screen space (except projection matrix) and the most recent RenderSurfaceImpl's space.
742 // nextHierarchyMatrix will only change if this layer uses a new RenderSurfa ceImpl, otherwise remains the same.
743 gfx::Transform nextHierarchyMatrix = fullHierarchyMatrix;
744 gfx::Transform sublayerMatrix;
745
746 gfx::Vector2dF renderSurfaceSublayerScale = MathUtil::ComputeTransform2dScal eComponents(combinedTransform, deviceScaleFactor * pageScaleFactor);
747
748 if (subtreeShouldRenderToSeparateSurface(layer, combinedTransform.IsScaleOrT ranslation())) {
749 // Check back-face visibility before continuing with this surface and it s subtree
750 if (!layer->double_sided() && transformToParentIsKnown(layer) && isSurfa ceBackFaceVisible(layer, combinedTransform))
751 return;
752
753 if (!layer->render_surface())
754 layer->CreateRenderSurface();
755
756 RenderSurfaceType* renderSurface = layer->render_surface();
757 renderSurface->ClearLayerLists();
758
759 // The owning layer's draw transform has a scale from content to layer
760 // space which we do not want; so here we use the combinedTransform
761 // instead of the drawTransform. However, we do need to add a different
762 // scale factor that accounts for the surface's pixel dimensions.
763 combinedTransform.Scale(1 / renderSurfaceSublayerScale.x(), 1 / renderSu rfaceSublayerScale.y());
764 renderSurface->SetDrawTransform(combinedTransform);
765
766 // The owning layer's transform was re-parented by the surface, so the l ayer's new drawTransform
767 // only needs to scale the layer to surface space.
768 layerDrawProperties.target_space_transform.MakeIdentity();
769 layerDrawProperties.target_space_transform.Scale(renderSurfaceSublayerSc ale.x() / layer->contents_scale_x(), renderSurfaceSublayerScale.y() / layer->con tents_scale_y());
770
771 // Inside the surface's subtree, we scale everything to the owning layer 's scale.
772 // The sublayer matrix transforms layer rects into target
773 // surface content space.
774 DCHECK(sublayerMatrix.IsIdentity());
775 sublayerMatrix.Scale(renderSurfaceSublayerScale.x(), renderSurfaceSublay erScale.y());
776
777 // The opacity value is moved from the layer to its surface, so that the entire subtree properly inherits opacity.
778 renderSurface->SetDrawOpacity(accumulatedDrawOpacity);
779 renderSurface->SetDrawOpacityIsAnimating(animatingOpacityToTarget);
780 animatingOpacityToTarget = false;
781 layerDrawProperties.opacity = 1;
782 layerDrawProperties.opacity_is_animating = animatingOpacityToTarget;
783 layerDrawProperties.screen_space_opacity_is_animating = animatingOpacity ToScreen;
784
785 renderSurface->SetTargetSurfaceTransformsAreAnimating(animatingTransform ToTarget);
786 renderSurface->SetScreenSpaceTransformsAreAnimating(animating_transform_ to_screen);
787 animatingTransformToTarget = false;
788 layerDrawProperties.target_space_transform_is_animating = animatingTrans formToTarget;
789 layerDrawProperties.screen_space_transform_is_animating = animating_tran sform_to_screen;
790
791 // Update the aggregate hierarchy matrix to include the transform of the
792 // newly created RenderSurfaceImpl.
793 nextHierarchyMatrix.PreconcatTransform(renderSurface->draw_transform());
794
795 // The new renderSurface here will correctly clip the entire subtree. So , we do
796 // not need to continue propagating the clipping state further down the tree. This
797 // way, we can avoid transforming clipRects from ancestor target surface space to
798 // current target surface space that could cause more w < 0 headaches.
799 subtreeShouldBeClipped = false;
800
801 if (layer->mask_layer()) {
802 DrawProperties<LayerType, RenderSurfaceType>& maskLayerDrawPropertie s = layer->mask_layer()->draw_properties();
803 maskLayerDrawProperties.render_target = layer;
804 maskLayerDrawProperties.visible_content_rect = gfx::Rect(gfx::Point( ), layer->content_bounds());
805 }
806
807 if (layer->replica_layer() && layer->replica_layer()->mask_layer()) {
808 DrawProperties<LayerType, RenderSurfaceType>& replicaMaskDrawPropert ies = layer->replica_layer()->mask_layer()->draw_properties();
809 replicaMaskDrawProperties.render_target = layer;
810 replicaMaskDrawProperties.visible_content_rect = gfx::Rect(gfx::Poin t(), layer->content_bounds());
811 }
812
813 // FIXME: make this smarter for the SkImageFilter case (check for
814 // pixel-moving filters)
815 if (layer->filters().hasFilterThatMovesPixels() || layer->filter())
816 nearestAncestorThatMovesPixels = renderSurface;
817
818 // The render surface clipRect is expressed in the space where this surf ace draws, i.e. the same space as clipRectFromAncestor.
819 renderSurface->SetIsClipped(ancestorClipsSubtree);
820 if (ancestorClipsSubtree) {
821 renderSurface->SetClipRect(clipRectFromAncestor);
822
823 gfx::Transform inverseSurfaceDrawTransform(gfx::Transform::kSkipInit ialization);
824 if (!renderSurface->draw_transform().GetInverse(&inverseSurfaceDrawT ransform)) {
825 // TODO(shawnsingh): Either we need to handle uninvertible trans forms
826 // here, or DCHECK that the transform is invertible.
827 }
828 clipRectForSubtreeInDescendantSpace = gfx::ToEnclosingRect(MathUtil: :ProjectClippedRect(inverseSurfaceDrawTransform, renderSurface->clip_rect()));
829 } else {
830 renderSurface->SetClipRect(gfx::Rect());
831 clipRectForSubtreeInDescendantSpace = clipRectFromAncestorInDescenda ntSpace;
832 }
833
834 renderSurface->SetNearestAncestorThatMovesPixels(nearestAncestorThatMove sPixels);
835
836 // If the new render surface is drawn translucent or with a non-integral translation
837 // then the subtree that gets drawn on this render surface cannot use LC D text.
838 subtreeCanUseLCDText = layerCanUseLCDText;
839
840 renderSurfaceLayerList.push_back(layer);
841 } else {
842 DCHECK(layer->parent());
843
844 // Note: layerDrawProperties.target_space_transform is computed above,
845 // before this if-else statement.
846 layerDrawProperties.target_space_transform_is_animating = animatingTrans formToTarget;
847 layerDrawProperties.screen_space_transform_is_animating = animating_tran sform_to_screen;
848 layerDrawProperties.opacity = accumulatedDrawOpacity;
849 layerDrawProperties.opacity_is_animating = animatingOpacityToTarget;
850 layerDrawProperties.screen_space_opacity_is_animating = animatingOpacity ToScreen;
851 sublayerMatrix = combinedTransform;
852
853 layer->ClearRenderSurface();
854
855 // Layers without renderSurfaces directly inherit the ancestor's clip st atus.
856 subtreeShouldBeClipped = ancestorClipsSubtree;
857 if (ancestorClipsSubtree)
858 clipRectForSubtree = clipRectFromAncestor;
859
860 // The surface's cached clipRect value propagates regardless of what cli pping goes on between layers here.
861 clipRectForSubtreeInDescendantSpace = clipRectFromAncestorInDescendantSp ace;
862
863 // Layers that are not their own renderTarget will render into the targe t of their nearest ancestor.
864 layerDrawProperties.render_target = layer->parent()->render_target();
865 }
866
867 if (adjustTextAA)
868 layerDrawProperties.can_use_lcd_text = layerCanUseLCDText;
869
870 gfx::Rect rectInTargetSpace = ToEnclosingRect(MathUtil::MapClippedRect(layer ->draw_transform(), contentRect));
871
872 if (layerClipsSubtree(layer)) {
873 subtreeShouldBeClipped = true;
874 if (ancestorClipsSubtree && !layer->render_surface()) {
875 clipRectForSubtree = clipRectFromAncestor;
876 clipRectForSubtree.Intersect(rectInTargetSpace);
877 } else
878 clipRectForSubtree = rectInTargetSpace;
879 }
880
881 // Flatten to 2D if the layer doesn't preserve 3D.
882 if (!layer->preserves_3d())
883 sublayerMatrix.FlattenTo2d();
884
885 // Apply the sublayer transform at the anchor point of the layer.
886 if (!layer->sublayer_transform().IsIdentity()) {
887 sublayerMatrix.Translate(layer->anchor_point().x() * bounds.width(), lay er->anchor_point().y() * bounds.height());
888 sublayerMatrix.PreconcatTransform(layer->sublayer_transform());
889 sublayerMatrix.Translate(-layer->anchor_point().x() * bounds.width(), -l ayer->anchor_point().y() * bounds.height());
890 }
891
892 LayerList& descendants = (layer->render_surface() ? layer->render_surface()- >layer_list() : layerList);
893
894 // Any layers that are appended after this point are in the layer's subtree and should be included in the sorting process.
895 unsigned sortingStartIndex = descendants.size();
896
897 if (!layerShouldBeSkipped(layer))
898 descendants.push_back(layer);
899
900 gfx::Transform nextScrollCompensationMatrix = computeScrollCompensationMatri xForChildren(layer, parentMatrix, currentScrollCompensationMatrix);;
901
902 gfx::Rect accumulatedDrawableContentRectOfChildren;
903 for (size_t i = 0; i < layer->children().size(); ++i) {
904 LayerType* child = LayerTreeHostCommon::getChildAsRawPtr(layer->children (), i);
905 gfx::Rect drawableContentRectOfChildSubtree;
906 calculateDrawPropertiesInternal<LayerType, LayerList, RenderSurfaceType> (child, sublayerMatrix, nextHierarchyMatrix, nextScrollCompensationMatrix,
907 clipRectForSubtree, clipRectForSubtreeInDescendantSpace, subtreeShouldBeClipped , nearestAncestorThatMovesPixels,
908 renderSurfaceLayerList, descendants, layerSorter, maxTextureSize, deviceScaleFa ctor, pageScaleFactor,
909 subtreeCanUseLCDText, drawableContentRectOfChildSubtree, updateTilePriorities);
910 if (!drawableContentRectOfChildSubtree.IsEmpty()) {
911 accumulatedDrawableContentRectOfChildren.Union(drawableContentRectOf ChildSubtree);
912 if (child->render_surface())
913 descendants.push_back(child);
914 }
915 }
916
917 if (layer->render_surface() && !isRootLayer(layer) && !layer->render_surface ()->layer_list().size()) {
918 removeSurfaceForEarlyExit(layer, renderSurfaceLayerList);
919 return;
920 }
921
922 // Compute the total drawableContentRect for this subtree (the rect is in ta rgetSurface space)
923 gfx::Rect localDrawableContentRectOfSubtree = accumulatedDrawableContentRect OfChildren;
924 if (layer->DrawsContent())
925 localDrawableContentRectOfSubtree.Union(rectInTargetSpace);
926 if (subtreeShouldBeClipped)
927 localDrawableContentRectOfSubtree.Intersect(clipRectForSubtree);
928
929 // Compute the layer's drawable content rect (the rect is in targetSurface s pace)
930 layerDrawProperties.drawable_content_rect = rectInTargetSpace;
931 if (subtreeShouldBeClipped)
932 layerDrawProperties.drawable_content_rect.Intersect(clipRectForSubtree);
933
934 // Tell the layer the rect that is clipped by. In theory we could use a
935 // tighter clipRect here (drawableContentRect), but that actually does not
936 // reduce how much would be drawn, and instead it would create unnecessary
937 // changes to scissor state affecting GPU performance.
938 layerDrawProperties.is_clipped = subtreeShouldBeClipped;
939 if (subtreeShouldBeClipped)
940 layerDrawProperties.clip_rect = clipRectForSubtree;
941 else {
942 // Initialize the clipRect to a safe value that will not clip the
943 // layer, just in case clipping is still accidentally used.
944 layerDrawProperties.clip_rect = rectInTargetSpace;
945 }
946
947 // Compute the layer's visible content rect (the rect is in content space)
948 layerDrawProperties.visible_content_rect = calculateVisibleContentRect(layer , clipRectForSubtreeInDescendantSpace, rectInTargetSpace);
949
950 // Compute the remaining properties for the render surface, if the layer has one.
951 if (isRootLayer(layer)) {
952 // The root layer's surface's contentRect is always the entire viewport.
953 DCHECK(layer->render_surface());
954 layer->render_surface()->SetContentRect(clipRectFromAncestor);
955 } else if (layer->render_surface() && !isRootLayer(layer)) {
956 RenderSurfaceType* renderSurface = layer->render_surface();
957 gfx::Rect clippedContentRect = localDrawableContentRectOfSubtree;
958
959 // Don't clip if the layer is reflected as the reflection shouldn't be
960 // clipped. If the layer is animating, then the surface's transform to
961 // its target is not known on the main thread, and we should not use it
962 // to clip.
963 if (!layer->replica_layer() && transformToParentIsKnown(layer)) {
964 // Note, it is correct to use ancestorClipsSubtree here, because we are looking at this layer's renderSurface, not the layer itself.
965 if (ancestorClipsSubtree && !clippedContentRect.IsEmpty()) {
966 gfx::Rect surfaceClipRect = LayerTreeHostCommon::calculateVisibl eRect(renderSurface->clip_rect(), clippedContentRect, renderSurface->draw_transf orm());
967 clippedContentRect.Intersect(surfaceClipRect);
968 }
969 }
970
971 // The RenderSurfaceImpl backing texture cannot exceed the maximum suppo rted
972 // texture size.
973 clippedContentRect.set_width(std::min(clippedContentRect.width(), maxTex tureSize));
974 clippedContentRect.set_height(std::min(clippedContentRect.height(), maxT extureSize));
975
976 if (clippedContentRect.IsEmpty()) {
977 renderSurface->ClearLayerLists();
978 removeSurfaceForEarlyExit(layer, renderSurfaceLayerList);
979 return;
980 }
981
982 renderSurface->SetContentRect(clippedContentRect);
983
984 // The owning layer's screenSpaceTransform has a scale from content to l ayer space which we need to undo and
985 // replace with a scale from the surface's subtree into layer space.
986 gfx::Transform screenSpaceTransform = layer->screen_space_transform();
987 screenSpaceTransform.Scale(layer->contents_scale_x() / renderSurfaceSubl ayerScale.x(), layer->contents_scale_y() / renderSurfaceSublayerScale.y());
988 renderSurface->SetScreenSpaceTransform(screenSpaceTransform);
989
990 if (layer->replica_layer()) {
991 gfx::Transform surfaceOriginToReplicaOriginTransform;
992 surfaceOriginToReplicaOriginTransform.Scale(renderSurfaceSublayerSca le.x(), renderSurfaceSublayerScale.y());
993 surfaceOriginToReplicaOriginTransform.Translate(layer->replica_layer ()->position().x() + layer->replica_layer()->anchor_point().x() * bounds.width() ,
994 layer->replica_layer ()->position().y() + layer->replica_layer()->anchor_point().y() * bounds.height( ));
995 surfaceOriginToReplicaOriginTransform.PreconcatTransform(layer->repl ica_layer()->transform());
996 surfaceOriginToReplicaOriginTransform.Translate(-layer->replica_laye r()->anchor_point().x() * bounds.width(), -layer->replica_layer()->anchor_point( ).y() * bounds.height());
997 surfaceOriginToReplicaOriginTransform.Scale(1 / renderSurfaceSublaye rScale.x(), 1 / renderSurfaceSublayerScale.y());
998
999 // Compute the replica's "originTransform" that maps from the replic a's origin space to the target surface origin space.
1000 gfx::Transform replicaOriginTransform = layer->render_surface()->dra w_transform() * surfaceOriginToReplicaOriginTransform;
1001 renderSurface->SetReplicaDrawTransform(replicaOriginTransform);
1002
1003 // Compute the replica's "screenSpaceTransform" that maps from the r eplica's origin space to the screen's origin space.
1004 gfx::Transform replicaScreenSpaceTransform = layer->render_surface() ->screen_space_transform() * surfaceOriginToReplicaOriginTransform;
1005 renderSurface->SetReplicaScreenSpaceTransform(replicaScreenSpaceTran sform);
1006 }
1007 }
1008
1009 if (updateTilePriorities)
1010 updateTilePrioritiesForLayer(layer);
1011
1012 // If neither this layer nor any of its children were added, early out.
1013 if (sortingStartIndex == descendants.size())
1014 return;
1015
1016 // If preserves-3d then sort all the descendants in 3D so that they can be
1017 // drawn from back to front. If the preserves-3d property is also set on the parent then
1018 // skip the sorting as the parent will sort all the descendants anyway.
1019 if (layerSorter && descendants.size() && layer->preserves_3d() && (!layer->p arent() || !layer->parent()->preserves_3d()))
1020 sortLayers(descendants.begin() + sortingStartIndex, descendants.end(), l ayerSorter);
1021
1022 if (layer->render_surface())
1023 drawableContentRectOfSubtree = gfx::ToEnclosingRect(layer->render_surfac e()->DrawableContentRect());
1024 else
1025 drawableContentRectOfSubtree = localDrawableContentRectOfSubtree;
1026
1027 if (layer->HasContributingDelegatedRenderPasses())
1028 layer->render_target()->render_surface()->AddContributingDelegatedRender PassLayer(layer);
1029 }
1030
1031 void LayerTreeHostCommon::calculateDrawProperties(Layer* rootLayer, const gfx::S ize& deviceViewportSize, float deviceScaleFactor, float pageScaleFactor, int max TextureSize, bool canUseLCDText, std::vector<scoped_refptr<Layer> >& renderSurfa ceLayerList)
1032 {
1033 gfx::Rect totalDrawableContentRect;
1034 gfx::Transform identityMatrix;
1035 gfx::Transform deviceScaleTransform;
1036 deviceScaleTransform.Scale(deviceScaleFactor, deviceScaleFactor);
1037 std::vector<scoped_refptr<Layer> > dummyLayerList;
1038
1039 // The root layer's renderSurface should receive the deviceViewport as the i nitial clipRect.
1040 bool subtreeShouldBeClipped = true;
1041 gfx::Rect deviceViewportRect(gfx::Point(), deviceViewportSize);
1042 bool updateTilePriorities = false;
1043
1044 // This function should have received a root layer.
1045 DCHECK(isRootLayer(rootLayer));
1046
1047 preCalculateMetaInformation<Layer>(rootLayer);
1048 calculateDrawPropertiesInternal<Layer, std::vector<scoped_refptr<Layer> >, R enderSurface>(
1049 rootLayer, deviceScaleTransform, identityMatrix, identityMatrix,
1050 deviceViewportRect, deviceViewportRect, subtreeShouldBeClipped, 0, rende rSurfaceLayerList,
1051 dummyLayerList, 0, maxTextureSize,
1052 deviceScaleFactor, pageScaleFactor, canUseLCDText, totalDrawableContentR ect,
1053 updateTilePriorities);
1054
1055 // The dummy layer list should not have been used.
1056 DCHECK(dummyLayerList.size() == 0);
1057 // A root layer renderSurface should always exist after calculateDrawPropert ies.
1058 DCHECK(rootLayer->render_surface());
1059 }
1060
1061 void LayerTreeHostCommon::calculateDrawProperties(LayerImpl* rootLayer, const gf x::Size& deviceViewportSize, float deviceScaleFactor, float pageScaleFactor, int maxTextureSize, bool canUseLCDText, std::vector<LayerImpl*>& renderSurfaceLayer List, bool updateTilePriorities)
1062 {
1063 gfx::Rect totalDrawableContentRect;
1064 gfx::Transform identityMatrix;
1065 gfx::Transform deviceScaleTransform;
1066 deviceScaleTransform.Scale(deviceScaleFactor, deviceScaleFactor);
1067 std::vector<LayerImpl*> dummyLayerList;
1068 LayerSorter layerSorter;
1069
1070 // The root layer's renderSurface should receive the deviceViewport as the i nitial clipRect.
1071 bool subtreeShouldBeClipped = true;
1072 gfx::Rect deviceViewportRect(gfx::Point(), deviceViewportSize);
1073
1074 // This function should have received a root layer.
1075 DCHECK(isRootLayer(rootLayer));
1076
1077 preCalculateMetaInformation<LayerImpl>(rootLayer);
1078 calculateDrawPropertiesInternal<LayerImpl, std::vector<LayerImpl*>, RenderSu rfaceImpl>(
1079 rootLayer, deviceScaleTransform, identityMatrix, identityMatrix,
1080 deviceViewportRect, deviceViewportRect, subtreeShouldBeClipped, 0, rende rSurfaceLayerList,
1081 dummyLayerList, &layerSorter, maxTextureSize,
1082 deviceScaleFactor, pageScaleFactor, canUseLCDText, totalDrawableContentR ect,
1083 updateTilePriorities);
1084
1085 // The dummy layer list should not have been used.
1086 DCHECK(dummyLayerList.size() == 0);
1087 // A root layer renderSurface should always exist after calculateDrawPropert ies.
1088 DCHECK(rootLayer->render_surface());
1089 }
1090
1091 static bool pointHitsRect(const gfx::PointF& screenSpacePoint, const gfx::Transf orm& localSpaceToScreenSpaceTransform, gfx::RectF localSpaceRect)
1092 {
1093 // If the transform is not invertible, then assume that this point doesn't h it this rect.
1094 gfx::Transform inverseLocalSpaceToScreenSpace(gfx::Transform::kSkipInitializ ation);
1095 if (!localSpaceToScreenSpaceTransform.GetInverse(&inverseLocalSpaceToScreenS pace))
1096 return false;
1097
1098 // Transform the hit test point from screen space to the local space of the given rect.
1099 bool clipped = false;
1100 gfx::PointF hitTestPointInLocalSpace = MathUtil::ProjectPoint(inverseLocalSp aceToScreenSpace, screenSpacePoint, &clipped);
1101
1102 // If projectPoint could not project to a valid value, then we assume that t his point doesn't hit this rect.
1103 if (clipped)
1104 return false;
1105
1106 return localSpaceRect.Contains(hitTestPointInLocalSpace);
1107 }
1108
1109 static bool pointHitsRegion(gfx::PointF screenSpacePoint, const gfx::Transform& screenSpaceTransform, const Region& layerSpaceRegion, float layerContentScaleX, float layerContentScaleY)
1110 {
1111 // If the transform is not invertible, then assume that this point doesn't h it this region.
1112 gfx::Transform inverseScreenSpaceTransform(gfx::Transform::kSkipInitializati on);
1113 if (!screenSpaceTransform.GetInverse(&inverseScreenSpaceTransform))
1114 return false;
1115
1116 // Transform the hit test point from screen space to the local space of the given region.
1117 bool clipped = false;
1118 gfx::PointF hitTestPointInContentSpace = MathUtil::ProjectPoint(inverseScree nSpaceTransform, screenSpacePoint, &clipped);
1119 gfx::PointF hitTestPointInLayerSpace = gfx::ScalePoint(hitTestPointInContent Space, 1 / layerContentScaleX, 1 / layerContentScaleY);
1120
1121 // If projectPoint could not project to a valid value, then we assume that t his point doesn't hit this region.
1122 if (clipped)
1123 return false;
1124
1125 return layerSpaceRegion.Contains(gfx::ToRoundedPoint(hitTestPointInLayerSpac e));
1126 }
1127
1128 static bool pointIsClippedBySurfaceOrClipRect(const gfx::PointF& screenSpacePoin t, LayerImpl* layer)
1129 {
1130 LayerImpl* current_layer = layer;
1131
1132 // Walk up the layer tree and hit-test any renderSurfaces and any layer clip Rects that are active.
1133 while (current_layer) {
1134 if (current_layer->render_surface() && !pointHitsRect(screenSpacePoint, current_layer->render_surface()->screen_space_transform(), current_layer->render _surface()->content_rect()))
1135 return true;
1136
1137 // Note that drawableContentRects are actually in targetSurface space, s o the transform we
1138 // have to provide is the target surface's screenSpaceTransform.
1139 LayerImpl* renderTarget = current_layer->render_target();
1140 if (layerClipsSubtree(current_layer) && !pointHitsRect(screenSpacePoint, renderTarget->render_surface()->screen_space_transform(), current_layer->drawab le_content_rect()))
1141 return true;
1142
1143 current_layer = current_layer->parent();
1144 }
1145
1146 // If we have finished walking all ancestors without having already exited, then the point is not clipped by any ancestors.
1147 return false; 1402 return false;
1148 } 1403
1149 1404 // Transform the hit test point from screen space to the local space of the
1150 LayerImpl* LayerTreeHostCommon::findLayerThatIsHitByPoint(const gfx::PointF& scr eenSpacePoint, const std::vector<LayerImpl*>& renderSurfaceLayerList) 1405 // given rect.
1151 { 1406 bool clipped = false;
1152 LayerImpl* foundLayer = 0; 1407 gfx::PointF hit_test_point_in_local_space = MathUtil::ProjectPoint(
1153 1408 inverse_local_space_to_screen_space, screen_space_point, &clipped);
1154 typedef LayerIterator<LayerImpl, std::vector<LayerImpl*>, RenderSurfaceImpl, LayerIteratorActions::FrontToBack> LayerIteratorType; 1409
1155 LayerIteratorType end = LayerIteratorType::End(&renderSurfaceLayerList); 1410 // If ProjectPoint could not project to a valid value, then we assume that
1156 1411 // this point doesn't hit this rect.
1157 for (LayerIteratorType it = LayerIteratorType::Begin(&renderSurfaceLayerList ); it != end; ++it) { 1412 if (clipped)
1158 // We don't want to consider renderSurfaces for hit testing. 1413 return false;
1159 if (!it.represents_itself()) 1414
1160 continue; 1415 return local_space_rect.Contains(hit_test_point_in_local_space);
1161 1416 }
1162 LayerImpl* current_layer = (*it); 1417
1163 1418 static bool PointHitsRegion(gfx::PointF screen_space_point,
1164 gfx::RectF contentRect(gfx::PointF(), current_layer->content_bounds()); 1419 const gfx::Transform& screen_space_transform,
1165 if (!pointHitsRect(screenSpacePoint, current_layer->screen_space_transfo rm(), contentRect)) 1420 const Region& layer_space_region,
1166 continue; 1421 float layer_content_scale_x,
1167 1422 float layer_content_scale_y) {
1168 // At this point, we think the point does hit the layer, but we need to walk up 1423 // If the transform is not invertible, then assume that this point doesn't hit
1169 // the parents to ensure that the layer was not clipped in such a way th at the 1424 // this region.
1170 // hit point actually should not hit the layer. 1425 gfx::Transform inverse_screen_space_transform(
1171 if (pointIsClippedBySurfaceOrClipRect(screenSpacePoint, current_layer)) 1426 gfx::Transform::kSkipInitialization);
1172 continue; 1427 if (!screen_space_transform.GetInverse(&inverse_screen_space_transform))
1173 1428 return false;
1174 // Skip the HUD layer. 1429
1175 if (current_layer == current_layer->layer_tree_impl()->hud_layer()) 1430 // Transform the hit test point from screen space to the local space of the
1176 continue; 1431 // given region.
1177 1432 bool clipped = false;
1178 foundLayer = current_layer; 1433 gfx::PointF hit_test_point_in_content_space = MathUtil::ProjectPoint(
1179 break; 1434 inverse_screen_space_transform, screen_space_point, &clipped);
1180 } 1435 gfx::PointF hit_test_point_in_layer_space =
1181 1436 gfx::ScalePoint(hit_test_point_in_content_space,
1182 // This can potentially return 0, which means the screenSpacePoint did not s uccessfully hit test any layers, not even the root layer. 1437 1.f / layer_content_scale_x,
1183 return foundLayer; 1438 1.f / layer_content_scale_y);
1184 } 1439
1185 1440 // If ProjectPoint could not project to a valid value, then we assume that
1186 LayerImpl* LayerTreeHostCommon::findLayerThatIsHitByPointInTouchHandlerRegion(co nst gfx::PointF& screenSpacePoint, const std::vector<LayerImpl*>& renderSurfaceL ayerList) 1441 // this point doesn't hit this region.
1187 { 1442 if (clipped)
1188 LayerImpl* foundLayer = 0; 1443 return false;
1189 1444
1190 typedef LayerIterator<LayerImpl, std::vector<LayerImpl*>, RenderSurfaceImpl, LayerIteratorActions::FrontToBack> LayerIteratorType; 1445 return layer_space_region.Contains(
1191 LayerIteratorType end = LayerIteratorType::End(&renderSurfaceLayerList); 1446 gfx::ToRoundedPoint(hit_test_point_in_layer_space));
1192 1447 }
1193 for (LayerIteratorType it = LayerIteratorType::Begin(&renderSurfaceLayerList ); it != end; ++it) { 1448
1194 // We don't want to consider renderSurfaces for hit testing. 1449 static bool PointIsClippedBySurfaceOrClipRect(gfx::PointF screen_space_point,
1195 if (!it.represents_itself()) 1450 LayerImpl* layer) {
1196 continue; 1451 LayerImpl* current_layer = layer;
1197 1452
1198 LayerImpl* current_layer = (*it); 1453 // Walk up the layer tree and hit-test any render_surfaces and any layer
1199 1454 // clip rects that are active.
1200 if (!layerHasTouchEventHandlersAt(screenSpacePoint, current_layer)) 1455 while (current_layer) {
1201 continue; 1456 if (current_layer->render_surface() &&
1202 1457 !PointHitsRect(
1203 foundLayer = current_layer; 1458 screen_space_point,
1204 break; 1459 current_layer->render_surface()->screen_space_transform(),
1205 } 1460 current_layer->render_surface()->content_rect()))
1206 1461 return true;
1207 // This can potentially return 0, which means the screenSpacePoint did not s uccessfully hit test any layers, not even the root layer. 1462
1208 return foundLayer; 1463 // Note that drawable content rects are actually in target surface space, so
1209 } 1464 // the transform we have to provide is the target surface's
1210 1465 // screen_space_transform.
1211 bool LayerTreeHostCommon::layerHasTouchEventHandlersAt(const gfx::PointF& screen SpacePoint, LayerImpl* layerImpl) { 1466 LayerImpl* render_target = current_layer->render_target();
1212 if (layerImpl->touch_event_handler_region().IsEmpty()) 1467 if (LayerClipsSubtree(current_layer) &&
1213 return false; 1468 !PointHitsRect(
1214 1469 screen_space_point,
1215 if (!pointHitsRegion(screenSpacePoint, layerImpl->screen_space_transform(), la yerImpl->touch_event_handler_region(), layerImpl->contents_scale_x(), layerImpl- >contents_scale_y())) 1470 render_target->render_surface()->screen_space_transform(),
1216 return false;; 1471 current_layer->drawable_content_rect()))
1217 1472 return true;
1218 // At this point, we think the point does hit the touch event handler region o n the layer, but we need to walk up 1473
1219 // the parents to ensure that the layer was not clipped in such a way that the 1474 current_layer = current_layer->parent();
1220 // hit point actually should not hit the layer. 1475 }
1221 if (pointIsClippedBySurfaceOrClipRect(screenSpacePoint, layerImpl)) 1476
1222 return false; 1477 // If we have finished walking all ancestors without having already exited,
1478 // then the point is not clipped by any ancestors.
1479 return false;
1480 }
1481
1482 LayerImpl* LayerTreeHostCommon::FindLayerThatIsHitByPoint(
1483 gfx::PointF screen_space_point,
1484 const std::vector<LayerImpl*>& render_surface_layer_list) {
1485 LayerImpl* found_layer = NULL;
1486
1487 typedef LayerIterator<LayerImpl,
1488 std::vector<LayerImpl*>,
1489 RenderSurfaceImpl,
1490 LayerIteratorActions::FrontToBack> LayerIteratorType;
1491 LayerIteratorType end = LayerIteratorType::End(&render_surface_layer_list);
1492
1493 for (LayerIteratorType
1494 it = LayerIteratorType::Begin(&render_surface_layer_list);
1495 it != end;
1496 ++it) {
1497 // We don't want to consider render_surfaces for hit testing.
1498 if (!it.represents_itself())
1499 continue;
1500
1501 LayerImpl* current_layer = (*it);
1502
1503 gfx::RectF content_rect(gfx::PointF(), current_layer->content_bounds());
1504 if (!PointHitsRect(screen_space_point,
1505 current_layer->screen_space_transform(),
1506 content_rect))
1507 continue;
1508
1509 // At this point, we think the point does hit the layer, but we need to walk
1510 // up the parents to ensure that the layer was not clipped in such a way
1511 // that the hit point actually should not hit the layer.
1512 if (PointIsClippedBySurfaceOrClipRect(screen_space_point, current_layer))
1513 continue;
1514
1515 // Skip the HUD layer.
1516 if (current_layer == current_layer->layer_tree_impl()->hud_layer())
1517 continue;
1518
1519 found_layer = current_layer;
1520 break;
1521 }
1522
1523 // This can potentially return NULL, which means the screen_space_point did
1524 // not successfully hit test any layers, not even the root layer.
1525 return found_layer;
1526 }
1527
1528 LayerImpl* LayerTreeHostCommon::FindLayerThatIsHitByPointInTouchHandlerRegion(
1529 gfx::PointF screen_space_point,
1530 const std::vector<LayerImpl*>& render_surface_layer_list) {
1531 LayerImpl* found_layer = NULL;
1532
1533 typedef LayerIterator<LayerImpl,
1534 std::vector<LayerImpl*>,
1535 RenderSurfaceImpl,
1536 LayerIteratorActions::FrontToBack> LayerIteratorType;
1537 LayerIteratorType end = LayerIteratorType::End(&render_surface_layer_list);
1538
1539 for (LayerIteratorType
1540 it = LayerIteratorType::Begin(&render_surface_layer_list);
1541 it != end;
1542 ++it) {
1543 // We don't want to consider render_surfaces for hit testing.
1544 if (!it.represents_itself())
1545 continue;
1546
1547 LayerImpl* current_layer = (*it);
1548
1549 if (!LayerHasTouchEventHandlersAt(screen_space_point, current_layer))
1550 continue;
1551
1552 found_layer = current_layer;
1553 break;
1554 }
1555
1556 // This can potentially return NULL, which means the screen_space_point did
1557 // not successfully hit test any layers, not even the root layer.
1558 return found_layer;
1559 }
1560
1561 bool LayerTreeHostCommon::LayerHasTouchEventHandlersAt(
1562 gfx::PointF screen_space_point,
1563 LayerImpl* layer_impl) {
1564 if (layer_impl->touch_event_handler_region().IsEmpty())
1565 return false;
1566
1567 if (!PointHitsRegion(screen_space_point,
1568 layer_impl->screen_space_transform(),
1569 layer_impl->touch_event_handler_region(),
1570 layer_impl->contents_scale_x(),
1571 layer_impl->contents_scale_y()))
1572 return false;
1573
1574 // At this point, we think the point does hit the touch event handler region
1575 // on the layer, but we need to walk up the parents to ensure that the layer
1576 // was not clipped in such a way that the hit point actually should not hit
1577 // the layer.
1578 if (PointIsClippedBySurfaceOrClipRect(screen_space_point, layer_impl))
1579 return false;
1223 1580
1224 return true; 1581 return true;
1225 } 1582 }
1226 } // namespace cc 1583 } // namespace cc
OLDNEW
« no previous file with comments | « cc/trees/layer_tree_host_common.h ('k') | cc/trees/layer_tree_host_common_unittest.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698