diff --git a/docs/chapters/curvefitting/comments.txt b/docs/chapters/curvefitting/comments.txt deleted file mode 100644 index 53ebcdb2..00000000 --- a/docs/chapters/curvefitting/comments.txt +++ /dev/null @@ -1,3 +0,0 @@ -## Additionals - -http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.96.5193&rep=rep1&type=pdf ? diff --git a/docs/chapters/curvefitting/content.en-GB.md b/docs/chapters/curvefitting/content.en-GB.md index 44ad1e95..fa0cc825 100644 --- a/docs/chapters/curvefitting/content.en-GB.md +++ b/docs/chapters/curvefitting/content.en-GB.md @@ -251,13 +251,11 @@ Here, the "to the power negative one" is the notation for the [matrix inverse](h So before we try that out, how much code is involved in implementing this? Honestly, that answer depends on how much you're going to be writing yourself. If you already have a matrix maths library available, then really not that much code at all. On the other hand, if you are writing this from scratch, you're going to have to write some utility functions for doing your matrix work for you, so it's really anywhere from 50 lines of code to maybe 200 lines of code. Not a bad price to pay for being able to fit curves to prespecified coordinates. -So let's try it out! The following graphic lets you place points, and will start computing exact-fit curves once you've placed at least three. You can click for more points, and the code will simply try to compute an exact fit using a Bézier curve of the appropriate order. Four points? Cubic Bézier. Five points? Quartic. And so on. Of course, this does break down at some point: depending on where you place your points, it might become mighty hard for the fitter to find an exact fit, and things might actually start looking horribly off once you hit 10th or higher order curves. But it might not! +So let's try it out! The following graphic lets you place points, and will start computing exact-fit curves once you've placed at least three. You can click for more points, and the code will simply try to compute an exact fit using a Bézier curve of the appropriate order. Four points? Cubic Bézier. Five points? Quartic. And so on. Of course, this does break down at some point: depending on where you place your points, it might become mighty hard for the fitter to find an exact fit, and things might actually start looking horribly off once there's enough points for compound [floating point rounding errors](https://en.wikipedia.org/wiki/Round-off_error#Floating-point_number_system) to start making a difference (which is around 10~11 points). -
- - - (this.sliders=set) } onChange={this.processTimeUpdate} /> - -
+ + +
+
-You'll note there is a convenient "toggle" buttons that lets you toggle between equidistance `t` values, and distance ratio along the polygon. Arguably more interesting is that once you have points to abstract a curve, you also get direct control over the time values through sliders for each, because if the time values are our degree of freedom, you should be able to freely manipulate them and see what the effect on your curve is. +You'll note there is a convenient "toggle" buttons that lets you toggle between equidistant `t` values, and distance ratio along the polygon formed by the points. Arguably more interesting is that once you have points to abstract a curve, you also get direct control over the time values through sliders for each, because if the time values are our degree of freedom, you should be able to freely manipulate them and see what the effect on your curve is. diff --git a/docs/chapters/curvefitting/curve-fitter.js b/docs/chapters/curvefitting/curve-fitter.js new file mode 100644 index 00000000..cd7956ab --- /dev/null +++ b/docs/chapters/curvefitting/curve-fitter.js @@ -0,0 +1,148 @@ +import invert from "./matrix-invert.js"; + +var binomialCoefficients = [[1],[1,1]]; + +function binomial(n,k) { + if (n===0) return 1; + var lut = binomialCoefficients; + while(n >= lut.length) { + var s = lut.length; + var nextRow = [1]; + for(var i=1,prev=s-1; i Mt.push([])); + M.forEach((row,r) => row.forEach((v,c) => Mt[c][r] = v)); + return Mt; +} + +function row(M,i) { + return M[i]; +} + +function col(M,i) { + var col = []; + for(var r=0, l=M.length; r a + _col[i]*v; + M[r][c] = _row.reduce(reducer, 0); + } + } + return M; +} + +function getValueColumn(P, prop) { + var col = []; + P.forEach(v => col.push([v[prop]])); + return col; +} + +function computeBasisMatrix(n) { + /* + We can form any basis matrix using a generative approach: + + - it's an M = (n x n) matrix + - it's a lower triangular matrix: all the entries above the main diagonal are zero + - the main diagonal consists of the binomial coefficients for n + - all entries are symmetric about the antidiagonal. + + What's more, if we number rows and columns starting at 0, then + the value at position M[r,c], with row=r and column=c, can be + expressed as: + + M[r,c] = (r choose c) * M[r,r] * S, + + where S = 1 if r+c is even, or -1 otherwise + + That is: the values in column c are directly computed off of the + binomial coefficients on the main diagonal, through multiplication + by a binomial based on matrix position, with the sign of the value + also determined by matrix position. This is actually very easy to + write out in code: + */ + + // form the square matrix, and set it to all zeroes + var M = [], i = n; + while (i--) { M[i] = "0".repeat(n).split('').map(v => parseInt(v)); } + + // populate the main diagonal + var k = n - 1; + for (i=0; i Math.pow(v,i)); +} + +function formTMatrix(S, n) { + n = n || S.length; + var Tp = []; + // it's easier to generate the transposed matrix: + for(var i=0; i this.toggle()); + sliders = find(`.sliders`); + this.mode = 0; + this.label = `Using equidistant t values`; +} + +toggle() { + this.mode = (this.mode + 1) % 2; + if (sliders) this.setSliderValues(this.mode); + redraw(); +} + +draw() { + clear(); + setColor('lightgrey'); + drawGrid(10); + + setColor('black'); + setFontSize(16); + setTextStroke(`white`, 4); + if (points.length > 2) { + curve = this.fitCurve(points); + curve.drawSkeleton(`blue`); + curve.drawCurve(); + + text(this.label, this.width/2, 20, CENTER); + } + + points.forEach(p => circle(p.x, p.y, 3)); +} + +fitCurve(points) { + let n = points.length; + let tvalues = sliders ? sliders.values : [...new Array(n)].map((_,i) =>i/(n-1)); + let bestFitData = fit(points, tvalues), + x = bestFitData.C.x, + y = bestFitData.C.y, + bpoints = x.map((r,i) => ( + {x: r[0], y: y[i][0]} + )); + return new Bezier(this, bpoints); +} + +updateSliders() { + if (sliders && points.length > 2) { + sliders.innerHTML = ``; + sliders.values = []; + this.sliders = points.map((p,i) => { + // TODO: this should probably be built into the graphics API as a + // things that you can do, e.g. clearSliders() and addSlider() + let s = document.createElement(`input`); + s.setAttribute(`type`, `range`); + s.setAttribute(`min`, `0`); + s.setAttribute(`max`, `1`); + s.setAttribute(`step`, `0.01`); + s.classList.add(`slide-control`); + sliders.values[i] = i/(points.length-1); + s.setAttribute(`value`, sliders.values[i]); + s.addEventListener(`input`, evt => { + this.label = `Using custom t values`; + sliders.values[i] = parseFloat(evt.target.value); + redraw(); + }); + sliders.append(s); + }); + } +} + +setSliderValues(mode) { + let n = points.length; + + // equidistant + if (mode === 0) { + this.label = `Using equidistant t values`; + sliders.values = [...new Array(n)].map((_,i) =>i/(n-1)); + } + + // polygonal distance + if (mode === 1) { + this.label = `Using polygonal distance t values`; + const D = [0]; + for(let i = 1; i { S[i] = v/len; }); + sliders.values = S; + } + + findAll(`.sliders input[type=range]`).forEach((s,i) => { + s.setAttribute(`value`, sliders.values[i]); + s.value = sliders.values[i]; + }); +} + +onMouseDown() { + if (!this.currentPoint) { + const {x, y} = this.cursor; + points.push({ x, y }); + resetMovable(points); + this.updateSliders(); + redraw(); + } +} diff --git a/docs/chapters/curvefitting/handler.js b/docs/chapters/curvefitting/handler.js deleted file mode 100644 index 62947ca2..00000000 --- a/docs/chapters/curvefitting/handler.js +++ /dev/null @@ -1,87 +0,0 @@ -var fit = require('../../../lib/curve-fitter.js'); - -module.exports = { - setup: function(api) { - this.api = api; - api.noDrag = true; // do not allow points to be dragged around - this.reset(); - }, - - reset: function() { - this.points = []; - this.sliders.setOptions([]); - this.curveset = false; - this.mode = 0; - if (this.api) { - let api = this.api; - api.setCurve(false); - api.reset(); - api.redraw(); - } - }, - - toggle: function() { - if (this.api) { - this.customTimeValues = false; - this.mode = (this.mode + 1) % fit.modes.length; - this.fitCurve(this.api); - this.api.redraw(); - } - }, - - draw: function(api, curve) { - api.setPanelCount(1); - api.reset(); - api.setColor('lightgrey'); - api.drawGrid(10,10); - - api.setColor('black'); - - if (!this.curveset && this.points.length > 2) { - curve = this.fitCurve(api); - } - - if (curve) { - api.drawCurve(curve); - api.drawSkeleton(curve); - } - - api.drawPoints(this.points); - - if (!this.customTimeValues) { - api.setFill(0); - api.text("using "+fit.modes[this.mode]+" t values", {x: 5, y: 10}); - } - }, - - processTimeUpdate(sliderid, timeValues) { - var api = this.api; - this.customTimeValues = true; - this.fitCurve(api, timeValues); - api.redraw(); - }, - - fitCurve(api, timeValues) { - let bestFitData = fit(this.points, timeValues || this.mode), - x = bestFitData.C.x, - y = bestFitData.C.y, - bpoints = []; - x.forEach((r,i) => { - bpoints.push({ - x: r[0], - y: y[i][0] - }); - }); - var curve = new api.Bezier(bpoints); - api.setCurve(curve); - this.curveset = true; - this.sliders.setOptions(bestFitData.S); - return curve; - }, - - onClick: function(evt, api) { - this.curveset = false; - this.points.push({x: api.mx, y: api.my }); - api.redraw(); - } -}; diff --git a/docs/chapters/curvefitting/matrix-invert.js b/docs/chapters/curvefitting/matrix-invert.js new file mode 100644 index 00000000..819e1d86 --- /dev/null +++ b/docs/chapters/curvefitting/matrix-invert.js @@ -0,0 +1,110 @@ +// Copied from http://blog.acipo.com/matrix-inversion-in-javascript/ + +// Returns the inverse of matrix `M`. +export default function matrix_invert(M) { + // I use Guassian Elimination to calculate the inverse: + // (1) 'augment' the matrix (left) by the identity (on the right) + // (2) Turn the matrix on the left into the identity by elemetry row ops + // (3) The matrix on the right is the inverse (was the identity matrix) + // There are 3 elemtary row ops: (I combine b and c in my code) + // (a) Swap 2 rows + // (b) Multiply a row by a scalar + // (c) Add 2 rows + + //if the matrix isn't square: exit (error) + if (M.length !== M[0].length) { + console.log('not square'); + return; + } + + //create the identity matrix (I), and a copy (C) of the original + var i = 0, + ii = 0, + j = 0, + dim = M.length, + e = 0, + t = 0; + var I = [], + C = []; + for (i = 0; i < dim; i += 1) { + // Create the row + I[I.length] = []; + C[C.length] = []; + for (j = 0; j < dim; j += 1) { + //if we're on the diagonal, put a 1 (for identity) + if (i == j) { + I[i][j] = 1; + } else { + I[i][j] = 0; + } + + // Also, make the copy of the original + C[i][j] = M[i][j]; + } + } + + // Perform elementary row operations + for (i = 0; i < dim; i += 1) { + // get the element e on the diagonal + e = C[i][i]; + + // if we have a 0 on the diagonal (we'll need to swap with a lower row) + if (e == 0) { + //look through every row below the i'th row + for (ii = i + 1; ii < dim; ii += 1) { + //if the ii'th row has a non-0 in the i'th col + if (C[ii][i] != 0) { + //it would make the diagonal have a non-0 so swap it + for (j = 0; j < dim; j++) { + e = C[i][j]; //temp store i'th row + C[i][j] = C[ii][j]; //replace i'th row by ii'th + C[ii][j] = e; //repace ii'th by temp + e = I[i][j]; //temp store i'th row + I[i][j] = I[ii][j]; //replace i'th row by ii'th + I[ii][j] = e; //repace ii'th by temp + } + //don't bother checking other rows since we've swapped + break; + } + } + //get the new diagonal + e = C[i][i]; + //if it's still 0, not invertable (error) + if (e == 0) { + return; + } + } + + // Scale this row down by e (so we have a 1 on the diagonal) + for (j = 0; j < dim; j++) { + C[i][j] = C[i][j] / e; //apply to original matrix + I[i][j] = I[i][j] / e; //apply to identity + } + + // Subtract this row (scaled appropriately for each row) from ALL of + // the other rows so that there will be 0's in this column in the + // rows above and below this one + for (ii = 0; ii < dim; ii++) { + // Only apply to other rows (we want a 1 on the diagonal) + if (ii == i) { + continue; + } + + // We want to change this element to 0 + e = C[ii][i]; + + // Subtract (the row above(or below) scaled by e) from (the + // current row) but start at the i'th column and assume all the + // stuff left of diagonal is 0 (which it should be if we made this + // algorithm correctly) + for (j = 0; j < dim; j++) { + C[ii][j] -= e * C[i][j]; //apply to original matrix + I[ii][j] -= e * I[i][j]; //apply to identity + } + } + } + + //we've done all operations, C should be the identity + //matrix I should be the inverse: + return I; +}; \ No newline at end of file diff --git a/docs/images/chapters/circles/fe32474b4616ee9478e1308308f1b6bf.svg b/docs/images/chapters/circles/fe32474b4616ee9478e1308308f1b6bf.svg new file mode 100644 index 00000000..0a70cf4b --- /dev/null +++ b/docs/images/chapters/circles/fe32474b4616ee9478e1308308f1b6bf.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/docs/images/chapters/control/14cb9fbbaae9e7d87ae6bef3ea7a782e.svg b/docs/images/chapters/control/14cb9fbbaae9e7d87ae6bef3ea7a782e.svg new file mode 100644 index 00000000..7e17c4e5 --- /dev/null +++ b/docs/images/chapters/control/14cb9fbbaae9e7d87ae6bef3ea7a782e.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/docs/images/chapters/control/49423783987ac4bc49fbe4c519dbc1d1.png b/docs/images/chapters/control/49423783987ac4bc49fbe4c519dbc1d1.png index c6757884..aa6f0a67 100644 Binary files a/docs/images/chapters/control/49423783987ac4bc49fbe4c519dbc1d1.png and b/docs/images/chapters/control/49423783987ac4bc49fbe4c519dbc1d1.png differ diff --git a/docs/images/chapters/control/afd21a9ba16965c2e7ec2d0d14892250.png b/docs/images/chapters/control/afd21a9ba16965c2e7ec2d0d14892250.png index f49dedc5..bb0f9ac1 100644 Binary files a/docs/images/chapters/control/afd21a9ba16965c2e7ec2d0d14892250.png and b/docs/images/chapters/control/afd21a9ba16965c2e7ec2d0d14892250.png differ diff --git a/docs/images/chapters/control/ecc15848fbe7b2176b0c89973f07c694.png b/docs/images/chapters/control/ecc15848fbe7b2176b0c89973f07c694.png index a0511790..35cc064a 100644 Binary files a/docs/images/chapters/control/ecc15848fbe7b2176b0c89973f07c694.png and b/docs/images/chapters/control/ecc15848fbe7b2176b0c89973f07c694.png differ diff --git a/docs/images/chapters/curvefitting/03ec73258d5c95eed39a2ea8665e0b07.svg b/docs/images/chapters/curvefitting/03ec73258d5c95eed39a2ea8665e0b07.svg index 42932101..1eca1765 100644 --- a/docs/images/chapters/curvefitting/03ec73258d5c95eed39a2ea8665e0b07.svg +++ b/docs/images/chapters/curvefitting/03ec73258d5c95eed39a2ea8665e0b07.svg @@ -1 +1 @@ - \ No newline at end of file + \ No newline at end of file diff --git a/docs/images/chapters/curvefitting/08f4beaebf83dca594ad125bdca7e436.svg b/docs/images/chapters/curvefitting/08f4beaebf83dca594ad125bdca7e436.svg index e9658b08..ef635a3d 100644 --- a/docs/images/chapters/curvefitting/08f4beaebf83dca594ad125bdca7e436.svg +++ b/docs/images/chapters/curvefitting/08f4beaebf83dca594ad125bdca7e436.svg @@ -1 +1 @@ - \ No newline at end of file + \ No newline at end of file diff --git a/docs/images/chapters/curvefitting/283bc9e8fe59a78d3c74860f62a66ecb.svg b/docs/images/chapters/curvefitting/283bc9e8fe59a78d3c74860f62a66ecb.svg index a8172fcd..600081ad 100644 --- a/docs/images/chapters/curvefitting/283bc9e8fe59a78d3c74860f62a66ecb.svg +++ b/docs/images/chapters/curvefitting/283bc9e8fe59a78d3c74860f62a66ecb.svg @@ -1 +1 @@ - \ No newline at end of file + \ No newline at end of file diff --git a/docs/images/chapters/curvefitting/2b8334727d3b004c6e87263fec6b32b7.svg b/docs/images/chapters/curvefitting/2b8334727d3b004c6e87263fec6b32b7.svg index 9e2dfcf1..0067f321 100644 --- a/docs/images/chapters/curvefitting/2b8334727d3b004c6e87263fec6b32b7.svg +++ b/docs/images/chapters/curvefitting/2b8334727d3b004c6e87263fec6b32b7.svg @@ -1 +1 @@ - \ No newline at end of file + \ No newline at end of file diff --git a/docs/images/chapters/curvefitting/2bef3da3828d63d690460ce9947dbde2.svg b/docs/images/chapters/curvefitting/2bef3da3828d63d690460ce9947dbde2.svg index 14d83cad..d1e4cbe5 100644 --- a/docs/images/chapters/curvefitting/2bef3da3828d63d690460ce9947dbde2.svg +++ b/docs/images/chapters/curvefitting/2bef3da3828d63d690460ce9947dbde2.svg @@ -1 +1 @@ - \ No newline at end of file + \ No newline at end of file diff --git a/docs/images/chapters/curvefitting/2d42758fba3370f52191306752c2705c.svg b/docs/images/chapters/curvefitting/2d42758fba3370f52191306752c2705c.svg index 17881f45..d0a2d5c8 100644 --- a/docs/images/chapters/curvefitting/2d42758fba3370f52191306752c2705c.svg +++ b/docs/images/chapters/curvefitting/2d42758fba3370f52191306752c2705c.svg @@ -1 +1 @@ - \ No newline at end of file + \ No newline at end of file diff --git a/docs/images/chapters/curvefitting/4ffad56e281ee79d0688e93033429f0a.svg b/docs/images/chapters/curvefitting/4ffad56e281ee79d0688e93033429f0a.svg index 79cc7461..2717e29e 100644 --- a/docs/images/chapters/curvefitting/4ffad56e281ee79d0688e93033429f0a.svg +++ b/docs/images/chapters/curvefitting/4ffad56e281ee79d0688e93033429f0a.svg @@ -1 +1 @@ - \ No newline at end of file + \ No newline at end of file diff --git a/docs/images/chapters/curvefitting/5f7fcb86ae1c19612b9fe02e23229e31.svg b/docs/images/chapters/curvefitting/5f7fcb86ae1c19612b9fe02e23229e31.svg index bc0bf6c5..255d87f1 100644 --- a/docs/images/chapters/curvefitting/5f7fcb86ae1c19612b9fe02e23229e31.svg +++ b/docs/images/chapters/curvefitting/5f7fcb86ae1c19612b9fe02e23229e31.svg @@ -1 +1 @@ - \ No newline at end of file + \ No newline at end of file diff --git a/docs/images/chapters/curvefitting/6202d7bd150c852b432d807c40fb1647.svg b/docs/images/chapters/curvefitting/6202d7bd150c852b432d807c40fb1647.svg index 9da51301..510cb83d 100644 --- a/docs/images/chapters/curvefitting/6202d7bd150c852b432d807c40fb1647.svg +++ b/docs/images/chapters/curvefitting/6202d7bd150c852b432d807c40fb1647.svg @@ -1 +1 @@ - \ No newline at end of file + \ No newline at end of file diff --git a/docs/images/chapters/curvefitting/78b8ba1aba2e4c9ad3f7890299c90152.svg b/docs/images/chapters/curvefitting/78b8ba1aba2e4c9ad3f7890299c90152.svg index cccbc329..6895819c 100644 --- a/docs/images/chapters/curvefitting/78b8ba1aba2e4c9ad3f7890299c90152.svg +++ b/docs/images/chapters/curvefitting/78b8ba1aba2e4c9ad3f7890299c90152.svg @@ -1 +1 @@ - \ No newline at end of file + \ No newline at end of file diff --git a/docs/images/chapters/curvefitting/7e5d59272621baf942bc722208ce70c2.svg b/docs/images/chapters/curvefitting/7e5d59272621baf942bc722208ce70c2.svg index 170d27e1..24a48dd5 100644 --- a/docs/images/chapters/curvefitting/7e5d59272621baf942bc722208ce70c2.svg +++ b/docs/images/chapters/curvefitting/7e5d59272621baf942bc722208ce70c2.svg @@ -1 +1 @@ - \ No newline at end of file + \ No newline at end of file diff --git a/docs/images/chapters/curvefitting/7eada6f12045423de24d9a2ab8e293b1.svg b/docs/images/chapters/curvefitting/7eada6f12045423de24d9a2ab8e293b1.svg index 25f02428..e0c1ceec 100644 --- a/docs/images/chapters/curvefitting/7eada6f12045423de24d9a2ab8e293b1.svg +++ b/docs/images/chapters/curvefitting/7eada6f12045423de24d9a2ab8e293b1.svg @@ -1 +1 @@ - \ No newline at end of file + \ No newline at end of file diff --git a/docs/images/chapters/curvefitting/875ca8eea72e727ccb881b4c0b6a3224.svg b/docs/images/chapters/curvefitting/875ca8eea72e727ccb881b4c0b6a3224.svg index a02129e9..ab5b0a03 100644 --- a/docs/images/chapters/curvefitting/875ca8eea72e727ccb881b4c0b6a3224.svg +++ b/docs/images/chapters/curvefitting/875ca8eea72e727ccb881b4c0b6a3224.svg @@ -1 +1 @@ - \ No newline at end of file + \ No newline at end of file diff --git a/docs/images/chapters/curvefitting/8d09f2be2c6db79ee966f170ffc25815.svg b/docs/images/chapters/curvefitting/8d09f2be2c6db79ee966f170ffc25815.svg index 1c31f02e..21b32468 100644 --- a/docs/images/chapters/curvefitting/8d09f2be2c6db79ee966f170ffc25815.svg +++ b/docs/images/chapters/curvefitting/8d09f2be2c6db79ee966f170ffc25815.svg @@ -1 +1 @@ - \ No newline at end of file + \ No newline at end of file diff --git a/docs/images/chapters/curvefitting/9151c0fdf9689ee598a2d029ab2ffe34.svg b/docs/images/chapters/curvefitting/9151c0fdf9689ee598a2d029ab2ffe34.svg index def94e94..dd636864 100644 --- a/docs/images/chapters/curvefitting/9151c0fdf9689ee598a2d029ab2ffe34.svg +++ b/docs/images/chapters/curvefitting/9151c0fdf9689ee598a2d029ab2ffe34.svg @@ -1 +1 @@ - \ No newline at end of file + \ No newline at end of file diff --git a/docs/images/chapters/curvefitting/94acb5850778dcb16c2ba3cfa676f537.svg b/docs/images/chapters/curvefitting/94acb5850778dcb16c2ba3cfa676f537.svg index 90d4c93e..06f1c69c 100644 --- a/docs/images/chapters/curvefitting/94acb5850778dcb16c2ba3cfa676f537.svg +++ b/docs/images/chapters/curvefitting/94acb5850778dcb16c2ba3cfa676f537.svg @@ -1 +1 @@ - \ No newline at end of file + \ No newline at end of file diff --git a/docs/images/chapters/curvefitting/ab334858d3fa309cc1a5ba535a2ca168.svg b/docs/images/chapters/curvefitting/ab334858d3fa309cc1a5ba535a2ca168.svg index 4d82266c..c160e8af 100644 --- a/docs/images/chapters/curvefitting/ab334858d3fa309cc1a5ba535a2ca168.svg +++ b/docs/images/chapters/curvefitting/ab334858d3fa309cc1a5ba535a2ca168.svg @@ -1 +1 @@ - \ No newline at end of file + \ No newline at end of file diff --git a/docs/images/chapters/curvefitting/bd8e8e294eec10d2bf6ef857c7c0c2c2.svg b/docs/images/chapters/curvefitting/bd8e8e294eec10d2bf6ef857c7c0c2c2.svg index 0cd86b17..202dc477 100644 --- a/docs/images/chapters/curvefitting/bd8e8e294eec10d2bf6ef857c7c0c2c2.svg +++ b/docs/images/chapters/curvefitting/bd8e8e294eec10d2bf6ef857c7c0c2c2.svg @@ -1 +1 @@ - \ No newline at end of file + \ No newline at end of file diff --git a/docs/images/chapters/curvefitting/c2c92587a184efa6c4fee45e4a3e32ed.png b/docs/images/chapters/curvefitting/c2c92587a184efa6c4fee45e4a3e32ed.png new file mode 100644 index 00000000..7cf3f918 Binary files /dev/null and b/docs/images/chapters/curvefitting/c2c92587a184efa6c4fee45e4a3e32ed.png differ diff --git a/docs/images/chapters/curvefitting/d84d1c71a3ce1918f53eaf8f9fe98ac4.svg b/docs/images/chapters/curvefitting/d84d1c71a3ce1918f53eaf8f9fe98ac4.svg index 047757ec..3f29b46c 100644 --- a/docs/images/chapters/curvefitting/d84d1c71a3ce1918f53eaf8f9fe98ac4.svg +++ b/docs/images/chapters/curvefitting/d84d1c71a3ce1918f53eaf8f9fe98ac4.svg @@ -1 +1 @@ - \ No newline at end of file + \ No newline at end of file diff --git a/docs/images/chapters/matrixsplit/77a11d65d7cffc4b84a85c4bec837792.svg b/docs/images/chapters/matrixsplit/77a11d65d7cffc4b84a85c4bec837792.svg new file mode 100644 index 00000000..36cae683 --- /dev/null +++ b/docs/images/chapters/matrixsplit/77a11d65d7cffc4b84a85c4bec837792.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/docs/index.html b/docs/index.html index 2a6b7ba4..56f8d640 100644 --- a/docs/index.html +++ b/docs/index.html @@ -353,7 +353,7 @@ function Bezier(3,t):

Also shown is the interpolation function for a 15th order Bézier function. As you can see, the start and end point contribute considerably more to the curve's shape than any other point in the control point set.

If we want to change the curve, we need to change the weights of each point, effectively changing the interpolations. The way to do this is about as straightforward as possible: just multiply each point with a value that changes its strength. These values are conventionally called "weights", and we can add them to our original Bézier function:

- +

That looks complicated, but as it so happens, the "weights" are actually just the coordinate values we want our curve to have: for an nth order curve, w0 is our start coordinate, wn is our last coordinate, and everything in between is a controlling coordinate. Say we want a cubic curve that starts at (110,150), is controlled by (25,190) and (210,250) and ends at (210,30), we use this Bézier curve:

Which gives us the curve we saw at the top of the article:

@@ -637,7 +637,7 @@ function drawCurve(points[], t):

Splitting curves using matrices

Another way to split curves is to exploit the matrix representation of a Bézier curve. In the section on matrices, we saw that we can represent curves as matrix multiplications. Specifically, we saw these two forms for the quadratic and cubic curves respectively: (we'll reverse the Bézier coefficients vector for legibility)

- +

and

Let's say we want to split the curve at some point t = z, forming two new (obviously smaller) Bézier curves. To find the coordinates for these two Bézier curves, we can use the matrix representation and some linear algebra. First, we separate out the actual "point on the curve" information into a new matrix multiplication:

@@ -1725,25 +1725,25 @@ for (coordinate, index) in LUT:

Revisiting the matrix representation

Rewriting Bézier functions to matrix form is fairly easy, if you first expand the function, and then arrange them into a multiple line form, where each line corresponds to a power of t, and each column is for a specific coefficient. First, we expand the function:

- +

And then we (trivially) rearrange the terms across multiple lines:

- +

This rearrangement has "factors of t" at each row (the first row is t⁰, i.e. "1", the second row is t¹, i.e. "t", the third row is t²) and "coefficient" at each column (the first column is all terms involving "a", the second all terms involving "b", the third all terms involving "c").

With that arrangement, we can easily decompose this as a matrix multiplication:

- +

We can do the same for the cubic curve, of course. We know the base function for cubics:

- +

So we write out the expansion and rearrange:

- +

Which we can then decompose:

- +

And, of course, we can do this for quartic curves too (skipping the expansion step):

- +

And so and on so on. Now, let's see how to use these T, M, and C, to do some curve fitting.

Let's get started: we're going to assume we picked the right order curve: for n points we're fitting an n-1th order curve, so we "start" with a vector P that represents the coordinates we already know, and for which we want to do curve fitting:

- +

Next, we need to figure out appropriate t values for each point in the curve, because we need something that lets us tie "the actual coordinate" to "some point on the curve". There's a fair number of different ways to do this (and a large part of optimizing "the perfect fit" is about picking appropriate t values), but in this case let's look at two "obvious" choices:

  1. equally spaced t values, and
  2. @@ -1752,27 +1752,27 @@ for (coordinate, index) in LUT:

    The first one is really simple: if we have n points, then we'll just assign each point i a t value of (i-1)/(n-1). So if we have four points, the first point will have t=(1-1)/(4-1)=0/3, the second point will have t=(2-1)/(4-1)=1/3, the third point will have t=2/3, and the last point will be t=1. We're just straight up spacing the t values to match the number of points we have.

    The second one is a little more interesting: since we're doing polynomial regression, we might as well exploit the fact that our base coordinates just constitute a collection of line segments. At the first point, we're fixing t=0, and the last point, we want t=1, and anywhere in between we're simply going to say that t is equal to the distance along the polygon, scaled to the [0,1] domain.

    To get these values, we first compute the general "distance along the polygon" matrix:

    - +

    Where length() is literally just that: the length of the line segment between the point we're looking at, and the previous point. This isn't quite enough, of course: we still need to make sure that all the values between i=1 and i=n fall in the [0,1] interval, so we need to scale all values down by whatever the total length of the polygon is:

    - +

    And now we can move on to the actual "curve fitting" part: what we want is a function that lets us compute "ideal" control point values such that if we build a Bézier curve with them, that curve passes through all our original points. Or, failing that, have an overall error distance that is as close to zero as we can get it. So, let's write out what the error distance looks like.

    As mentioned before, this function is really just "the distance between the actual coordinate, and the coordinate that the curve evaluates to for the associated t value", which we'll square to get rid of any pesky negative signs:

    - +

    Since this function only deals with individual coordinates, we'll need to sum over all coordinates in order to get the full error function. So, we literally just do that; the total error function is simply the sum of all these individual errors:

    - +

    And here's the trick that justifies using matrices: while we can work with individual values using calculus, with matrices we can compute as many values as we make our matrices big, all at the "same time", We can replace the individual terms pi with the full P coordinate matrix, and we can replace Bézier(si) with the matrix representation T x M x C we talked about before, which gives us:

    - +

    In which we can replace the rather cumbersome "squaring" operation with a more conventional matrix equivalent:

    - +

    Here, the letter T is used instead of the number 2, to represent the matrix transpose; each row in the original matrix becomes a column in the transposed matrix instead (row one becomes column one, row two becomes column two, and so on).

    This leaves one problem: T isn't actually the matrix we want: we don't want symbolic t values, we want the actual numerical values that we computed for S, so we need to form a new matrix, which we'll call 𝕋, that makes use of those, and then use that 𝕋 instead of T in our error function:

    - +

    Which, because of the first and last values in S, means:

    - +

    Now we can properly write out the error function as matrix operations:

    - +

    So, we have our error function: we now need to figure out the expression for where that function has minimal value, e.g. where the error between the true coordinates and the coordinates generated by the curve fitting is smallest. Like in standard calculus, this requires taking the derivative, and determining where that derivative is zero:

    - +

    Where did this derivative come from?

    @@ -1782,18 +1782,20 @@ for (coordinate, index) in LUT:

    Now, given the above derivative, we can rearrange the terms (following the rules of matrix algebra) so that we end up with an expression for C:

    - +

    Here, the "to the power negative one" is the notation for the matrix inverse. But that's all we have to do: we're done. Starting with P and inventing some t values based on the polygon the coordinates in P define, we can compute the corresponding Bézier coordinates C that specify a curve that goes through our points. Or, if it can't go through them exactly, as near as possible.

    So before we try that out, how much code is involved in implementing this? Honestly, that answer depends on how much you're going to be writing yourself. If you already have a matrix maths library available, then really not that much code at all. On the other hand, if you are writing this from scratch, you're going to have to write some utility functions for doing your matrix work for you, so it's really anywhere from 50 lines of code to maybe 200 lines of code. Not a bad price to pay for being able to fit curves to prespecified coordinates.

    -

    So let's try it out! The following graphic lets you place points, and will start computing exact-fit curves once you've placed at least three. You can click for more points, and the code will simply try to compute an exact fit using a Bézier curve of the appropriate order. Four points? Cubic Bézier. Five points? Quartic. And so on. Of course, this does break down at some point: depending on where you place your points, it might become mighty hard for the fitter to find an exact fit, and things might actually start looking horribly off once you hit 10th or higher order curves. But it might not!

    -
    - - - (this.sliders=set) } onChange={this.processTimeUpdate} /> - -
    +

    So let's try it out! The following graphic lets you place points, and will start computing exact-fit curves once you've placed at least three. You can click for more points, and the code will simply try to compute an exact fit using a Bézier curve of the appropriate order. Four points? Cubic Bézier. Five points? Quartic. And so on. Of course, this does break down at some point: depending on where you place your points, it might become mighty hard for the fitter to find an exact fit, and things might actually start looking horribly off once there's enough points for compound floating point rounding errors to start making a difference (which is around 10~11 points).

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

    You'll note there is a convenient "toggle" buttons that lets you toggle between equidistance t values, and distance ratio along the polygon. Arguably more interesting is that once you have points to abstract a curve, you also get direct control over the time values through sliders for each, because if the time values are our degree of freedom, you should be able to freely manipulate them and see what the effect on your curve is.

    +

    You'll note there is a convenient "toggle" buttons that lets you toggle between equidistant t values, and distance ratio along the polygon formed by the points. Arguably more interesting is that once you have points to abstract a curve, you also get direct control over the time values through sliders for each, because if the time values are our degree of freedom, you should be able to freely manipulate them and see what the effect on your curve is.

@@ -2042,7 +2044,7 @@ for (coordinate, index) in LUT:

which we can then substitute in the expression for a:

A quick check shows that plugging these values for a and b into the expressions for Cx and Cy give the same x/y coordinates for both "a away from A" and "b away from B", so let's continue: now that we know the coordinate values for C, we know where our on-curve point T for t=0.5 (or angle φ/2) is, because we can just evaluate the Bézier polynomial, and we know where the circle arc's actual point P is for angle φ/2:

- +

We compute T, observing that if t=0.5, the polynomial values (1-t)², 2(1-t)t, and t² are 0.25, 0.5, and 0.25 respectively:

Which, worked out for the x and y components, gives:

diff --git a/docs/ja-JP/index.html b/docs/ja-JP/index.html index 073a3792..1d95fdf8 100644 --- a/docs/ja-JP/index.html +++ b/docs/ja-JP/index.html @@ -634,7 +634,7 @@ function drawCurve(points[], t):

行列による曲線の分割

曲線分割には、ベジエ曲線の行列表現を利用する方法もあります。行列についての節では、行列の乗算で曲線が表現できることを確認しました。特に2次・3次のベジエ曲線に関しては、それぞれ以下のような形になりました(読みやすさのため、ベジエの係数ベクトルを反転させています)。

- +

ならびに

曲線をある点t = zで分割し、新しく2つの(自明ですが、より短い)ベジエ曲線を作ることを考えましょう。曲線の行列表現と線形代数を利用すると、この2つのベジエ曲線の座標を求めることができます。まず、実際の「曲線上の点」の情報を分解し、新しい行列の積のかたちにします。

@@ -1722,25 +1722,25 @@ for (coordinate, index) in LUT:

Revisiting the matrix representation

Rewriting Bézier functions to matrix form is fairly easy, if you first expand the function, and then arrange them into a multiple line form, where each line corresponds to a power of t, and each column is for a specific coefficient. First, we expand the function:

- +

And then we (trivially) rearrange the terms across multiple lines:

- +

This rearrangement has "factors of t" at each row (the first row is t⁰, i.e. "1", the second row is t¹, i.e. "t", the third row is t²) and "coefficient" at each column (the first column is all terms involving "a", the second all terms involving "b", the third all terms involving "c").

With that arrangement, we can easily decompose this as a matrix multiplication:

- +

We can do the same for the cubic curve, of course. We know the base function for cubics:

- +

So we write out the expansion and rearrange:

- +

Which we can then decompose:

- +

And, of course, we can do this for quartic curves too (skipping the expansion step):

- +

And so and on so on. Now, let's see how to use these T, M, and C, to do some curve fitting.

Let's get started: we're going to assume we picked the right order curve: for n points we're fitting an n-1th order curve, so we "start" with a vector P that represents the coordinates we already know, and for which we want to do curve fitting:

- +

Next, we need to figure out appropriate t values for each point in the curve, because we need something that lets us tie "the actual coordinate" to "some point on the curve". There's a fair number of different ways to do this (and a large part of optimizing "the perfect fit" is about picking appropriate t values), but in this case let's look at two "obvious" choices:

  1. equally spaced t values, and
  2. @@ -1749,27 +1749,27 @@ for (coordinate, index) in LUT:

    The first one is really simple: if we have n points, then we'll just assign each point i a t value of (i-1)/(n-1). So if we have four points, the first point will have t=(1-1)/(4-1)=0/3, the second point will have t=(2-1)/(4-1)=1/3, the third point will have t=2/3, and the last point will be t=1. We're just straight up spacing the t values to match the number of points we have.

    The second one is a little more interesting: since we're doing polynomial regression, we might as well exploit the fact that our base coordinates just constitute a collection of line segments. At the first point, we're fixing t=0, and the last point, we want t=1, and anywhere in between we're simply going to say that t is equal to the distance along the polygon, scaled to the [0,1] domain.

    To get these values, we first compute the general "distance along the polygon" matrix:

    - +

    Where length() is literally just that: the length of the line segment between the point we're looking at, and the previous point. This isn't quite enough, of course: we still need to make sure that all the values between i=1 and i=n fall in the [0,1] interval, so we need to scale all values down by whatever the total length of the polygon is:

    - +

    And now we can move on to the actual "curve fitting" part: what we want is a function that lets us compute "ideal" control point values such that if we build a Bézier curve with them, that curve passes through all our original points. Or, failing that, have an overall error distance that is as close to zero as we can get it. So, let's write out what the error distance looks like.

    As mentioned before, this function is really just "the distance between the actual coordinate, and the coordinate that the curve evaluates to for the associated t value", which we'll square to get rid of any pesky negative signs:

    - +

    Since this function only deals with individual coordinates, we'll need to sum over all coordinates in order to get the full error function. So, we literally just do that; the total error function is simply the sum of all these individual errors:

    - +

    And here's the trick that justifies using matrices: while we can work with individual values using calculus, with matrices we can compute as many values as we make our matrices big, all at the "same time", We can replace the individual terms pi with the full P coordinate matrix, and we can replace Bézier(si) with the matrix representation T x M x C we talked about before, which gives us:

    - +

    In which we can replace the rather cumbersome "squaring" operation with a more conventional matrix equivalent:

    - +

    Here, the letter T is used instead of the number 2, to represent the matrix transpose; each row in the original matrix becomes a column in the transposed matrix instead (row one becomes column one, row two becomes column two, and so on).

    This leaves one problem: T isn't actually the matrix we want: we don't want symbolic t values, we want the actual numerical values that we computed for S, so we need to form a new matrix, which we'll call 𝕋, that makes use of those, and then use that 𝕋 instead of T in our error function:

    - +

    Which, because of the first and last values in S, means:

    - +

    Now we can properly write out the error function as matrix operations:

    - +

    So, we have our error function: we now need to figure out the expression for where that function has minimal value, e.g. where the error between the true coordinates and the coordinates generated by the curve fitting is smallest. Like in standard calculus, this requires taking the derivative, and determining where that derivative is zero:

    - +

    Where did this derivative come from?

    @@ -1779,18 +1779,20 @@ for (coordinate, index) in LUT:

    Now, given the above derivative, we can rearrange the terms (following the rules of matrix algebra) so that we end up with an expression for C:

    - +

    Here, the "to the power negative one" is the notation for the matrix inverse. But that's all we have to do: we're done. Starting with P and inventing some t values based on the polygon the coordinates in P define, we can compute the corresponding Bézier coordinates C that specify a curve that goes through our points. Or, if it can't go through them exactly, as near as possible.

    So before we try that out, how much code is involved in implementing this? Honestly, that answer depends on how much you're going to be writing yourself. If you already have a matrix maths library available, then really not that much code at all. On the other hand, if you are writing this from scratch, you're going to have to write some utility functions for doing your matrix work for you, so it's really anywhere from 50 lines of code to maybe 200 lines of code. Not a bad price to pay for being able to fit curves to prespecified coordinates.

    -

    So let's try it out! The following graphic lets you place points, and will start computing exact-fit curves once you've placed at least three. You can click for more points, and the code will simply try to compute an exact fit using a Bézier curve of the appropriate order. Four points? Cubic Bézier. Five points? Quartic. And so on. Of course, this does break down at some point: depending on where you place your points, it might become mighty hard for the fitter to find an exact fit, and things might actually start looking horribly off once you hit 10th or higher order curves. But it might not!

    -
    - - - (this.sliders=set) } onChange={this.processTimeUpdate} /> - -
    +

    So let's try it out! The following graphic lets you place points, and will start computing exact-fit curves once you've placed at least three. You can click for more points, and the code will simply try to compute an exact fit using a Bézier curve of the appropriate order. Four points? Cubic Bézier. Five points? Quartic. And so on. Of course, this does break down at some point: depending on where you place your points, it might become mighty hard for the fitter to find an exact fit, and things might actually start looking horribly off once there's enough points for compound floating point rounding errors to start making a difference (which is around 10~11 points).

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

    You'll note there is a convenient "toggle" buttons that lets you toggle between equidistance t values, and distance ratio along the polygon. Arguably more interesting is that once you have points to abstract a curve, you also get direct control over the time values through sliders for each, because if the time values are our degree of freedom, you should be able to freely manipulate them and see what the effect on your curve is.

    +

    You'll note there is a convenient "toggle" buttons that lets you toggle between equidistant t values, and distance ratio along the polygon formed by the points. Arguably more interesting is that once you have points to abstract a curve, you also get direct control over the time values through sliders for each, because if the time values are our degree of freedom, you should be able to freely manipulate them and see what the effect on your curve is.

