Removed data compression UMA from ProxyService
[chromium-blink-merge.git] / cc / trees / layer_sorter.cc
blob8f3454e8514957ff47c5d194b62b4e65e64efa63
1 // Copyright 2011 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "cc/trees/layer_sorter.h"
7 #include <algorithm>
8 #include <deque>
9 #include <limits>
10 #include <vector>
12 #include "base/logging.h"
13 #include "cc/base/math_util.h"
14 #include "cc/layers/render_surface_impl.h"
15 #include "ui/gfx/transform.h"
17 namespace cc {
19 // This epsilon is used to determine if two layers are too close to each other
20 // to be able to tell which is in front of the other. It's a relative epsilon
21 // so it is robust to changes in scene scale. This value was chosen by picking
22 // a value near machine epsilon and then increasing it until the flickering on
23 // the test scene went away.
24 const float k_layer_epsilon = 1e-4f;
26 // Tests if two edges defined by their endpoints (a,b) and (c,d) intersect.
27 // Returns true and the point of intersection if they do and false otherwise.
28 static bool EdgeEdgeTest(const gfx::PointF& a,
29 const gfx::PointF& b,
30 const gfx::PointF& c,
31 const gfx::PointF& d,
32 gfx::PointF* r) {
33 gfx::Vector2dF u = b - a;
34 gfx::Vector2dF v = d - c;
35 gfx::Vector2dF w = a - c;
37 float denom = static_cast<float>(gfx::CrossProduct(u, v));
39 // If denom == 0 then the edges are parallel. While they could be overlapping
40 // we don't bother to check here as the we'll find their intersections from
41 // the corner to quad tests.
42 if (!denom)
43 return false;
45 float s = static_cast<float>(gfx::CrossProduct(v, w)) / denom;
46 if (s < 0.f || s > 1.f)
47 return false;
49 float t = static_cast<float>(gfx::CrossProduct(u, w)) / denom;
50 if (t < 0.f || t > 1.f)
51 return false;
53 u.Scale(s);
54 *r = a + u;
55 return true;
58 GraphNode::GraphNode(LayerImpl* layer_impl)
59 : layer(layer_impl),
60 incoming_edge_weight(0.f) {}
62 GraphNode::~GraphNode() {}
64 LayerSorter::LayerSorter()
65 : z_range_(0.f) {}
67 LayerSorter::~LayerSorter() {}
69 static float CheckFloatingPointNumericAccuracy(float a, float b) {
70 float abs_dif = std::abs(b - a);
71 float abs_max = std::max(std::abs(b), std::abs(a));
72 // Check to see if we've got a result with a reasonable amount of error.
73 return abs_dif / abs_max;
76 // Checks whether layer "a" draws on top of layer "b". The weight value returned
77 // is an indication of the maximum z-depth difference between the layers or zero
78 // if the layers are found to be intesecting (some features are in front and
79 // some are behind).
80 LayerSorter::ABCompareResult LayerSorter::CheckOverlap(LayerShape* a,
81 LayerShape* b,
82 float z_threshold,
83 float* weight) {
84 *weight = 0.f;
86 // Early out if the projected bounds don't overlap.
87 if (!a->projected_bounds.Intersects(b->projected_bounds))
88 return None;
90 gfx::PointF aPoints[4] = { a->projected_quad.p1(),
91 a->projected_quad.p2(),
92 a->projected_quad.p3(),
93 a->projected_quad.p4() };
94 gfx::PointF bPoints[4] = { b->projected_quad.p1(),
95 b->projected_quad.p2(),
96 b->projected_quad.p3(),
97 b->projected_quad.p4() };
99 // Make a list of points that inside both layer quad projections.
100 std::vector<gfx::PointF> overlap_points;
102 // Check all four corners of one layer against the other layer's quad.
103 for (int i = 0; i < 4; ++i) {
104 if (a->projected_quad.Contains(bPoints[i]))
105 overlap_points.push_back(bPoints[i]);
106 if (b->projected_quad.Contains(aPoints[i]))
107 overlap_points.push_back(aPoints[i]);
110 // Check all the edges of one layer for intersection with the other layer's
111 // edges.
112 gfx::PointF r;
113 for (int ea = 0; ea < 4; ++ea)
114 for (int eb = 0; eb < 4; ++eb)
115 if (EdgeEdgeTest(aPoints[ea], aPoints[(ea + 1) % 4],
116 bPoints[eb], bPoints[(eb + 1) % 4],
117 &r))
118 overlap_points.push_back(r);
120 if (overlap_points.empty())
121 return None;
123 // Check the corresponding layer depth value for all overlap points to
124 // determine which layer is in front.
125 float max_positive = 0.f;
126 float max_negative = 0.f;
128 // This flag tracks the existance of a numerically accurate seperation
129 // between two layers. If there is no accurate seperation, the layers
130 // cannot be effectively sorted.
131 bool accurate = false;
133 for (size_t o = 0; o < overlap_points.size(); o++) {
134 float za = a->LayerZFromProjectedPoint(overlap_points[o]);
135 float zb = b->LayerZFromProjectedPoint(overlap_points[o]);
137 // Here we attempt to avoid numeric issues with layers that are too
138 // close together. If we have 2-sided quads that are very close
139 // together then we will draw them in document order to avoid
140 // flickering. The correct solution is for the content maker to turn
141 // on back-face culling or move the quads apart (if they're not two
142 // sides of one object).
143 if (CheckFloatingPointNumericAccuracy(za, zb) > k_layer_epsilon)
144 accurate = true;
146 float diff = za - zb;
147 if (diff > max_positive)
148 max_positive = diff;
149 if (diff < max_negative)
150 max_negative = diff;
153 // If we can't tell which should come first, we use document order.
154 if (!accurate)
155 return ABeforeB;
157 float max_diff =
158 std::abs(max_positive) > std::abs(max_negative) ?
159 max_positive : max_negative;
161 // If the results are inconsistent (and the z difference substantial to rule
162 // out numerical errors) then the layers are intersecting. We will still
163 // return an order based on the maximum depth difference but with an edge
164 // weight of zero these layers will get priority if a graph cycle is present
165 // and needs to be broken.
166 if (max_positive > z_threshold && max_negative < -z_threshold)
167 *weight = 0.f;
168 else
169 *weight = std::abs(max_diff);
171 // Maintain relative order if the layers have the same depth at all
172 // intersection points.
173 if (max_diff <= 0.f)
174 return ABeforeB;
176 return BBeforeA;
179 LayerShape::LayerShape() {}
181 LayerShape::LayerShape(float width,
182 float height,
183 const gfx::Transform& draw_transform) {
184 gfx::QuadF layer_quad(gfx::RectF(0.f, 0.f, width, height));
186 // Compute the projection of the layer quad onto the z = 0 plane.
188 gfx::PointF clipped_quad[8];
189 int num_vertices_in_clipped_quad;
190 MathUtil::MapClippedQuad(draw_transform,
191 layer_quad,
192 clipped_quad,
193 &num_vertices_in_clipped_quad);
195 if (num_vertices_in_clipped_quad < 3) {
196 projected_bounds = gfx::RectF();
197 return;
200 projected_bounds =
201 MathUtil::ComputeEnclosingRectOfVertices(clipped_quad,
202 num_vertices_in_clipped_quad);
204 // NOTE: it will require very significant refactoring and overhead to deal
205 // with generalized polygons or multiple quads per layer here. For the sake of
206 // layer sorting it is equally correct to take a subsection of the polygon
207 // that can be made into a quad. This will only be incorrect in the case of
208 // intersecting layers, which are not supported yet anyway.
209 projected_quad.set_p1(clipped_quad[0]);
210 projected_quad.set_p2(clipped_quad[1]);
211 projected_quad.set_p3(clipped_quad[2]);
212 if (num_vertices_in_clipped_quad >= 4) {
213 projected_quad.set_p4(clipped_quad[3]);
214 } else {
215 // This will be a degenerate quad that is actually a triangle.
216 projected_quad.set_p4(clipped_quad[2]);
219 // Compute the normal of the layer's plane.
220 bool clipped = false;
221 gfx::Point3F c1 =
222 MathUtil::MapPoint(draw_transform, gfx::Point3F(0.f, 0.f, 0.f), &clipped);
223 gfx::Point3F c2 =
224 MathUtil::MapPoint(draw_transform, gfx::Point3F(0.f, 1.f, 0.f), &clipped);
225 gfx::Point3F c3 =
226 MathUtil::MapPoint(draw_transform, gfx::Point3F(1.f, 0.f, 0.f), &clipped);
227 // TODO(shawnsingh): Deal with clipping.
228 gfx::Vector3dF c12 = c2 - c1;
229 gfx::Vector3dF c13 = c3 - c1;
230 layer_normal = gfx::CrossProduct(c13, c12);
232 transform_origin = c1;
235 LayerShape::~LayerShape() {}
237 // Returns the Z coordinate of a point on the layer that projects
238 // to point p which lies on the z = 0 plane. It does it by computing the
239 // intersection of a line starting from p along the Z axis and the plane
240 // of the layer.
241 float LayerShape::LayerZFromProjectedPoint(const gfx::PointF& p) const {
242 gfx::Vector3dF z_axis(0.f, 0.f, 1.f);
243 gfx::Vector3dF w = gfx::Point3F(p) - transform_origin;
245 float d = gfx::DotProduct(layer_normal, z_axis);
246 float n = -gfx::DotProduct(layer_normal, w);
248 // Check if layer is parallel to the z = 0 axis which will make it
249 // invisible and hence returning zero is fine.
250 if (!d)
251 return 0.f;
253 // The intersection point would be given by:
254 // p + (n / d) * u but since we are only interested in the
255 // z coordinate and p's z coord is zero, all we need is the value of n/d.
256 return n / d;
259 void LayerSorter::CreateGraphNodes(LayerImplList::iterator first,
260 LayerImplList::iterator last) {
261 DVLOG(2) << "Creating graph nodes:";
262 float min_z = FLT_MAX;
263 float max_z = -FLT_MAX;
264 for (LayerImplList::const_iterator it = first; it < last; it++) {
265 nodes_.push_back(GraphNode(*it));
266 GraphNode& node = nodes_.at(nodes_.size() - 1);
267 RenderSurfaceImpl* render_surface = node.layer->render_surface();
268 if (!node.layer->DrawsContent() && !render_surface)
269 continue;
271 DVLOG(2) << "Layer " << node.layer->id() <<
272 " (" << node.layer->bounds().width() <<
273 " x " << node.layer->bounds().height() << ")";
275 gfx::Transform draw_transform;
276 float layer_width, layer_height;
277 if (render_surface) {
278 draw_transform = render_surface->draw_transform();
279 layer_width = render_surface->content_rect().width();
280 layer_height = render_surface->content_rect().height();
281 } else {
282 draw_transform = node.layer->draw_transform();
283 layer_width = node.layer->content_bounds().width();
284 layer_height = node.layer->content_bounds().height();
287 node.shape = LayerShape(layer_width, layer_height, draw_transform);
289 max_z = std::max(max_z, node.shape.transform_origin.z());
290 min_z = std::min(min_z, node.shape.transform_origin.z());
293 z_range_ = std::abs(max_z - min_z);
296 void LayerSorter::CreateGraphEdges() {
297 DVLOG(2) << "Edges:";
298 // Fraction of the total z_range below which z differences
299 // are not considered reliable.
300 const float z_threshold_factor = 0.01f;
301 float z_threshold = z_range_ * z_threshold_factor;
303 for (size_t na = 0; na < nodes_.size(); na++) {
304 GraphNode& node_a = nodes_[na];
305 if (!node_a.layer->DrawsContent() && !node_a.layer->render_surface())
306 continue;
307 for (size_t nb = na + 1; nb < nodes_.size(); nb++) {
308 GraphNode& node_b = nodes_[nb];
309 if (!node_b.layer->DrawsContent() && !node_b.layer->render_surface())
310 continue;
311 float weight = 0.f;
312 ABCompareResult overlap_result = CheckOverlap(&node_a.shape,
313 &node_b.shape,
314 z_threshold,
315 &weight);
316 GraphNode* start_node = NULL;
317 GraphNode* end_node = NULL;
318 if (overlap_result == ABeforeB) {
319 start_node = &node_a;
320 end_node = &node_b;
321 } else if (overlap_result == BBeforeA) {
322 start_node = &node_b;
323 end_node = &node_a;
326 if (start_node) {
327 DVLOG(2) << start_node->layer->id() << " -> " << end_node->layer->id();
328 edges_.push_back(GraphEdge(start_node, end_node, weight));
333 for (size_t i = 0; i < edges_.size(); i++) {
334 GraphEdge& edge = edges_[i];
335 active_edges_[&edge] = &edge;
336 edge.from->outgoing.push_back(&edge);
337 edge.to->incoming.push_back(&edge);
338 edge.to->incoming_edge_weight += edge.weight;
342 // Finds and removes an edge from the list by doing a swap with the
343 // last element of the list.
344 void LayerSorter::RemoveEdgeFromList(GraphEdge* edge,
345 std::vector<GraphEdge*>* list) {
346 std::vector<GraphEdge*>::iterator iter =
347 std::find(list->begin(), list->end(), edge);
348 DCHECK(iter != list->end());
349 list->erase(iter);
352 // Sorts the given list of layers such that they can be painted in a
353 // back-to-front order. Sorting produces correct results for non-intersecting
354 // layers that don't have cyclical order dependencies. Cycles and intersections
355 // are broken (somewhat) aribtrarily. Sorting of layers is done via a
356 // topological sort of a directed graph whose nodes are the layers themselves.
357 // An edge from node A to node B signifies that layer A needs to be drawn before
358 // layer B. If A and B have no dependency between each other, then we preserve
359 // the ordering of those layers as they were in the original list.
361 // The draw order between two layers is determined by projecting the two
362 // triangles making up each layer quad to the Z = 0 plane, finding points of
363 // intersection between the triangles and backprojecting those points to the
364 // plane of the layer to determine the corresponding Z coordinate. The layer
365 // with the lower Z coordinate (farther from the eye) needs to be rendered
366 // first.
368 // If the layer projections don't intersect, then no edges (dependencies) are
369 // created between them in the graph. HOWEVER, in this case we still need to
370 // preserve the ordering of the original list of layers, since that list should
371 // already have proper z-index ordering of layers.
373 void LayerSorter::Sort(LayerImplList::iterator first,
374 LayerImplList::iterator last) {
375 DVLOG(2) << "Sorting start ----";
376 CreateGraphNodes(first, last);
378 CreateGraphEdges();
380 std::vector<GraphNode*> sorted_list;
381 std::deque<GraphNode*> no_incoming_edge_node_list;
383 // Find all the nodes that don't have incoming edges.
384 for (NodeList::iterator la = nodes_.begin(); la < nodes_.end(); la++) {
385 if (!la->incoming.size())
386 no_incoming_edge_node_list.push_back(&(*la));
389 DVLOG(2) << "Sorted list: ";
390 while (active_edges_.size() || no_incoming_edge_node_list.size()) {
391 while (no_incoming_edge_node_list.size()) {
392 // It is necessary to preserve the existing ordering of layers, when there
393 // are no explicit dependencies (because this existing ordering has
394 // correct z-index/layout ordering). To preserve this ordering, we process
395 // Nodes in the same order that they were added to the list.
396 GraphNode* from_node = no_incoming_edge_node_list.front();
397 no_incoming_edge_node_list.pop_front();
399 // Add it to the final list.
400 sorted_list.push_back(from_node);
402 DVLOG(2) << from_node->layer->id() << ", ";
404 // Remove all its outgoing edges from the graph.
405 for (size_t i = 0; i < from_node->outgoing.size(); i++) {
406 GraphEdge* outgoing_edge = from_node->outgoing[i];
408 active_edges_.erase(outgoing_edge);
409 RemoveEdgeFromList(outgoing_edge, &outgoing_edge->to->incoming);
410 outgoing_edge->to->incoming_edge_weight -= outgoing_edge->weight;
412 if (!outgoing_edge->to->incoming.size())
413 no_incoming_edge_node_list.push_back(outgoing_edge->to);
415 from_node->outgoing.clear();
418 if (!active_edges_.size())
419 break;
421 // If there are still active edges but the list of nodes without incoming
422 // edges is empty then we have run into a cycle. Break the cycle by finding
423 // the node with the smallest overall incoming edge weight and use it. This
424 // will favor nodes that have zero-weight incoming edges i.e. layers that
425 // are being occluded by a layer that intersects them.
426 float min_incoming_edge_weight = FLT_MAX;
427 GraphNode* next_node = NULL;
428 for (size_t i = 0; i < nodes_.size(); i++) {
429 if (nodes_[i].incoming.size() &&
430 nodes_[i].incoming_edge_weight < min_incoming_edge_weight) {
431 min_incoming_edge_weight = nodes_[i].incoming_edge_weight;
432 next_node = &nodes_[i];
435 DCHECK(next_node);
436 // Remove all its incoming edges.
437 for (size_t e = 0; e < next_node->incoming.size(); e++) {
438 GraphEdge* incoming_edge = next_node->incoming[e];
440 active_edges_.erase(incoming_edge);
441 RemoveEdgeFromList(incoming_edge, &incoming_edge->from->outgoing);
443 next_node->incoming.clear();
444 next_node->incoming_edge_weight = 0.f;
445 no_incoming_edge_node_list.push_back(next_node);
446 DVLOG(2) << "Breaking cycle by cleaning up incoming edges from " <<
447 next_node->layer->id() <<
448 " (weight = " << min_incoming_edge_weight << ")";
451 // Note: The original elements of the list are in no danger of having their
452 // ref count go to zero here as they are all nodes of the layer hierarchy and
453 // are kept alive by their parent nodes.
454 int count = 0;
455 for (LayerImplList::iterator it = first; it < last; it++)
456 *it = sorted_list[count++]->layer;
458 DVLOG(2) << "Sorting end ----";
460 nodes_.clear();
461 edges_.clear();
462 active_edges_.clear();
465 } // namespace cc