diff --git a/docs/chapters/arcapproximation/arc.js b/docs/chapters/arcapproximation/arc.js new file mode 100644 index 00000000..66d19e94 --- /dev/null +++ b/docs/chapters/arcapproximation/arc.js @@ -0,0 +1,101 @@ +// setup={this.setupCubic} draw={this.drawSingleArc} onKeyDown={this.props.onKeyDown} + +let curve, utils = Bezier.getUtils(); + +setup() { + curve = Bezier.defaultCubic(this); + setMovable(curve.points); + setSlider(`.slide-control`, `error`, 0.5); +} + +draw() { + clear(); + + curve.drawSkeleton(); + curve.drawCurve(); + + setColor(`#FF000040`); + let a = this.getArc(curve); + arc( + a.x, a.y, a.r, a.s, a.e, + // draw a wedge, not just the arc + a.x, a.y + ); + + setColor("black"); + text(`Arc approximation with total error ${this.error}`, this.width/2, 15, CENTER); + curve.drawPoints(); +} + +getArc(curve) { + let ts = 0, + te = 1, + tm = te, + safety = 0, + np1 = curve.get(ts), np2, np3, + arc, + currGood = false, + prevGood = false, + done, + prev_e = 1, + step = 0; + + // Find where the good/bad boundary is + te = 1; + + // step 2: find the best possible arc + do { + prevGood = currGood; + tm = (ts + te) / 2; + step++; + + np2 = curve.get(tm); + np3 = curve.get(te); + + arc = utils.getccenter(np1, np2, np3); + arc.interval = { start: ts, end: te, }; + + let error = this.computeError(arc, np1, ts, te); + currGood = (error <= this.error); + + done = prevGood && !currGood; + if (!done) prev_e = te; + + // this arc is fine: try a wider arc + if (currGood) { + // if e is already at max, then we're done for this arc. + if (te >= 1) { + // make sure we cap at t=1 + arc.interval.end = prev_e = 1; + // if we capped the arc segment to t=1 we also need to make sure that + // the arc's end angle is correct with respect to the bezier end point. + if (te > 1) { + let d = { + x: arc.x + arc.r * cos(arc.e), + y: arc.y + arc.r * sin(arc.e), + }; + arc.e += utils.angle({ x: arc.x, y: arc.y }, d, curve.points[3]); + } + done = true; + break; + } + // if not, move it up by half the iteration distance + te = te + (te - ts) / 2; + } + + // This is a bad arc: we need to move 'e' down to find a good arc + else { te = tm; } + } while (!done && safety++ < 100); + + return arc; +} + +computeError(pc, np1, s, e) { + const q = (e - s) / 4, + c1 = curve.get(s + q), + c2 = curve.get(e - q), + ref = dist(pc.x, pc.y, np1.x, np1.y), + d1 = dist(pc.x, pc.y, c1.x, c1.y), + d2 = dist(pc.x, pc.y, c2.x, c2.y); + return abs(d1 - ref) + abs(d2 - ref); +} diff --git a/docs/chapters/arcapproximation/arcs.js b/docs/chapters/arcapproximation/arcs.js new file mode 100644 index 00000000..607ecf8f --- /dev/null +++ b/docs/chapters/arcapproximation/arcs.js @@ -0,0 +1,30 @@ +// setup={this.setupCubic} draw={this.drawSingleArc} onKeyDown={this.props.onKeyDown} + +let curve, utils = Bezier.getUtils(); + +setup() { + curve = Bezier.defaultCubic(this); + setMovable(curve.points); + setSlider(`.slide-control`, `error`, 0.5); +} + +draw() { + clear(); + + curve.drawSkeleton(); + curve.drawCurve(); + + // See "arc.js" for the code required to find arcs on the curve. + let arcs = curve.arcs(this.error); + arcs.forEach(a => { + setColor( randomColor(0.3) ); + arc( + a.x, a.y, a.r, a.s, a.e, + a.x, a.y + ); + }); + + setColor("black"); + text(`Arc approximation with total error ${this.error}`, this.width/2, 15, CENTER); + curve.drawPoints(); +} diff --git a/docs/chapters/arcapproximation/content.en-GB.md b/docs/chapters/arcapproximation/content.en-GB.md index ffadbae0..1019c1e9 100644 --- a/docs/chapters/arcapproximation/content.en-GB.md +++ b/docs/chapters/arcapproximation/content.en-GB.md @@ -6,44 +6,40 @@ We already saw in the section on circle approximation that this will never yield The approach is fairly simple: pick a starting point on the curve, and pick two points that are further along the curve. Determine the circle that goes through those three points, and see if it fits the part of the curve we're trying to approximate. Decent fit? Try spacing the points further apart. Bad fit? Try spacing the points closer together. Keep doing this until you've found the "good approximation/bad approximation" boundary, record the "good" arc, and then move the starting point up to overlap the end point we previously found. Rinse and repeat until we've covered the entire curve. -So: step 1, how do we find a circle through three points? That part is actually really simple. You may remember (if you ever learned it!) that a line between two points on a circle is called a [chord](https://en.wikipedia.org/wiki/Chord_%28geometry%29), and one property of chords is that the line from the center of any chord, perpendicular to that chord, passes through the center of the circle. +We already saw how to fit a circle through three points in the section on [creating a curve from three points](#pointcurves), and finding the arc through those points is straight-forward: pick one of the three points as start point, pick another as an end point, and the arc has to necessarily go from the start point, to the end point, over the remaining point. -So: if we have have three points, we have three (different) chords, and consequently, three (different) lines that go from those chords through the center of the circle. So we find the centers of the chords, find the perpendicular lines, find the intersection of those lines, and thus find the center of the circle. +So, how can we convert a Bézier curve into a (sequence of) circular arc(s)? -The following graphic shows this procedure with a different colour for each chord and its associated perpendicular through the center. You can move the points around as much as you like, those lines will always meet! - - - -So, with the procedure on how to find a circle through three points, finding the arc through those points is straight-forward: pick one of the three points as start point, pick another as an end point, and the arc has to necessarily go from the start point, over the remaining point, to the end point. - -So how can we convert a Bézier curve into a (sequence of) circular arc(s)? - -- Start at t=0 -- Pick two points further down the curve at some value m = t + n and e = t + 2n +- Start at `t=0` +- Pick two points further down the curve at some value `m = t + n` and `e = t + 2n` - Find the arc that these points define - Determine how close the found arc is to the curve: - - Pick two additional points e1 = t + n/2 and e2 = t + n + n/2. + - Pick two additional points `e1 = t + n/2` and `e2 = t + n + n/2`. - These points, if the arc is a good approximation of the curve interval chosen, should - lie on the circle, so their distance to the center of the circle should be the + lie `on` the circle, so their distance to the center of the circle should be the same as the distance from any of the three other points to the center. - For point points, determine the (absolute) error between the radius of the circle, and the - actual distance from the center of the circle to the point on the curve. + `actual` distance from the center of the circle to the point on the curve. - If this error is too high, we consider the arc bad, and try a smaller interval. -The result of this is shown in the next graphic: we start at a guaranteed failure: s=0, e=1. That's the entire curve. The midpoint is simply at t=0.5, and then we start performing a [Binary Search](https://en.wikipedia.org/wiki/Binary_search_algorithm). +The result of this is shown in the next graphic: we start at a guaranteed failure: s=0, e=1. That's the entire curve. The midpoint is simply at `t=0.5`, and then we start performing a [binary search](https://en.wikipedia.org/wiki/Binary_search_algorithm). -1. We start with {0, 0.5, 1} -2. That'll fail, so we retry with the interval halved: {0, 0.25, 0.5} - - If that arc's good, we move back up by half distance: {0, 0.375, 0.75}. - - However, if the arc was still bad, we move down by half the distance: {0, 0.125, 0.25}. -3. We keep doing this over and over until we have two arcs found in sequence of which the first arc is good, and the second arc is bad. When we find that pair, we've found the boundary between a good approximation and a bad approximation, and we pick the former. +1. We start with `low=0`, `mid=0.5` and `high=1` +2. That'll fail, so we retry with the interval halved: `{0, 0.25, 0.5}` + - If that arc's good, we move back up by half distance: `{0, 0.375, 0.75}`. + - However, if the arc was still bad, we move _down_ by half the distance: `{0, 0.125, 0.25}`. +3. We keep doing this over and over until we have two arcs, in sequence, of which the first arc is good, and the second arc is bad. When we find that pair, we've found the boundary between a good approximation and a bad approximation, and we pick the good arc. The following graphic shows the result of this approach, with a default error threshold of 0.5, meaning that if an arc is off by a combined half pixel over both verification points, then we treat the arc as bad. This is an extremely simple error policy, but already works really well. Note that the graphic is still interactive, and you can use your up and down arrow keys keys to increase or decrease the error threshold, to see what the effect of a smaller or larger error threshold is. - + + + With that in place, all that's left now is to "restart" the procedure by treating the found arc's end point as the new to-be-determined arc's starting point, and using points further down the curve. We keep trying this until the found end point is for t=1, at which point we are done. Again, the following graphic allows for up and down arrow key input to increase or decrease the error threshold, so you can see how picking a different threshold changes the number of arcs that are necessary to reasonably approximate a curve: - + + + So... what is this good for? Obviously, if you're working with technologies that can't do curves, but can do lines and circles, then the answer is pretty straightforward, but what else? There are some reasons why you might need this technique: using circular arcs means you can determine whether a coordinate lies "on" your curve really easily (simply compute the distance to each circular arc center, and if any of those are close to the arc radii, at an angle between the arc start and end, bingo, this point can be treated as lying "on the curve"). Another benefit is that this approximation is "linear": you can almost trivially travel along the arcs at fixed speed. You can also trivially compute the arc length of the approximated curve (it's a bit like curve flattening). The only thing to bear in mind is that this is a lossy equivalence: things that you compute based on the approximation are guaranteed "off" by some small value, and depending on how much precision you need, arc approximation is either going to be super useful, or completely useless. It's up to you to decide which, based on your application! diff --git a/docs/chapters/arcapproximation/handler.js b/docs/chapters/arcapproximation/handler.js deleted file mode 100644 index 084fbd64..00000000 --- a/docs/chapters/arcapproximation/handler.js +++ /dev/null @@ -1,184 +0,0 @@ -var atan2 = Math.atan2, PI = Math.PI, TAU = 2*PI, cos = Math.cos, sin = Math.sin; - -module.exports = { - // These are functions that can be called "From the page", - // rather than being internal to the sketch. This is useful - // for making on-page controls hook into the sketch code. - statics: { - keyHandlingOptions: { - propName: "error", - values: { - "38": 0.1, // up arrow - "40": -0.1 // down arrow - }, - controller: function(api) { - if (api.error < 0.1) { - api.error = 0.1; - } - } - } - }, - - /** - * Setup up a skeleton curve that, when using its - * points for a B-spline, can form a circle. - */ - setupCircle: function(api) { - var curve = new api.Bezier(70,70, 140,40, 240,130); - api.setCurve(curve); - }, - - /** - * Set up the default quadratic curve. - */ - setupQuadratic: function(api) { - var curve = api.getDefaultQuadratic(); - api.setCurve(curve); - }, - - /** - * Set up the default cubic curve. - */ - setupCubic: function(api) { - var curve = api.getDefaultCubic(); - api.setCurve(curve); - api.error = 0.5; - }, - - /** - * Given three points, find the (only!) circle - * that passes through all three points, based - * on the fact that the perpendiculars of the - * chords between the points all cross each - * other at the center of that circle. - */ - getCCenter: function(api, p1, p2, p3) { - // deltas - var dx1 = (p2.x - p1.x), - dy1 = (p2.y - p1.y), - dx2 = (p3.x - p2.x), - dy2 = (p3.y - p2.y); - - // perpendiculars (quarter circle turned) - var dx1p = dx1 * cos(PI/2) - dy1 * sin(PI/2), - dy1p = dx1 * sin(PI/2) + dy1 * cos(PI/2), - dx2p = dx2 * cos(PI/2) - dy2 * sin(PI/2), - dy2p = dx2 * sin(PI/2) + dy2 * cos(PI/2); - - // chord midpoints - var mx1 = (p1.x + p2.x)/2, - my1 = (p1.y + p2.y)/2, - mx2 = (p2.x + p3.x)/2, - my2 = (p2.y + p3.y)/2; - - // midpoint offsets - var mx1n = mx1 + dx1p, - my1n = my1 + dy1p, - mx2n = mx2 + dx2p, - my2n = my2 + dy2p; - - // intersection of these lines: - var i = api.utils.lli8(mx1,my1,mx1n,my1n, mx2,my2,mx2n,my2n); - var r = api.utils.dist(i,p1); - - // arc start/end values, over mid point - var s = atan2(p1.y - i.y, p1.x - i.x), - m = atan2(p2.y - i.y, p2.x - i.x), - e = atan2(p3.y - i.y, p3.x - i.x); - - // determine arc direction (cw/ccw correction) - var __; - if (sm || m>e) { s += TAU; } - if (s>e) { __=e; e=s; s=__; } - } else { - if (e api.drawCircle(p,3)); - - // chords and perpendicular lines - var m; - - api.setColor("blue"); - api.drawLine(pts[0], pts[1]); - m = {x: (pts[0].x + pts[1].x)/2, y: (pts[0].y + pts[1].y)/2}; - api.drawLine(m, {x:C.x+(C.x-m.x), y:C.y+(C.y-m.y)}); - - api.setColor("red"); - api.drawLine(pts[1], pts[2]); - m = {x: (pts[1].x + pts[2].x)/2, y: (pts[1].y + pts[2].y)/2}; - api.drawLine(m, {x:C.x+(C.x-m.x), y:C.y+(C.y-m.y)}); - - api.setColor("green"); - api.drawLine(pts[2], pts[0]); - m = {x: (pts[2].x + pts[0].x)/2, y: (pts[2].y + pts[0].y)/2}; - api.drawLine(m, {x:C.x+(C.x-m.x), y:C.y+(C.y-m.y)}); - - // center - api.setColor("black"); - api.drawPoint(C); - api.setFill("black"); - api.text("Intersection point", C, {x:-25, y:10}); - }, - - /** - * Draw a single arc being fit to a Bezier curve, - * to show off the general application. - */ - drawSingleArc: function(api, curve) { - api.reset(); - var arcs = curve.arcs(api.error); - api.drawSkeleton(curve); - api.drawCurve(curve); - - var a = arcs[0]; - api.setColor("red"); - api.setFill("rgba(255,0,0,0.2)"); - api.debug = true; - api.drawArc(a); - - api.setFill("black"); - api.text("Arc approximation with total error " + api.utils.round(api.error,1), {x:10, y:15}); - }, - - /** - * Draw an arc approximation for an entire Bezier curve. - */ - drawArcs: function(api, curve) { - api.reset(); - var arcs = curve.arcs(api.error); - api.drawSkeleton(curve); - api.drawCurve(curve); - arcs.forEach(a => { - api.setRandomColor(0.3); - api.setFill(api.getColor()); - api.drawArc(a); - }); - - api.setFill("black"); - api.text("Arc approximation with total error " + api.utils.round(api.error,1) + " per arc segment", {x:10, y:15}); - } -}; diff --git a/docs/chapters/bsplined/content.en-GB.md b/docs/chapters/bsplined/content.en-GB.md index 967ff0de..db104be2 100644 --- a/docs/chapters/bsplined/content.en-GB.md +++ b/docs/chapters/bsplined/content.en-GB.md @@ -24,41 +24,47 @@ So, much as for Bézier derivatives, we see a derivative function that is simply As a concrete example, let's look at cubic (=degree 3) B-Spline with five coordinates, and with uniform knot vector of length 3 + 5 + 1 = 9: -\[\begin{array}{l} - d = 3, \\ - P = {(50,240), (185,30), (320,135), (455,25), (560,255)}, \\ - knots = {0,1,2,3,4,5,6,7,8} -\end{array}\] +\[ + \begin{array}{l} + d = 3, \\ + P = {(50,240), (185,30), (320,135), (455,25), (560,255)}, \\ + knots = {0,1,2,3,4,5,6,7,8} + \end{array} +\] Applying the above knowledge, we end up with a new B-Spline of degree d-1, with four points P': -\[\begin{array}{l} - P_0 \prime = \frac{d}{knot_{i+d+1} - knot_{i+1}} (P_{i+1} - P_i) - = \frac{3}{knot_{4} - knot_{1}} (P_1 - P_0) - = \frac{3}{3} (P_1 - P_0) - = (135, -210) \\ - P_1 \prime = \frac{d}{knot_{i+d+1} - knot_{i+1}} (P_{i+1} - P_i) - = \frac{3}{knot_{5} - knot_{2}} (P_2 - P_1) - = \frac{3}{3} (P_2 - P_1) - = (135, 105) \\ - P_2 \prime = \frac{d}{knot_{i+d+1} - knot_{i+1}} (P_{i+1} - P_i) - = \frac{3}{knot_{6} - knot_{3}} (P_3 - P_2) - = \frac{3}{3} (P_3 - P_2) - = (135, -110) \\ - P_3 \prime = \frac{d}{knot_{i+d+1} - knot_{i+1}} (P_{i+1} - P_i) - = \frac{3}{knot_{7} - knot_{4}} (P_4 - P_3) - = \frac{3}{3} (P_4 - P_3) - = (105, 230) \\ -\end{array}\] +\[ + \begin{array}{l} + P_0 \prime = \frac{d}{knot_{i+d+1} - knot_{i+1}} (P_{i+1} - P_i) + = \frac{3}{knot_{4} - knot_{1}} (P_1 - P_0) + = \frac{3}{3} (P_1 - P_0) + = (135, -210) \\ + P_1 \prime = \frac{d}{knot_{i+d+1} - knot_{i+1}} (P_{i+1} - P_i) + = \frac{3}{knot_{5} - knot_{2}} (P_2 - P_1) + = \frac{3}{3} (P_2 - P_1) + = (135, 105) \\ + P_2 \prime = \frac{d}{knot_{i+d+1} - knot_{i+1}} (P_{i+1} - P_i) + = \frac{3}{knot_{6} - knot_{3}} (P_3 - P_2) + = \frac{3}{3} (P_3 - P_2) + = (135, -110) \\ + P_3 \prime = \frac{d}{knot_{i+d+1} - knot_{i+1}} (P_{i+1} - P_i) + = \frac{3}{knot_{7} - knot_{4}} (P_4 - P_3) + = \frac{3}{3} (P_4 - P_3) + = (105, 230) \\ + \end{array} +\] So, we end up with a derivative that has as parameters: -\[\begin{array}{l} - d = 3, \\ - P = {(50,240), (185,30), (320,135), (455,25), (560,255)}, \\ - knots = {0,1,2,3,4,5,6,7,8} -\end{array}\] +\[ + \begin{array}{l} + d = 3, \\ + P = {(50,240), (185,30), (320,135), (455,25), (560,255)}, \\ + knots = {0,1,2,3,4,5,6,7,8} + \end{array} +\] diff --git a/docs/chapters/bsplines/basic-sketch.js b/docs/chapters/bsplines/basic-sketch.js deleted file mode 100644 index 9a3e97af..00000000 --- a/docs/chapters/bsplines/basic-sketch.js +++ /dev/null @@ -1,30 +0,0 @@ -module.exports = { - degree: 3, - activeDistance: 9, - - setup() { - this.size(600, 300); - this.draw(); - }, - - draw() { - this.clear(); - this.grid(25); - var p = this.points[0]; - this.points.forEach(n => { - this.stroke(200); - this.line(n.x, n.y, p.x, p.y); - p = n; - this.stroke(0); - this.circle(p.x, p.y, 4); - }); - this.drawSplineData(); - }, - - drawSplineData() { - if (this.points.length <= this.degree) return; - var mapped = this.points.map(p => [p.x, p.y]); - this.drawCurve(mapped); - this.drawKnots(mapped); - } -}; diff --git a/docs/chapters/bsplines/basic.js b/docs/chapters/bsplines/basic.js new file mode 100644 index 00000000..8251fc19 --- /dev/null +++ b/docs/chapters/bsplines/basic.js @@ -0,0 +1,57 @@ +let points=[]; + +setup() { + points = [ + {x:25, y:160}, + {x:90, y:75}, + {x:190,y:245}, + {x:290,y:25}, + {x:400,y:255}, + {x:480,y:70}, + {x:560,y:170} + ]; + setMovable(points); +} + +draw() { + clear(); + + setStroke(`lightgrey`); + drawGrid(20); + + setStroke(`#CC00CC99`); + for (let i=0, e=points.length-1, p, n; i circle(p.x, p.y, 3)); + + this.drawSplineData(); +} + +drawSplineData() { + // we'll need at least 4 points + if (points.length <= 3) return; + + let spline = new BSpline(this, points); + + noFill(); + setStroke(`black`); + start(); + spline.getLUT((points.length - 3) * 20).forEach(p => vertex(p.x, p.y)); + end(); +} + +onMouseDown() { + if (!this.currentPoint) { + points.push({ + x: this.cursor.x, + y: this.cursor.y + }); + resetMovable(points); + redraw(); + } +} diff --git a/docs/chapters/bsplines/center-cut-bspline.js b/docs/chapters/bsplines/center-cut-bspline.js deleted file mode 100644 index bc3a6f4a..00000000 --- a/docs/chapters/bsplines/center-cut-bspline.js +++ /dev/null @@ -1,52 +0,0 @@ -module.exports = { - degree: 3, - activeDistance: 9, - - setup() { - this.size(400, 400); - - var TAU = Math.PI*2; - for (let i=0; i { - this.stroke(200); - this.line(n.x, n.y, p.x, p.y); - p = n; - this.stroke(0); - this.circle(p.x, p.y, 4); - }); - this.drawSplineData(); - }, - - drawSplineData() { - if (this.points.length <= this.degree) return; - var mapped = this.points.map(p => [p.x, p.y]); - this.drawCurve(mapped); - this.drawKnots(mapped); - } -}; diff --git a/docs/chapters/bsplines/content.en-GB.md b/docs/chapters/bsplines/content.en-GB.md index 0bf1fd2e..5502fc08 100644 --- a/docs/chapters/bsplines/content.en-GB.md +++ b/docs/chapters/bsplines/content.en-GB.md @@ -4,9 +4,9 @@ No discussion on Bézier curves is complete without also giving mention of that First off: B-Splines are [piecewise polynomial interpolation curves](https://en.wikipedia.org/wiki/Piecewise), where the "single curve" is built by performing polynomial interpolation over a set of points, using a sliding window of a fixed number of points. For instance, a "cubic" B-Spline defined by twelve points will have its curve built by evaluating the polynomial interpolation of four points, and the curve can be treated as a lot of different sections, each controlled by four points at a time, such that the full curve consists of smoothly connected sections defined by points {1,2,3,4}, {2,3,4,5}, ..., {8,9,10,11}, and finally {9,10,11,12}, for eight sections. -What do they look like? They look like this! .. okay that's an empty graph, but simply click to place some point, with the stipulation that you need at least four point to see any curve. More than four points simply draws a longer B-Spline curve: +What do they look like? They look like this! Tap on the graphic to add more points, and move points around to see how they map to the spline curve drawn. - + The important part to notice here is that we are **not** doing the same thing with B-Splines that we do for poly-Béziers or Catmull-Rom curves: both of the latter simply define new sections as literally "new sections based on new points", so a 12 point cubic poly-Bézier curve is actually impossible, because we start with a four point curve, and then add three more points for each section that follows, so we can only have 4, 7, 10, 13, 16, etc point Poly-Béziers. Similarly, while Catmull-Rom curves can grow by adding single points, this addition of a single point introduces three implicit Bézier points. Cubic B-Splines, on the other hand, are smooth interpolations of *each possible curve involving four consecutive points*, such that at any point along the curve except for our start and end points, our on-curve coordinate is defined by four control points. @@ -17,6 +17,7 @@ Consider the difference to be this: In order to make this interpolation of curves work, the maths is necessarily more complex than the maths for Bézier curves, so let's have a look at how things work. + ## How to compute a B-Spline curve: some maths Given a B-Spline of degree `d` and thus order `k=d+1` (so a quadratic B-Spline is degree 2 and order 3, a cubic B-Spline is degree 3 and order 4, etc) and `n` control points `P0` through `Pn-1`, we can compute a point on the curve for some value `t` in the interval [0,1] (where 0 is the start of the curve, and 1 the end, just like for Bézier curves), by evaluating the following function: @@ -47,6 +48,7 @@ So this is where we see the interpolation: N(t) for an (i,k) pair (that is, for And this function finally has a straight up evaluation: if a `t` value lies within a knot-specific interval once we reach a `k=1` value, it "counts", otherwise it doesn't. We did cheat a little, though, because for all these values we need to scale our `t` value first, so that it lies in the interval bounded by `knots[d]` and `knots[n]`, which are the start point and end point where curvature is controlled by exactly `order` control points. For instance, for degree 3 (=order 4) and 7 control points, with knot vector [1,2,3,4,5,6,7,8,9,10,11], we map `t` from [the interval 0,1] to the interval [4,8], and then use that value in the functions above, instead. + ## Can we simplify that? We can, yes. @@ -98,10 +100,13 @@ One thing we need to keep in mind is that we're working with a spline that is co If we run this computation "down", starting at d(3,3), then without special code in place we would be computing quite a few terms multiple times at each step. On the other hand, we can also start with that last "column", we can generate the terminating d() values first, then compute the a() constants, perform our multiplications, generate the previous step's d() values, compute their a() constants, do the multiplications, etc. until we end up all the way back at the top. If we run our computation this way, we don't need any explicit caching, we can just "recycle" the list of numbers we start with and simply update them as we move up the triangle. So, let's implement that! + ## Cool, cool... but I don't know what to do with that information I know, this is pretty mathy, so let's have a look at what happens when we change parameters here. We can't change the maths for the interpolation functions, so that gives us only one way to control what happens here: the knot vector itself. As such, let's look at the graph that shows the interpolation functions for a cubic B-Spline with seven points with a uniform knot vector (so we see seven identical functions), representing how much each point (represented by one function each) influences the total curvature, given our knot values. And, because exploration is the key to discovery, let's make the knot vector a thing we can actually manipulate. Normally a proper knot vector has a constraint that any value is strictly equal to, or larger than the previous ones, but screw it this is programming, let's ignore that hard restriction and just mess with the knots however we like. + +
this.bindKnots(owner, knots, "interpolation-graph")}/> @@ -111,6 +116,7 @@ Changing the values in the knot vector changes how much each point influences th After reading the rest of this section you may want to come back here to try some specific knot vectors, and see if the resulting interpolation landscape makes sense given what you will now think should happen! + ## Running the computation Unlike the de Casteljau algorithm, where the `t` value stays the same at every iteration, for B-Splines that is not the case, and so we end having to (for each point we evaluate) run a fairly involving bit of recursive computation. The algorithm is discussed on [this Michigan Tech](http://www.cs.mtu.edu/~shene/COURSES/cs3621/NOTES/spline/de-Boor.html) page, but an easier to read version is implemented by [b-spline.js](https://github.com/thibauts/b-spline/blob/master/index.js#L59-L71), so we'll look at its code. @@ -140,12 +146,14 @@ for(let L = 1; L <= order; L++) { (A nice bit of behaviour in this code is that we work the interpolation "backwards", starting at `i=s` at each level of the interpolation, and we stop when `i = s - order + level`, so we always end up with a value for `i` such that those `v[i-1]` don't try to use an array index that doesn't exist) + ## Open vs. closed paths Much like poly-Béziers, B-Splines can be either open, running from the first point to the last point, or closed, where the first and last point are *the same point*. However, because B-Splines are an interpolation of curves, not just point, we can't simply make the first and last point the same, we need to link a few point point: for an order `d` B-Spline, we need to make the last `d` point the same as the first `d` points. And the easiest way to do this is to simply append `points.splice(0,d)` to `points`. Done! Of course if we want to manipulate these kind of curves we need to make sure to mark them as "closed" so that we know the coordinate for `points[0]` and `points[n-k]` etc. are the same coordinate, and manipulating one will equally manipulate the other, but programming generally makes this really easy by storing references to coordinates (or other linked values such as coordinate weights, discussed in the NURBS section) rather than separate coordinate objects. + ## Manipulating the curve through the knot vector The most important thing to understand when it comes to B-Splines is that they work *because* of the concept of a knot vector. As mentioned above, knots represent "where individual control points start/stop influencing the curve", but we never looked at the *values* that go in the knot vector. If you look back at the N() and a() functions, you see that interpolations are based on intervals in the knot vector, rather than the actual values in the knot vector, and we can exploit this to do some pretty interesting things with clever manipulation of the knot vector. Specifically there are four things we can do that are worth looking at: @@ -155,27 +163,28 @@ The most important thing to understand when it comes to B-Splines is that they w 3. we can collapse sequential knots to the same value, locally lowering curve complexity using "null" intervals, and 4. we can form a special case non-uniform vector, by combining (1) and (3) to for a vector with collapsed start and end knots, with a uniform vector in between. + ### Uniform B-Splines The most straightforward type of B-Spline is the uniform spline. In a uniform spline, the knots are distributed uniformly over the entire curve interval. For instance, if we have a knot vector of length twelve, then a uniform knot vector would be [0,1,2,3,...,9,10,11]. Or [4,5,6,...,13,14,15], which defines *the same intervals*, or even [0,2,3,...,18,20,22], which also defines *the same intervals*, just scaled by a constant factor, which becomes normalised during interpolation and so does not contribute to the curvature. -
- - this.bindKnots(owner, knots, "uniform-spline")}/> -
+ + + This is an important point: the intervals that the knot vector defines are *relative* intervals, so it doesn't matter if every interval is size 1, or size 100 - the relative differences between the intervals is what shapes any particular curve. The problem with uniform knot vectors is that, as we need `order` control points before we have any curve with which we can perform interpolation, the curve does not "start" at the first point, nor "ends" at the last point. Instead there are "gaps". We can get rid of these, by being clever about how we apply the following uniformity-breaking approach instead... + ### Reducing local curve complexity by collapsing intervals -By collapsing knot intervals by making two or more consecutive knots have the same value, we can reduce the curve complexity in the sections that are affected by the knots involved. This can have drastic effects: for every interval collapse, the curve order goes down, and curve continuity goes down, to the point where collapsing `order` knots creates a situation where all continuity is lost and the curve "kinks". +Collapsing knot intervals, by making two or more consecutive knots have the same value, allows us to reduce the curve complexity in the sections that are affected by the knots involved. This can have drastic effects: for every interval collapse, the curve order goes down, and curve continuity goes down, to the point where collapsing `order` knots creates a situation where all continuity is lost and the curve "kinks". + + + + -
- - this.bindKnots(owner, knots, "center-cut-bspline")}/> -
### Open-Uniform B-Splines @@ -183,31 +192,24 @@ By combining knot interval collapsing at the start and end of the curve, with un For any curve of degree `D` with control points `N`, we can define a knot vector of length `N+D+1` in which the values `0 ... D+1` are the same, the values `D+1 ... N+1` follow the "uniform" pattern, and the values `N+1 ... N+D+1` are the same again. For example, a cubic B-Spline with 7 control points can have a knot vector [0,0,0,0,1,2,3,4,4,4,4], or it might have the "identical" knot vector [0,0,0,0,2,4,6,8,8,8,8], etc. Again, it is the relative differences that determine the curve shape. -
- - this.bindKnots(owner, knots, "open-uniform-bspline")}/> -
+ + + + ### Non-uniform B-Splines -This is essentially the "free form" version of a B-Spline, and also the least interesting to look at, as without any specific reason to pick specific knot intervals, there is nothing particularly interesting going on. There is one constraint to the knot vector, and that is that any value `knots[k+1]` should be equal to, or greater than `knots[k]`. +This is essentially the "free form" version of a B-Spline, and also the least interesting to look at, as without any specific reason to pick specific knot intervals, there is nothing particularly interesting going on. There is one constraint to the knot vector, other than that any value `knots[k+1]` should be greater than or equal to `knots[k]`. ## One last thing: Rational B-Splines While it is true that this section on B-Splines is running quite long already, there is one more thing we need to talk about, and that's "Rational" splines, where the rationality applies to the "ratio", or relative weights, of the control points themselves. By introducing a ratio vector with weights to apply to each control point, we greatly increase our influence over the final curve shape: the more weight a control point carries, the close to that point the spline curve will lie, a bit like turning up the gravity of a control point. -
- { - // - } - - { - // this.bindKnots(owner, knots, "rational-uniform-bspline"); - this.bindWeights(owner, weights, closed, "rational-uniform-bspline-weights"); - }} /> -
+ + + -Of course this brings us to the final topic that any text on B-Splines must touch on before calling it a day: the NURBS, or Non-Uniform Rational B-Spline (NURBS is not a plural, the capital S actually just stands for "spline", but a lot of people mistakenly treat it as if it is, so now you know better). NURBS are an important type of curve in computer-facilitated design, used a lot in 3D modelling (as NURBS surfaces) as well as in arbitrary-precision 2D design due to the level of control a NURBS curve offers designers. +Of course this brings us to the final topic that any text on B-Splines must touch on before calling it a day: the [NURBS](https://en.wikipedia.org/wiki/Non-uniform_rational_B-spline), or Non-Uniform Rational B-Spline (NURBS is not a plural, the capital S actually just stands for "spline", but a lot of people mistakenly treat it as if it is, so now you know better). NURBS is an important type of curve in computer-facilitated design, used a lot in 3D modelling (typically as NURBS surfaces) as well as in arbitrary-precision 2D design due to the level of control a NURBS curve offers designers. While a true non-uniform rational B-Spline would be hard to work with, when we talk about NURBS we typically mean the Open-Uniform Rational B-Spline, or OURBS, but that doesn't roll off the tongue nearly as nicely, and so remember that when people talk about NURBS, they typically mean open-uniform, which has the useful property of starting the curve at the first control point, and ending it at the last. diff --git a/docs/chapters/bsplines/handler.js b/docs/chapters/bsplines/handler.js deleted file mode 100644 index a8a0a796..00000000 --- a/docs/chapters/bsplines/handler.js +++ /dev/null @@ -1,16 +0,0 @@ -module.exports = { - basicSketch: require('./basic-sketch'), - interpolationGraph: require('./interpolation-graph'), - uniformBSpline: require('./uniform-bspline'), - centerCutBSpline: require('./center-cut-bspline'), - openUniformBSpline: require('./open-uniform-bspline'), - rationalUniformBSpline: require('./rational-uniform-bspline'), - - bindKnots: function(owner, knots, ref) { - this.refs[ref].bindKnots(owner, knots); - }, - - bindWeights: function(owner, weights, closed, ref) { - this.refs[ref].bindWeights(owner, weights, closed); - } -}; diff --git a/docs/chapters/bsplines/open-uniform-bspline.js b/docs/chapters/bsplines/open-uniform-bspline.js deleted file mode 100644 index d60be4bd..00000000 --- a/docs/chapters/bsplines/open-uniform-bspline.js +++ /dev/null @@ -1,45 +0,0 @@ -module.exports = { - degree: 3, - activeDistance: 9, - - setup() { - this.size(400, 400); - - var TAU = Math.PI*2; - for (let i=0; i { - this.stroke(200); - this.line(n.x, n.y, p.x, p.y); - p = n; - this.stroke(0); - this.circle(p.x, p.y, 4); - }); - this.drawSplineData(); - }, - - drawSplineData() { - if (this.points.length <= this.degree) return; - var mapped = this.points.map(p => [p.x, p.y]); - this.drawCurve(mapped); - this.drawKnots(mapped); - } -}; diff --git a/docs/chapters/bsplines/rational-uniform-bspline.js b/docs/chapters/bsplines/rational-uniform-bspline.js deleted file mode 100644 index f3d823aa..00000000 --- a/docs/chapters/bsplines/rational-uniform-bspline.js +++ /dev/null @@ -1,50 +0,0 @@ -module.exports = { - degree: 3, - activeDistance: 9, - weights: [], - - setup() { - this.size(400, 400); - - var TAU = Math.PI*2; - var r = this.width/3; - for (let i=0; i<6; i++) { - this.points.push({ - x: this.width/2 + r * Math.cos(i/6 * TAU), - y: this.height/2 + r * Math.sin(i/6 * TAU) - }); - } - this.points = this.points.concat(this.points.slice(0,3)); - this.closed = this.degree; - - this.knots = this.formKnots(this.points); - this.weights = this.formWeights(this.points); - - if(this.props.controller) { - this.props.controller(this, this.knots, this.weights, this.closed); - } - - this.draw(); - }, - - draw() { - this.clear(); - this.grid(25); - var p = this.points[0]; - this.points.forEach(n => { - this.stroke(200); - this.line(n.x, n.y, p.x, p.y); - p = n; - this.stroke(0); - this.circle(p.x, p.y, 4); - }); - this.drawSplineData(); - }, - - drawSplineData() { - if (this.points.length <= this.degree) return; - var mapped = this.points.map(p => [p.x, p.y]); - this.drawCurve(mapped); - this.drawKnots(mapped); - } -}; diff --git a/docs/chapters/bsplines/rational-uniform.js b/docs/chapters/bsplines/rational-uniform.js new file mode 100644 index 00000000..5ff300ad --- /dev/null +++ b/docs/chapters/bsplines/rational-uniform.js @@ -0,0 +1,43 @@ +let points=[]; + +setup() { + var r = this.width/3; + for (let i=0; i<6; i++) { + points.push({ + x: this.width/2 + r * Math.cos(i/6 * TAU), + y: this.height/2 + r * Math.sin(i/6 * TAU) + }); + } + points = points.concat(points.slice(0,3)); + setMovable(points); +} + +draw() { + clear(); + + setStroke(`lightgrey`); + drawGrid(20); + + setStroke(`#CC00CC99`); + for (let i=0, e=points.length-1, p, n; i circle(p.x, p.y, 3)); + + this.drawSplineData(); +} + +drawSplineData() { + const spline = new BSpline(this, points, !!this.parameters.open); + spline.formWeights(); + + noFill(); + setStroke(`black`); + start(); + spline.getLUT((points.length - 3) * 20).forEach(p => vertex(p.x, p.y)); + end(); +} diff --git a/docs/chapters/bsplines/reduced.js b/docs/chapters/bsplines/reduced.js new file mode 100644 index 00000000..51566015 --- /dev/null +++ b/docs/chapters/bsplines/reduced.js @@ -0,0 +1,49 @@ +let points=[], knots; + +setup() { + for (let s=TAU/9, i=s/2; i circle(p.x, p.y, 3)); + + this.drawSplineData(); +} + +drawSplineData() { + const spline = new BSpline(this, points, !!this.parameters.open); + + const knots = spline.formKnots(); + const m = round(points.length/2)|0; + knots[m+0] = knots[m]; + knots[m+1] = knots[m]; + knots[m+2] = knots[m]; + for (let i=m+3; i vertex(p.x, p.y)); + end(); +} diff --git a/docs/chapters/bsplines/uniform-bspline.js b/docs/chapters/bsplines/uniform-bspline.js deleted file mode 100644 index 7da2a7ed..00000000 --- a/docs/chapters/bsplines/uniform-bspline.js +++ /dev/null @@ -1,43 +0,0 @@ -module.exports = { - degree: 3, - activeDistance: 9, - - setup() { - this.size(400, 400); - - var TAU = Math.PI*2; - for (let i=0; i { - this.stroke(200); - this.line(n.x, n.y, p.x, p.y); - p = n; - this.stroke(0); - this.circle(p.x, p.y, 4); - }); - this.drawSplineData(); - }, - - drawSplineData() { - if (this.points.length <= this.degree) return; - var mapped = this.points.map(p => [p.x, p.y]); - this.drawCurve(mapped); - this.drawKnots(mapped); - } -}; diff --git a/docs/chapters/bsplines/uniform.js b/docs/chapters/bsplines/uniform.js new file mode 100644 index 00000000..b96579e7 --- /dev/null +++ b/docs/chapters/bsplines/uniform.js @@ -0,0 +1,41 @@ +let points=[]; + +setup() { + for (let s=TAU/9, i=s/2; i circle(p.x, p.y, 3)); + + this.drawSplineData(); +} + +drawSplineData() { + const spline = new BSpline(this, points); + spline.formKnots(!!this.parameters.open); + + noFill(); + setStroke(`black`); + start(); + spline.getLUT((points.length - 3) * 20).forEach(p => vertex(p.x, p.y)); + end(); +} diff --git a/docs/chapters/circles_cubic/circle.js b/docs/chapters/circles_cubic/circle.js index 3a35ad85..32dc4ce3 100644 --- a/docs/chapters/circles_cubic/circle.js +++ b/docs/chapters/circles_cubic/circle.js @@ -1,7 +1,7 @@ let curve, r; setup() { - r = (this.width/4) | 0; + r = 100; curve = new Bezier(this, [ { x: r, y: 0 }, { x: r, y: 0.55228 * r }, diff --git a/docs/chapters/circles_cubic/content.en-GB.md b/docs/chapters/circles_cubic/content.en-GB.md index 64f77689..4d6af720 100644 --- a/docs/chapters/circles_cubic/content.en-GB.md +++ b/docs/chapters/circles_cubic/content.en-GB.md @@ -179,4 +179,4 @@ Which, in decimal values, rounded to six significant digits, is: Of course, this is for a circle with radius 1, so if you have a different radius circle, simply multiply the coordinate by the radius you need. And then finally, forming a full curve is now a simple a matter of mirroring these coordinates about the origin: - + diff --git a/docs/chapters/curveintersection/curve-curve.js b/docs/chapters/curveintersection/curve-curve.js index 6acf0a7c..ccb1184c 100644 --- a/docs/chapters/curveintersection/curve-curve.js +++ b/docs/chapters/curveintersection/curve-curve.js @@ -4,7 +4,7 @@ setup() { setPanelCount(3); this.pairReset(); this.setupEventListening(); - setSlider(`.slide-control`, `epsilon`, 1.0, v => this.reset()); + setSlider(`.slide-control`, `epsilon`, 1.0, v => this.reset(v)); } pairReset() { @@ -15,11 +15,12 @@ pairReset() { this.reset(); } -reset() { +reset(v) { if (next && next.disabled) next.disabled = false; this.pairs = [[curve1, curve2]]; this.finals = []; this.step = 0; + return v; } setupEventListening() { diff --git a/docs/images/chapters/arcapproximation/6f30b487d0cb60a4caeed4a199c48253.png b/docs/images/chapters/arcapproximation/6f30b487d0cb60a4caeed4a199c48253.png new file mode 100644 index 00000000..2d06daa7 Binary files /dev/null and b/docs/images/chapters/arcapproximation/6f30b487d0cb60a4caeed4a199c48253.png differ diff --git a/docs/images/chapters/arcapproximation/7c9cce8142fa3e85bb124520f40645ff.png b/docs/images/chapters/arcapproximation/7c9cce8142fa3e85bb124520f40645ff.png new file mode 100644 index 00000000..6429f0c7 Binary files /dev/null and b/docs/images/chapters/arcapproximation/7c9cce8142fa3e85bb124520f40645ff.png differ diff --git a/docs/images/chapters/bsplined/c32c4cabe4193e4b4c5e1d0e46aacf72.svg b/docs/images/chapters/bsplined/2708c130a4a45cef8c998c94da3dd2b5.svg similarity index 100% rename from docs/images/chapters/bsplined/c32c4cabe4193e4b4c5e1d0e46aacf72.svg rename to docs/images/chapters/bsplined/2708c130a4a45cef8c998c94da3dd2b5.svg diff --git a/docs/images/chapters/bsplined/15f9e6eea05599fe6a5eac609ca42cfa.svg b/docs/images/chapters/bsplined/6b7f07a5f80edaef59d07e86e9d9a668.svg similarity index 100% rename from docs/images/chapters/bsplined/15f9e6eea05599fe6a5eac609ca42cfa.svg rename to docs/images/chapters/bsplined/6b7f07a5f80edaef59d07e86e9d9a668.svg diff --git a/docs/images/chapters/bsplines/0f3451c711c0fe5d0b018aa4aa77d855.svg b/docs/images/chapters/bsplines/0f3451c711c0fe5d0b018aa4aa77d855.svg index fc065693..027f3e19 100644 --- a/docs/images/chapters/bsplines/0f3451c711c0fe5d0b018aa4aa77d855.svg +++ b/docs/images/chapters/bsplines/0f3451c711c0fe5d0b018aa4aa77d855.svg @@ -1,82 +1,86 @@ - - - + + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - - - - - - - - - - - - - + + - - + + - - - - - + + - - - - - + + - - + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/images/chapters/bsplines/4c8f9814c50c708757eeb5a68afabb7f.svg b/docs/images/chapters/bsplines/4c8f9814c50c708757eeb5a68afabb7f.svg index 354cd5b9..dd56e5d2 100644 --- a/docs/images/chapters/bsplines/4c8f9814c50c708757eeb5a68afabb7f.svg +++ b/docs/images/chapters/bsplines/4c8f9814c50c708757eeb5a68afabb7f.svg @@ -1,185 +1,187 @@ - - - + + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - - - - - - - - - - - - - + + - - - - - - - - + + - - + + - - - - - + + - - + + - - + + + + + - - + + - - + + + + + + + + - - - - - - - - + + - - + + - - + + + + - - + + - - + + + + + + + + + + + + + + + + + + + + diff --git a/docs/images/chapters/bsplines/5d3b04c3161a3429ce651bb7a5fa0399.png b/docs/images/chapters/bsplines/5d3b04c3161a3429ce651bb7a5fa0399.png new file mode 100644 index 00000000..a4778691 Binary files /dev/null and b/docs/images/chapters/bsplines/5d3b04c3161a3429ce651bb7a5fa0399.png differ diff --git a/docs/images/chapters/bsplines/610232b8f7ce7ef3f0f012d55e385c6d.png b/docs/images/chapters/bsplines/610232b8f7ce7ef3f0f012d55e385c6d.png new file mode 100644 index 00000000..8c1e929f Binary files /dev/null and b/docs/images/chapters/bsplines/610232b8f7ce7ef3f0f012d55e385c6d.png differ diff --git a/docs/images/chapters/bsplines/763838ea6f9e6c6aa63ea5f9c6d9542f.svg b/docs/images/chapters/bsplines/763838ea6f9e6c6aa63ea5f9c6d9542f.svg index 7cbd2dcb..12d10fc9 100644 --- a/docs/images/chapters/bsplines/763838ea6f9e6c6aa63ea5f9c6d9542f.svg +++ b/docs/images/chapters/bsplines/763838ea6f9e6c6aa63ea5f9c6d9542f.svg @@ -1,134 +1,140 @@ - - - + + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - - - - - - - - - - - - - - - - - - - - - - - - - + + - - + + - - - - - + + - - + + + + + + + + - - - - - + + - - - - - + + - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/images/chapters/bsplines/7962d6fea86da6f53a7269fba30f0138.svg b/docs/images/chapters/bsplines/7962d6fea86da6f53a7269fba30f0138.svg index 859bdeae..3019a4fd 100644 --- a/docs/images/chapters/bsplines/7962d6fea86da6f53a7269fba30f0138.svg +++ b/docs/images/chapters/bsplines/7962d6fea86da6f53a7269fba30f0138.svg @@ -1,535 +1,535 @@ - - - + + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + diff --git a/docs/images/chapters/bsplines/892209dad8fd1f839470dd061e870913.svg b/docs/images/chapters/bsplines/892209dad8fd1f839470dd061e870913.svg index 30df74d0..b2da3c53 100644 --- a/docs/images/chapters/bsplines/892209dad8fd1f839470dd061e870913.svg +++ b/docs/images/chapters/bsplines/892209dad8fd1f839470dd061e870913.svg @@ -1,135 +1,135 @@ - - - + + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - - + + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - - - - + + - - + + - - + + - - + + - - + + + + + diff --git a/docs/images/chapters/bsplines/8caa3e8ff614ad9731b15dacaba98c3c.png b/docs/images/chapters/bsplines/8caa3e8ff614ad9731b15dacaba98c3c.png new file mode 100644 index 00000000..05f11b8d Binary files /dev/null and b/docs/images/chapters/bsplines/8caa3e8ff614ad9731b15dacaba98c3c.png differ diff --git a/docs/images/chapters/bsplines/93146ea89bb21999d9e18b57dd1bdd29.png b/docs/images/chapters/bsplines/93146ea89bb21999d9e18b57dd1bdd29.png new file mode 100644 index 00000000..99dc2d9a Binary files /dev/null and b/docs/images/chapters/bsplines/93146ea89bb21999d9e18b57dd1bdd29.png differ diff --git a/docs/images/chapters/bsplines/adac18ea69cc58e01c8d5e15498e4aa6.svg b/docs/images/chapters/bsplines/adac18ea69cc58e01c8d5e15498e4aa6.svg index eb651b31..d244bf76 100644 --- a/docs/images/chapters/bsplines/adac18ea69cc58e01c8d5e15498e4aa6.svg +++ b/docs/images/chapters/bsplines/adac18ea69cc58e01c8d5e15498e4aa6.svg @@ -1,135 +1,131 @@ - - - + + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - - - - - - - - - - + + - - + + + + + - - - - - + + - - + + + + + + + + - - + + - - + + - - + + - - - - + + - - + + - - + + - - - - + + - - + + - - + + - - + + + + + diff --git a/docs/images/chapters/bsplines/cf45d1ea00d4866abc8a058b130299b4.svg b/docs/images/chapters/bsplines/cf45d1ea00d4866abc8a058b130299b4.svg index 23a877f0..0725f717 100644 --- a/docs/images/chapters/bsplines/cf45d1ea00d4866abc8a058b130299b4.svg +++ b/docs/images/chapters/bsplines/cf45d1ea00d4866abc8a058b130299b4.svg @@ -1,307 +1,307 @@ - - - + + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - - + + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - - - - - - - - - - - - - - - - - - - - - - - - - - + + - - + + - - + + - - + + + + + + + + - - - - - + + - - + + - - + + + + + - - + + + + + - - + + - - + + + + + + + + + + + + + + - - - - - - - - + + - - - - - + + - - + + - - - - - + + - - + + - - + + + + + + + + + + + + + + - - + + - - + + - - - - - - - - - - - + + - - + + - - + + + + + + + + + + + + + + + + + - - + + - - + + - - - - + + diff --git a/docs/images/chapters/bsplines/fc654445500dd595d6ae9de27a3dc46c.png b/docs/images/chapters/bsplines/fc654445500dd595d6ae9de27a3dc46c.png new file mode 100644 index 00000000..0c09c7db Binary files /dev/null and b/docs/images/chapters/bsplines/fc654445500dd595d6ae9de27a3dc46c.png differ diff --git a/docs/images/chapters/circles_cubic/3c6f863c77cc2100573bf71adaabc12e.png b/docs/images/chapters/circles_cubic/3c6f863c77cc2100573bf71adaabc12e.png deleted file mode 100644 index f536960f..00000000 Binary files a/docs/images/chapters/circles_cubic/3c6f863c77cc2100573bf71adaabc12e.png and /dev/null differ diff --git a/docs/images/chapters/circles_cubic/8676cce0d4394ae095c7e50be1238aa0.png b/docs/images/chapters/circles_cubic/8676cce0d4394ae095c7e50be1238aa0.png new file mode 100644 index 00000000..94dc255a Binary files /dev/null and b/docs/images/chapters/circles_cubic/8676cce0d4394ae095c7e50be1238aa0.png differ diff --git a/docs/images/chapters/curveintersection/eae3bb142567d9e2b8c1e4d42e8ef505.png b/docs/images/chapters/curveintersection/914e097fe4341697e05b6fd328cc4c91.png similarity index 100% rename from docs/images/chapters/curveintersection/eae3bb142567d9e2b8c1e4d42e8ef505.png rename to docs/images/chapters/curveintersection/914e097fe4341697e05b6fd328cc4c91.png diff --git a/docs/index.html b/docs/index.html index 2c1e6963..619bdd6d 100644 --- a/docs/index.html +++ b/docs/index.html @@ -1588,7 +1588,7 @@ lli = function(line1, line2): Scripts are disabled. Showing fallback image. - + @@ -2265,10 +2265,10 @@ for p = 1 to points.length-3 (inclusive):

Which, in decimal values, rounded to six significant digits, is:

Of course, this is for a circle with radius 1, so if you have a different radius circle, simply multiply the coordinate by the radius you need. And then finally, forming a full curve is now a simple a matter of mirroring these coordinates about the origin:

- + Scripts are disabled. Showing fallback image. - + @@ -2278,43 +2278,52 @@ for p = 1 to points.length-3 (inclusive):

Let's look at doing the exact opposite of the previous section: rather than approximating circular arc using Bézier curves, let's approximate Bézier curves using circular arcs.

We already saw in the section on circle approximation that this will never yield a perfect equivalent, but sometimes you need circular arcs, such as when you're working with fabrication machinery, or simple vector languages that understand lines and circles, but not much else.

The approach is fairly simple: pick a starting point on the curve, and pick two points that are further along the curve. Determine the circle that goes through those three points, and see if it fits the part of the curve we're trying to approximate. Decent fit? Try spacing the points further apart. Bad fit? Try spacing the points closer together. Keep doing this until you've found the "good approximation/bad approximation" boundary, record the "good" arc, and then move the starting point up to overlap the end point we previously found. Rinse and repeat until we've covered the entire curve.

-

So: step 1, how do we find a circle through three points? That part is actually really simple. You may remember (if you ever learned it!) that a line between two points on a circle is called a chord, and one property of chords is that the line from the center of any chord, perpendicular to that chord, passes through the center of the circle.

-

So: if we have have three points, we have three (different) chords, and consequently, three (different) lines that go from those chords through the center of the circle. So we find the centers of the chords, find the perpendicular lines, find the intersection of those lines, and thus find the center of the circle.

-

The following graphic shows this procedure with a different colour for each chord and its associated perpendicular through the center. You can move the points around as much as you like, those lines will always meet!

- - -

So, with the procedure on how to find a circle through three points, finding the arc through those points is straight-forward: pick one of the three points as start point, pick another as an end point, and the arc has to necessarily go from the start point, over the remaining point, to the end point.

-

So how can we convert a Bézier curve into a (sequence of) circular arc(s)?

+

We already saw how to fit a circle through three points in the section on creating a curve from three points, and finding the arc through those points is straight-forward: pick one of the three points as start point, pick another as an end point, and the arc has to necessarily go from the start point, to the end point, over the remaining point.

+

So, how can we convert a Bézier curve into a (sequence of) circular arc(s)?

    -
  • Start at t=0
  • -
  • Pick two points further down the curve at some value m = t + n and e = t + 2n
  • +
  • Start at t=0
  • +
  • Pick two points further down the curve at some value m = t + n and e = t + 2n
  • Find the arc that these points define
  • Determine how close the found arc is to the curve:
      -
    • Pick two additional points e1 = t + n/2 and e2 = t + n + n/2.
    • +
    • Pick two additional points e1 = t + n/2 and e2 = t + n + n/2.
    • These points, if the arc is a good approximation of the curve interval chosen, should - lie on the circle, so their distance to the center of the circle should be the + lie on the circle, so their distance to the center of the circle should be the same as the distance from any of the three other points to the center.
    • For point points, determine the (absolute) error between the radius of the circle, and the -actual distance from the center of the circle to the point on the curve.
    • +actual distance from the center of the circle to the point on the curve.
    • If this error is too high, we consider the arc bad, and try a smaller interval.
-

The result of this is shown in the next graphic: we start at a guaranteed failure: s=0, e=1. That's the entire curve. The midpoint is simply at t=0.5, and then we start performing a Binary Search.

+

The result of this is shown in the next graphic: we start at a guaranteed failure: s=0, e=1. That's the entire curve. The midpoint is simply at t=0.5, and then we start performing a binary search.

    -
  1. We start with {0, 0.5, 1}
  2. -
  3. That'll fail, so we retry with the interval halved: {0, 0.25, 0.5}
      -
    • If that arc's good, we move back up by half distance: {0, 0.375, 0.75}.
    • -
    • However, if the arc was still bad, we move down by half the distance: {0, 0.125, 0.25}.
    • +
    • We start with low=0, mid=0.5 and high=1
    • +
    • That'll fail, so we retry with the interval halved: {0, 0.25, 0.5}
        +
      • If that arc's good, we move back up by half distance: {0, 0.375, 0.75}.
      • +
      • However, if the arc was still bad, we move down by half the distance: {0, 0.125, 0.25}.
    • -
    • We keep doing this over and over until we have two arcs found in sequence of which the first arc is good, and the second arc is bad. When we find that pair, we've found the boundary between a good approximation and a bad approximation, and we pick the former.
    • +
    • We keep doing this over and over until we have two arcs, in sequence, of which the first arc is good, and the second arc is bad. When we find that pair, we've found the boundary between a good approximation and a bad approximation, and we pick the good arc.

The following graphic shows the result of this approach, with a default error threshold of 0.5, meaning that if an arc is off by a combined half pixel over both verification points, then we treat the arc as bad. This is an extremely simple error policy, but already works really well. Note that the graphic is still interactive, and you can use your up and down arrow keys keys to increase or decrease the error threshold, to see what the effect of a smaller or larger error threshold is.

- + + + Scripts are disabled. Showing fallback image. + + + + +

With that in place, all that's left now is to "restart" the procedure by treating the found arc's end point as the new to-be-determined arc's starting point, and using points further down the curve. We keep trying this until the found end point is for t=1, at which point we are done. Again, the following graphic allows for up and down arrow key input to increase or decrease the error threshold, so you can see how picking a different threshold changes the number of arcs that are necessary to reasonably approximate a curve:

- + + + Scripts are disabled. Showing fallback image. + + + + +

So... what is this good for? Obviously, if you're working with technologies that can't do curves, but can do lines and circles, then the answer is pretty straightforward, but what else? There are some reasons why you might need this technique: using circular arcs means you can determine whether a coordinate lies "on" your curve really easily (simply compute the distance to each circular arc center, and if any of those are close to the arc radii, at an angle between the arc start and end, bingo, this point can be treated as lying "on the curve"). Another benefit is that this approximation is "linear": you can almost trivially travel along the arcs at fixed speed. You can also trivially compute the arc length of the approximated curve (it's a bit like curve flattening). The only thing to bear in mind is that this is a lossy equivalence: things that you compute based on the approximation are guaranteed "off" by some small value, and depending on how much precision you need, arc approximation is either going to be super useful, or completely useless. It's up to you to decide which, based on your application!

@@ -2323,8 +2332,13 @@ for p = 1 to points.length-3 (inclusive):

B-Splines

No discussion on Bézier curves is complete without also giving mention of that other beast in the curve design space: B-Splines. Easily confused to mean Bézier splines, that's not actually what they are; they are "basis function" splines, which makes a lot of difference, and we'll be looking at those differences in this section. We're not going to dive as deep into B-Splines as we have for Bézier curves (that would be an entire primer on its own) but we'll be looking at how B-Splines work, what kind of maths is involved in computing them, and how to draw them based on a number of parameters that you can pick for individual B-Splines.

First off: B-Splines are piecewise polynomial interpolation curves, where the "single curve" is built by performing polynomial interpolation over a set of points, using a sliding window of a fixed number of points. For instance, a "cubic" B-Spline defined by twelve points will have its curve built by evaluating the polynomial interpolation of four points, and the curve can be treated as a lot of different sections, each controlled by four points at a time, such that the full curve consists of smoothly connected sections defined by points {1,2,3,4}, {2,3,4,5}, ..., {8,9,10,11}, and finally {9,10,11,12}, for eight sections.

-

What do they look like? They look like this! .. okay that's an empty graph, but simply click to place some point, with the stipulation that you need at least four point to see any curve. More than four points simply draws a longer B-Spline curve:

- +

What do they look like? They look like this! Tap on the graphic to add more points, and move points around to see how they map to the spline curve drawn.

+ + + Scripts are disabled. Showing fallback image. + + +

The important part to notice here is that we are not doing the same thing with B-Splines that we do for poly-Béziers or Catmull-Rom curves: both of the latter simply define new sections as literally "new sections based on new points", so a 12 point cubic poly-Bézier curve is actually impossible, because we start with a four point curve, and then add three more points for each section that follows, so we can only have 4, 7, 10, 13, 16, etc point Poly-Béziers. Similarly, while Catmull-Rom curves can grow by adding single points, this addition of a single point introduces three implicit Bézier points. Cubic B-Splines, on the other hand, are smooth interpolations of each possible curve involving four consecutive points, such that at any point along the curve except for our start and end points, our on-curve coordinate is defined by four control points.

Consider the difference to be this:

@@ -2335,31 +2349,33 @@ for p = 1 to points.length-3 (inclusive):

In order to make this interpolation of curves work, the maths is necessarily more complex than the maths for Bézier curves, so let's have a look at how things work.

How to compute a B-Spline curve: some maths

Given a B-Spline of degree d and thus order k=d+1 (so a quadratic B-Spline is degree 2 and order 3, a cubic B-Spline is degree 3 and order 4, etc) and n control points P0 through Pn-1, we can compute a point on the curve for some value t in the interval [0,1] (where 0 is the start of the curve, and 1 the end, just like for Bézier curves), by evaluating the following function:

- +

Which, honestly, doesn't tell us all that much. All we can see is that a point on a B-Spline curve is defined as "a mix of all the control points, weighted somehow", where the weighting is achieved through the N(...) function, subscripted with an obvious parameter i, which comes from our summation, and some magical parameter k. So we need to know two things: 1. what does N(t) do, and 2. what is that k? Let's cover both, in reverse order.

The parameter k represents the "knot interval" over which a section of curve is defined. As we learned earlier, a B-Spline curve is itself an interpoliation of curves, and we can treat each transition where a control point starts or stops influencing the total curvature as a "knot on the curve". Doing so for a degree d B-Spline with n control point gives us d + n + 1 knots, defining d + n intervals along the curve, and it is these intervals that the above k subscript to the N() function applies to.

Then the N() function itself. What does it look like?

- +

So this is where we see the interpolation: N(t) for an (i,k) pair (that is, for a step in the above summation, on a specific knot interval) is a mix between N(t) for (i,k-1) and N(t) for (i+1,k-1), so we see that this is a recursive iteration where i goes up, and k goes down, so it seem reasonable to expect that this recursion has to stop at some point; obviously, it does, and specifically it does so for the following i/k values:

- +

And this function finally has a straight up evaluation: if a t value lies within a knot-specific interval once we reach a k=1 value, it "counts", otherwise it doesn't. We did cheat a little, though, because for all these values we need to scale our t value first, so that it lies in the interval bounded by knots[d] and knots[n], which are the start point and end point where curvature is controlled by exactly order control points. For instance, for degree 3 (=order 4) and 7 control points, with knot vector [1,2,3,4,5,6,7,8,9,10,11], we map t from [the interval 0,1] to the interval [4,8], and then use that value in the functions above, instead.

Can we simplify that?

We can, yes.

People far smarter than us have looked at this work, and two in particular — Maurice Cox and Carl de Boor — came to a mathematically pleasing solution: to compute a point P(t), we can compute this point by evaluating d(t) on a curve section between knots i and i+1:

- +

This is another recursive function, with k values decreasing from the curve order to 1, and the value α (alpha) defined by:

- +

That looks complicated, but it's not. Computing alpha is just a fraction involving known, plain numbers and once we have our alpha value, computing (1-alpha) is literally just "computing one minus alpha". Computing this d() function is thus simply a matter of "computing simple arithmetics but with recursion", which might be computationally expensive because we're doing "a lot of" steps, but is also computationally cheap because each step only involves very simple maths. Of course as before the recursion has to stop:

- +

So, we see two stopping conditions: either i becomes 0, in which case d() is zero, or k becomes zero, in which case we get the same "either 1 or 0" that we saw in the N() function above.

Thanks to Cox and de Boor, we can compute points on a B-Spline pretty easily: we just need to compute a triangle of interconnected values. For instance, d() for i=3, k=3 yields the following triangle:

- +

That is, we compute d(3,3) as a mixture of d(2,3) and d(2,2): d(3,3) = a(3,3) x d(2,3) + (1-a(3,3)) x d(2,2)... and we simply keep expanding our triangle until we reach the terminating function parameters. Done deal!

One thing we need to keep in mind is that we're working with a spline that is constrained by its control points, so even though the d(..., k) values are zero or one at the lowest level, they are really "zero or one, times their respective control point", so in the next section you'll see the algorithm for running through the computation in a way that starts with a copy of the control point vector and then works its way up to that single point: that's pretty essential!

If we run this computation "down", starting at d(3,3), then without special code in place we would be computing quite a few terms multiple times at each step. On the other hand, we can also start with that last "column", we can generate the terminating d() values first, then compute the a() constants, perform our multiplications, generate the previous step's d() values, compute their a() constants, do the multiplications, etc. until we end up all the way back at the top. If we run our computation this way, we don't need any explicit caching, we can just "recycle" the list of numbers we start with and simply update them as we move up the triangle. So, let's implement that!

Cool, cool... but I don't know what to do with that information

I know, this is pretty mathy, so let's have a look at what happens when we change parameters here. We can't change the maths for the interpolation functions, so that gives us only one way to control what happens here: the knot vector itself. As such, let's look at the graph that shows the interpolation functions for a cubic B-Spline with seven points with a uniform knot vector (so we see seven identical functions), representing how much each point (represented by one function each) influences the total curvature, given our knot values. And, because exploration is the key to discovery, let's make the knot vector a thing we can actually manipulate. Normally a proper knot vector has a constraint that any value is strictly equal to, or larger than the previous ones, but screw it this is programming, let's ignore that hard restriction and just mess with the knots however we like.

+ +
this.bindKnots(owner, knots, "interpolation-graph")}/> @@ -2398,44 +2414,56 @@ for(let L = 1; L <= order; L++) {

Uniform B-Splines

The most straightforward type of B-Spline is the uniform spline. In a uniform spline, the knots are distributed uniformly over the entire curve interval. For instance, if we have a knot vector of length twelve, then a uniform knot vector would be [0,1,2,3,...,9,10,11]. Or [4,5,6,...,13,14,15], which defines the same intervals, or even [0,2,3,...,18,20,22], which also defines the same intervals, just scaled by a constant factor, which becomes normalised during interpolation and so does not contribute to the curvature.

-
- - this.bindKnots(owner, knots, "uniform-spline")}/> -
+ + + Scripts are disabled. Showing fallback image. + + + + +

This is an important point: the intervals that the knot vector defines are relative intervals, so it doesn't matter if every interval is size 1, or size 100 - the relative differences between the intervals is what shapes any particular curve.

The problem with uniform knot vectors is that, as we need order control points before we have any curve with which we can perform interpolation, the curve does not "start" at the first point, nor "ends" at the last point. Instead there are "gaps". We can get rid of these, by being clever about how we apply the following uniformity-breaking approach instead...

Reducing local curve complexity by collapsing intervals

-

By collapsing knot intervals by making two or more consecutive knots have the same value, we can reduce the curve complexity in the sections that are affected by the knots involved. This can have drastic effects: for every interval collapse, the curve order goes down, and curve continuity goes down, to the point where collapsing order knots creates a situation where all continuity is lost and the curve "kinks".

-
- - this.bindKnots(owner, knots, "center-cut-bspline")}/> -
+

Collapsing knot intervals, by making two or more consecutive knots have the same value, allows us to reduce the curve complexity in the sections that are affected by the knots involved. This can have drastic effects: for every interval collapse, the curve order goes down, and curve continuity goes down, to the point where collapsing order knots creates a situation where all continuity is lost and the curve "kinks".

+ + + Scripts are disabled. Showing fallback image. + + + + + +

Open-Uniform B-Splines

By combining knot interval collapsing at the start and end of the curve, with uniform knots in between, we can overcome the problem of the curve not starting and ending where we'd kind of like it to:

For any curve of degree D with control points N, we can define a knot vector of length N+D+1 in which the values 0 ... D+1 are the same, the values D+1 ... N+1 follow the "uniform" pattern, and the values N+1 ... N+D+1 are the same again. For example, a cubic B-Spline with 7 control points can have a knot vector [0,0,0,0,1,2,3,4,4,4,4], or it might have the "identical" knot vector [0,0,0,0,2,4,6,8,8,8,8], etc. Again, it is the relative differences that determine the curve shape.

-
- - this.bindKnots(owner, knots, "open-uniform-bspline")}/> -
+ + + Scripts are disabled. Showing fallback image. + + + + + +

Non-uniform B-Splines

-

This is essentially the "free form" version of a B-Spline, and also the least interesting to look at, as without any specific reason to pick specific knot intervals, there is nothing particularly interesting going on. There is one constraint to the knot vector, and that is that any value knots[k+1] should be equal to, or greater than knots[k].

+

This is essentially the "free form" version of a B-Spline, and also the least interesting to look at, as without any specific reason to pick specific knot intervals, there is nothing particularly interesting going on. There is one constraint to the knot vector, other than that any value knots[k+1] should be greater than or equal to knots[k].

One last thing: Rational B-Splines

While it is true that this section on B-Splines is running quite long already, there is one more thing we need to talk about, and that's "Rational" splines, where the rationality applies to the "ratio", or relative weights, of the control points themselves. By introducing a ratio vector with weights to apply to each control point, we greatly increase our influence over the final curve shape: the more weight a control point carries, the close to that point the spline curve will lie, a bit like turning up the gravity of a control point.

-
- { - // - } - - { - // this.bindKnots(owner, knots, "rational-uniform-bspline"); - this.bindWeights(owner, weights, closed, "rational-uniform-bspline-weights"); - }} /> -
+ + + Scripts are disabled. Showing fallback image. + + + + + -

Of course this brings us to the final topic that any text on B-Splines must touch on before calling it a day: the NURBS, or Non-Uniform Rational B-Spline (NURBS is not a plural, the capital S actually just stands for "spline", but a lot of people mistakenly treat it as if it is, so now you know better). NURBS are an important type of curve in computer-facilitated design, used a lot in 3D modelling (as NURBS surfaces) as well as in arbitrary-precision 2D design due to the level of control a NURBS curve offers designers.

+

Of course this brings us to the final topic that any text on B-Splines must touch on before calling it a day: the NURBS, or Non-Uniform Rational B-Spline (NURBS is not a plural, the capital S actually just stands for "spline", but a lot of people mistakenly treat it as if it is, so now you know better). NURBS is an important type of curve in computer-facilitated design, used a lot in 3D modelling (typically as NURBS surfaces) as well as in arbitrary-precision 2D design due to the level of control a NURBS curve offers designers.

While a true non-uniform rational B-Spline would be hard to work with, when we talk about NURBS we typically mean the Open-Uniform Rational B-Spline, or OURBS, but that doesn't roll off the tongue nearly as nicely, and so remember that when people talk about NURBS, they typically mean open-uniform, which has the useful property of starting the curve at the first control point, and ending it at the last.

Extending our implementation to cover rational splines

The algorithm for working with Rational B-Splines is virtually identical to the regular algorithm, and the extension to work in the control point weights is fairly simple: we extend each control point from a point in its original number of dimensions (2D, 3D, etc) to one dimension higher, scaling the original dimensions by the control point's weight, and then assigning that weight as its value for the extended dimension.

diff --git a/docs/ja-JP/index.html b/docs/ja-JP/index.html index f4d6ce83..eaad6187 100644 --- a/docs/ja-JP/index.html +++ b/docs/ja-JP/index.html @@ -1584,7 +1584,7 @@ lli = function(line1, line2): Scripts are disabled. Showing fallback image. - + @@ -2261,10 +2261,10 @@ for p = 1 to points.length-3 (inclusive):

Which, in decimal values, rounded to six significant digits, is:

Of course, this is for a circle with radius 1, so if you have a different radius circle, simply multiply the coordinate by the radius you need. And then finally, forming a full curve is now a simple a matter of mirroring these coordinates about the origin:

- + Scripts are disabled. Showing fallback image. - + @@ -2274,43 +2274,52 @@ for p = 1 to points.length-3 (inclusive):

Let's look at doing the exact opposite of the previous section: rather than approximating circular arc using Bézier curves, let's approximate Bézier curves using circular arcs.

We already saw in the section on circle approximation that this will never yield a perfect equivalent, but sometimes you need circular arcs, such as when you're working with fabrication machinery, or simple vector languages that understand lines and circles, but not much else.

The approach is fairly simple: pick a starting point on the curve, and pick two points that are further along the curve. Determine the circle that goes through those three points, and see if it fits the part of the curve we're trying to approximate. Decent fit? Try spacing the points further apart. Bad fit? Try spacing the points closer together. Keep doing this until you've found the "good approximation/bad approximation" boundary, record the "good" arc, and then move the starting point up to overlap the end point we previously found. Rinse and repeat until we've covered the entire curve.

-

So: step 1, how do we find a circle through three points? That part is actually really simple. You may remember (if you ever learned it!) that a line between two points on a circle is called a chord, and one property of chords is that the line from the center of any chord, perpendicular to that chord, passes through the center of the circle.

-

So: if we have have three points, we have three (different) chords, and consequently, three (different) lines that go from those chords through the center of the circle. So we find the centers of the chords, find the perpendicular lines, find the intersection of those lines, and thus find the center of the circle.

-

The following graphic shows this procedure with a different colour for each chord and its associated perpendicular through the center. You can move the points around as much as you like, those lines will always meet!

- - -

So, with the procedure on how to find a circle through three points, finding the arc through those points is straight-forward: pick one of the three points as start point, pick another as an end point, and the arc has to necessarily go from the start point, over the remaining point, to the end point.

-

So how can we convert a Bézier curve into a (sequence of) circular arc(s)?

+

We already saw how to fit a circle through three points in the section on creating a curve from three points, and finding the arc through those points is straight-forward: pick one of the three points as start point, pick another as an end point, and the arc has to necessarily go from the start point, to the end point, over the remaining point.

+

So, how can we convert a Bézier curve into a (sequence of) circular arc(s)?

    -
  • Start at t=0
  • -
  • Pick two points further down the curve at some value m = t + n and e = t + 2n
  • +
  • Start at t=0
  • +
  • Pick two points further down the curve at some value m = t + n and e = t + 2n
  • Find the arc that these points define
  • Determine how close the found arc is to the curve:
      -
    • Pick two additional points e1 = t + n/2 and e2 = t + n + n/2.
    • +
    • Pick two additional points e1 = t + n/2 and e2 = t + n + n/2.
    • These points, if the arc is a good approximation of the curve interval chosen, should - lie on the circle, so their distance to the center of the circle should be the + lie on the circle, so their distance to the center of the circle should be the same as the distance from any of the three other points to the center.
    • For point points, determine the (absolute) error between the radius of the circle, and the -actual distance from the center of the circle to the point on the curve.
    • +actual distance from the center of the circle to the point on the curve.
    • If this error is too high, we consider the arc bad, and try a smaller interval.
-

The result of this is shown in the next graphic: we start at a guaranteed failure: s=0, e=1. That's the entire curve. The midpoint is simply at t=0.5, and then we start performing a Binary Search.

+

The result of this is shown in the next graphic: we start at a guaranteed failure: s=0, e=1. That's the entire curve. The midpoint is simply at t=0.5, and then we start performing a binary search.

    -
  1. We start with {0, 0.5, 1}
  2. -
  3. That'll fail, so we retry with the interval halved: {0, 0.25, 0.5}
      -
    • If that arc's good, we move back up by half distance: {0, 0.375, 0.75}.
    • -
    • However, if the arc was still bad, we move down by half the distance: {0, 0.125, 0.25}.
    • +
    • We start with low=0, mid=0.5 and high=1
    • +
    • That'll fail, so we retry with the interval halved: {0, 0.25, 0.5}
        +
      • If that arc's good, we move back up by half distance: {0, 0.375, 0.75}.
      • +
      • However, if the arc was still bad, we move down by half the distance: {0, 0.125, 0.25}.
    • -
    • We keep doing this over and over until we have two arcs found in sequence of which the first arc is good, and the second arc is bad. When we find that pair, we've found the boundary between a good approximation and a bad approximation, and we pick the former.
    • +
    • We keep doing this over and over until we have two arcs, in sequence, of which the first arc is good, and the second arc is bad. When we find that pair, we've found the boundary between a good approximation and a bad approximation, and we pick the good arc.

The following graphic shows the result of this approach, with a default error threshold of 0.5, meaning that if an arc is off by a combined half pixel over both verification points, then we treat the arc as bad. This is an extremely simple error policy, but already works really well. Note that the graphic is still interactive, and you can use your up and down arrow keys keys to increase or decrease the error threshold, to see what the effect of a smaller or larger error threshold is.

- + + + Scripts are disabled. Showing fallback image. + + + + +

With that in place, all that's left now is to "restart" the procedure by treating the found arc's end point as the new to-be-determined arc's starting point, and using points further down the curve. We keep trying this until the found end point is for t=1, at which point we are done. Again, the following graphic allows for up and down arrow key input to increase or decrease the error threshold, so you can see how picking a different threshold changes the number of arcs that are necessary to reasonably approximate a curve:

- + + + Scripts are disabled. Showing fallback image. + + + + +

So... what is this good for? Obviously, if you're working with technologies that can't do curves, but can do lines and circles, then the answer is pretty straightforward, but what else? There are some reasons why you might need this technique: using circular arcs means you can determine whether a coordinate lies "on" your curve really easily (simply compute the distance to each circular arc center, and if any of those are close to the arc radii, at an angle between the arc start and end, bingo, this point can be treated as lying "on the curve"). Another benefit is that this approximation is "linear": you can almost trivially travel along the arcs at fixed speed. You can also trivially compute the arc length of the approximated curve (it's a bit like curve flattening). The only thing to bear in mind is that this is a lossy equivalence: things that you compute based on the approximation are guaranteed "off" by some small value, and depending on how much precision you need, arc approximation is either going to be super useful, or completely useless. It's up to you to decide which, based on your application!

@@ -2319,8 +2328,13 @@ for p = 1 to points.length-3 (inclusive):

B-Splines

No discussion on Bézier curves is complete without also giving mention of that other beast in the curve design space: B-Splines. Easily confused to mean Bézier splines, that's not actually what they are; they are "basis function" splines, which makes a lot of difference, and we'll be looking at those differences in this section. We're not going to dive as deep into B-Splines as we have for Bézier curves (that would be an entire primer on its own) but we'll be looking at how B-Splines work, what kind of maths is involved in computing them, and how to draw them based on a number of parameters that you can pick for individual B-Splines.

First off: B-Splines are piecewise polynomial interpolation curves, where the "single curve" is built by performing polynomial interpolation over a set of points, using a sliding window of a fixed number of points. For instance, a "cubic" B-Spline defined by twelve points will have its curve built by evaluating the polynomial interpolation of four points, and the curve can be treated as a lot of different sections, each controlled by four points at a time, such that the full curve consists of smoothly connected sections defined by points {1,2,3,4}, {2,3,4,5}, ..., {8,9,10,11}, and finally {9,10,11,12}, for eight sections.

-

What do they look like? They look like this! .. okay that's an empty graph, but simply click to place some point, with the stipulation that you need at least four point to see any curve. More than four points simply draws a longer B-Spline curve:

- +

What do they look like? They look like this! Tap on the graphic to add more points, and move points around to see how they map to the spline curve drawn.

+ + + Scripts are disabled. Showing fallback image. + + +

The important part to notice here is that we are not doing the same thing with B-Splines that we do for poly-Béziers or Catmull-Rom curves: both of the latter simply define new sections as literally "new sections based on new points", so a 12 point cubic poly-Bézier curve is actually impossible, because we start with a four point curve, and then add three more points for each section that follows, so we can only have 4, 7, 10, 13, 16, etc point Poly-Béziers. Similarly, while Catmull-Rom curves can grow by adding single points, this addition of a single point introduces three implicit Bézier points. Cubic B-Splines, on the other hand, are smooth interpolations of each possible curve involving four consecutive points, such that at any point along the curve except for our start and end points, our on-curve coordinate is defined by four control points.

Consider the difference to be this:

@@ -2331,31 +2345,33 @@ for p = 1 to points.length-3 (inclusive):

In order to make this interpolation of curves work, the maths is necessarily more complex than the maths for Bézier curves, so let's have a look at how things work.

How to compute a B-Spline curve: some maths

Given a B-Spline of degree d and thus order k=d+1 (so a quadratic B-Spline is degree 2 and order 3, a cubic B-Spline is degree 3 and order 4, etc) and n control points P0 through Pn-1, we can compute a point on the curve for some value t in the interval [0,1] (where 0 is the start of the curve, and 1 the end, just like for Bézier curves), by evaluating the following function:

- +

Which, honestly, doesn't tell us all that much. All we can see is that a point on a B-Spline curve is defined as "a mix of all the control points, weighted somehow", where the weighting is achieved through the N(...) function, subscripted with an obvious parameter i, which comes from our summation, and some magical parameter k. So we need to know two things: 1. what does N(t) do, and 2. what is that k? Let's cover both, in reverse order.

The parameter k represents the "knot interval" over which a section of curve is defined. As we learned earlier, a B-Spline curve is itself an interpoliation of curves, and we can treat each transition where a control point starts or stops influencing the total curvature as a "knot on the curve". Doing so for a degree d B-Spline with n control point gives us d + n + 1 knots, defining d + n intervals along the curve, and it is these intervals that the above k subscript to the N() function applies to.

Then the N() function itself. What does it look like?

- +

So this is where we see the interpolation: N(t) for an (i,k) pair (that is, for a step in the above summation, on a specific knot interval) is a mix between N(t) for (i,k-1) and N(t) for (i+1,k-1), so we see that this is a recursive iteration where i goes up, and k goes down, so it seem reasonable to expect that this recursion has to stop at some point; obviously, it does, and specifically it does so for the following i/k values:

- +

And this function finally has a straight up evaluation: if a t value lies within a knot-specific interval once we reach a k=1 value, it "counts", otherwise it doesn't. We did cheat a little, though, because for all these values we need to scale our t value first, so that it lies in the interval bounded by knots[d] and knots[n], which are the start point and end point where curvature is controlled by exactly order control points. For instance, for degree 3 (=order 4) and 7 control points, with knot vector [1,2,3,4,5,6,7,8,9,10,11], we map t from [the interval 0,1] to the interval [4,8], and then use that value in the functions above, instead.

Can we simplify that?

We can, yes.

People far smarter than us have looked at this work, and two in particular — Maurice Cox and Carl de Boor — came to a mathematically pleasing solution: to compute a point P(t), we can compute this point by evaluating d(t) on a curve section between knots i and i+1:

- +

This is another recursive function, with k values decreasing from the curve order to 1, and the value α (alpha) defined by:

- +

That looks complicated, but it's not. Computing alpha is just a fraction involving known, plain numbers and once we have our alpha value, computing (1-alpha) is literally just "computing one minus alpha". Computing this d() function is thus simply a matter of "computing simple arithmetics but with recursion", which might be computationally expensive because we're doing "a lot of" steps, but is also computationally cheap because each step only involves very simple maths. Of course as before the recursion has to stop:

- +

So, we see two stopping conditions: either i becomes 0, in which case d() is zero, or k becomes zero, in which case we get the same "either 1 or 0" that we saw in the N() function above.

Thanks to Cox and de Boor, we can compute points on a B-Spline pretty easily: we just need to compute a triangle of interconnected values. For instance, d() for i=3, k=3 yields the following triangle:

- +

That is, we compute d(3,3) as a mixture of d(2,3) and d(2,2): d(3,3) = a(3,3) x d(2,3) + (1-a(3,3)) x d(2,2)... and we simply keep expanding our triangle until we reach the terminating function parameters. Done deal!

One thing we need to keep in mind is that we're working with a spline that is constrained by its control points, so even though the d(..., k) values are zero or one at the lowest level, they are really "zero or one, times their respective control point", so in the next section you'll see the algorithm for running through the computation in a way that starts with a copy of the control point vector and then works its way up to that single point: that's pretty essential!

If we run this computation "down", starting at d(3,3), then without special code in place we would be computing quite a few terms multiple times at each step. On the other hand, we can also start with that last "column", we can generate the terminating d() values first, then compute the a() constants, perform our multiplications, generate the previous step's d() values, compute their a() constants, do the multiplications, etc. until we end up all the way back at the top. If we run our computation this way, we don't need any explicit caching, we can just "recycle" the list of numbers we start with and simply update them as we move up the triangle. So, let's implement that!

Cool, cool... but I don't know what to do with that information

I know, this is pretty mathy, so let's have a look at what happens when we change parameters here. We can't change the maths for the interpolation functions, so that gives us only one way to control what happens here: the knot vector itself. As such, let's look at the graph that shows the interpolation functions for a cubic B-Spline with seven points with a uniform knot vector (so we see seven identical functions), representing how much each point (represented by one function each) influences the total curvature, given our knot values. And, because exploration is the key to discovery, let's make the knot vector a thing we can actually manipulate. Normally a proper knot vector has a constraint that any value is strictly equal to, or larger than the previous ones, but screw it this is programming, let's ignore that hard restriction and just mess with the knots however we like.

+ +
this.bindKnots(owner, knots, "interpolation-graph")}/> @@ -2394,44 +2410,56 @@ for(let L = 1; L <= order; L++) {

Uniform B-Splines

The most straightforward type of B-Spline is the uniform spline. In a uniform spline, the knots are distributed uniformly over the entire curve interval. For instance, if we have a knot vector of length twelve, then a uniform knot vector would be [0,1,2,3,...,9,10,11]. Or [4,5,6,...,13,14,15], which defines the same intervals, or even [0,2,3,...,18,20,22], which also defines the same intervals, just scaled by a constant factor, which becomes normalised during interpolation and so does not contribute to the curvature.

-
- - this.bindKnots(owner, knots, "uniform-spline")}/> -
+ + + Scripts are disabled. Showing fallback image. + + + + +

This is an important point: the intervals that the knot vector defines are relative intervals, so it doesn't matter if every interval is size 1, or size 100 - the relative differences between the intervals is what shapes any particular curve.

The problem with uniform knot vectors is that, as we need order control points before we have any curve with which we can perform interpolation, the curve does not "start" at the first point, nor "ends" at the last point. Instead there are "gaps". We can get rid of these, by being clever about how we apply the following uniformity-breaking approach instead...

Reducing local curve complexity by collapsing intervals

-

By collapsing knot intervals by making two or more consecutive knots have the same value, we can reduce the curve complexity in the sections that are affected by the knots involved. This can have drastic effects: for every interval collapse, the curve order goes down, and curve continuity goes down, to the point where collapsing order knots creates a situation where all continuity is lost and the curve "kinks".

-
- - this.bindKnots(owner, knots, "center-cut-bspline")}/> -
+

