1/*
2 * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 Apple Inc. All rights reserved.
3 * Copyright (C) 2008, 2010 Nokia Corporation and/or its subsidiary(-ies)
4 * Copyright (C) 2007 Alp Toker <alp@atoker.com>
5 * Copyright (C) 2008 Eric Seidel <eric@webkit.org>
6 * Copyright (C) 2008 Dirk Schulze <krit@webkit.org>
7 * Copyright (C) 2010 Torch Mobile (Beijing) Co. Ltd. All rights reserved.
8 * Copyright (C) 2012, 2013 Intel Corporation. All rights reserved.
9 * Copyright (C) 2012, 2013 Adobe Systems Incorporated. All rights reserved.
10 *
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
13 * are met:
14 *
15 * 1.  Redistributions of source code must retain the above copyright
16 *     notice, this list of conditions and the following disclaimer.
17 * 2.  Redistributions in binary form must reproduce the above copyright
18 *     notice, this list of conditions and the following disclaimer in the
19 *     documentation and/or other materials provided with the distribution.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER "AS IS" AND ANY
22 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
24 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
25 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
26 * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
27 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
28 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
30 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
31 * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 * SUCH DAMAGE.
33 */
34
35#include "config.h"
36#include "core/html/canvas/CanvasPathMethods.h"
37
38#include "bindings/core/v8/ExceptionState.h"
39#include "core/dom/ExceptionCode.h"
40#include "platform/geometry/FloatRect.h"
41#include "platform/transforms/AffineTransform.h"
42#include "wtf/MathExtras.h"
43
44namespace blink {
45
46void CanvasPathMethods::closePath()
47{
48    if (m_path.isEmpty())
49        return;
50
51    FloatRect boundRect = m_path.boundingRect();
52    if (boundRect.width() || boundRect.height())
53        m_path.closeSubpath();
54}
55
56void CanvasPathMethods::moveTo(float x, float y)
57{
58    if (!std::isfinite(x) || !std::isfinite(y))
59        return;
60    if (!isTransformInvertible())
61        return;
62    m_path.moveTo(FloatPoint(x, y));
63}
64
65void CanvasPathMethods::lineTo(float x, float y)
66{
67    if (!std::isfinite(x) || !std::isfinite(y))
68        return;
69    if (!isTransformInvertible())
70        return;
71
72    FloatPoint p1 = FloatPoint(x, y);
73    if (!m_path.hasCurrentPoint())
74        m_path.moveTo(p1);
75    else if (p1 != m_path.currentPoint())
76        m_path.addLineTo(p1);
77}
78
79void CanvasPathMethods::quadraticCurveTo(float cpx, float cpy, float x, float y)
80{
81    if (!std::isfinite(cpx) || !std::isfinite(cpy) || !std::isfinite(x) || !std::isfinite(y))
82        return;
83    if (!isTransformInvertible())
84        return;
85    if (!m_path.hasCurrentPoint())
86        m_path.moveTo(FloatPoint(cpx, cpy));
87
88    FloatPoint p1 = FloatPoint(x, y);
89    FloatPoint cp = FloatPoint(cpx, cpy);
90    if (p1 != m_path.currentPoint() || p1 != cp)
91        m_path.addQuadCurveTo(cp, p1);
92}
93
94void CanvasPathMethods::bezierCurveTo(float cp1x, float cp1y, float cp2x, float cp2y, float x, float y)
95{
96    if (!std::isfinite(cp1x) || !std::isfinite(cp1y) || !std::isfinite(cp2x) || !std::isfinite(cp2y) || !std::isfinite(x) || !std::isfinite(y))
97        return;
98    if (!isTransformInvertible())
99        return;
100    if (!m_path.hasCurrentPoint())
101        m_path.moveTo(FloatPoint(cp1x, cp1y));
102
103    FloatPoint p1 = FloatPoint(x, y);
104    FloatPoint cp1 = FloatPoint(cp1x, cp1y);
105    FloatPoint cp2 = FloatPoint(cp2x, cp2y);
106    if (p1 != m_path.currentPoint() || p1 != cp1 ||  p1 != cp2)
107        m_path.addBezierCurveTo(cp1, cp2, p1);
108}
109
110void CanvasPathMethods::arcTo(float x1, float y1, float x2, float y2, float r, ExceptionState& exceptionState)
111{
112    if (!std::isfinite(x1) || !std::isfinite(y1) || !std::isfinite(x2) || !std::isfinite(y2) || !std::isfinite(r))
113        return;
114
115    if (r < 0) {
116        exceptionState.throwDOMException(IndexSizeError, "The radius provided (" + String::number(r) + ") is negative.");
117        return;
118    }
119
120    if (!isTransformInvertible())
121        return;
122
123    FloatPoint p1 = FloatPoint(x1, y1);
124    FloatPoint p2 = FloatPoint(x2, y2);
125
126    if (!m_path.hasCurrentPoint())
127        m_path.moveTo(p1);
128    else if (p1 == m_path.currentPoint() || p1 == p2 || !r)
129        lineTo(x1, y1);
130    else
131        m_path.addArcTo(p1, p2, r);
132}
133
134namespace {
135
136float adjustEndAngle(float startAngle, float endAngle, bool anticlockwise)
137{
138    float newEndAngle = endAngle;
139    /* http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#dom-context-2d-arc
140     * If the anticlockwise argument is false and endAngle-startAngle is equal to or greater than 2pi, or,
141     * if the anticlockwise argument is true and startAngle-endAngle is equal to or greater than 2pi,
142     * then the arc is the whole circumference of this ellipse, and the point at startAngle along this circle's circumference,
143     * measured in radians clockwise from the ellipse's semi-major axis, acts as both the start point and the end point.
144     */
145    if (!anticlockwise && endAngle - startAngle >= twoPiFloat)
146        newEndAngle = startAngle + twoPiFloat;
147    else if (anticlockwise && startAngle - endAngle >= twoPiFloat)
148        newEndAngle = startAngle - twoPiFloat;
149
150    /*
151     * Otherwise, the arc is the path along the circumference of this ellipse from the start point to the end point,
152     * going anti-clockwise if the anticlockwise argument is true, and clockwise otherwise.
153     * Since the points are on the ellipse, as opposed to being simply angles from zero,
154     * the arc can never cover an angle greater than 2pi radians.
155     */
156    /* NOTE: When startAngle = 0, endAngle = 2Pi and anticlockwise = true, the spec does not indicate clearly.
157     * We draw the entire circle, because some web sites use arc(x, y, r, 0, 2*Math.PI, true) to draw circle.
158     * We preserve backward-compatibility.
159     */
160    else if (!anticlockwise && startAngle > endAngle)
161        newEndAngle = startAngle + (twoPiFloat - fmodf(startAngle - endAngle, twoPiFloat));
162    else if (anticlockwise && startAngle < endAngle)
163        newEndAngle = startAngle - (twoPiFloat - fmodf(endAngle - startAngle, twoPiFloat));
164
165    ASSERT(ellipseIsRenderable(startAngle, newEndAngle));
166    return newEndAngle;
167}
168
169inline void lineToFloatPoint(CanvasPathMethods* path, const FloatPoint& p)
170{
171    path->lineTo(p.x(), p.y());
172}
173
174inline FloatPoint getPointOnEllipse(float radiusX, float radiusY, float theta)
175{
176    return FloatPoint(radiusX * cosf(theta), radiusY * sinf(theta));
177}
178
179void canonicalizeAngle(float* startAngle, float* endAngle)
180{
181    // Make 0 <= startAngle < 2*PI
182    float newStartAngle = *startAngle;
183    if (newStartAngle < 0)
184        newStartAngle = twoPiFloat + fmodf(newStartAngle, -twoPiFloat);
185    else
186        newStartAngle = fmodf(newStartAngle, twoPiFloat);
187
188    float delta = newStartAngle - *startAngle;
189    *startAngle = newStartAngle;
190    *endAngle = *endAngle + delta;
191    ASSERT(newStartAngle >= 0 && newStartAngle < twoPiFloat);
192}
193
194/*
195 * degenerateEllipse() handles a degenerated ellipse using several lines.
196 *
197 * Let's see a following example: line to ellipse to line.
198 *        _--^\
199 *       (     )
200 * -----(      )
201 *            )
202 *           /--------
203 *
204 * If radiusX becomes zero, the ellipse of the example is degenerated.
205 *         _
206 *        // P
207 *       //
208 * -----//
209 *      /
210 *     /--------
211 *
212 * To draw the above example, need to get P that is a local maximum point.
213 * Angles for P are 0.5Pi and 1.5Pi in the ellipse coordinates.
214 *
215 * If radiusY becomes zero, the result is as follows.
216 * -----__
217 *        --_
218 *          ----------
219 *            ``P
220 * Angles for P are 0 and Pi in the ellipse coordinates.
221 *
222 * To handle both cases, degenerateEllipse() lines to start angle, local maximum points(every 0.5Pi), and end angle.
223 * NOTE: Before ellipse() calls this function, adjustEndAngle() is called, so endAngle - startAngle must be equal to or less than 2Pi.
224 */
225void degenerateEllipse(CanvasPathMethods* path, float x, float y, float radiusX, float radiusY, float rotation, float startAngle, float endAngle, bool anticlockwise)
226{
227    ASSERT(ellipseIsRenderable(startAngle, endAngle));
228    ASSERT(startAngle >= 0 && startAngle < twoPiFloat);
229    ASSERT((anticlockwise && (startAngle - endAngle) >= 0) || (!anticlockwise && (endAngle - startAngle) >= 0));
230
231    FloatPoint center(x, y);
232    AffineTransform rotationMatrix;
233    rotationMatrix.rotateRadians(rotation);
234    // First, if the object's path has any subpaths, then the method must add a straight line from the last point in the subpath to the start point of the arc.
235    lineToFloatPoint(path, center + rotationMatrix.mapPoint(getPointOnEllipse(radiusX, radiusY, startAngle)));
236    if ((!radiusX && !radiusY) || startAngle == endAngle)
237        return;
238
239    if (!anticlockwise) {
240        // startAngle - fmodf(startAngle, piOverTwoFloat) + piOverTwoFloat is the one of (0, 0.5Pi, Pi, 1.5Pi, 2Pi)
241        // that is the closest to startAngle on the clockwise direction.
242        for (float angle = startAngle - fmodf(startAngle, piOverTwoFloat) + piOverTwoFloat; angle < endAngle; angle += piOverTwoFloat)
243            lineToFloatPoint(path, center + rotationMatrix.mapPoint(getPointOnEllipse(radiusX, radiusY, angle)));
244    } else {
245        for (float angle = startAngle - fmodf(startAngle, piOverTwoFloat); angle > endAngle; angle -= piOverTwoFloat)
246            lineToFloatPoint(path, center + rotationMatrix.mapPoint(getPointOnEllipse(radiusX, radiusY, angle)));
247    }
248
249    lineToFloatPoint(path, center + rotationMatrix.mapPoint(getPointOnEllipse(radiusX, radiusY, endAngle)));
250}
251
252} // namespace
253
254void CanvasPathMethods::arc(float x, float y, float radius, float startAngle, float endAngle, bool anticlockwise, ExceptionState& exceptionState)
255{
256    if (!std::isfinite(x) || !std::isfinite(y) || !std::isfinite(radius) || !std::isfinite(startAngle) || !std::isfinite(endAngle))
257        return;
258
259    if (radius < 0) {
260        exceptionState.throwDOMException(IndexSizeError, "The radius provided (" + String::number(radius) + ") is negative.");
261        return;
262    }
263
264    if (!isTransformInvertible())
265        return;
266
267    if (!radius || startAngle == endAngle) {
268        // The arc is empty but we still need to draw the connecting line.
269        lineTo(x + radius * cosf(startAngle), y + radius * sinf(startAngle));
270        return;
271    }
272
273    canonicalizeAngle(&startAngle, &endAngle);
274    float adjustedEndAngle = adjustEndAngle(startAngle, endAngle, anticlockwise);
275    m_path.addArc(FloatPoint(x, y), radius, startAngle, adjustedEndAngle, anticlockwise);
276}
277
278void CanvasPathMethods::ellipse(float x, float y, float radiusX, float radiusY, float rotation, float startAngle, float endAngle, bool anticlockwise, ExceptionState& exceptionState)
279{
280    if (!std::isfinite(x) || !std::isfinite(y) || !std::isfinite(radiusX) || !std::isfinite(radiusY) || !std::isfinite(rotation) || !std::isfinite(startAngle) || !std::isfinite(endAngle))
281        return;
282
283    if (radiusX < 0) {
284        exceptionState.throwDOMException(IndexSizeError, "The major-axis radius provided (" + String::number(radiusX) + ") is negative.");
285        return;
286    }
287    if (radiusY < 0) {
288        exceptionState.throwDOMException(IndexSizeError, "The minor-axis radius provided (" + String::number(radiusY) + ") is negative.");
289        return;
290    }
291
292    if (!isTransformInvertible())
293        return;
294
295    canonicalizeAngle(&startAngle, &endAngle);
296    float adjustedEndAngle = adjustEndAngle(startAngle, endAngle, anticlockwise);
297    if (!radiusX || !radiusY || startAngle == adjustedEndAngle) {
298        // The ellipse is empty but we still need to draw the connecting line to start point.
299        degenerateEllipse(this, x, y, radiusX, radiusY, rotation, startAngle, adjustedEndAngle, anticlockwise);
300        return;
301    }
302
303    m_path.addEllipse(FloatPoint(x, y), radiusX, radiusY, rotation, startAngle, adjustedEndAngle, anticlockwise);
304}
305
306void CanvasPathMethods::rect(float x, float y, float width, float height)
307{
308    if (!isTransformInvertible())
309        return;
310
311    if (!std::isfinite(x) || !std::isfinite(y) || !std::isfinite(width) || !std::isfinite(height))
312        return;
313
314    if (!width && !height) {
315        m_path.moveTo(FloatPoint(x, y));
316        return;
317    }
318
319    m_path.addRect(FloatRect(x, y, width, height));
320}
321}
322