1 // Copyright 2012 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/base/math_util.h"
11 #include "base/values.h"
12 #include "ui/gfx/quad_f.h"
13 #include "ui/gfx/rect.h"
14 #include "ui/gfx/rect_conversions.h"
15 #include "ui/gfx/rect_f.h"
16 #include "ui/gfx/transform.h"
17 #include "ui/gfx/vector2d_f.h"
21 const double MathUtil::kPiDouble
= 3.14159265358979323846;
22 const float MathUtil::kPiFloat
= 3.14159265358979323846f
;
24 static HomogeneousCoordinate
ProjectHomogeneousPoint(
25 const gfx::Transform
& transform
,
27 // In this case, the layer we are trying to project onto is perpendicular to
28 // ray (point p and z-axis direction) that we are trying to project. This
29 // happens when the layer is rotated so that it is infinitesimally thin, or
30 // when it is co-planar with the camera origin -- i.e. when the layer is
32 if (!transform
.matrix().get(2, 2))
33 return HomogeneousCoordinate(0.0, 0.0, 0.0, 1.0);
35 SkMScalar z
= -(transform
.matrix().get(2, 0) * p
.x() +
36 transform
.matrix().get(2, 1) * p
.y() +
37 transform
.matrix().get(2, 3)) /
38 transform
.matrix().get(2, 2);
39 HomogeneousCoordinate
result(p
.x(), p
.y(), z
, 1.0);
40 transform
.matrix().mapMScalars(result
.vec
, result
.vec
);
44 static HomogeneousCoordinate
MapHomogeneousPoint(
45 const gfx::Transform
& transform
,
46 const gfx::Point3F
& p
) {
47 HomogeneousCoordinate
result(p
.x(), p
.y(), p
.z(), 1.0);
48 transform
.matrix().mapMScalars(result
.vec
, result
.vec
);
52 static HomogeneousCoordinate
ComputeClippedPointForEdge(
53 const HomogeneousCoordinate
& h1
,
54 const HomogeneousCoordinate
& h2
) {
55 // Points h1 and h2 form a line in 4d, and any point on that line can be
56 // represented as an interpolation between h1 and h2:
57 // p = (1-t) h1 + (t) h2
59 // We want to compute point p such that p.w == epsilon, where epsilon is a
60 // small non-zero number. (but the smaller the number is, the higher the risk
62 // To do this, we solve for t in the following equation:
63 // p.w = epsilon = (1-t) * h1.w + (t) * h2.w
65 // Once paramter t is known, the rest of p can be computed via
66 // p = (1-t) h1 + (t) h2.
68 // Technically this is a special case of the following assertion, but its a
69 // good idea to keep it an explicit sanity check here.
70 DCHECK_NE(h2
.w(), h1
.w());
71 // Exactly one of h1 or h2 (but not both) must be on the negative side of the
72 // w plane when this is called.
73 DCHECK(h1
.ShouldBeClipped() ^ h2
.ShouldBeClipped());
75 SkMScalar w
= 0.00001; // or any positive non-zero small epsilon
77 SkMScalar t
= (w
- h1
.w()) / (h2
.w() - h1
.w());
79 SkMScalar x
= (1 - t
) * h1
.x() + t
* h2
.x();
80 SkMScalar y
= (1 - t
) * h1
.y() + t
* h2
.y();
81 SkMScalar z
= (1 - t
) * h1
.z() + t
* h2
.z();
83 return HomogeneousCoordinate(x
, y
, z
, w
);
86 static inline void ExpandBoundsToIncludePoint(float* xmin
,
91 *xmin
= std::min(p
.x(), *xmin
);
92 *xmax
= std::max(p
.x(), *xmax
);
93 *ymin
= std::min(p
.y(), *ymin
);
94 *ymax
= std::max(p
.y(), *ymax
);
97 static inline void AddVertexToClippedQuad(gfx::PointF new_vertex
,
98 gfx::PointF clipped_quad
[8],
99 int* num_vertices_in_clipped_quad
) {
100 clipped_quad
[*num_vertices_in_clipped_quad
] = new_vertex
;
101 (*num_vertices_in_clipped_quad
)++;
104 gfx::Rect
MathUtil::MapClippedRect(const gfx::Transform
& transform
,
105 gfx::Rect src_rect
) {
106 return gfx::ToEnclosingRect(MapClippedRect(transform
, gfx::RectF(src_rect
)));
109 gfx::RectF
MathUtil::MapClippedRect(const gfx::Transform
& transform
,
110 const gfx::RectF
& src_rect
) {
111 if (transform
.IsIdentityOrTranslation()) {
113 gfx::Vector2dF(SkMScalarToFloat(transform
.matrix().get(0, 3)),
114 SkMScalarToFloat(transform
.matrix().get(1, 3)));
117 // Apply the transform, but retain the result in homogeneous coordinates.
119 SkMScalar quad
[4 * 2]; // input: 4 x 2D points
120 quad
[0] = src_rect
.x();
121 quad
[1] = src_rect
.y();
122 quad
[2] = src_rect
.right();
123 quad
[3] = src_rect
.y();
124 quad
[4] = src_rect
.right();
125 quad
[5] = src_rect
.bottom();
126 quad
[6] = src_rect
.x();
127 quad
[7] = src_rect
.bottom();
129 SkMScalar result
[4 * 4]; // output: 4 x 4D homogeneous points
130 transform
.matrix().map2(quad
, 4, result
);
132 HomogeneousCoordinate
hc0(result
[0], result
[1], result
[2], result
[3]);
133 HomogeneousCoordinate
hc1(result
[4], result
[5], result
[6], result
[7]);
134 HomogeneousCoordinate
hc2(result
[8], result
[9], result
[10], result
[11]);
135 HomogeneousCoordinate
hc3(result
[12], result
[13], result
[14], result
[15]);
136 return ComputeEnclosingClippedRect(hc0
, hc1
, hc2
, hc3
);
139 gfx::RectF
MathUtil::ProjectClippedRect(const gfx::Transform
& transform
,
140 const gfx::RectF
& src_rect
) {
141 if (transform
.IsIdentityOrTranslation()) {
143 gfx::Vector2dF(SkMScalarToFloat(transform
.matrix().get(0, 3)),
144 SkMScalarToFloat(transform
.matrix().get(1, 3)));
147 // Perform the projection, but retain the result in homogeneous coordinates.
148 gfx::QuadF q
= gfx::QuadF(src_rect
);
149 HomogeneousCoordinate h1
= ProjectHomogeneousPoint(transform
, q
.p1());
150 HomogeneousCoordinate h2
= ProjectHomogeneousPoint(transform
, q
.p2());
151 HomogeneousCoordinate h3
= ProjectHomogeneousPoint(transform
, q
.p3());
152 HomogeneousCoordinate h4
= ProjectHomogeneousPoint(transform
, q
.p4());
154 return ComputeEnclosingClippedRect(h1
, h2
, h3
, h4
);
157 void MathUtil::MapClippedQuad(const gfx::Transform
& transform
,
158 const gfx::QuadF
& src_quad
,
159 gfx::PointF clipped_quad
[8],
160 int* num_vertices_in_clipped_quad
) {
161 HomogeneousCoordinate h1
=
162 MapHomogeneousPoint(transform
, gfx::Point3F(src_quad
.p1()));
163 HomogeneousCoordinate h2
=
164 MapHomogeneousPoint(transform
, gfx::Point3F(src_quad
.p2()));
165 HomogeneousCoordinate h3
=
166 MapHomogeneousPoint(transform
, gfx::Point3F(src_quad
.p3()));
167 HomogeneousCoordinate h4
=
168 MapHomogeneousPoint(transform
, gfx::Point3F(src_quad
.p4()));
170 // The order of adding the vertices to the array is chosen so that
171 // clockwise / counter-clockwise orientation is retained.
173 *num_vertices_in_clipped_quad
= 0;
175 if (!h1
.ShouldBeClipped()) {
176 AddVertexToClippedQuad(
177 h1
.CartesianPoint2d(), clipped_quad
, num_vertices_in_clipped_quad
);
180 if (h1
.ShouldBeClipped() ^ h2
.ShouldBeClipped()) {
181 AddVertexToClippedQuad(
182 ComputeClippedPointForEdge(h1
, h2
).CartesianPoint2d(),
184 num_vertices_in_clipped_quad
);
187 if (!h2
.ShouldBeClipped()) {
188 AddVertexToClippedQuad(
189 h2
.CartesianPoint2d(), clipped_quad
, num_vertices_in_clipped_quad
);
192 if (h2
.ShouldBeClipped() ^ h3
.ShouldBeClipped()) {
193 AddVertexToClippedQuad(
194 ComputeClippedPointForEdge(h2
, h3
).CartesianPoint2d(),
196 num_vertices_in_clipped_quad
);
199 if (!h3
.ShouldBeClipped()) {
200 AddVertexToClippedQuad(
201 h3
.CartesianPoint2d(), clipped_quad
, num_vertices_in_clipped_quad
);
204 if (h3
.ShouldBeClipped() ^ h4
.ShouldBeClipped()) {
205 AddVertexToClippedQuad(
206 ComputeClippedPointForEdge(h3
, h4
).CartesianPoint2d(),
208 num_vertices_in_clipped_quad
);
211 if (!h4
.ShouldBeClipped()) {
212 AddVertexToClippedQuad(
213 h4
.CartesianPoint2d(), clipped_quad
, num_vertices_in_clipped_quad
);
216 if (h4
.ShouldBeClipped() ^ h1
.ShouldBeClipped()) {
217 AddVertexToClippedQuad(
218 ComputeClippedPointForEdge(h4
, h1
).CartesianPoint2d(),
220 num_vertices_in_clipped_quad
);
223 DCHECK_LE(*num_vertices_in_clipped_quad
, 8);
226 gfx::RectF
MathUtil::ComputeEnclosingRectOfVertices(gfx::PointF vertices
[],
228 if (num_vertices
< 2)
231 float xmin
= std::numeric_limits
<float>::max();
232 float xmax
= -std::numeric_limits
<float>::max();
233 float ymin
= std::numeric_limits
<float>::max();
234 float ymax
= -std::numeric_limits
<float>::max();
236 for (int i
= 0; i
< num_vertices
; ++i
)
237 ExpandBoundsToIncludePoint(&xmin
, &xmax
, &ymin
, &ymax
, vertices
[i
]);
239 return gfx::RectF(gfx::PointF(xmin
, ymin
),
240 gfx::SizeF(xmax
- xmin
, ymax
- ymin
));
243 gfx::RectF
MathUtil::ComputeEnclosingClippedRect(
244 const HomogeneousCoordinate
& h1
,
245 const HomogeneousCoordinate
& h2
,
246 const HomogeneousCoordinate
& h3
,
247 const HomogeneousCoordinate
& h4
) {
248 // This function performs clipping as necessary and computes the enclosing 2d
249 // gfx::RectF of the vertices. Doing these two steps simultaneously allows us
250 // to avoid the overhead of storing an unknown number of clipped vertices.
252 // If no vertices on the quad are clipped, then we can simply return the
253 // enclosing rect directly.
254 bool something_clipped
= h1
.ShouldBeClipped() || h2
.ShouldBeClipped() ||
255 h3
.ShouldBeClipped() || h4
.ShouldBeClipped();
256 if (!something_clipped
) {
257 gfx::QuadF mapped_quad
= gfx::QuadF(h1
.CartesianPoint2d(),
258 h2
.CartesianPoint2d(),
259 h3
.CartesianPoint2d(),
260 h4
.CartesianPoint2d());
261 return mapped_quad
.BoundingBox();
264 bool everything_clipped
= h1
.ShouldBeClipped() && h2
.ShouldBeClipped() &&
265 h3
.ShouldBeClipped() && h4
.ShouldBeClipped();
266 if (everything_clipped
)
269 float xmin
= std::numeric_limits
<float>::max();
270 float xmax
= -std::numeric_limits
<float>::max();
271 float ymin
= std::numeric_limits
<float>::max();
272 float ymax
= -std::numeric_limits
<float>::max();
274 if (!h1
.ShouldBeClipped())
275 ExpandBoundsToIncludePoint(&xmin
, &xmax
, &ymin
, &ymax
,
276 h1
.CartesianPoint2d());
278 if (h1
.ShouldBeClipped() ^ h2
.ShouldBeClipped())
279 ExpandBoundsToIncludePoint(&xmin
,
283 ComputeClippedPointForEdge(h1
, h2
)
284 .CartesianPoint2d());
286 if (!h2
.ShouldBeClipped())
287 ExpandBoundsToIncludePoint(&xmin
, &xmax
, &ymin
, &ymax
,
288 h2
.CartesianPoint2d());
290 if (h2
.ShouldBeClipped() ^ h3
.ShouldBeClipped())
291 ExpandBoundsToIncludePoint(&xmin
,
295 ComputeClippedPointForEdge(h2
, h3
)
296 .CartesianPoint2d());
298 if (!h3
.ShouldBeClipped())
299 ExpandBoundsToIncludePoint(&xmin
, &xmax
, &ymin
, &ymax
,
300 h3
.CartesianPoint2d());
302 if (h3
.ShouldBeClipped() ^ h4
.ShouldBeClipped())
303 ExpandBoundsToIncludePoint(&xmin
,
307 ComputeClippedPointForEdge(h3
, h4
)
308 .CartesianPoint2d());
310 if (!h4
.ShouldBeClipped())
311 ExpandBoundsToIncludePoint(&xmin
, &xmax
, &ymin
, &ymax
,
312 h4
.CartesianPoint2d());
314 if (h4
.ShouldBeClipped() ^ h1
.ShouldBeClipped())
315 ExpandBoundsToIncludePoint(&xmin
,
319 ComputeClippedPointForEdge(h4
, h1
)
320 .CartesianPoint2d());
322 return gfx::RectF(gfx::PointF(xmin
, ymin
),
323 gfx::SizeF(xmax
- xmin
, ymax
- ymin
));
326 gfx::QuadF
MathUtil::MapQuad(const gfx::Transform
& transform
,
329 if (transform
.IsIdentityOrTranslation()) {
330 gfx::QuadF
mapped_quad(q
);
332 gfx::Vector2dF(SkMScalarToFloat(transform
.matrix().get(0, 3)),
333 SkMScalarToFloat(transform
.matrix().get(1, 3)));
338 HomogeneousCoordinate h1
=
339 MapHomogeneousPoint(transform
, gfx::Point3F(q
.p1()));
340 HomogeneousCoordinate h2
=
341 MapHomogeneousPoint(transform
, gfx::Point3F(q
.p2()));
342 HomogeneousCoordinate h3
=
343 MapHomogeneousPoint(transform
, gfx::Point3F(q
.p3()));
344 HomogeneousCoordinate h4
=
345 MapHomogeneousPoint(transform
, gfx::Point3F(q
.p4()));
347 *clipped
= h1
.ShouldBeClipped() || h2
.ShouldBeClipped() ||
348 h3
.ShouldBeClipped() || h4
.ShouldBeClipped();
350 // Result will be invalid if clipped == true. But, compute it anyway just in
351 // case, to emulate existing behavior.
352 return gfx::QuadF(h1
.CartesianPoint2d(),
353 h2
.CartesianPoint2d(),
354 h3
.CartesianPoint2d(),
355 h4
.CartesianPoint2d());
358 gfx::PointF
MathUtil::MapPoint(const gfx::Transform
& transform
,
361 HomogeneousCoordinate h
= MapHomogeneousPoint(transform
, gfx::Point3F(p
));
365 return h
.CartesianPoint2d();
368 // The cartesian coordinates will be invalid after dividing by w.
371 // Avoid dividing by w if w == 0.
373 return gfx::PointF();
375 // This return value will be invalid because clipped == true, but (1) users of
376 // this code should be ignoring the return value when clipped == true anyway,
377 // and (2) this behavior is more consistent with existing behavior of WebKit
378 // transforms if the user really does not ignore the return value.
379 return h
.CartesianPoint2d();
382 gfx::Point3F
MathUtil::MapPoint(const gfx::Transform
& transform
,
383 const gfx::Point3F
& p
,
385 HomogeneousCoordinate h
= MapHomogeneousPoint(transform
, p
);
389 return h
.CartesianPoint3d();
392 // The cartesian coordinates will be invalid after dividing by w.
395 // Avoid dividing by w if w == 0.
397 return gfx::Point3F();
399 // This return value will be invalid because clipped == true, but (1) users of
400 // this code should be ignoring the return value when clipped == true anyway,
401 // and (2) this behavior is more consistent with existing behavior of WebKit
402 // transforms if the user really does not ignore the return value.
403 return h
.CartesianPoint3d();
406 gfx::QuadF
MathUtil::ProjectQuad(const gfx::Transform
& transform
,
409 gfx::QuadF projected_quad
;
411 projected_quad
.set_p1(ProjectPoint(transform
, q
.p1(), &clipped_point
));
412 *clipped
= clipped_point
;
413 projected_quad
.set_p2(ProjectPoint(transform
, q
.p2(), &clipped_point
));
414 *clipped
|= clipped_point
;
415 projected_quad
.set_p3(ProjectPoint(transform
, q
.p3(), &clipped_point
));
416 *clipped
|= clipped_point
;
417 projected_quad
.set_p4(ProjectPoint(transform
, q
.p4(), &clipped_point
));
418 *clipped
|= clipped_point
;
420 return projected_quad
;
423 gfx::PointF
MathUtil::ProjectPoint(const gfx::Transform
& transform
,
426 HomogeneousCoordinate h
= ProjectHomogeneousPoint(transform
, p
);
429 // The cartesian coordinates will be valid in this case.
431 return h
.CartesianPoint2d();
434 // The cartesian coordinates will be invalid after dividing by w.
437 // Avoid dividing by w if w == 0.
439 return gfx::PointF();
441 // This return value will be invalid because clipped == true, but (1) users of
442 // this code should be ignoring the return value when clipped == true anyway,
443 // and (2) this behavior is more consistent with existing behavior of WebKit
444 // transforms if the user really does not ignore the return value.
445 return h
.CartesianPoint2d();
448 gfx::RectF
MathUtil::ScaleRectProportional(const gfx::RectF
& input_outer_rect
,
449 const gfx::RectF
& scale_outer_rect
,
450 const gfx::RectF
& scale_inner_rect
) {
451 gfx::RectF output_inner_rect
= input_outer_rect
;
452 float scale_rect_to_input_scale_x
=
453 scale_outer_rect
.width() / input_outer_rect
.width();
454 float scale_rect_to_input_scale_y
=
455 scale_outer_rect
.height() / input_outer_rect
.height();
457 gfx::Vector2dF top_left_diff
=
458 scale_inner_rect
.origin() - scale_outer_rect
.origin();
459 gfx::Vector2dF bottom_right_diff
=
460 scale_inner_rect
.bottom_right() - scale_outer_rect
.bottom_right();
461 output_inner_rect
.Inset(top_left_diff
.x() / scale_rect_to_input_scale_x
,
462 top_left_diff
.y() / scale_rect_to_input_scale_y
,
463 -bottom_right_diff
.x() / scale_rect_to_input_scale_x
,
464 -bottom_right_diff
.y() / scale_rect_to_input_scale_y
);
465 return output_inner_rect
;
468 static inline float ScaleOnAxis(double a
, double b
, double c
) {
469 // Do the sqrt as a double to not lose precision.
470 return static_cast<float>(std::sqrt(a
* a
+ b
* b
+ c
* c
));
473 gfx::Vector2dF
MathUtil::ComputeTransform2dScaleComponents(
474 const gfx::Transform
& transform
,
475 float fallback_value
) {
476 if (transform
.HasPerspective())
477 return gfx::Vector2dF(fallback_value
, fallback_value
);
478 float x_scale
= ScaleOnAxis(transform
.matrix().getDouble(0, 0),
479 transform
.matrix().getDouble(1, 0),
480 transform
.matrix().getDouble(2, 0));
481 float y_scale
= ScaleOnAxis(transform
.matrix().getDouble(0, 1),
482 transform
.matrix().getDouble(1, 1),
483 transform
.matrix().getDouble(2, 1));
484 return gfx::Vector2dF(x_scale
, y_scale
);
487 float MathUtil::SmallestAngleBetweenVectors(gfx::Vector2dF v1
,
489 double dot_product
= gfx::DotProduct(v1
, v2
) / v1
.Length() / v2
.Length();
490 // Clamp to compensate for rounding errors.
491 dot_product
= std::max(-1.0, std::min(1.0, dot_product
));
492 return static_cast<float>(Rad2Deg(std::acos(dot_product
)));
495 gfx::Vector2dF
MathUtil::ProjectVector(gfx::Vector2dF source
,
496 gfx::Vector2dF destination
) {
497 float projected_length
=
498 gfx::DotProduct(source
, destination
) / destination
.LengthSquared();
499 return gfx::Vector2dF(projected_length
* destination
.x(),
500 projected_length
* destination
.y());
503 scoped_ptr
<base::Value
> MathUtil::AsValue(gfx::Size s
) {
504 scoped_ptr
<base::DictionaryValue
> res(new base::DictionaryValue());
505 res
->SetDouble("width", s
.width());
506 res
->SetDouble("height", s
.height());
507 return res
.PassAs
<base::Value
>();
510 scoped_ptr
<base::Value
> MathUtil::AsValue(gfx::SizeF s
) {
511 scoped_ptr
<base::DictionaryValue
> res(new base::DictionaryValue());
512 res
->SetDouble("width", s
.width());
513 res
->SetDouble("height", s
.height());
514 return res
.PassAs
<base::Value
>();
517 scoped_ptr
<base::Value
> MathUtil::AsValue(gfx::Rect r
) {
518 scoped_ptr
<base::ListValue
> res(new base::ListValue());
519 res
->AppendInteger(r
.x());
520 res
->AppendInteger(r
.y());
521 res
->AppendInteger(r
.width());
522 res
->AppendInteger(r
.height());
523 return res
.PassAs
<base::Value
>();
526 bool MathUtil::FromValue(const base::Value
* raw_value
, gfx::Rect
* out_rect
) {
527 const base::ListValue
* value
= NULL
;
528 if (!raw_value
->GetAsList(&value
))
531 if (value
->GetSize() != 4)
536 ok
&= value
->GetInteger(0, &x
);
537 ok
&= value
->GetInteger(1, &y
);
538 ok
&= value
->GetInteger(2, &w
);
539 ok
&= value
->GetInteger(3, &h
);
543 *out_rect
= gfx::Rect(x
, y
, w
, h
);
547 scoped_ptr
<base::Value
> MathUtil::AsValue(gfx::PointF pt
) {
548 scoped_ptr
<base::ListValue
> res(new base::ListValue());
549 res
->AppendDouble(pt
.x());
550 res
->AppendDouble(pt
.y());
551 return res
.PassAs
<base::Value
>();
554 scoped_ptr
<base::Value
> MathUtil::AsValue(const gfx::QuadF
& q
) {
555 scoped_ptr
<base::ListValue
> res(new base::ListValue());
556 res
->AppendDouble(q
.p1().x());
557 res
->AppendDouble(q
.p1().y());
558 res
->AppendDouble(q
.p2().x());
559 res
->AppendDouble(q
.p2().y());
560 res
->AppendDouble(q
.p3().x());
561 res
->AppendDouble(q
.p3().y());
562 res
->AppendDouble(q
.p4().x());
563 res
->AppendDouble(q
.p4().y());
564 return res
.PassAs
<base::Value
>();
567 scoped_ptr
<base::Value
> MathUtil::AsValue(const gfx::RectF
& rect
) {
568 scoped_ptr
<base::ListValue
> res(new base::ListValue());
569 res
->AppendDouble(rect
.x());
570 res
->AppendDouble(rect
.y());
571 res
->AppendDouble(rect
.width());
572 res
->AppendDouble(rect
.height());
573 return res
.PassAs
<base::Value
>();
576 scoped_ptr
<base::Value
> MathUtil::AsValue(const gfx::Transform
& transform
) {
577 scoped_ptr
<base::ListValue
> res(new base::ListValue());
578 const SkMatrix44
& m
= transform
.matrix();
579 for (int row
= 0; row
< 4; ++row
) {
580 for (int col
= 0; col
< 4; ++col
)
581 res
->AppendDouble(m
.getDouble(row
, col
));
583 return res
.PassAs
<base::Value
>();
586 scoped_ptr
<base::Value
> MathUtil::AsValueSafely(double value
) {
587 return scoped_ptr
<base::Value
>(base::Value::CreateDoubleValue(
588 std::min(value
, std::numeric_limits
<double>::max())));
591 scoped_ptr
<base::Value
> MathUtil::AsValueSafely(float value
) {
592 return scoped_ptr
<base::Value
>(base::Value::CreateDoubleValue(
593 std::min(value
, std::numeric_limits
<float>::max())));