Collapsing knot intervals, by making two or more consecutive knots have the same value, allows us to reduce the curve complexity in the sections that are affected by the knots involved. This can have drastic effects: for every interval collapse, the curve order goes down, and curve continuity goes down, to the point where collapsing order knots creates a situation where all continuity is lost and the curve "kinks".

+ + + Scripts are disabled. Showing fallback image. + + + + + +

Open-Uniform B-Splines

By combining knot interval collapsing at the start and end of the curve, with uniform knots in between, we can overcome the problem of the curve not starting and ending where we'd kind of like it to:

For any curve of degree D with control points N, we can define a knot vector of length N+D+1 in which the values 0 ... D+1 are the same, the values D+1 ... N+1 follow the "uniform" pattern, and the values N+1 ... N+D+1 are the same again. For example, a cubic B-Spline with 7 control points can have a knot vector [0,0,0,0,1,2,3,4,4,4,4], or it might have the "identical" knot vector [0,0,0,0,2,4,6,8,8,8,8], etc. Again, it is the relative differences that determine the curve shape.

-
- - this.bindKnots(owner, knots, "open-uniform-bspline")}/> -
+ + + Scripts are disabled. Showing fallback image. + + + + + +

Non-uniform B-Splines

-

This is essentially the "free form" version of a B-Spline, and also the least interesting to look at, as without any specific reason to pick specific knot intervals, there is nothing particularly interesting going on. There is one constraint to the knot vector, and that is that any value knots[k+1] should be equal to, or greater than knots[k].

+

This is essentially the "free form" version of a B-Spline, and also the least interesting to look at, as without any specific reason to pick specific knot intervals, there is nothing particularly interesting going on. There is one constraint to the knot vector, other than that any value knots[k+1] should be greater than or equal to knots[k].

One last thing: Rational B-Splines

While it is true that this section on B-Splines is running quite long already, there is one more thing we need to talk about, and that's "Rational" splines, where the rationality applies to the "ratio", or relative weights, of the control points themselves. By introducing a ratio vector with weights to apply to each control point, we greatly increase our influence over the final curve shape: the more weight a control point carries, the close to that point the spline curve will lie, a bit like turning up the gravity of a control point.

-
- { - // - } - - { - // this.bindKnots(owner, knots, "rational-uniform-bspline"); - this.bindWeights(owner, weights, closed, "rational-uniform-bspline-weights"); - }} /> -
+ + + Scripts are disabled. Showing fallback image. + + + + + -

Of course this brings us to the final topic that any text on B-Splines must touch on before calling it a day: the NURBS, or Non-Uniform Rational B-Spline (NURBS is not a plural, the capital S actually just stands for "spline", but a lot of people mistakenly treat it as if it is, so now you know better). NURBS are an important type of curve in computer-facilitated design, used a lot in 3D modelling (as NURBS surfaces) as well as in arbitrary-precision 2D design due to the level of control a NURBS curve offers designers.

+

Of course this brings us to the final topic that any text on B-Splines must touch on before calling it a day: the NURBS, or Non-Uniform Rational B-Spline (NURBS is not a plural, the capital S actually just stands for "spline", but a lot of people mistakenly treat it as if it is, so now you know better). NURBS is an important type of curve in computer-facilitated design, used a lot in 3D modelling (typically as NURBS surfaces) as well as in arbitrary-precision 2D design due to the level of control a NURBS curve offers designers.

While a true non-uniform rational B-Spline would be hard to work with, when we talk about NURBS we typically mean the Open-Uniform Rational B-Spline, or OURBS, but that doesn't roll off the tongue nearly as nicely, and so remember that when people talk about NURBS, they typically mean open-uniform, which has the useful property of starting the curve at the first control point, and ending it at the last.

Extending our implementation to cover rational splines

The algorithm for working with Rational B-Splines is virtually identical to the regular algorithm, and the extension to work in the control point weights is fairly simple: we extend each control point from a point in its original number of dimensions (2D, 3D, etc) to one dimension higher, scaling the original dimensions by the control point's weight, and then assigning that weight as its value for the extended dimension.

diff --git a/docs/js/custom-element/api/graphics-api.js b/docs/js/custom-element/api/graphics-api.js index 0f69ca4d..8ef60858 100644 --- a/docs/js/custom-element/api/graphics-api.js +++ b/docs/js/custom-element/api/graphics-api.js @@ -1,5 +1,6 @@ import { enrich } from "../lib/enrich.js"; import { Bezier } from "./types/bezier.js"; +import { BSpline } from "./types/bspline.js"; import { Vector } from "./types/vector.js"; import { Matrix } from "./types/matrix.js"; import { Shape } from "./util/shape.js"; @@ -791,4 +792,4 @@ class GraphicsAPI extends BaseAPI { } } -export { GraphicsAPI, Bezier, Vector, Matrix, Shape }; +export { GraphicsAPI, Bezier, BSpline, Vector, Matrix, Shape }; diff --git a/docs/js/custom-element/api/types/bspline.js b/docs/js/custom-element/api/types/bspline.js new file mode 100644 index 00000000..91cd1f33 --- /dev/null +++ b/docs/js/custom-element/api/types/bspline.js @@ -0,0 +1,85 @@ +import interpolate from "../util/spline.js"; + +// cubic B-Spline +const DEGREE = 3; + +class BSpline { + constructor(apiInstance, points) { + this.api = apiInstance; + this.ctx = apiInstance.ctx; + + // the spline library needs points in array format [x,y] rather than object format {x:..., y:...} + this.points = points.map((v) => { + if (v instanceof Array) return v; + return [v.x, v.y]; + }); + } + + getLUT(count) { + let c = count - 1; + return [...new Array(count)].map((_, i) => { + let p = interpolate(i / c, DEGREE, this.points, this.knots, this.weights); + return { x: p[0], y: p[1] }; + }); + } + + formKnots(open = false) { + if (!open) return this.formUniformKnots(); + + let knots = [], + l = this.points.length, + m = l - DEGREE; + + // form the open-uniform knot vector + for (let i = 1; i < l - DEGREE; i++) { + knots.push(i + DEGREE); + } + // add [degree] zeroes at the front + for (let i = 0; i <= DEGREE; i++) { + knots = [DEGREE].concat(knots); + } + // add [degree] max-values to the back + for (let i = 0; i <= DEGREE; i++) { + knots.push(m + DEGREE); + } + + return (this.knots = knots); + } + + formUniformKnots() { + return (this.knots = [...new Array(this.points.length + DEGREE + 1)].map( + (_, i) => i + )); + } + + formNodes() { + const knots = this.knots; + const domain = [DEGREE, knots.length - 1 - DEGREE], + nodes = []; + + for (let k = 0; k < this.points.length; k++) { + let node = 0; + for (let offset = 1; offset <= DEGREE; offset++) { + node += knots[k + offset]; + } + node /= DEGREE; + if (node < knots[domain[0]]) continue; + if (node > knots[domain[1]]) continue; + nodes.push(node); + } + + return (this.nodes = nodes); + } + + formWeights() { + return (this.weights = this.points.map((p) => 1)); + } + + setDegree(d) { + DEGREE += d; + this.knots = this.formKnots(); + this.nodes = this.formNodes(); + } +} + +export { BSpline }; diff --git a/docs/js/custom-element/api/util/spline.js b/docs/js/custom-element/api/util/spline.js new file mode 100644 index 00000000..3b16f754 --- /dev/null +++ b/docs/js/custom-element/api/util/spline.js @@ -0,0 +1,88 @@ +// https://github.com/thibauts/b-spline +export default function interpolate( + t, + degree, + points, + knots, + weights, + result, + scaled +) { + var i, j, s, l; // function-scoped iteration variables + var n = points.length; // points count + var d = points[0].length; // point dimensionality + + if (degree < 1) throw new Error("degree must be at least 1 (linear)"); + if (degree > n - 1) + throw new Error("degree must be less than or equal to point count - 1"); + + if (!weights) { + // build weight vector of length [n] + weights = []; + for (i = 0; i < n; i++) { + weights[i] = 1; + } + } + + if (!knots) { + // build knot vector of length [n + degree + 1] + var knots = []; + for (i = 0; i < n + degree + 1; i++) { + knots[i] = i; + } + } else { + if (knots.length !== n + degree + 1) + throw new Error("bad knot vector length"); + } + + var domain = [degree, knots.length - 1 - degree]; + + var low = knots[domain[0]]; + var high = knots[domain[1]]; + + // remap t to the domain where the spline is defined + if (!scaled) { + t = t * (high - low) + low; + } + + if (t < low || t > high) throw new Error("out of bounds"); + + // find s (the spline segment) for the [t] value provided + for (s = domain[0]; s < domain[1]; s++) { + if (t >= knots[s] && t <= knots[s + 1]) { + break; + } + } + + // convert points to homogeneous coordinates + var v = []; + for (i = 0; i < n; i++) { + v[i] = []; + for (j = 0; j < d; j++) { + v[i][j] = points[i][j] * weights[i]; + } + v[i][d] = weights[i]; + } + + // l (level) goes from 1 to the curve degree + 1 + var alpha; + for (l = 1; l <= degree + 1; l++) { + // build level l of the pyramid + for (i = s; i > s - degree - 1 + l; i--) { + alpha = (t - knots[i]) / (knots[i + degree + 1 - l] - knots[i]); + + // interpolate each component + for (j = 0; j < d + 1; j++) { + v[i][j] = (1 - alpha) * v[i - 1][j] + alpha * v[i][j]; + } + } + } + + // convert back to cartesian and return + var result = result || []; + for (i = 0; i < d; i++) { + result[i] = v[s][i] / v[s][d]; + } + + return result; +} diff --git a/docs/js/custom-element/graphics-element.js b/docs/js/custom-element/graphics-element.js index c6f81bba..e952b697 100644 --- a/docs/js/custom-element/graphics-element.js +++ b/docs/js/custom-element/graphics-element.js @@ -207,7 +207,7 @@ class GraphicsElement extends CustomElement { * Program source: ${src} * Data attributes: ${JSON.stringify(this.dataset)} */ - import { GraphicsAPI, Bezier, Vector, Matrix, Shape } from "${MODULE_PATH}/api/graphics-api.js"; + import { GraphicsAPI, Bezier, BSpline, Vector, Matrix, Shape } from "${MODULE_PATH}/api/graphics-api.js"; ${globalCode} diff --git a/docs/zh-CN/index.html b/docs/zh-CN/index.html index f7a8c269..8c628ff1 100644 --- a/docs/zh-CN/index.html +++ b/docs/zh-CN/index.html @@ -1578,7 +1578,7 @@ lli = function(line1, line2): Scripts are disabled. Showing fallback image. - + @@ -2255,10 +2255,10 @@ for p = 1 to points.length-3 (inclusive):