@@ -2039,7 +2041,7 @@ for (coordinate, index) in LUT:

which we can then substitute in the expression for a:

A quick check shows that plugging these values for a and b into the expressions for Cx and Cy give the same x/y coordinates for both "a away from A" and "b away from B", so let's continue: now that we know the coordinate values for C, we know where our on-curve point T for t=0.5 (or angle φ/2) is, because we can just evaluate the Bézier polynomial, and we know where the circle arc's actual point P is for angle φ/2:

- +

We compute T, observing that if t=0.5, the polynomial values (1-t)², 2(1-t)t, and t² are 0.25, 0.5, and 0.25 respectively:

Which, worked out for the x and y components, gives:

diff --git a/docs/js/custom-element/api/graphics-api.js b/docs/js/custom-element/api/graphics-api.js index a2ab9261..2e9e1298 100644 --- a/docs/js/custom-element/api/graphics-api.js +++ b/docs/js/custom-element/api/graphics-api.js @@ -633,11 +633,12 @@ class GraphicsAPI extends BaseAPI { * convenient grid drawing function */ drawGrid(division = 20) { - for (let x = (division / 2) | 0; x < this.width; x += division) { - this.line({ x, y: 0 }, { x, y: this.height }); + let w = this.panelWidth ?? this.width; + for (let x = (division / 2) | 0; x < w; x += division) { + this.line(x, 0, x, this.height); } for (let y = (division / 2) | 0; y < this.height; y += division) { - this.line({ x: 0, y }, { x: this.width, y }); + this.line(0, y, w, y); } } diff --git a/docs/placeholder-style.css b/docs/placeholder-style.css index 6a457e42..4c73a97b 100644 --- a/docs/placeholder-style.css +++ b/docs/placeholder-style.css @@ -143,5 +143,6 @@ p code { } .slide-control { + display: block; width: 100%; -} \ No newline at end of file +} diff --git a/docs/zh-CN/index.html b/docs/zh-CN/index.html index 7c5bc62a..c7c20560 100644 --- a/docs/zh-CN/index.html +++ b/docs/zh-CN/index.html @@ -349,7 +349,7 @@ function Bezier(3,t):

上面有一张是15th阶的插值方程。如你所见,在所有控制点中,起点和终点对曲线形状的贡献比其他点更大些。

如果我们要改变曲线,就需要改变每个点的权重,有效地改变插值。可以很直接地做到这个:只要用一个值乘以每个点,来改变它的强度。这个值照惯例称为“权重”,我们可以将它加入我们原始的贝塞尔函数:

- +

看起来很复杂,但实际上“权重”只是我们想让曲线所拥有的坐标值:对于一条nth阶曲线,w0是起始坐标,wn是终点坐标,中间的所有点都是控制点坐标。假设说一条曲线的起点为(120,160),终点为(220,40),并受点(35,200)和点(220,260)的控制,贝塞尔曲线方程就为:

这就是我们在文章开头看到的曲线:

@@ -628,7 +628,7 @@ function drawCurve(points[], t):

Splitting curves using matrices

Another way to split curves is to exploit the matrix representation of a Bézier curve. In the section on matrices, we saw that we can represent curves as matrix multiplications. Specifically, we saw these two forms for the quadratic and cubic curves respectively: (we'll reverse the Bézier coefficients vector for legibility)

- +

and

Let's say we want to split the curve at some point t = z, forming two new (obviously smaller) Bézier curves. To find the coordinates for these two Bézier curves, we can use the matrix representation and some linear algebra. First, we separate out the actual "point on the curve" information into a new matrix multiplication:

@@ -1716,25 +1716,25 @@ for (coordinate, index) in LUT:

Revisiting the matrix representation

Rewriting Bézier functions to matrix form is fairly easy, if you first expand the function, and then arrange them into a multiple line form, where each line corresponds to a power of t, and each column is for a specific coefficient. First, we expand the function:

- +

And then we (trivially) rearrange the terms across multiple lines:

- +

This rearrangement has "factors of t" at each row (the first row is t⁰, i.e. "1", the second row is t¹, i.e. "t", the third row is t²) and "coefficient" at each column (the first column is all terms involving "a", the second all terms involving "b", the third all terms involving "c").

With that arrangement, we can easily decompose this as a matrix multiplication:

- +

We can do the same for the cubic curve, of course. We know the base function for cubics:

- +

So we write out the expansion and rearrange:

- +

Which we can then decompose:

- +

And, of course, we can do this for quartic curves too (skipping the expansion step):

- +

And so and on so on. Now, let's see how to use these T, M, and C, to do some curve fitting.

Let's get started: we're going to assume we picked the right order curve: for n points we're fitting an n-1th order curve, so we "start" with a vector P that represents the coordinates we already know, and for which we want to do curve fitting:

- +

Next, we need to figure out appropriate t values for each point in the curve, because we need something that lets us tie "the actual coordinate" to "some point on the curve". There's a fair number of different ways to do this (and a large part of optimizing "the perfect fit" is about picking appropriate t values), but in this case let's look at two "obvious" choices:

  1. equally spaced t values, and
  2. @@ -1743,27 +1743,27 @@ for (coordinate, index) in LUT:

    The first one is really simple: if we have n points, then we'll just assign each point i a t value of (i-1)/(n-1). So if we have four points, the first point will have t=(1-1)/(4-1)=0/3, the second point will have t=(2-1)/(4-1)=1/3, the third point will have t=2/3, and the last point will be t=1. We're just straight up spacing the t values to match the number of points we have.

    The second one is a little more interesting: since we're doing polynomial regression, we might as well exploit the fact that our base coordinates just constitute a collection of line segments. At the first point, we're fixing t=0, and the last point, we want t=1, and anywhere in between we're simply going to say that t is equal to the distance along the polygon, scaled to the [0,1] domain.

    To get these values, we first compute the general "distance along the polygon" matrix:

    - +

    Where length() is literally just that: the length of the line segment between the point we're looking at, and the previous point. This isn't quite enough, of course: we still need to make sure that all the values between i=1 and i=n fall in the [0,1] interval, so we need to scale all values down by whatever the total length of the polygon is:

    - +

    And now we can move on to the actual "curve fitting" part: what we want is a function that lets us compute "ideal" control point values such that if we build a Bézier curve with them, that curve passes through all our original points. Or, failing that, have an overall error distance that is as close to zero as we can get it. So, let's write out what the error distance looks like.

    As mentioned before, this function is really just "the distance between the actual coordinate, and the coordinate that the curve evaluates to for the associated t value", which we'll square to get rid of any pesky negative signs:

    - +

    Since this function only deals with individual coordinates, we'll need to sum over all coordinates in order to get the full error function. So, we literally just do that; the total error function is simply the sum of all these individual errors:

    - +

    And here's the trick that justifies using matrices: while we can work with individual values using calculus, with matrices we can compute as many values as we make our matrices big, all at the "same time", We can replace the individual terms pi with the full P coordinate matrix, and we can replace Bézier(si) with the matrix representation T x M x C we talked about before, which gives us:

    - +

    In which we can replace the rather cumbersome "squaring" operation with a more conventional matrix equivalent:

    - +

    Here, the letter T is used instead of the number 2, to represent the matrix transpose; each row in the original matrix becomes a column in the transposed matrix instead (row one becomes column one, row two becomes column two, and so on).

    This leaves one problem: T isn't actually the matrix we want: we don't want symbolic t values, we want the actual numerical values that we computed for S, so we need to form a new matrix, which we'll call 𝕋, that makes use of those, and then use that 𝕋 instead of T in our error function:

    - +

    Which, because of the first and last values in S, means:

    - +

    Now we can properly write out the error function as matrix operations:

    - +

    So, we have our error function: we now need to figure out the expression for where that function has minimal value, e.g. where the error between the true coordinates and the coordinates generated by the curve fitting is smallest. Like in standard calculus, this requires taking the derivative, and determining where that derivative is zero:

    - +

    Where did this derivative come from?

    @@ -1773,18 +1773,20 @@ for (coordinate, index) in LUT:

    Now, given the above derivative, we can rearrange the terms (following the rules of matrix algebra) so that we end up with an expression for C:

    - +

    Here, the "to the power negative one" is the notation for the matrix inverse. But that's all we have to do: we're done. Starting with P and inventing some t values based on the polygon the coordinates in P define, we can compute the corresponding Bézier coordinates C that specify a curve that goes through our points. Or, if it can't go through them exactly, as near as possible.

    So before we try that out, how much code is involved in implementing this? Honestly, that answer depends on how much you're going to be writing yourself. If you already have a matrix maths library available, then really not that much code at all. On the other hand, if you are writing this from scratch, you're going to have to write some utility functions for doing your matrix work for you, so it's really anywhere from 50 lines of code to maybe 200 lines of code. Not a bad price to pay for being able to fit curves to prespecified coordinates.

    -

    So let's try it out! The following graphic lets you place points, and will start computing exact-fit curves once you've placed at least three. You can click for more points, and the code will simply try to compute an exact fit using a Bézier curve of the appropriate order. Four points? Cubic Bézier. Five points? Quartic. And so on. Of course, this does break down at some point: depending on where you place your points, it might become mighty hard for the fitter to find an exact fit, and things might actually start looking horribly off once you hit 10th or higher order curves. But it might not!

    -
    - - - (this.sliders=set) } onChange={this.processTimeUpdate} /> - -
    +

    So let's try it out! The following graphic lets you place points, and will start computing exact-fit curves once you've placed at least three. You can click for more points, and the code will simply try to compute an exact fit using a Bézier curve of the appropriate order. Four points? Cubic Bézier. Five points? Quartic. And so on. Of course, this does break down at some point: depending on where you place your points, it might become mighty hard for the fitter to find an exact fit, and things might actually start looking horribly off once there's enough points for compound floating point rounding errors to start making a difference (which is around 10~11 points).

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

    You'll note there is a convenient "toggle" buttons that lets you toggle between equidistance t values, and distance ratio along the polygon. Arguably more interesting is that once you have points to abstract a curve, you also get direct control over the time values through sliders for each, because if the time values are our degree of freedom, you should be able to freely manipulate them and see what the effect on your curve is.

    +

    You'll note there is a convenient "toggle" buttons that lets you toggle between equidistant t values, and distance ratio along the polygon formed by the points. Arguably more interesting is that once you have points to abstract a curve, you also get direct control over the time values through sliders for each, because if the time values are our degree of freedom, you should be able to freely manipulate them and see what the effect on your curve is.

@@ -2033,7 +2035,7 @@ for (coordinate, index) in LUT:

which we can then substitute in the expression for a:

A quick check shows that plugging these values for a and b into the expressions for Cx and Cy give the same x/y coordinates for both "a away from A" and "b away from B", so let's continue: now that we know the coordinate values for C, we know where our on-curve point T for t=0.5 (or angle φ/2) is, because we can just evaluate the Bézier polynomial, and we know where the circle arc's actual point P is for angle φ/2:

- +

We compute T, observing that if t=0.5, the polynomial values (1-t)², 2(1-t)t, and t² are 0.25, 0.5, and 0.25 respectively:

Which, worked out for the x and y components, gives: