paper.js/src/path/Curve.js

1249 lines
37 KiB
JavaScript
Raw Normal View History

2011-03-06 19:50:44 -05:00
/*
* Paper.js - The Swiss Army Knife of Vector Graphics Scripting.
2011-03-07 20:41:50 -05:00
* http://paperjs.org/
*
* Copyright (c) 2011 - 2013, Juerg Lehni & Jonathan Puckey
2011-03-06 19:50:44 -05:00
* http://lehni.org/ & http://jonathanpuckey.com/
*
2011-07-01 06:17:45 -04:00
* Distributed under the MIT license. See LICENSE file for details.
*
2011-03-07 20:41:50 -05:00
* All rights reserved.
2011-03-06 19:50:44 -05:00
*/
/**
* @name Curve
*
2011-06-27 08:58:17 -04:00
* @class The Curve object represents the parts of a path that are connected by
* two following {@link Segment} objects. The curves of a path can be accessed
* through its {@link Path#curves} array.
2011-06-27 08:58:17 -04:00
*
* While a segment describe the anchor point and its incoming and outgoing
* handles, a Curve object describes the curve passing between two such
* segments. Curves and segments represent two different ways of looking at the
* same thing, but focusing on different aspects. Curves for example offer many
* convenient ways to work with parts of the path, finding lengths, positions or
* tangents at given offsets.
*/
var Curve = this.Curve = Base.extend(/** @lends Curve# */{
2011-05-23 11:24:36 -04:00
/**
* Creates a new curve object.
*
2013-04-21 09:43:57 -04:00
* @name Curve#initialize
2011-05-23 11:24:36 -04:00
* @param {Segment} segment1
* @param {Segment} segment2
*/
2013-04-21 09:43:57 -04:00
/**
* Creates a new curve object.
*
* @name Curve#initialize
* @param {Point} point1
* @param {Point} handle1
* @param {Point} handle2
* @param {Point} point2
*/
/**
* Creates a new curve object.
*
* @name Curve#initialize
* @ignore
* @param {Number} x1
* @param {Number} y1
* @param {Number} handle1x
* @param {Number} handle1y
* @param {Number} handle2x
* @param {Number} handle2y
* @param {Number} x2
* @param {Number} y2
*/
initialize: function(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7) {
var count = arguments.length;
2013-04-25 20:47:11 -04:00
if (count === 0) {
2011-03-06 07:24:15 -05:00
this._segment1 = new Segment();
this._segment2 = new Segment();
} else if (count == 1) {
// Note: This copies from existing segments through bean getters
2011-03-06 07:24:15 -05:00
this._segment1 = new Segment(arg0.segment1);
this._segment2 = new Segment(arg0.segment2);
} else if (count == 2) {
this._segment1 = new Segment(arg0);
this._segment2 = new Segment(arg1);
} else {
var point1, handle1, handle2, point2;
if (count == 4) {
point1 = arg0;
handle1 = arg1;
handle2 = arg2;
point2 = arg3;
} else if (count == 8) {
// Convert getValue() array back to points and handles so we
// can create segments for those.
point1 = [arg0, arg1];
point2 = [arg6, arg7];
handle1 = [arg2 - arg0, arg7 - arg1];
handle2 = [arg4 - arg6, arg5 - arg7];
}
this._segment1 = new Segment(point1, null, handle1);
this._segment2 = new Segment(point2, handle2, null);
2011-03-06 07:24:15 -05:00
}
},
_changed: function() {
// Clear cached values.
delete this._length;
delete this._bounds;
},
2011-03-06 07:24:15 -05:00
/**
* The first anchor point of the curve.
*
2011-05-23 11:24:36 -04:00
* @type Point
* @bean
2011-03-06 07:24:15 -05:00
*/
getPoint1: function() {
return this._segment1._point;
},
setPoint1: function(point) {
point = Point.read(arguments);
2011-03-06 07:24:15 -05:00
this._segment1._point.set(point.x, point.y);
},
/**
* The second anchor point of the curve.
*
2011-05-23 11:24:36 -04:00
* @type Point
* @bean
2011-03-06 07:24:15 -05:00
*/
getPoint2: function() {
return this._segment2._point;
},
setPoint2: function(point) {
point = Point.read(arguments);
2011-03-06 07:24:15 -05:00
this._segment2._point.set(point.x, point.y);
},
2011-03-06 07:24:15 -05:00
/**
* The handle point that describes the tangent in the first anchor point.
*
2011-05-23 11:24:36 -04:00
* @type Point
* @bean
2011-03-06 07:24:15 -05:00
*/
getHandle1: function() {
return this._segment1._handleOut;
},
setHandle1: function(point) {
point = Point.read(arguments);
2011-03-06 07:24:15 -05:00
this._segment1._handleOut.set(point.x, point.y);
},
/**
* The handle point that describes the tangent in the second anchor point.
*
2011-05-23 11:24:36 -04:00
* @type Point
* @bean
2011-03-06 07:24:15 -05:00
*/
getHandle2: function() {
return this._segment2._handleIn;
},
setHandle2: function(point) {
point = Point.read(arguments);
2011-03-06 07:24:15 -05:00
this._segment2._handleIn.set(point.x, point.y);
},
/**
* The first segment of the curve.
*
2011-05-23 11:24:36 -04:00
* @type Segment
* @bean
2011-03-06 07:24:15 -05:00
*/
getSegment1: function() {
return this._segment1;
},
/**
* The second segment of the curve.
*
2011-05-23 11:24:36 -04:00
* @type Segment
* @bean
2011-03-06 07:24:15 -05:00
*/
getSegment2: function() {
return this._segment2;
},
2011-05-23 11:24:36 -04:00
/**
* The path that the curve belongs to.
*
2011-05-23 11:24:36 -04:00
* @type Path
* @bean
*/
2011-03-06 08:26:09 -05:00
getPath: function() {
return this._path;
},
2011-05-23 11:24:36 -04:00
/**
* The index of the curve in the {@link Path#curves} array.
*
* @type Number
2011-05-23 11:24:36 -04:00
* @bean
*/
2011-03-06 08:26:09 -05:00
getIndex: function() {
return this._segment1._index;
2011-03-06 08:26:09 -05:00
},
2011-05-23 11:24:36 -04:00
/**
* The next curve in the {@link Path#curves} array that the curve
* belongs to.
*
2011-05-23 11:24:36 -04:00
* @type Curve
* @bean
*/
2011-03-06 08:26:09 -05:00
getNext: function() {
var curves = this._path && this._path._curves;
return curves && (curves[this._segment1._index + 1]
2011-04-30 18:22:29 -04:00
|| this._path._closed && curves[0]) || null;
2011-03-06 08:26:09 -05:00
},
2011-05-23 11:24:36 -04:00
/**
* The previous curve in the {@link Path#curves} array that the curve
* belongs to.
*
2011-05-23 11:24:36 -04:00
* @type Curve
* @bean
*/
2011-03-06 08:26:09 -05:00
getPrevious: function() {
var curves = this._path && this._path._curves;
return curves && (curves[this._segment1._index - 1]
2011-04-30 18:22:29 -04:00
|| this._path._closed && curves[curves.length - 1]) || null;
2011-03-06 08:26:09 -05:00
},
2011-04-21 13:54:32 -04:00
2011-05-23 11:24:36 -04:00
/**
* Specifies whether the handles of the curve are selected.
*
* @type Boolean
2011-05-23 11:24:36 -04:00
* @bean
*/
2011-04-21 13:54:32 -04:00
isSelected: function() {
return this.getHandle1().isSelected() && this.getHandle2().isSelected();
2011-04-21 13:54:32 -04:00
},
2011-03-06 08:26:09 -05:00
2011-05-23 11:24:36 -04:00
setSelected: function(selected) {
this.getHandle1().setSelected(selected);
this.getHandle2().setSelected(selected);
},
getValues: function() {
return Curve.getValues(this._segment1, this._segment2);
},
getPoints: function() {
// Convert to array of absolute points
var coords = this.getValues(),
points = [];
for (var i = 0; i < 8; i += 2)
points.push(Point.create(coords[i], coords[i + 1]));
return points;
},
2011-05-23 11:24:36 -04:00
// DOCS: document Curve#getLength(from, to)
/**
* The approximated length of the curve in points.
*
* @type Number
2011-05-23 11:24:36 -04:00
* @bean
*/
// Hide parameters from Bootstrap so it injects bean too
getLength: function(/* from, to */) {
var from = arguments[0],
to = arguments[1],
2013-04-25 20:47:11 -04:00
fullLength = arguments.length === 0 || from === 0 && to === 1;
if (fullLength && this._length != null)
return this._length;
var length = Curve.getLength(this.getValues(), from, to);
if (fullLength)
this._length = length;
return length;
},
getArea: function() {
return Curve.getArea(this.getValues());
},
getPart: function(from, to) {
return new Curve(Curve.getPart(this.getValues(), from, to));
},
/**
* Checks if this curve is linear, meaning it does not define any curve
* handle.
* @return {Boolean} {@true the curve is linear}
*/
isLinear: function() {
return this._segment1._handleOut.isZero()
&& this._segment2._handleIn.isZero();
},
getIntersections: function(curve) {
return Curve.getIntersections(this.getValues(), curve.getValues(),
this, curve, []);
},
getCrossings: function(point, roots) {
// Implementation of the crossing number algorithm:
// http://en.wikipedia.org/wiki/Point_in_polygon
// Solve the y-axis cubic polynomial for point.y and count all solutions
// to the right of point.x as crossings.
var vals = this.getValues(),
2012-12-15 05:24:46 -05:00
count = Curve.solveCubic(vals, 1, point.y, roots),
crossings = 0,
tolerance = /*#=*/ Numerical.TOLERANCE,
abs = Math.abs;
// Checks the y-slope between the current curve and the previous for a
// change of orientation, when a solution is found at t == 0
function changesOrientation(curve, tangent) {
return Curve.evaluate(curve.getPrevious().getValues(), 1, true, 1).y
* tangent.y > 0;
}
// TODO: See if this speeds up code, or slows it down:
// var bounds = this.getBounds();
// if (point.y < bounds.getTop() || point.y > bounds.getBottom()
// || point.x > bounds.getRight())
// return 0;
if (count === -1) {
// Infinite solutions, so we have a horizontal curve.
// Find parameter through getParameterOf()
roots[0] = Curve.getParameterOf(vals, point.x, point.y);
count = roots[0] !== null ? 1 : 0;
}
2012-12-15 05:24:46 -05:00
for (var i = 0; i < count; i++) {
var t = roots[i];
if (t > -tolerance && t < 1 - tolerance) {
var pt = Curve.evaluate(vals, t, true, 0);
if (point.x < pt.x + tolerance) {
// Passing 1 for Curve.evaluate() type calculates tangents
var tan = Curve.evaluate(vals, t, true, 1);
// Handle all kind of edge cases when points are on contours
// or rays are touching countours, to termine wether the
// crossing counts or not.
// See if the actual point is on the countour:
if (abs(pt.x - point.x) < tolerance) {
// Do not count the crossing if it is on the left hand
// side of the shape (tangent pointing upwards), since
// the ray will go out the other end, count as
// crossing there, and the point is on the contour, so
// to be considered inside.
var angle = tan.getAngle();
if (angle > -180 && angle < 0
// Handle special case where point is on a corner,
// in which case this crossing is skipped if both
// tangents have the same orientation.
&& (t > tolerance || changesOrientation(this, tan)))
continue;
} else {
// Skip touching stationary points:
if (abs(tan.y) < tolerance
// Check derivate for stationary points. If root is
// close to 0 and not changing vertical orientation
// from the previous curve, do not count this root,
// as it's touching a corner.
|| t < tolerance && !changesOrientation(this, tan))
continue;
}
crossings++;
}
}
}
return crossings;
},
// TODO: adjustThroughPoint
2011-05-23 11:24:36 -04:00
/**
* Returns a reversed version of the curve, without modifying the curve
* itself.
*
2011-05-23 11:24:36 -04:00
* @return {Curve} a reversed version of the curve
*/
reverse: function() {
return new Curve(this._segment2.reverse(), this._segment1.reverse());
},
2012-12-30 13:49:17 -05:00
/**
* Divides the curve into two at the specified position. The curve itself is
* modified and becomes the first part, the second part is returned as a new
* curve. If the modified curve belongs to a path item, the second part is
* added to it.
*
2012-12-30 13:49:17 -05:00
* @param parameter the position at which to split the curve as a value
* between 0 and 1 {@default 0.5}
* @return {Curve} the second part of the divided curve
*/
divide: function(parameter) {
var res = null;
// Accept CurveLocation objects, and objects that act like them:
if (parameter && parameter.curve === this)
parameter = parameter.parameter;
if (parameter > 0 && parameter < 1) {
var parts = Curve.subdivide(this.getValues(), parameter),
isLinear = this.isLinear(),
2012-12-30 13:49:17 -05:00
left = parts[0],
2013-05-04 00:00:46 -04:00
right = parts[1];
2012-12-30 13:49:17 -05:00
// Write back the results:
if (!isLinear) {
2013-05-04 00:00:46 -04:00
this._segment1._handleOut.set(left[2] - left[0],
left[3] - left[1]);
// segment2 is the end segment. By inserting newSegment
// between segment1 and 2, 2 becomes the end segment.
// Convert absolute -> relative
2013-05-04 00:00:46 -04:00
this._segment2._handleIn.set(right[4] - right[6],
right[5] - right[7]);
}
2012-12-30 13:49:17 -05:00
// Create the new segment, convert absolute -> relative:
2012-12-30 13:49:17 -05:00
var x = left[6], y = left[7],
segment = new Segment(Point.create(x, y),
2013-05-04 00:00:46 -04:00
!isLinear && Point.create(left[4] - x, left[5] - y),
!isLinear && Point.create(right[2] - x, right[3] - y));
2012-12-30 13:49:17 -05:00
// Insert it in the segments list, if needed:
if (this._path) {
// Insert at the end if this curve is a closing curve of a
// closed path, since otherwise it would be inserted at 0.
if (this._segment1._index > 0 && this._segment2._index === 0) {
2012-12-30 13:49:17 -05:00
this._path.add(segment);
} else {
this._path.insert(this._segment2._index, segment);
}
// The way Path#_add handles curves, this curve will always
// become the owner of the newly inserted segment.
// TODO: I expect this.getNext() to produce the correct result,
// but since we're inserting differently in _add (something
2013-05-04 00:00:46 -04:00
// linked with CurveLocation#divide()), this is not the case...
res = this; // this.getNext();
2012-12-30 13:49:17 -05:00
} else {
// otherwise create it from the result of split
var end = this._segment2;
this._segment2 = segment;
res = new Curve(segment, end);
}
}
return res;
},
/**
* Splits the path that this curve belongs to at the given parameter, using
* {@link Path#split(index, parameter)}.
*
* @return {Path} the second part of the split path
*/
split: function(parameter) {
return this._path
? this._path.split(this._segment1._index, parameter)
: null;
},
2011-05-23 11:24:36 -04:00
/**
* Returns a copy of the curve.
*
2011-05-23 11:24:36 -04:00
* @return {Curve}
*/
clone: function() {
return new Curve(this._segment1, this._segment2);
},
2011-05-23 11:24:36 -04:00
/**
* @return {String} A string representation of the curve.
2011-05-23 11:24:36 -04:00
*/
toString: function() {
2011-05-02 03:57:55 -04:00
var parts = [ 'point1: ' + this._segment1._point ];
if (!this._segment1._handleOut.isZero())
parts.push('handle1: ' + this._segment1._handleOut);
if (!this._segment2._handleIn.isZero())
parts.push('handle2: ' + this._segment2._handleIn);
parts.push('point2: ' + this._segment2._point);
return '{ ' + parts.join(', ') + ' }';
},
// Mess with indentation in order to get more line-space below...
statics: {
create: function(path, segment1, segment2) {
var curve = Base.create(Curve);
curve._path = path;
curve._segment1 = segment1;
curve._segment2 = segment2;
return curve;
},
getValues: function(segment1, segment2) {
var p1 = segment1._point,
h1 = segment1._handleOut,
h2 = segment2._handleIn,
p2 = segment2._point;
return [
p1._x, p1._y,
p1._x + h1._x, p1._y + h1._y,
p2._x + h2._x, p2._y + h2._y,
p2._x, p2._y
];
},
evaluate: function(v, offset, isParameter, type) {
var t = isParameter ? offset : Curve.getParameterAt(v, offset, 0),
p1x = v[0], p1y = v[1],
c1x = v[2], c1y = v[3],
c2x = v[4], c2y = v[5],
p2x = v[6], p2y = v[7],
x, y;
// Handle special case at beginning / end of curve
2013-04-20 20:26:51 -04:00
if (type === 0 && (t === 0 || t === 1)) {
x = t === 0 ? p1x : p2x;
y = t === 0 ? p1y : p2y;
} else {
// Calculate the polynomial coefficients.
var cx = 3 * (c1x - p1x),
bx = 3 * (c2x - c1x) - cx,
ax = p2x - p1x - cx - bx,
cy = 3 * (c1y - p1y),
by = 3 * (c2y - c1y) - cy,
ay = p2y - p1y - cy - by;
switch (type) {
case 0: // point
// Calculate the curve point at parameter value t
x = ((ax * t + bx) * t + cx) * t + p1x;
y = ((ay * t + by) * t + cy) * t + p1y;
break;
2013-04-20 20:26:51 -04:00
case 1: // tangent, 1st derivative
case 2: // normal, 1st derivative
// Prevent tangents and normals of length 0:
// http://stackoverflow.com/questions/10506868/
var tMin = /*#=*/ Numerical.TOLERANCE;
if (t < tMin && c1x == p1x && c1y == p1y
|| t > 1 - tMin && c2x == p2x && c2y == p2y) {
x = c2x - c1x;
y = c2y - c1y;
} else {
// Simply use the derivation of the bezier function for both
// the x and y coordinates:
x = (3 * ax * t + 2 * bx) * t + cx;
y = (3 * ay * t + 2 * by) * t + cy;
}
break;
2013-04-20 20:26:51 -04:00
case 3: // curvature, 2nd derivative
x = 6 * ax * t + 2 * bx;
y = 6 * ay * t + 2 * by;
break;
}
}
// The normal is simply the rotated tangent:
return type == 2 ? new Point(y, -x) : new Point(x, y);
},
subdivide: function(v, t) {
var p1x = v[0], p1y = v[1],
c1x = v[2], c1y = v[3],
c2x = v[4], c2y = v[5],
p2x = v[6], p2y = v[7];
if (t === undefined)
t = 0.5;
// Triangle computation, with loops unrolled.
var u = 1 - t,
// Interpolate from 4 to 3 points
p3x = u * p1x + t * c1x, p3y = u * p1y + t * c1y,
p4x = u * c1x + t * c2x, p4y = u * c1y + t * c2y,
p5x = u * c2x + t * p2x, p5y = u * c2y + t * p2y,
// Interpolate from 3 to 2 points
p6x = u * p3x + t * p4x, p6y = u * p3y + t * p4y,
p7x = u * p4x + t * p5x, p7y = u * p4y + t * p5y,
// Interpolate from 2 points to 1 point
p8x = u * p6x + t * p7x, p8y = u * p6y + t * p7y;
// We now have all the values we need to build the subcurves:
return [
[p1x, p1y, p3x, p3y, p6x, p6y, p8x, p8y], // left
[p8x, p8y, p7x, p7y, p5x, p5y, p2x, p2y] // right
];
},
// Converts from the point coordinates (p1, c1, c2, p2) for one axis to
// the polynomial coefficients and solves the polynomial for val
solveCubic: function (v, coord, val, roots) {
var p1 = v[coord],
c1 = v[coord + 2],
c2 = v[coord + 4],
p2 = v[coord + 6],
c = 3 * (c1 - p1),
b = 3 * (c2 - c1) - c,
a = p2 - p1 - c - b;
return Numerical.solveCubic(a, b, c, p1 - val, roots);
},
getParameterOf: function(v, x, y) {
// Handle beginnings and end seperately, as they are not detected
// sometimes.
if (Math.abs(v[0] - x) < /*#=*/ Numerical.TOLERANCE
&& Math.abs(v[1] - y) < /*#=*/ Numerical.TOLERANCE)
return 0;
if (Math.abs(v[6] - x) < /*#=*/ Numerical.TOLERANCE
&& Math.abs(v[7] - y) < /*#=*/ Numerical.TOLERANCE)
return 1;
var txs = [],
tys = [],
sx = Curve.solveCubic(v, 0, x, txs),
sy = Curve.solveCubic(v, 1, y, tys),
tx, ty;
// sx, sy == -1 means infinite solutions:
// Loop through all solutions for x and match with solutions for y,
// to see if we either have a matching pair, or infinite solutions
// for one or the other.
for (var cx = 0; sx == -1 || cx < sx;) {
if (sx == -1 || (tx = txs[cx++]) >= 0 && tx <= 1) {
for (var cy = 0; sy == -1 || cy < sy;) {
if (sy == -1 || (ty = tys[cy++]) >= 0 && ty <= 1) {
// Handle infinite solutions by assigning root of
// the other polynomial
if (sx == -1) tx = ty;
else if (sy == -1) ty = tx;
// Use average if we're within tolerance
if (Math.abs(tx - ty) < /*#=*/ Numerical.TOLERANCE)
return (tx + ty) * 0.5;
}
}
// Avoid endless loops here: If sx is infinite and there was
// no fitting ty, there's no solution for this bezier
if (sx == -1)
break;
}
}
return null;
},
// TODO: Find better name
getPart: function(v, from, to) {
if (from > 0)
v = Curve.subdivide(v, from)[1]; // [1] right
// Interpolate the parameter at 'to' in the new curve and
// cut there.
if (to < 1)
v = Curve.subdivide(v, (to - from) / (1 - from))[0]; // [0] left
return v;
},
isLinear: function(v) {
return v[0] === v[2] && v[1] === v[3] && v[4] === v[6] && v[5] === v[7];
},
isFlatEnough: function(v, tolerance) {
// Thanks to Kaspar Fischer and Roger Willcocks for the following:
// http://hcklbrrfnn.files.wordpress.com/2012/08/bez.pdf
var p1x = v[0], p1y = v[1],
c1x = v[2], c1y = v[3],
c2x = v[4], c2y = v[5],
p2x = v[6], p2y = v[7],
ux = 3 * c1x - 2 * p1x - p2x,
uy = 3 * c1y - 2 * p1y - p2y,
vx = 3 * c2x - 2 * p2x - p1x,
vy = 3 * c2y - 2 * p2y - p1y;
return Math.max(ux * ux, vx * vx) + Math.max(uy * uy, vy * vy)
< 10 * tolerance * tolerance;
},
getBounds: function(v) {
var min = v.slice(0, 2), // Start with values of point1
max = min.slice(), // clone
2013-04-09 10:55:09 -04:00
roots = [0, 0];
for (var i = 0; i < 2; i++)
Curve._addBounds(v[i], v[i + 2], v[i + 4], v[i + 6],
i, 0, min, max, roots);
return Rectangle.create(min[0], min[1], max[0] - min[0], max[1] - min[1]);
},
/**
* Private helper for both Curve.getBounds() and Path.getBounds(), which
* finds the 0-crossings of the derivative of a bezier curve polynomial, to
* determine potential extremas when finding the bounds of a curve.
* Note: padding is only used for Path.getBounds().
*/
_addBounds: function(v0, v1, v2, v3, coord, padding, min, max, roots) {
// Code ported and further optimised from:
// http://blog.hackers-cafe.net/2009/06/how-to-calculate-bezier-curves-bounding.html
function add(value, padding) {
var left = value - padding,
right = value + padding;
if (left < min[coord])
min[coord] = left;
if (right > max[coord])
max[coord] = right;
}
// Calculate derivative of our bezier polynomial, divided by 3.
// Doing so allows for simpler calculations of a, b, c and leads to the
// same quadratic roots.
var a = 3 * (v1 - v2) - v0 + v3,
b = 2 * (v0 + v2) - 4 * v1,
2013-02-08 19:12:57 -05:00
c = v1 - v0,
count = Numerical.solveQuadratic(a, b, c, roots),
// Add some tolerance for good roots, as t = 0 / 1 are added
// seperately anyhow, and we don't want joins to be added with
// radiuses in getStrokeBounds()
tMin = /*#=*/ Numerical.TOLERANCE,
tMax = 1 - tMin;
// Only add strokeWidth to bounds for points which lie within 0 < t < 1
// The corner cases for cap and join are handled in getStrokeBounds()
add(v3, 0);
for (var j = 0; j < count; j++) {
var t = roots[j],
u = 1 - t;
// Test for good roots and only add to bounds if good.
if (tMin < t && t < tMax)
// Calculate bezier polynomial at t.
add(u * u * u * v0
+ 3 * u * u * t * v1
+ 3 * u * t * t * v2
+ t * t * t * v3,
padding);
}
},
// We need to provide the original left curve reference to the
// #getIntersections() calls as it is required to create the resulting
2012-12-27 14:19:23 -05:00
// CurveLocation objects.
getIntersections: function(v1, v2, curve1, curve2, locations) {
var bounds1 = this.getBounds(v1),
bounds2 = this.getBounds(v2);
/*#*/ if (options.debug) {
new Path.Rectangle({
rectangle: bounds1,
strokeColor: 'green',
strokeWidth: 0.1
});
new Path.Rectangle({
rectangle: bounds2,
strokeColor: 'red',
strokeWidth: 0.1
});
/*#*/ }
if (bounds1.touches(bounds2)) {
// See if both curves are flat enough to be treated as lines, either
// because they have no control points at all, or are "flat enough"
// If the curve was flat in a previous iteration, we don't need to
// recalculate since it does not need further subdivision then.
if ((this.isLinear(v1)
|| this.isFlatEnough(v1, /*#=*/ Numerical.TOLERANCE))
&& (this.isLinear(v2)
|| this.isFlatEnough(v2, /*#=*/ Numerical.TOLERANCE))) {
/*#*/ if (options.debug) {
new Path.Line({
from: [v1[0], v1[1]],
to: [v1[6], v1[7]],
strokeColor: 'green',
strokeWidth: 0.1
});
new Path.Line({
from: [v2[0], v2[1]],
to: [v2[6], v2[7]],
strokeColor: 'red',
strokeWidth: 0.1
});
/*#*/ }
2012-12-27 14:19:23 -05:00
// See if the parametric equations of the lines interesct.
2013-04-09 23:36:38 -04:00
var point = new Line(v1[0], v1[1], v1[6], v1[7], false)
.intersect(new Line(v2[0], v2[1], v2[6], v2[7], false));
if (point) {
// Avoid duplicates when hitting segments (closed paths too)
var first = locations[0],
last = locations[locations.length - 1];
if ((!first || !point.equals(first._point))
&& (!last || !point.equals(last._point)))
// Passing null for parameter leads to lazy determination
// of parameter values in CurveLocation#getParameter()
// only once they are requested.
locations.push(new CurveLocation(curve1, null, point,
curve2));
}
} else {
2012-12-27 14:19:23 -05:00
// Subdivide both curves, and see if they intersect.
// If one of the curves is flat already, no further subdivion
// is required.
var v1s = this.subdivide(v1),
v2s = this.subdivide(v2);
for (var i = 0; i < 2; i++)
for (var j = 0; j < 2; j++)
this.getIntersections(v1s[i], v2s[j], curve1, curve2,
locations);
}
}
return locations;
}
}}, Base.each(['getBounds', 'getStrokeBounds', 'getHandleBounds', 'getRoughBounds'],
// Note: Although Curve.getBounds() exists, we are using Path.getBounds() to
// determine the bounds of Curve objects with defined segment1 and segment2
// values Curve.getBounds() can be used directly on curve arrays, without
// the need to create a Curve object first, as required by the code that
// finds path interesections.
function(name) {
this[name] = function() {
if (!this._bounds)
this._bounds = {};
var bounds = this._bounds[name];
if (!bounds) {
// Calculate the curve bounds by passing a segment list for the
// curve to the static Path.get*Boudns methods.
bounds = this._bounds[name] = Path[name](
[this._segment1, this._segment2], false, this._path._style);
}
return bounds.clone();
};
},
/** @lends Curve# */{
/**
* The bounding rectangle of the curve excluding stroke width.
*
* @name Curve#getBounds
* @type Rectangle
* @bean
*/
/**
* The bounding rectangle of the curve including stroke width.
*
* @name Curve#getStrokeBounds
* @type Rectangle
* @bean
*/
/**
* The bounding rectangle of the curve including handles.
*
* @name Curve#getHandleBounds
* @type Rectangle
* @bean
*/
/**
* The rough bounding rectangle of the curve that is shure to include all of
* the drawing, including stroke width.
*
* @name Curve#getRoughBounds
* @type Rectangle
* @bean
* @ignore
*/
2013-04-20 20:26:51 -04:00
}), Base.each(['getPoint', 'getTangent', 'getNormal', 'getCurvature'],
// Note: Although Curve.getBounds() exists, we are using Path.getBounds() to
// determine the bounds of Curve objects with defined segment1 and segment2
// values Curve.getBounds() can be used directly on curve arrays, without
// the need to create a Curve object first, as required by the code that
// finds path interesections.
function(name, index) {
this[name + 'At'] = function(offset, isParameter) {
return Curve.evaluate(this.getValues(), offset, isParameter, index);
};
// Deprecated and undocumented, but keep around for now.
// TODO: Remove once enough time has passed (28.01.2013)
this[name] = function(parameter) {
return Curve.evaluate(this.getValues(), parameter, true, index);
};
},
/** @lends Curve# */{
/**
* Calculates the curve time parameter of the specified offset on the path,
* relative to the provided start parameter. If offset is a negative value,
* the parameter is searched to the left of the start parameter. If no start
* parameter is provided, a default of {@code 0} for positive values of
* {@code offset} and {@code 1} for negative values of {@code offset}.
* @param {Number} offset
* @param {Number} [start]
* @return {Number} the curve time parameter at the specified offset.
*/
getParameterAt: function(offset, start) {
return Curve.getParameterAt(this.getValues(), offset,
start !== undefined ? start : offset < 0 ? 1 : 0);
},
/**
* Returns the curve time parameter of the specified point if it lies on the
* curve, {@code null} otherwise.
* @param {Point} point the point on the curve.
* @return {Number} the curve time parameter of the specified point.
*/
getParameterOf: function(point) {
point = Point.read(arguments);
return Curve.getParameterOf(this.getValues(), point.x, point.y);
},
/**
* Calculates the curve location at the specified offset or curve time
* parameter.
* @param {Number} offset the offset on the curve, or the curve time
* parameter if {@code isParameter} is {@code true}
* @param {Boolean} [isParameter=false] pass {@code true} if {@code offset}
* is a curve time parameter.
* @return {CurveLocation} the curve location at the specified the offset.
*/
getLocationAt: function(offset, isParameter) {
if (!isParameter)
offset = this.getParameterAt(offset);
return new CurveLocation(this, offset);
},
/**
* Returns the curve location of the specified point if it lies on the
* curve, {@code null} otherwise.
* @param {Point} point the point on the curve.
* @return {CurveLocation} the curve location of the specified point.
*/
getLocationOf: function(point) {
var t = this.getParameterOf.apply(this, arguments);
return t != null ? new CurveLocation(this, t) : null;
}
/**
* Returns the point on the curve at the specified offset.
*
* @name Curve#getPointAt
* @function
* @param {Number} offset the offset on the curve, or the curve time
* parameter if {@code isParameter} is {@code true}
* @param {Boolean} [isParameter=false] pass {@code true} if {@code offset}
* is a curve time parameter.
* @return {Point} the point on the curve at the specified offset.
*/
/**
2013-04-20 20:26:51 -04:00
* Returns the tangent vector of the curve at the specified position.
*
* @name Curve#getTangentAt
* @function
* @param {Number} offset the offset on the curve, or the curve time
* parameter if {@code isParameter} is {@code true}
* @param {Boolean} [isParameter=false] pass {@code true} if {@code offset}
* is a curve time parameter.
2013-04-20 20:26:51 -04:00
* @return {Point} the tangent of the curve at the specified offset.
*/
/**
2013-04-20 20:26:51 -04:00
* Returns the normal vector of the curve at the specified position.
*
* @name Curve#getNormalAt
* @function
* @param {Number} offset the offset on the curve, or the curve time
* parameter if {@code isParameter} is {@code true}
* @param {Boolean} [isParameter=false] pass {@code true} if {@code offset}
* is a curve time parameter.
* @return {Point} the normal of the curve at the specified offset.
2013-04-20 20:26:51 -04:00
*/
/**
* Returns the curvature vector of the curve at the specified position.
*
* @name Curve#getCurvatureAt
* @function
* @param {Number} offset the offset on the curve, or the curve time
* parameter if {@code isParameter} is {@code true}
* @param {Boolean} [isParameter=false] pass {@code true} if {@code offset}
2013-04-20 20:26:51 -04:00
* is a curve time parameter.
* @return {Point} the curvature of the curve at the specified offset.
*/
}),
new function() { // Scope for methods that require numerical integration
function getLengthIntegrand(v) {
// Calculate the coefficients of a Bezier derivative.
var p1x = v[0], p1y = v[1],
c1x = v[2], c1y = v[3],
c2x = v[4], c2y = v[5],
p2x = v[6], p2y = v[7],
ax = 9 * (c1x - c2x) + 3 * (p2x - p1x),
bx = 6 * (p1x + c2x) - 12 * c1x,
cx = 3 * (c1x - p1x),
ay = 9 * (c1y - c2y) + 3 * (p2y - p1y),
by = 6 * (p1y + c2y) - 12 * c1y,
cy = 3 * (c1y - p1y);
return function(t) {
// Calculate quadratic equations of derivatives for x and y
var dx = (ax * t + bx) * t + cx,
dy = (ay * t + by) * t + cy;
return Math.sqrt(dx * dx + dy * dy);
2011-05-02 06:23:42 -04:00
};
}
2011-03-25 13:58:20 -04:00
// Amount of integral evaluations for the interval 0 <= a < b <= 1
function getIterations(a, b) {
// Guess required precision based and size of range...
// TODO: There should be much better educated guesses for
// this. Also, what does this depend on? Required precision?
return Math.max(2, Math.min(16, Math.ceil(Math.abs(b - a) * 32)));
}
return {
statics: true,
getLength: function(v, a, b) {
if (a === undefined)
a = 0;
if (b === undefined)
b = 1;
// if (p1 == c1 && p2 == c2):
if (v[0] == v[2] && v[1] == v[3] && v[6] == v[4] && v[7] == v[5]) {
// Straight line
var dx = v[6] - v[0], // p2x - p1x
dy = v[7] - v[1]; // p2y - p1y
return (b - a) * Math.sqrt(dx * dx + dy * dy);
}
var ds = getLengthIntegrand(v);
return Numerical.integrate(ds, a, b, getIterations(a, b));
},
getArea: function(v) {
var p1x = v[0], p1y = v[1],
c1x = v[2], c1y = v[3],
c2x = v[4], c2y = v[5],
p2x = v[6], p2y = v[7];
// http://objectmix.com/graphics/133553-area-closed-bezier-curve.html
2013-04-25 20:47:11 -04:00
return ( 3.0 * c1y * p1x - 1.5 * c1y * c2x
- 1.5 * c1y * p2x - 3.0 * p1y * c1x
- 1.5 * p1y * c2x - 0.5 * p1y * p2x
+ 1.5 * c2y * p1x + 1.5 * c2y * c1x
- 3.0 * c2y * p2x + 0.5 * p2y * p1x
+ 1.5 * p2y * c1x + 3.0 * p2y * c2x) / 10;
},
getParameterAt: function(v, offset, start) {
2013-04-25 20:47:11 -04:00
if (offset === 0)
return start;
// See if we're going forward or backward, and handle cases
// differently
var forward = offset > 0,
a = forward ? start : 0,
b = forward ? 1 : start,
offset = Math.abs(offset),
// Use integrand to calculate both range length and part
// lengths in f(t) below.
ds = getLengthIntegrand(v),
// Get length of total range
rangeLength = Numerical.integrate(ds, a, b,
getIterations(a, b));
if (offset >= rangeLength)
return forward ? b : a;
// Use offset / rangeLength for an initial guess for t, to
// bring us closer:
var guess = offset / rangeLength,
length = 0;
// Iteratively calculate curve range lengths, and add them up,
// using integration precision depending on the size of the
// range. This is much faster and also more precise than not
// modifing start and calculating total length each time.
function f(t) {
var count = getIterations(start, t);
length += start < t
? Numerical.integrate(ds, start, t, count)
: -Numerical.integrate(ds, t, start, count);
start = t;
return length - offset;
}
return Numerical.findRoot(f, ds,
forward ? a + guess : b - guess, // Initial guess for x
a, b, 16, /*#=*/ Numerical.TOLERANCE);
}
};
}, new function() { // Scope for nearest point on curve problem
// Solving the Nearest Point-on-Curve Problem and A Bezier-Based Root-Finder
// by Philip J. Schneider from "Graphics Gems", Academic Press, 1990
// Optimised for Paper.js
var maxDepth = 32,
epsilon = Math.pow(2, -maxDepth - 1);
2011-07-07 10:09:02 -04:00
var zCubic = [
[1.0, 0.6, 0.3, 0.1],
[0.4, 0.6, 0.6, 0.4],
[0.1, 0.3, 0.6, 1.0]
];
var xAxis = new Line(new Point(0, 0), new Point(1, 0));
/**
* Given a point and a Bezier curve, generate a 5th-degree Bezier-format
* equation whose solution finds the point on the curve nearest the
* user-defined point.
*/
function toBezierForm(v, point) {
var n = 3, // degree of B(t)
degree = 5, // degree of B(t) . P
c = [],
d = [],
cd = [],
w = [];
for(var i = 0; i <= n; i++) {
// Determine the c's -- these are vectors created by subtracting
// point point from each of the control points
c[i] = v[i].subtract(point);
// Determine the d's -- these are vectors created by subtracting
// each control point from the next
if (i < n)
d[i] = v[i + 1].subtract(v[i]).multiply(n);
}
// Create the c,d table -- this is a table of dot products of the
// c's and d's
for (var row = 0; row < n; row++) {
cd[row] = [];
2011-07-07 10:09:02 -04:00
for (var column = 0; column <= n; column++)
cd[row][column] = d[row].dot(c[column]);
}
// Now, apply the z's to the dot products, on the skew diagonal
// Also, set up the x-values, making these "points"
for (var i = 0; i <= degree; i++)
w[i] = new Point(i / degree, 0);
2012-08-07 12:10:53 -04:00
for (var k = 0; k <= degree; k++) {
var lb = Math.max(0, k - n + 1),
ub = Math.min(k, n);
for (var i = lb; i <= ub; i++) {
var j = k - i;
w[k].y += cd[j][i] * zCubic[j][i];
}
}
return w;
}
/**
* Given a 5th-degree equation in Bernstein-Bezier form, find all of the
* roots in the interval [0, 1]. Return the number of roots found.
*/
function findRoots(w, depth) {
switch (countCrossings(w)) {
case 0:
// No solutions here
return [];
case 1:
// Unique solution
// Stop recursion when the tree is deep enough
// if deep enough, return 1 solution at midpoint
if (depth >= maxDepth)
return [0.5 * (w[0].x + w[5].x)];
// Compute intersection of chord from first control point to last
// with x-axis.
if (isFlatEnough(w)) {
var line = new Line(w[0], w[5], true);
return [ Numerical.isZero(line.vector.getLength(true))
? line.point.x
: xAxis.intersect(line).x ];
}
}
// Otherwise, solve recursively after
// subdividing control polygon
var p = [[]],
left = [],
right = [];
for (var j = 0; j <= 5; j++)
2013-04-25 20:47:11 -04:00
p[0][j] = new Point(w[j]);
// Triangle computation
for (var i = 1; i <= 5; i++) {
p[i] = [];
for (var j = 0 ; j <= 5 - i; j++)
p[i][j] = p[i - 1][j].add(p[i - 1][j + 1]).multiply(0.5);
}
for (var j = 0; j <= 5; j++) {
left[j] = p[j][0];
right[j] = p[5 - j][j];
}
return findRoots(left, depth + 1).concat(findRoots(right, depth + 1));
}
/**
* Count the number of times a Bezier control polygon crosses the x-axis.
* This number is >= the number of roots.
*/
function countCrossings(v) {
var crossings = 0,
prevSign = null;
for (var i = 0, l = v.length; i < l; i++) {
var sign = v[i].y < 0 ? -1 : 1;
if (prevSign != null && sign != prevSign)
crossings++;
prevSign = sign;
}
return crossings;
}
/**
* Check if the control polygon of a Bezier curve is flat enough for
* recursive subdivision to bottom out.
*/
function isFlatEnough(v) {
// Find the perpendicular distance from each interior control point to
// line connecting v[0] and v[degree]
// Derive the implicit equation for line connecting first
// and last control points
var n = v.length - 1,
a = v[0].y - v[n].y,
b = v[n].x - v[0].x,
c = v[0].x * v[n].y - v[n].x * v[0].y,
maxAbove = 0,
maxBelow = 0;
// Find the largest distance
for (var i = 1; i < n; i++) {
// Compute distance from each of the points to that line
var val = a * v[i].x + b * v[i].y + c,
2011-07-08 16:26:22 -04:00
dist = val * val;
if (val < 0 && dist > maxBelow) {
maxBelow = dist;
} else if (dist > maxAbove) {
maxAbove = dist;
}
}
// Compute intercepts of bounding box
2011-07-08 16:26:22 -04:00
return Math.abs((maxAbove + maxBelow) / (2 * a * (a * a + b * b)))
< epsilon;
}
return {
getNearestLocation: function(point) {
// NOTE: If we allow #matrix on Path, we need to inverse-transform
// point here first.
// point = this._matrix.inverseTransform(point);
var w = toBezierForm(this.getPoints(), point);
// Also look at beginning and end of curve (t = 0 / 1)
var roots = findRoots(w, 0).concat([0, 1]);
2011-07-06 16:21:49 -04:00
var minDist = Infinity,
minT,
minPoint;
2011-07-06 16:21:49 -04:00
// There are always roots, since we add [0, 1] above.
for (var i = 0; i < roots.length; i++) {
var pt = this.getPointAt(roots[i], true),
dist = point.getDistance(pt, true);
// We're comparing squared distances
2011-07-06 16:21:49 -04:00
if (dist < minDist) {
minDist = dist;
minT = roots[i];
2011-07-06 16:21:49 -04:00
minPoint = pt;
}
}
return new CurveLocation(this, minT, minPoint, null,
Math.sqrt(minDist));
},
getNearestPoint: function(point) {
return this.getNearestLocation(point).getPoint();
}
};
});