Which, in decimal values, rounded to six significant digits, is:

Of course, this is for a circle with radius 1, so if you have a different radius circle, simply multiply the coordinate by the radius you need. And then finally, forming a full curve is now a simple a matter of mirroring these coordinates about the origin:

- + Scripts are disabled. Showing fallback image. - + @@ -2268,43 +2268,52 @@ for p = 1 to points.length-3 (inclusive):

Let's look at doing the exact opposite of the previous section: rather than approximating circular arc using Bézier curves, let's approximate Bézier curves using circular arcs.

We already saw in the section on circle approximation that this will never yield a perfect equivalent, but sometimes you need circular arcs, such as when you're working with fabrication machinery, or simple vector languages that understand lines and circles, but not much else.

The approach is fairly simple: pick a starting point on the curve, and pick two points that are further along the curve. Determine the circle that goes through those three points, and see if it fits the part of the curve we're trying to approximate. Decent fit? Try spacing the points further apart. Bad fit? Try spacing the points closer together. Keep doing this until you've found the "good approximation/bad approximation" boundary, record the "good" arc, and then move the starting point up to overlap the end point we previously found. Rinse and repeat until we've covered the entire curve.

-

So: step 1, how do we find a circle through three points? That part is actually really simple. You may remember (if you ever learned it!) that a line between two points on a circle is called a chord, and one property of chords is that the line from the center of any chord, perpendicular to that chord, passes through the center of the circle.

-

So: if we have have three points, we have three (different) chords, and consequently, three (different) lines that go from those chords through the center of the circle. So we find the centers of the chords, find the perpendicular lines, find the intersection of those lines, and thus find the center of the circle.

-

The following graphic shows this procedure with a different colour for each chord and its associated perpendicular through the center. You can move the points around as much as you like, those lines will always meet!

- - -

So, with the procedure on how to find a circle through three points, finding the arc through those points is straight-forward: pick one of the three points as start point, pick another as an end point, and the arc has to necessarily go from the start point, over the remaining point, to the end point.

-

So how can we convert a Bézier curve into a (sequence of) circular arc(s)?

+

We already saw how to fit a circle through three points in the section on creating a curve from three points, and finding the arc through those points is straight-forward: pick one of the three points as start point, pick another as an end point, and the arc has to necessarily go from the start point, to the end point, over the remaining point.

+

So, how can we convert a Bézier curve into a (sequence of) circular arc(s)?

    -
  • Start at t=0
  • -
  • Pick two points further down the curve at some value m = t + n and e = t + 2n
  • +
  • Start at t=0
  • +
  • Pick two points further down the curve at some value m = t + n and e = t + 2n
  • Find the arc that these points define
  • Determine how close the found arc is to the curve:
      -
    • Pick two additional points e1 = t + n/2 and e2 = t + n + n/2.
    • +
    • Pick two additional points e1 = t + n/2 and e2 = t + n + n/2.
    • These points, if the arc is a good approximation of the curve interval chosen, should - lie on the circle, so their distance to the center of the circle should be the + lie on the circle, so their distance to the center of the circle should be the same as the distance from any of the three other points to the center.
    • For point points, determine the (absolute) error between the radius of the circle, and the -actual distance from the center of the circle to the point on the curve.
    • +actual distance from the center of the circle to the point on the curve.
    • If this error is too high, we consider the arc bad, and try a smaller interval.
-

The result of this is shown in the next graphic: we start at a guaranteed failure: s=0, e=1. That's the entire curve. The midpoint is simply at t=0.5, and then we start performing a Binary Search.

+

The result of this is shown in the next graphic: we start at a guaranteed failure: s=0, e=1. That's the entire curve. The midpoint is simply at t=0.5, and then we start performing a binary search.

    -
  1. We start with {0, 0.5, 1}
  2. -
  3. That'll fail, so we retry with the interval halved: {0, 0.25, 0.5}
      -
    • If that arc's good, we move back up by half distance: {0, 0.375, 0.75}.
    • -
    • However, if the arc was still bad, we move down by half the distance: {0, 0.125, 0.25}.
    • +
    • We start with low=0, mid=0.5 and high=1
    • +
    • That'll fail, so we retry with the interval halved: {0, 0.25, 0.5}
        +
      • If that arc's good, we move back up by half distance: {0, 0.375, 0.75}.
      • +
      • However, if the arc was still bad, we move down by half the distance: {0, 0.125, 0.25}.
    • -
    • We keep doing this over and over until we have two arcs found in sequence of which the first arc is good, and the second arc is bad. When we find that pair, we've found the boundary between a good approximation and a bad approximation, and we pick the former.
    • +
    • We keep doing this over and over until we have two arcs, in sequence, of which the first arc is good, and the second arc is bad. When we find that pair, we've found the boundary between a good approximation and a bad approximation, and we pick the good arc.

The following graphic shows the result of this approach, with a default error threshold of 0.5, meaning that if an arc is off by a combined half pixel over both verification points, then we treat the arc as bad. This is an extremely simple error policy, but already works really well. Note that the graphic is still interactive, and you can use your up and down arrow keys keys to increase or decrease the error threshold, to see what the effect of a smaller or larger error threshold is.

- + + + Scripts are disabled. Showing fallback image. + + + + +

With that in place, all that's left now is to "restart" the procedure by treating the found arc's end point as the new to-be-determined arc's starting point, and using points further down the curve. We keep trying this until the found end point is for t=1, at which point we are done. Again, the following graphic allows for up and down arrow key input to increase or decrease the error threshold, so you can see how picking a different threshold changes the number of arcs that are necessary to reasonably approximate a curve:

- + + + Scripts are disabled. Showing fallback image. + + + + +

So... what is this good for? Obviously, if you're working with technologies that can't do curves, but can do lines and circles, then the answer is pretty straightforward, but what else? There are some reasons why you might need this technique: using circular arcs means you can determine whether a coordinate lies "on" your curve really easily (simply compute the distance to each circular arc center, and if any of those are close to the arc radii, at an angle between the arc start and end, bingo, this point can be treated as lying "on the curve"). Another benefit is that this approximation is "linear": you can almost trivially travel along the arcs at fixed speed. You can also trivially compute the arc length of the approximated curve (it's a bit like curve flattening). The only thing to bear in mind is that this is a lossy equivalence: things that you compute based on the approximation are guaranteed "off" by some small value, and depending on how much precision you need, arc approximation is either going to be super useful, or completely useless. It's up to you to decide which, based on your application!

@@ -2313,8 +2322,13 @@ for p = 1 to points.length-3 (inclusive):

B-Splines

No discussion on Bézier curves is complete without also giving mention of that other beast in the curve design space: B-Splines. Easily confused to mean Bézier splines, that's not actually what they are; they are "basis function" splines, which makes a lot of difference, and we'll be looking at those differences in this section. We're not going to dive as deep into B-Splines as we have for Bézier curves (that would be an entire primer on its own) but we'll be looking at how B-Splines work, what kind of maths is involved in computing them, and how to draw them based on a number of parameters that you can pick for individual B-Splines.

First off: B-Splines are piecewise polynomial interpolation curves, where the "single curve" is built by performing polynomial interpolation over a set of points, using a sliding window of a fixed number of points. For instance, a "cubic" B-Spline defined by twelve points will have its curve built by evaluating the polynomial interpolation of four points, and the curve can be treated as a lot of different sections, each controlled by four points at a time, such that the full curve consists of smoothly connected sections defined by points {1,2,3,4}, {2,3,4,5}, ..., {8,9,10,11}, and finally {9,10,11,12}, for eight sections.

-

What do they look like? They look like this! .. okay that's an empty graph, but simply click to place some point, with the stipulation that you need at least four point to see any curve. More than four points simply draws a longer B-Spline curve:

- +

What do they look like? They look like this! Tap on the graphic to add more points, and move points around to see how they map to the spline curve drawn.

+ + + Scripts are disabled. Showing fallback image. + + +

The important part to notice here is that we are not doing the same thing with B-Splines that we do for poly-Béziers or Catmull-Rom curves: both of the latter simply define new sections as literally "new sections based on new points", so a 12 point cubic poly-Bézier curve is actually impossible, because we start with a four point curve, and then add three more points for each section that follows, so we can only have 4, 7, 10, 13, 16, etc point Poly-Béziers. Similarly, while Catmull-Rom curves can grow by adding single points, this addition of a single point introduces three implicit Bézier points. Cubic B-Splines, on the other hand, are smooth interpolations of each possible curve involving four consecutive points, such that at any point along the curve except for our start and end points, our on-curve coordinate is defined by four control points.

Consider the difference to be this:

@@ -2325,31 +2339,33 @@ for p = 1 to points.length-3 (inclusive):

In order to make this interpolation of curves work, the maths is necessarily more complex than the maths for Bézier curves, so let's have a look at how things work.

How to compute a B-Spline curve: some maths

Given a B-Spline of degree d and thus order k=d+1 (so a quadratic B-Spline is degree 2 and order 3, a cubic B-Spline is degree 3 and order 4, etc) and n control points P0 through Pn-1, we can compute a point on the curve for some value t in the interval [0,1] (where 0 is the start of the curve, and 1 the end, just like for Bézier curves), by evaluating the following function:

- +

Which, honestly, doesn't tell us all that much. All we can see is that a point on a B-Spline curve is defined as "a mix of all the control points, weighted somehow", where the weighting is achieved through the N(...) function, subscripted with an obvious parameter i, which comes from our summation, and some magical parameter k. So we need to know two things: 1. what does N(t) do, and 2. what is that k? Let's cover both, in reverse order.

The parameter k represents the "knot interval" over which a section of curve is defined. As we learned earlier, a B-Spline curve is itself an interpoliation of curves, and we can treat each transition where a control point starts or stops influencing the total curvature as a "knot on the curve". Doing so for a degree d B-Spline with n control point gives us d + n + 1 knots, defining d + n intervals along the curve, and it is these intervals that the above k subscript to the N() function applies to.

Then the N() function itself. What does it look like?

- +

So this is where we see the interpolation: N(t) for an (i,k) pair (that is, for a step in the above summation, on a specific knot interval) is a mix between N(t) for (i,k-1) and N(t) for (i+1,k-1), so we see that this is a recursive iteration where i goes up, and k goes down, so it seem reasonable to expect that this recursion has to stop at some point; obviously, it does, and specifically it does so for the following i/k values:

- +

And this function finally has a straight up evaluation: if a t value lies within a knot-specific interval once we reach a k=1 value, it "counts", otherwise it doesn't. We did cheat a little, though, because for all these values we need to scale our t value first, so that it lies in the interval bounded by knots[d] and knots[n], which are the start point and end point where curvature is controlled by exactly order control points. For instance, for degree 3 (=order 4) and 7 control points, with knot vector [1,2,3,4,5,6,7,8,9,10,11], we map t from [the interval 0,1] to the interval [4,8], and then use that value in the functions above, instead.

Can we simplify that?

We can, yes.

People far smarter than us have looked at this work, and two in particular — Maurice Cox and Carl de Boor — came to a mathematically pleasing solution: to compute a point P(t), we can compute this point by evaluating d(t) on a curve section between knots i and i+1:

- +

This is another recursive function, with k values decreasing from the curve order to 1, and the value α (alpha) defined by:

- +

That looks complicated, but it's not. Computing alpha is just a fraction involving known, plain numbers and once we have our alpha value, computing (1-alpha) is literally just "computing one minus alpha". Computing this d() function is thus simply a matter of "computing simple arithmetics but with recursion", which might be computationally expensive because we're doing "a lot of" steps, but is also computationally cheap because each step only involves very simple maths. Of course as before the recursion has to stop:

- +

So, we see two stopping conditions: either i becomes 0, in which case d() is zero, or k becomes zero, in which case we get the same "either 1 or 0" that we saw in the N() function above.

Thanks to Cox and de Boor, we can compute points on a B-Spline pretty easily: we just need to compute a triangle of interconnected values. For instance, d() for i=3, k=3 yields the following triangle:

- +

That is, we compute d(3,3) as a mixture of d(2,3) and d(2,2): d(3,3) = a(3,3) x d(2,3) + (1-a(3,3)) x d(2,2)... and we simply keep expanding our triangle until we reach the terminating function parameters. Done deal!

One thing we need to keep in mind is that we're working with a spline that is constrained by its control points, so even though the d(..., k) values are zero or one at the lowest level, they are really "zero or one, times their respective control point", so in the next section you'll see the algorithm for running through the computation in a way that starts with a copy of the control point vector and then works its way up to that single point: that's pretty essential!

If we run this computation "down", starting at d(3,3), then without special code in place we would be computing quite a few terms multiple times at each step. On the other hand, we can also start with that last "column", we can generate the terminating d() values first, then compute the a() constants, perform our multiplications, generate the previous step's d() values, compute their a() constants, do the multiplications, etc. until we end up all the way back at the top. If we run our computation this way, we don't need any explicit caching, we can just "recycle" the list of numbers we start with and simply update them as we move up the triangle. So, let's implement that!

Cool, cool... but I don't know what to do with that information

I know, this is pretty mathy, so let's have a look at what happens when we change parameters here. We can't change the maths for the interpolation functions, so that gives us only one way to control what happens here: the knot vector itself. As such, let's look at the graph that shows the interpolation functions for a cubic B-Spline with seven points with a uniform knot vector (so we see seven identical functions), representing how much each point (represented by one function each) influences the total curvature, given our knot values. And, because exploration is the key to discovery, let's make the knot vector a thing we can actually manipulate. Normally a proper knot vector has a constraint that any value is strictly equal to, or larger than the previous ones, but screw it this is programming, let's ignore that hard restriction and just mess with the knots however we like.

+ +
this.bindKnots(owner, knots, "interpolation-graph")}/> @@ -2388,44 +2404,56 @@ for(let L = 1; L <= order; L++) {

Uniform B-Splines

The most straightforward type of B-Spline is the uniform spline. In a uniform spline, the knots are distributed uniformly over the entire curve interval. For instance, if we have a knot vector of length twelve, then a uniform knot vector would be [0,1,2,3,...,9,10,11]. Or [4,5,6,...,13,14,15], which defines the same intervals, or even [0,2,3,...,18,20,22], which also defines the same intervals, just scaled by a constant factor, which becomes normalised during interpolation and so does not contribute to the curvature.

-
- - this.bindKnots(owner, knots, "uniform-spline")}/> -
+ + + Scripts are disabled. Showing fallback image. + + + + +

This is an important point: the intervals that the knot vector defines are relative intervals, so it doesn't matter if every interval is size 1, or size 100 - the relative differences between the intervals is what shapes any particular curve.

The problem with uniform knot vectors is that, as we need order control points before we have any curve with which we can perform interpolation, the curve does not "start" at the first point, nor "ends" at the last point. Instead there are "gaps". We can get rid of these, by being clever about how we apply the following uniformity-breaking approach instead...

Reducing local curve complexity by collapsing intervals

-

By collapsing knot intervals by making two or more consecutive knots have the same value, we can reduce the curve complexity in the sections that are affected by the knots involved. This can have drastic effects: for every interval collapse, the curve order goes down, and curve continuity goes down, to the point where collapsing order knots creates a situation where all continuity is lost and the curve "kinks".

-
- - this.bindKnots(owner, knots, "center-cut-bspline")}/> -
+

Collapsing knot intervals, by making two or more consecutive knots have the same value, allows us to reduce the curve complexity in the sections that are affected by the knots involved. This can have drastic effects: for every interval collapse, the curve order goes down, and curve continuity goes down, to the point where collapsing order knots creates a situation where all continuity is lost and the curve "kinks".

+ + + Scripts are disabled. Showing fallback image. + + + + + +

Open-Uniform B-Splines

By combining knot interval collapsing at the start and end of the curve, with uniform knots in between, we can overcome the problem of the curve not starting and ending where we'd kind of like it to:

For any curve of degree D with control points N, we can define a knot vector of length N+D+1 in which the values 0 ... D+1 are the same, the values D+1 ... N+1 follow the "uniform" pattern, and the values N+1 ... N+D+1 are the same again. For example, a cubic B-Spline with 7 control points can have a knot vector [0,0,0,0,1,2,3,4,4,4,4], or it might have the "identical" knot vector [0,0,0,0,2,4,6,8,8,8,8], etc. Again, it is the relative differences that determine the curve shape.

-
- - this.bindKnots(owner, knots, "open-uniform-bspline")}/> -
+ + + Scripts are disabled. Showing fallback image. + + + + + +

Non-uniform B-Splines

-

This is essentially the "free form" version of a B-Spline, and also the least interesting to look at, as without any specific reason to pick specific knot intervals, there is nothing particularly interesting going on. There is one constraint to the knot vector, and that is that any value knots[k+1] should be equal to, or greater than knots[k].

+

This is essentially the "free form" version of a B-Spline, and also the least interesting to look at, as without any specific reason to pick specific knot intervals, there is nothing particularly interesting going on. There is one constraint to the knot vector, other than that any value knots[k+1] should be greater than or equal to knots[k].

One last thing: Rational B-Splines

While it is true that this section on B-Splines is running quite long already, there is one more thing we need to talk about, and that's "Rational" splines, where the rationality applies to the "ratio", or relative weights, of the control points themselves. By introducing a ratio vector with weights to apply to each control point, we greatly increase our influence over the final curve shape: the more weight a control point carries, the close to that point the spline curve will lie, a bit like turning up the gravity of a control point.

-
- { - // - } - - { - // this.bindKnots(owner, knots, "rational-uniform-bspline"); - this.bindWeights(owner, weights, closed, "rational-uniform-bspline-weights"); - }} /> -
+ + + Scripts are disabled. Showing fallback image. + + + + + -

Of course this brings us to the final topic that any text on B-Splines must touch on before calling it a day: the NURBS, or Non-Uniform Rational B-Spline (NURBS is not a plural, the capital S actually just stands for "spline", but a lot of people mistakenly treat it as if it is, so now you know better). NURBS are an important type of curve in computer-facilitated design, used a lot in 3D modelling (as NURBS surfaces) as well as in arbitrary-precision 2D design due to the level of control a NURBS curve offers designers.

+

Of course this brings us to the final topic that any text on B-Splines must touch on before calling it a day: the NURBS, or Non-Uniform Rational B-Spline (NURBS is not a plural, the capital S actually just stands for "spline", but a lot of people mistakenly treat it as if it is, so now you know better). NURBS is an important type of curve in computer-facilitated design, used a lot in 3D modelling (typically as NURBS surfaces) as well as in arbitrary-precision 2D design due to the level of control a NURBS curve offers designers.

While a true non-uniform rational B-Spline would be hard to work with, when we talk about NURBS we typically mean the Open-Uniform Rational B-Spline, or OURBS, but that doesn't roll off the tongue nearly as nicely, and so remember that when people talk about NURBS, they typically mean open-uniform, which has the useful property of starting the curve at the first control point, and ending it at the last.

Extending our implementation to cover rational splines

The algorithm for working with Rational B-Splines is virtually identical to the regular algorithm, and the extension to work in the control point weights is fairly simple: we extend each control point from a point in its original number of dimensions (2D, 3D, etc) to one dimension higher, scaling the original dimensions by the control point's weight, and then assigning that weight as its value for the extended dimension.

diff --git a/src/build/markdown/generate-graphics-module.js b/src/build/markdown/generate-graphics-module.js index 4f9c6e15..eab63349 100644 --- a/src/build/markdown/generate-graphics-module.js +++ b/src/build/markdown/generate-graphics-module.js @@ -36,7 +36,7 @@ function generateGraphicsModule(chapter, code, width, height, dataset) { let moduleCode = ` import CanvasBuilder from 'canvas'; - import { GraphicsAPI, Bezier, Vector, Matrix, Shape } from "${GRAPHICS_API_LOCATION}"; + import { GraphicsAPI, Bezier, BSpline, Vector, Matrix, Shape } from "${GRAPHICS_API_LOCATION}"; ${globalCode}