diff --git a/article.js b/article.js index b1c5451c..192abd8e 100644 --- a/article.js +++ b/article.js @@ -67,4 +67,4 @@ href:"http://pomax.github.io/gh-weblog/downloads/canonical-curve.nb"},"here's"), var t=e.getDefaultQuadratic();t.points[0].y-=10,e.setCurve(t)},setupCubic:function(e){var t=e.getDefaultCubic();t.points[2].y-=20,e.setCurve(t),e.lut=t.getLUT(100)},draw:function(e,t){e.reset(),e.drawSkeleton(t),e.drawCurve(t);var n=e.getPanelHeight();if(e.setColor("black"),e.t){e.drawCircle(e.curve.get(e.t),3),e.setColor("lightgrey");var r,i,a,o=e.drawHull(t,e.t),s=e.utils;6===o.length?(r=t.points[1],i=o[5],a=s.lli4(r,i,t.points[0],t.points[2]),e.setColor("lightgrey"),e.drawLine(t.points[0],t.points[2])):10===o.length&&(r=o[5],i=o[9],a=s.lli4(r,i,t.points[0],t.points[3]),e.setColor("lightgrey"),e.drawLine(t.points[0],t.points[3])),e.setColor("#00FF00"),e.drawLine(r,i),e.setColor("red"),e.drawLine(i,a),e.setColor("black"),e.drawCircle(a,3),e.setFill("black"),e.text("A",{x:10+r.x,y:r.y}),e.text("B (t = "+e.utils.round(e.t,2)+")",{x:10+i.x,y:i.y}),e.text("C",{x:10+a.x,y:a.y});var l=s.dist(r,i),u=s.dist(i,a),c=l/u;e.text("d1 (A-B): "+s.round(l,2)+", d2 (B-C): "+s.round(u,2)+", ratio (d1/d2): "+s.round(c,4),{x:10,y:n-7})}},setCT:function(e,t){t.t=e.offsetX/t.getPanelWidth()},drawCTgraph:function(e){e.reset(),e.setColor("black");var t=e.getPanelWidth(),n=20,r=t-2*n;e.drawAxes(n,"t",0,1,"u",0,1),e.setColor("blue");var i=function(t){var i=e.u(t),a={x:n+t*r,y:n+i*r};return a};if(e.drawFunction(i),e.t){var a=e.u(e.t),o=e.utils.round(a,3),s=e.utils.round(1-a,3),l=i(e.t);e.drawLine({x:l.x,y:n},l),e.drawLine({x:n,y:l.y},l),e.drawCircle(l,3),e.setFill("blue"),e.text(" t = "+e.utils.round(e.t,3),{x:l.x+10,y:l.y-7}),e.text("u(t) = "+e.utils.round(a,3),{x:l.x+10,y:l.y+7}),e.setFill("black"),e.text("C = "+o+" * start + "+s+" * end",{x:t/2-n,y:n+r})}},drawQCT:function(e){e.u=e.u||function(e){var t=(e-1)*(e-1),n=2*e*e-2*e+1;return t/n},this.drawCTgraph(e)},drawCCT:function(e){e.u=e.u||function(e){var t=(1-e)*(1-e)*(1-e),n=e*e*e+t;return t/n},this.drawCTgraph(e)},render:function(){return r.createElement("section",null,r.createElement(a,this.props),r.createElement("p",null,"De Casteljau's algorithm is the pivotal algorithm when it comes to Bézier curves. You can use it not just to split curves, but also to draw them efficiently (especially for high-order Bézier curves), as well as to come up with curves based on three points and a tangent. Particularly this last thing is really useful because it lets us \"mould\" a curve, by picking it up at some point, and dragging that point around to change the curve's shape."),r.createElement("p",null,"How does that work? Succinctly: we run de Casteljau's algorithm in reverse!"),r.createElement("p",null,"In order to run de Casteljau's algorithm in reverse, we need a few basic things: a start and end point, a point on the curve that want to be moving around, which has an associated ",r.createElement("i",null,"t"),' value, and a point we\'ve not explicitly talked about before, and as far as I know has no explicit name, but lives one iteration higher in the de Casteljau process then our on-curve point does. I like to call it "A" for reasons that will become obvious.'),r.createElement("p",null,'So let\'s use graphics instead of text to see where this "A" is, because text only gets us so far: in the following graphic, click anywhere on the curves to see the identity information that we\'ll be using to run de Casteljau in reverse (you can manipulate the curve even after picking a point. Note the "ratio" value when you do so: does it change?):'),r.createElement("div",{className:"figure"},r.createElement(i,{inline:!0,preset:"abc",title:"Projections in a quadratic Bézier curve",setup:this.setupQuadratic,draw:this.draw,onClick:this.onClick}),r.createElement(i,{inline:!0,preset:"abc",title:"Projections in a cubic Bézier curve",setup:this.setupCubic,draw:this.draw,onClick:this.onClick})),r.createElement("p",null,"Clicking anywhere on the curves shows us three things:"),r.createElement("ol",null,r.createElement("li",null,"our on-curve point; let's call that ",r.createElement("b",null,"B"),","),r.createElement("li",null,"a point at the tip of B's \"hat\", on de Casteljau step up; let's call that ",r.createElement("b",null,"A"),", and"),r.createElement("li",null,"a point that we get by projecting B onto the start--end baseline; let's call that ",r.createElement("b",null,"C"),".")),r.createElement("p",null,"These three values ABC hide an important identity formula for quadratic and cubic Bézier curves: for any point on the curve with some ",r.createElement("i",null,"t")," value, the ratio distance of C along baseline is fixed: if some ",r.createElement("i",null,"t")," value sets up a C that is 20% away from the start and 80% away from the end, then it doesn't matter where the start, end, or control points are: for that ",r.createElement("i",null,"t")," value, C will ",r.createElement("em",null,"always")," lie at 20% from the start and 80% from the end point. Go ahead, pick an on-curve point in either graphic and then move all the other points around: if you only move the control points, start and end won't move, and so neither will C, and if you move either start or end point, C will move but its relative position will not change. The following function stays true:"),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/f48f095d9c37c079ff6a5f71b3047397aa7dfc6b.svg",style:{width:"13.19985rem",height:"1.125rem"}})),r.createElement("p",null,"So that just leaves finding A."),r.createElement("div",{className:"note"},r.createElement("p",null,"While that relation is fixed, the function ",r.createElement("i",null,"u(t)")," differs depending on whether we're working with quadratic or cubic curves:"),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/b2db06c0139cd2c346ce764393f5c7252a16b5f2.svg",style:{width:"12.524849999999999rem",height:"5.70015rem"}})),r.createElement("p",null,"So, if we know the start and end coordinates, and we know the ",r.createElement("i",null,"t")," value, we know C:"),r.createElement("div",{className:"figure"},r.createElement(i,{inline:!0,preset:"abc",title:"Quadratic value of C for t",draw:this.drawQCT,onMouseMove:this.setCT}),r.createElement(i,{inline:!0,preset:"abc",title:"Cubic value of C for t",draw:this.drawCCT,onMouseMove:this.setCT})),r.createElement("p",null,"Mouse-over the graphs to see the expression for C, given the ",r.createElement("i",null,"t")," value at the mouse pointer.")),r.createElement("p",null,"There's also another important bit of information that is inherent to the ABC values: while the distances between A and B, and B and C, are dynamic (based on where we put B), the ",r.createElement("em",null,"ratio")," between the two distances is stable: given some ",r.createElement("i",null,"t")," value, the following always holds:"),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/6cb3e94fe9164128a25570a32abed15baa726f17.svg",style:{width:"17.92485rem",height:"2.7rem"}})),r.createElement("p",null,"This leads to a pretty powerful bit of knowledge: merely by knowing the ",r.createElement("i",null,"t")," value of some on curve point, we know where C has to be (as per the above note), and because we know B and C, and thus have the distance between them, we know where A has to be:"),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/1dffb79b42799c95c899e689b074361f662ec807.svg",style:{width:"15.525rem",height:"2.55015rem"}})),r.createElement("p",null,"And that's it, all values found."),r.createElement("div",{className:"note"},r.createElement("p",null,"Much like the ",r.createElement("i",null,"u(t)")," function in the above note, the ",r.createElement("i",null,"ratio(t)")," function depends on whether we're looking at quadratic or cubic curves. Their form is intrinsically related to the ",r.createElement("i",null,"u(t)")," function in that they both come rolling out of the same function evalution, explained over on ",r.createElement("a",{href:"http://mathoverflow.net/questions/122257/finding-the-formula-for-Bézier-curve-ratios-hull-point-point-baseline"},"MathOverflow"),' by Boris Zbarsky and myself. The ratio functions are the "s(t)" functions from the answers there, while the "u(t)" functions have the same name both here and on MathOverflow.'),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/51ecfbffec979f90ab93a54a5de8cbeb83e150ad.svg",style:{width:"14.475150000000001rem",height:"2.7rem"}})),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/5f2bb71795c615637d632da70b722938cb103b03.svg",style:{width:"15.075000000000001rem",height:"2.77515rem"}})),r.createElement("p",null,'Unfortunately, this trick only works for quadratic and cubic curves. Once we hit higher order curves, things become a lot less predictable; the "fixed point ',r.createElement("i",null,"C"),'" is no longer fixed, moving around as we move the control points, and projections of ',r.createElement("i",null,"B")," onto the line between start and end may actually lie on that line before the start, or after the end, and there are no simple ratios that we can exploit.")),r.createElement("p",null,"So: if we know B and its corresponding ",r.createElement("i",null,"t"),' value, then we know all the ABC values, which —together with a start and end coordinate— gives us the necessary information to reconstruct a curve\'s "de Casteljau skeleton", which means that two points and a value between 0 and 1, we can come up with a curve. And that opens up possibilities: curve manipulation by dragging an on-curve point, curve fitting of "a bunch of coordinates", these are useful things, and we\'ll look at both in the next sections.'))}});e.exports=o},function(e,t,n){"use strict";var r=n(2),i=n(215),a=n(221),o=Math.abs,s=r.createClass({displayName:"Moulding",getDefaultProps:function(){return{title:"Manipulating a curve"}},setupQuadratic:function(e){e.setPanelCount(3);var t=e.getDefaultQuadratic();t.points[2].x-=30,e.setCurve(t)},setupCubic:function(e){e.setPanelCount(3);var t=new e.Bezier([100,230,30,160,200,50,210,160]);t.points[2].y-=20,e.setCurve(t),e.lut=t.getLUT(100)},saveCurve:function(e,t){t.t&&(t.setCurve(t.newcurve),t.t=!1,t.redraw())},findTValue:function(e,t){var n=t.curve.on({x:e.offsetX,y:e.offsetY},7);return.05>n||n>.95?!1:n},markQB:function(e,t){if(t.t=this.findTValue(e,t),t.t){var n=t.t,r=2*n,i=r*n-r,a=i+1,s=o(i/a),l=t.curve,u=t.A=l.points[1],c=t.B=l.get(n);t.C=t.utils.lli4(u,c,l.points[0],l.points[2]),t.ratio=s}},markCB:function(e,t){if(t.t=this.findTValue(e,t),t.t){var n=t.t,r=1-n,i=n*n*n,a=r*r*r,s=i+a,l=s-1,u=o(l/s),c=t.curve,h=c.hull(n),d=t.A=h[5],p=t.B=c.get(n);t.db=c.derivative(n),t.C=t.utils.lli4(d,p,c.points[0],c.points[3]),t.ratio=u}},drag:function(e,t){if(t.t){var n=t.newB={x:e.offsetX,y:e.offsetY};t.newA={x:n.x-(t.C.x-n.x)/t.ratio,y:n.y-(t.C.y-n.y)/t.ratio}}},dragQB:function(e,t){t.t&&(this.drag(e,t),t.update=[t.newA])},dragCB:function(e,t){if(t.t){this.drag(e,t);var n=t.curve,r=n.hull(t.t),i=t.B,a=r[7],o=r[8],s={x:a.x-i.x,y:a.y-i.y},l={x:o.x-i.x,y:o.y-i.y},u=n.points,c={x:t.newB.x+s.x,y:t.newB.y+s.y},h={x:t.newA.x-(t.newA.x-c.x)/(1-t.t),y:t.newA.y-(t.newA.y-c.y)/(1-t.t)},d={x:t.newB.x+l.x,y:t.newB.y+l.y},p={x:t.newA.x+(d.x-t.newA.x)/t.t,y:t.newA.y+(d.y-t.newA.y)/t.t},f={x:u[0].x+(h.x-u[0].x)/t.t,y:u[0].y+(h.y-u[0].y)/t.t},m={x:u[3].x-(u[3].x-p.x)/(1-t.t),y:u[3].y-(u[3].y-p.y)/(1-t.t)};t.p1=c,t.p2=d,t.sc1=h,t.sc2=p,t.nc1=f,t.nc2=m,t.update=[f,m]}},drawMould:function(e,t){e.reset(),e.drawSkeleton(t),e.drawCurve(t);var n=e.getPanelWidth(),r=e.getPanelHeight(),i={x:n,y:0},a=e.utils.round;if(e.setColor("black"),e.drawLine({x:0,y:0},{x:0,y:r},i),e.drawLine({x:n,y:0},{x:n,y:r},i),e.t){e.drawCircle(t.get(e.t),3),e.npts=[t.points[0]].concat(e.update).concat([t.points.slice(-1)[0]]),e.newcurve=new e.Bezier(e.npts),e.setColor("lightgrey"),e.drawCurve(e.newcurve);var o=e.drawHull(e.newcurve,e.t,i);if(e.drawLine(e.npts[0],e.npts.slice(-1)[0],i),e.drawLine(e.newA,e.newB,i),e.setColor("grey"),e.drawCircle(e.newA,3,i),e.setColor("blue"),e.drawCircle(e.B,3,i),e.drawCircle(e.C,3,i),e.drawCircle(e.newB,3,i),e.drawLine(e.B,e.C,i),e.drawLine(e.newB,e.C,i),e.setFill("black"),e.text("A'",e.newA,{x:i.x+7,y:i.y+1}),e.text("start",t.get(0),{x:i.x+7,y:i.y+1}),e.text("end",t.get(1),{x:i.x+7,y:i.y+1}),e.setFill("blue"),e.text("B'",e.newB,{x:i.x+7,y:i.y+1}),e.text("B, at t = "+a(e.t,2),e.B,{x:i.x+7,y:i.y+1}),e.text("C",e.C,{x:i.x+7,y:i.y+1}),3===t.order){var s=t.hull(e.t);e.drawLine(s[7],s[8],i),e.drawLine(o[7],o[8],i),e.drawCircle(o[7],3,i),e.drawCircle(o[8],3,i),e.text("e1",o[7],{x:i.x+7,y:i.y+1}),e.text("e2",o[8],{x:i.x+7,y:i.y+1})}i.x+=n,e.setColor("lightgrey"),e.drawSkeleton(e.newcurve,i),e.setColor("black"),e.drawCurve(e.newcurve,i)}else i.x+=n,e.drawCurve(t,i)},render:function(){return r.createElement("section",null,r.createElement(a,this.props),r.createElement("p",null,'Armed with knowledge of the "ABC" relation, we can now update a curve interactively, by letting people click anywhere on the curve, find the ',r.createElement("em",null,"t"),'-value matching that coordinate, and then letting them drag that point around. With every drag update we\'ll have a new point "B", which we can combine with the fixed point "C" to find our new point A. Once we have those, we can reconstruct the de Casteljau skeleton and thus construct a new curve with the same start/end points as the original curve, passing through the user-selected point B, with correct new control points.'),r.createElement(i,{preset:"moulding",title:"Moulding a quadratic Bézier curve",setup:this.setupQuadratic,draw:this.drawMould,onClick:this.placeMouldPoint,onMouseDown:this.markQB,onMouseDrag:this.dragQB,onMouseUp:this.saveCurve}),r.createElement("p",null,r.createElement("strong",null,"Click-dragging the curve itself")," shows what we're using to compute the new coordinates: while dragging you will see the original points B and its corresponding ",r.createElement("i",null,"t"),"-value, the original point C for that ",r.createElement("i",null,"t"),"-value, as well as the new point B' based on the mouse cursor. Since we know the ",r.createElement("i",null,"t"),"-value for this configuration, we can compute the ABC ratio for this configuration, and we know that our new point A' should like at a distance:"),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/e361e1235c94bbe87e95834c7fcfb6ab96e028b9.svg",style:{width:"15.600150000000001rem",height:"2.3998500000000003rem"}})),r.createElement("p",null,"For quadratic curves, this means we're done, since the new point A' is equivalent to the new quadratic control point. For cubic curves, we need to do a little more work:"),r.createElement(i,{preset:"moulding",title:"Moulding a cubic Bézier curve",setup:this.setupCubic,draw:this.drawMould,onClick:this.placeMouldPoint,onMouseDown:this.markCB,onMouseDrag:this.dragCB,onMouseUp:this.saveCurve}),r.createElement("p",null,"To help understand what's going on, the cubic graphic shows the full de Casteljau construction \"hull\" when repositioning point B. We compute A` in exactly the same way as before, but we also record the final strut line that forms B in the original curve. Given A', B', and the endpoints e1 and e2 of the strut line relative to B', we can now compute where the new control points should be. Remember that B' lies on line e1--e2 at a distance ",r.createElement("i",null,"t"),", because that's how Bézier curves work. In the same manner, we know the distance A--e1 is only line-interval [0,t] of the full segment, and A--e2 is only line-interval [t,1], so constructing the new control points is fairly easy."),r.createElement("p",null,"First, we construct the one-level-of-de-Casteljau-up points:"),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/f813a7d607787329d242bfbfa28570c88c3e30f5.svg",style:{width:"9.975150000000001rem",height:"5.09985rem"}})),r.createElement("p",null,"And then we can compute the new control points:"),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/4ec5f4148752a3d332a922048700d2c71918342f.svg",style:{width:"11.700000000000001rem",height:"4.64985rem"}})),r.createElement("p",null,"And that's cubic curve manipulation."))}});e.exports=s},function(e,t,n){"use strict";var r=n(2),i=n(215),a=n(221),o=Math.abs,s=r.createClass({displayName:"PointCurves",getDefaultProps:function(){return{title:"Creating a curve from three points"}},setup:function(e){e.lpts=[{x:56,y:153},{x:144,y:83},{x:188,y:185}]},onClick:function(e,t){3==t.lpts.length&&(t.lpts=[]),t.lpts.push({x:e.offsetX,y:e.offsetY}),t.redraw()},getQRatio:function(e){var t=2*e,n=t*e-t,r=n+1;return o(n/r)},getCRatio:function(e){var t=1-e,n=e*e*e,r=t*t*t,i=n+r,a=i-1;return o(a/i)},drawQuadratic:function(e,t){var n=["start","t=0.5","end"];if(e.reset(),e.setColor("lightblue"),e.drawGrid(10,10),e.setFill("black"),e.setColor("black"),e.lpts.forEach(function(t,r){e.drawCircle(t,3),e.text(n[r],t,{x:5,y:2})}),3===e.lpts.length){var r=e.lpts[0],i=e.lpts[2],a=e.lpts[1],o={x:(r.x+i.x)/2,y:(r.y+i.y)/2};e.setColor("blue"),e.drawLine(r,i),e.drawLine(a,o),e.drawCircle(o,3);var s=this.getQRatio(.5),l={x:a.x+(a.x-o.x)/s,y:a.y+(a.y-o.y)/s};t=new e.Bezier([r,l,i]),e.setColor("lightgrey"),e.drawLine(l,a),e.drawLine(l,r),e.drawLine(l,i),e.setColor("black"),e.drawCircle(l,1),e.drawCurve(t)}},drawCubic:function(e,t){var n=["start","t=0.5","end"];if(e.reset(),e.setFill("black"),e.setColor("black"),e.lpts.forEach(function(t,r){e.drawCircle(t,3),e.text(n[r],t,{x:5,y:2})}),e.setColor("lightblue"),e.drawGrid(10,10),3===e.lpts.length){var r=e.lpts[0],i=e.lpts[2],a=e.lpts[1],o={x:(r.x+i.x)/2,y:(r.y+i.y)/2};e.setColor("blue"),e.drawLine(r,i),e.drawLine(a,o),e.drawCircle(o,1);var s=this.getCRatio(.5),l={x:a.x+(a.x-o.x)/s,y:a.y+(a.y-o.y)/s},u=e.utils.dist(r,i),c=u/8,h=e.utils.dist(a,o),d=4,p=c+h/d,f=p*(i.x-r.x)/u,m=p*(i.y-r.y)/u,g={x:a.x-f,y:a.y-m},v={x:a.x+f,y:a.y+m},y={x:l.x+2*(g.x-l.x),y:l.y+2*(g.y-l.y)},w={x:l.x+2*(v.x-l.x),y:l.y+2*(v.y-l.y)},b={x:r.x+2*(y.x-r.x),y:r.y+2*(y.y-r.y)},_={x:i.x+2*(w.x-i.x),y:i.y+2*(w.y-i.y)};t=new e.Bezier([r,b,_,i]),e.drawLine(g,v),e.setColor("lightgrey"),e.drawLine(l,o),e.drawLine(l,y),e.drawLine(l,w),e.drawLine(r,b),e.drawLine(i,_),e.drawLine(b,_),e.setColor("black"),e.drawCircle(l,1),e.drawCircle(b,1),e.drawCircle(_,1),e.drawCurve(t)}},render:function(){return r.createElement("section",null,r.createElement(a,this.props),r.createElement("p",null,"Given the preceding section on curve manipulation, we can also generate quadratic and cubic curves from any three points. However, unlike circle-fitting, which requires just three points, Bézier curve fitting requires three points, as well as a ",r.createElement("i",null,"t")," value, so we can figure out where point 'C' needs to be."),r.createElement("p",null,"The following graphic lets you place three points, and will use the preceding sections on the ABC ratio and curve construction to form a quadratic curve through them. You can move the points you've placed around by click-dragging, or try a new curve by drawing new points with pure clicks. (There's some freedom here, so for illustrative purposes we clamped ",r.createElement("i",null,"t")," to simply be 0.5, lets us bypass some maths, since a ",r.createElement("i",null,"t")," value of 0.5 always puts C in the middle of the start--end line segment)"),r.createElement(i,{preset:"generate",title:"Fitting a quadratic Bézier curve",setup:this.setup,draw:this.drawQuadratic,onClick:this.onClick}),r.createElement("p",null,'For cubic curves we also need some values to construct the "de Casteljau line through B" with, and that gives us quite a bit of choice. Since we\'ve clamped ',r.createElement("i",null,"t"),' to 0.5, we\'ll set up a line through B parallel to the line start--end, with a length that is proportional to the length of the line B--C: the further away from the baseline B is, the wider its construction line will be, and so the more "bulby" the curve will look. This still gives us some freedom in terms of exactly how to scale the length of the construction line as we move B closer or further away from the baseline, so I simply picked some values that sort-of-kind-of look right in that if a circle through (start,B,end) forms a perfect hemisphere, the cubic curve constructed forms something close to a hemisphere, too, and if the points lie on a line, then the curve constructed has the control points very close to B, while still lying between B and the correct curve end point:'),r.createElement(i,{preset:"generate",title:"Fitting a cubic Bézier curve",setup:this.setup,draw:this.drawCubic,onClick:this.onClick}),r.createElement("p",null,'In each graphic, the blue parts are the values that we "just have" simply by setting up our three points, combined with our decision on which ',r.createElement("i",null,"t")," value to use (and construction line orientation and length for cubic curves). There are of course many ways to determine a combination of ",r.createElement("i",null,"t"),' and tangent values that lead to a more "æsthetic" curve, but this will be left as an exercise to the reader, since there are many, and æsthetics are often quite personal.'))}});e.exports=s},function(e,t,n){"use strict";var r=n(2),i=n(221),a=r.createClass({displayName:"CatmullRomConversion",getDefaultProps:function(){return{title:"Bézier curves and Catmull-Rom curves"}},render:function(){return r.createElement("section",null,r.createElement(i,this.props),r.createElement("p",null,"Taking an excursion to different splines, the other common design curve is the ",r.createElement("a",{href:"https://en.wikipedia.org/wiki/Cubic_Hermite_spline#Catmull.E2.80.93Rom_spline"},"Catmull-Rom spline"),". Now, a Catmull-Rom spline is a form of cubic Hermite spline, and as it so happens the cubic Bézier curve is also a cubic Hermite spline, so maybe... maybe we can convert one into the other, and back, with some simple substitutions?"),r.createElement("p",null,'Unlike Bézier curves, Catmull-Rom splines pass through each point used to define the curve, except the first and last, which makes sense if you read the "natural language" description for how a Catmull-Rom spline works: a Catmull-Rom spline is a curve that, at each point P',r.createElement("sub",null,"x"),", has a tangent along the line P",r.createElement("sub",null,"x-1")," to P",r.createElement("sub",null,"x+1"),". The curve runs from points P",r.createElement("sub",null,"2")," to P",r.createElement("sub",null,"n-1"),', and has a "tension" that determines how fast the curve passes through each point. The lower the tension, the faster the curve goes through each point, and the bigger its local tangent is.'),r.createElement("p",null,"I'll be showing the conversion to and from Catmull-Rom curves for the tension that the Processing language uses for its Catmull-Rom algorithm."),r.createElement("p",null,"We start with showing the Catmull-Rom matrix form:"),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/5fc1c44e623f2a9fbeefdaa204557479e3debf5a.svg",style:{width:"30.150000000000002rem",height:"5.70015rem"}})),r.createElement("p",null,"However, there's something funny going on here: the coordinate column matrix looks weird. The reason is that Catmull-Rom curves are actually curve segments that are described by two points, and two tangents; the curve leaves a point V1 (if we have four coordinates instead, this is coordinate 2), arriving at a point V2 (coordinate 3), with the curve departing V1 with a tangent vector V'1 (equal to the tangent from coordinate 1 to coordinate 3) and arriving at V2 with tangent vector V'2 (equal to the tangent from coordinate 2 to coordinate 4). So if we want to express this as a matrix form based on four coordinates, we get this representation instead:"),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/40b9ca9b5755a4be49517ddfa630fef7b8e23067.svg",style:{width:"29.475rem",height:"6.525rem"}})),r.createElement("div",{className:"note"},r.createElement("h2",null,"Where did that 2 come from?"),r.createElement("p",null,"Catmull-Rom splines are based on the concept of tension: the higher the tensions, the shorter the tangents at the departure and arrival points. The basic Catmull-Rom curve arrives and departs with tangents equal to half the distance between the two adjacent points, so that's where that 2 came from."),r.createElement("p",null,'However, the "real" matrix is this:'),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/7bf9b5e971866babedd991ccdde5c4ab104297e5.svg",style:{width:"24.75rem",height:"6.60015rem"}})),r.createElement("p",null,"This bakes in the tension factor τ explicitly.")),r.createElement("p",null,'Plugging this into the "two coordinates and two tangent vectors" matrix form, we get:'),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/4818f8797c35f23c2b9883aa986b1129b2fa151a.svg",style:{width:"21.45015rem",height:"5.70015rem"}})),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/08f77989369f664cbc0fb7526791efd4c5299d70.svg",style:{width:"35.47485rem",height:"5.47515rem"}})),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/c7ae769c5370469b16523bab6f34abf0dd6749be.svg",style:{width:"28.425150000000002rem",height:"5.54985rem"}})),r.createElement("p",null,"So let's find out which transformation matrix we need in order to convert from Catmull-Rom to Bézier:"),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/7250f1c57e2bd66ec4349e4e88db4d5d74401a06.svg",style:{width:"50.85rem",height:"5.54985rem"}})),r.createElement("p",null,"The difference is somewhere in the actual hermite matrix, since the ",r.createElement("em",null,"t")," and coordinate values are identical, so let's solve that matrix equasion:"),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/8a42b24fca3aaf6b8ec08e84b7e91c43e26e8acf.svg",style:{width:"28.575rem",height:"5.54985rem"}})),r.createElement("p",null,"We left-multiply both sides by the inverse of the Bézier matrix, to get rid of the Bézier matrix on the right side of the equals sign:"),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/0e111d6e846f4d7204dec484005f74993e66c6c9.svg",style:{width:"58.19985rem",height:"5.70015rem"}})),r.createElement("p",null,"Which gives us:"),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/f94b80113772d90a4fbc93d4495cb5767e5c8123.svg",style:{width:"12.6rem",height:"5.47515rem"}})),r.createElement("p",null,"Multiplying this ",r.createElement("strong",null,r.createElement("em",null,"A"))," with our coordinates will give us a proper Bézier matrix expression again:"),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/d088274e440ceeac2916a0f32176682d776c1c57.svg",style:{width:"31.725rem",height:"5.47515rem"}})),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/9e68f80b270d3445d9f9cb28ff2c5aed219aa9d2.svg",style:{width:"25.650000000000002rem",height:"6.60015rem"}})),r.createElement("p",null,"So a Catmull-Rom to Bézier conversion, based on coordinates, requires turning the Catmull-Rom coordinates on the left into the Bézier coordinates on the right (with τ being our tension factor):"),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/f0c5a707b590eaf8899a927ce39fd186a6acecf3.svg",style:{width:"18.07515rem",height:"6.67485rem"}})),r.createElement("p",null,"And the other way around, a Bézier to Catmull-Rom conversion requires turning the Bézier coordinates on the left this time into the Catmull-Rom coordinates on the right. Note that there is no tension this time, because Bézier curves don't have any. Converting from Bézier to Catmull-Rom is simply a default-tension Catmull-Rom curve:"),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/51da95daf2645abd9903a4e28749a6d01826625c.svg",style:{width:"21.150000000000002rem",height:"5.625rem"}})),r.createElement("p",null,"Done. We can now draw the curves we want using either Bézier curves or Catmull-Rom splines, the choice mostly being which drawing algorithms we have natively available."))}});e.exports=a},function(e,t,n){"use strict";var r=n(2),i=n(215),a=n(221),o=n(224),s=r.createClass({displayName:"CatmullRomMoulding",statics:{keyHandlingOptions:{propName:"distance",values:{38:1,40:-1}}},getDefaultProps:function(){return{title:"Creating a Catmull-Rom curve from three points"}},setup:function(e){e.setPanelCount(3),e.lpts=[{x:56,y:153},{x:144,y:83},{x:188,y:185}],e.distance=0},convert:function(e,t,n,r){var i=.5;return[t,{x:t.x+(n.x-e.x)/(6*i),y:t.y+(n.y-e.y)/(6*i)},{x:n.x-(r.x-t.x)/(6*i),y:n.y-(r.y-t.y)/(6*i)},n]},draw:function(e){e.reset(),e.setColor("lightblue"),e.drawGrid(10,10);var t=e.lpts;e.setColor("black"),e.setFill("black"),t.forEach(function(t,n){e.drawCircle(t,3),e.text("point "+(n+1),t,{x:10,y:7})});var n=e.getPanelWidth(),r=e.getPanelHeight(),i={x:n,y:0};e.setColor("lightblue"),e.drawGrid(10,10,i),e.setColor("black"),e.drawLine({x:0,y:0},{x:0,y:r},i),t.forEach(function(t,n){e.drawCircle(t,3,i)});var a=t[0],o=t[1],s=t[2],l=s.x-a.x,u=s.y-a.y,c=Math.sqrt(l*l+u*u);l/=c,u/=c,e.drawLine(a,s,i);var h={x:a.x+(s.x-o.x)-e.distance*l,y:a.y+(s.y-o.y)-e.distance*u},d={x:a.x+(s.x-o.x)+e.distance*l,y:a.y+(s.y-o.y)+e.distance*u},p=e.utils.lli4(a,s,o,{x:(h.x+d.x)/2,y:(h.y+d.y)/2});e.setColor("blue"),e.drawCircle(p,3,i),e.drawLine(t[1],p,i),e.setColor("#666"),e.drawLine(p,h,i),e.drawLine(p,d,i),e.setFill("blue"),e.text("p0",h,{x:-20+i.x,y:i.y+2}),e.text("p4",d,{x:10+i.x,y:i.y+2}),e.setColor("red"),e.drawCircle(h,3,i),e.drawLine(o,h,i),e.drawLine(a,{x:a.x+(o.x-h.x)/5,y:a.y+(o.y-h.y)/5},i),e.setColor("#00FF00"),e.drawCircle(d,3,i),e.drawLine(o,d,i),e.drawLine(s,{x:s.x+(d.x-o.x)/5,y:s.y+(d.y-o.y)/5},i);var f=new e.Bezier(this.convert(h,a,o,s)),m=new e.Bezier(this.convert(a,o,s,d));e.setColor("lightgrey"),e.drawCurve(f,i),e.drawCurve(m,i),i.x+=n,e.setColor("lightblue"),e.drawGrid(10,10,i),e.setColor("black"),e.drawLine({x:0,y:0},{x:0,y:r},i),e.drawCurve(f,i),e.drawCurve(m,i),e.drawPoints(f.points,i),e.drawPoints(m.points,i),e.setColor("lightgrey"),e.drawLine(f.points[0],f.points[1],i),e.drawLine(f.points[2],m.points[1],i),e.drawLine(m.points[2],m.points[3],i)},render:function(){return r.createElement("section",null,r.createElement(a,this.props),r.createElement("p",null,"Now, we saw how to fit a Bézier curve to three points, but if Catmull-Rom curves go through points, why can't we just use those to do curve fitting, instead?"),r.createElement("p",null,"As a matter of fact, we can, but there's a difference between the kind of curve fitting we did in the previous section, and the kind of curve fitting that we can do with Catmull-Rom curves. In the previous section we came up with a single curve that goes through three points. There was a decent amount of maths and computation involved, and the end result was three or four coordinates that described a single curve, depending on whether we were fitting a quadratic or cubic curve."),r.createElement("p",null,"Using Catmull-Rom curves, we need virtually no computation, but even though we end up with one Catmull-Rom curve of ",r.createElement("i",null,"n")," points, in order to draw the equivalent curve using cubic Bézier curves we need a massive ",r.createElement("i",null,"3n-1")," points (and that's without double-counting points that are shared by consecutive cubic curves)."),r.createElement("p",null,'In the following graphic, on the left we see three points that we want to draw a Catmull-Rom curve through (which we can move around freely, by the way), with in the second panel some of the "interesting" Catmull-Rom information: in black there\'s the baseline start--end, which will act as tangent orientation for the curve at point p2. We also see a virtual point p0 and p4, which are initially just point p2 reflected over the baseline. However, by using the up and down cursor key we can offset these points parallel to the baseline. Why would we want to do this? Because the line p0--p2 acts as departure tangent at p1, and the line p2--p4 acts as arrival tangent at p3. Play around with the graphic a bit to get an idea of what all of that meant:'),r.createElement(i,{ preset:"threepanel",title:"Catmull-Rom curve fitting",setup:this.setup,draw:this.draw,onKeyDown:this.props.onKeyDown}),r.createElement("p",null,"As should be obvious by now, Catmull-Rom curves are great for \"fitting a curvature to some points\", but if we want to convert that curve to Bézier form we're going to end up with a lot of separate (but visually joined) Bézier curves. Depending on what we want to do, that'll be either unnecessary work, or exactly what we want: which it is depends entirely on you."))}});e.exports=o(s)},function(e,t,n){"use strict";var r=n(2),i=n(215),a=n(221),o=Math.atan2,s=Math.sqrt,l=Math.sin,u=Math.cos,c=r.createClass({displayName:"PolyBezier",getDefaultProps:function(){return{title:"Forming poly-Bézier curves"}},setupQuadratic:function(e){var t=e.getPanelWidth(),n=e.getPanelHeight(),r=t/2,i=n/2,a=40,o=[{x:r,y:a},{x:t-a,y:a},{x:t-a,y:i},{x:t-a,y:n-a},{x:r,y:n-a},{x:a,y:n-a},{x:a,y:i},{x:a,y:a}];e.lpts=o},setupCubic:function(e){var t=e.getPanelWidth(),n=e.getPanelHeight(),r=t/2,i=n/2,a=40,o=(t-2*a)/2,s=.55228,l=s*o,u=[{x:r,y:a},{x:r+l,y:a},{x:t-a,y:i-l},{x:t-a,y:i},{x:t-a,y:i+l},{x:r+l,y:n-a},{x:r,y:n-a},{x:r-l,y:n-a},{x:a,y:i+l},{x:a,y:i},{x:a,y:i-l},{x:r-l,y:a}];e.lpts=u},movePointsQuadraticLD:function(e,t){for(var n,r,i,a=1;4>a;a++)n=t+(2*a-2)+e.lpts.length,n=e.lpts[n%e.lpts.length],r=t+(2*a-1),r=e.lpts[r%e.lpts.length],i=t+2*a,i=e.lpts[i%e.lpts.length],i.x=r.x+(r.x-n.x),i.y=r.y+(r.y-n.y);i=t+6,i=e.lpts[i%e.lpts.length],e.problem=i},movePointsCubicLD:function(e,t){var n,r;t%3===1?(r=t-1,r+=0>r?e.lpts.length:0,n=t-2,n+=0>n?e.lpts.length:0):(r=(t+1)%e.lpts.length,n=(t+2)%e.lpts.length),r=e.lpts[r],n=e.lpts[n],n.x=r.x+(r.x-e.mp.x),n.y=r.y+(r.y-e.mp.y)},linkDerivatives:function(e,t){if(t.mp){var n=8===t.lpts.length,r=t.mp_idx;n?r%2!==0&&this.movePointsQuadraticLD(t,r):r%3!==0&&this.movePointsCubicLD(t,r)}},movePointsQuadraticDirOnly:function(e,t){var n,r,i;[-1,1].forEach(function(a){n=e.mp,r=t+a+e.lpts.length,r=e.lpts[r%e.lpts.length],i=t+2*a+e.lpts.length,i=e.lpts[i%e.lpts.length];var c=o(r.y-n.y,r.x-n.x),h=i.x-r.x,d=i.y-r.y,p=s(h*h+d*d);i.x=r.x+p*u(c),i.y=r.y+p*l(c)}),i=t+4,i=e.lpts[i%e.lpts.length],e.problem=i},movePointsCubicDirOnly:function(e,t){var n,r;t%3===1?(r=t-1,r+=0>r?e.lpts.length:0,n=t-2,n+=0>n?e.lpts.length:0):(r=(t+1)%e.lpts.length,n=(t+2)%e.lpts.length),r=e.lpts[r],n=e.lpts[n];var i=o(r.y-e.mp.y,r.x-e.mp.x),a=n.x-r.x,c=n.y-r.y,h=s(a*a+c*c);n.x=r.x+h*u(i),n.y=r.y+h*l(i)},linkDirection:function(e,t){if(t.mp){var n=8===t.lpts.length,r=t.mp_idx;n?r%2!==0&&this.movePointsQuadraticDirOnly(t,r):r%3!==0&&this.movePointsCubicDirOnly(t,r)}},bufferPoints:function(e,t){t.bpts=JSON.parse(JSON.stringify(t.lpts))},moveQuadraticPoint:function(e,t){this.moveCubicPoint(e,t),[-1,1].forEach(function(n){var r=t-n+e.lpts.length;r=e.lpts[r%e.lpts.length];var i=t-2*n+e.lpts.length;i=e.lpts[i%e.lpts.length];var a=t-3*n+e.lpts.length;a=e.lpts[a%e.lpts.length];var c=o(i.y-r.y,i.x-r.x),h=a.x-i.x,d=a.y-i.y,p=s(h*h+d*d);a.x=i.x+p*u(c),a.y=i.y+p*l(c)});var n=t+4;n=e.lpts[n%e.lpts.length],e.problem=n},moveCubicPoint:function(e,t){var n=e.bpts[t],r=e.lpts[t],i=r.x-n.x,a=r.y-n.y,o=e.lpts.length,s=t-1+o,l=t+1,u=e.bpts[s%o],c=e.bpts[l%o],h=e.lpts[s%o],d=e.lpts[l%o];return h.x=u.x+i,h.y=u.y+a,d.x=c.x+i,d.y=c.y+a,{x:i,y:a}},modelCurve:function(e,t){if(t.mp){var n=8===t.lpts.length,r=t.mp_idx;n?r%2!==0?this.movePointsQuadraticDirOnly(t,r):this.moveQuadraticPoint(t,r):r%3!==0?this.movePointsCubicDirOnly(t,r):this.moveCubicPoint(t,r)}},draw:function(e,t){e.reset();var n=e.lpts,r=8===n.length,i=r?new e.Bezier(n[0],n[1],n[2]):new e.Bezier(n[0],n[1],n[2],n[3]);e.drawSkeleton(i,!1,!0),e.drawCurve(i);var a=r?new e.Bezier(n[2],n[3],n[4]):new e.Bezier(n[3],n[4],n[5],n[6]);e.drawSkeleton(a,!1,!0),e.drawCurve(a);var o=r?new e.Bezier(n[4],n[5],n[6]):new e.Bezier(n[6],n[7],n[8],n[9]);e.drawSkeleton(o,!1,!0),e.drawCurve(o);var s=r?new e.Bezier(n[6],n[7],n[0]):new e.Bezier(n[9],n[10],n[11],n[0]);e.drawSkeleton(s,!1,!0),e.drawCurve(s),e.problem&&(e.setColor("red"),e.drawCircle(e.problem,5))},render:function(){return r.createElement("section",null,r.createElement(a,this.props),r.createElement("p",null,"Much like lines can be chained together to form polygons, Bézier curves can be chained together to form poly-Béziers, and the only trick required is to make sure that:"),r.createElement("ol",null,r.createElement("li",null,"the end point of each section is the starting point of the following section, and"),r.createElement("li",null,"the derivatives across that dual point line up.")),r.createElement("p",null,"Unless, of course, you want discontinuities; then you don't even need 2."),r.createElement("p",null,"We'll cover three forms of poly-Bézier curves in this section. First, we'll look at the kind that just follows point 1. where the end point of a segment is the same point as the start point of the next segment. This leads to poly-Béziers that are pretty hard to work with, but they're the easiest to implement:"),r.createElement(i,{preset:"poly",title:"Unlinked quadratic poly-Bézier",setup:this.setupQuadratic,draw:this.draw}),r.createElement(i,{preset:"poly",title:"Unlinked cubic poly-Bézier",setup:this.setupCubic,draw:this.draw}),r.createElement("p",null,'Dragging the control points around only affects the curve segments that the control point belongs to, and moving an on-curve point leaves the control points where they are, which is not the most useful for practical modelling purposes. So, let\'s add in the logic we need to make things a little better. We\'ll start by linking up control points by ensuring that the "incoming" derivative at an on-curve point is the same as it\'s "outgoing" derivative:'),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/37740bb1a0b7b1ff48bf3454e52295fc717cacbb.svg",style:{width:"8.400150000000002rem",height:"1.27485rem"}})),r.createElement("p",null,"We can effect this quite easily, because we know that the vector from a curve's last control point to its last on-curve point is equal to the derivative vector. If we want to ensure that the first control point of the next curve matches that, all we have to do is mirror that last control point through the last on-curve point. And mirroring any point A through any point B is really simple:"),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/ce6e3939608c4ed0598107b06543c2301b91bb7f.svg",style:{width:"21.97485rem",height:"2.7rem"}})),r.createElement("p",null,"So let's implement that and see what it gets us. The following two graphics show a quadratic and a cubic poly-Bézier curve again, but this time moving the control points around moves others, too. However, you might see something unexpected going on for quadratic curves..."),r.createElement(i,{preset:"poly",title:"Loosely connected quadratic poly-Bézier",setup:this.setupQuadratic,draw:this.draw,onMouseMove:this.linkDerivatives}),r.createElement(i,{preset:"poly",title:"Loosely connected cubic poly-Bézier",setup:this.setupCubic,draw:this.draw,onMouseMove:this.linkDerivatives}),r.createElement("p",null,"As you can see, quadratic curves are particularly ill-suited for poly-Bézier curves, as all the control points are effectively linked. Move one of them, and you move all of them. Not only that, but if we move the on-curve points, it's possible to get a situation where a control point's positions is different depending on whether it's the reflection of its left or right neighbouring control point: we can't even form a proper rule-conforming curve! This means that we cannot use quadratic poly-Béziers for anything other than really, really simple shapes. And even then, they're probably the wrong choice. Cubic curves are pretty decent, but the fact that the derivatives are linked means we can't manipulate curves as well as we might if we relaxed the constraints a little."),r.createElement("p",null,"So: let's relax the requirement a little."),r.createElement("p",null,"We can change the constraint so that we still preserve the ",r.createElement("em",null,"angle")," of the derivatives across sections (so transitions from one section to the next will still look natural), but give up the requirement that they should also have the same ",r.createElement("em",null,"vector length"),". Doing so will give us a much more useful kind of poly-Bézier curve:"),r.createElement(i,{preset:"poly",title:"Loosely connected quadratic poly-Bézier",setup:this.setupQuadratic,draw:this.draw,onMouseMove:this.linkDirection}),r.createElement(i,{preset:"poly",title:"Loosely connected cubic poly-Bézier",setup:this.setupCubic,draw:this.draw,onMouseMove:this.linkDirection}),r.createElement("p",null,"Cubic curves are now better behaved when it comes to dragging control points around, but the quadratic poly-Bézier still has the problem that moving one control points will move the control points and may ending up defining \"the next\" control point in a way that doesn't work. Quadratic curves really aren't very useful to work with..."),r.createElement("p",null,"Finally, we also want to make sure that moving the on-curve coordinates preserves the relative positions of the associated control points. With that, we get to the kind of curve control that you might be familiar with from applications like Photoshop, Inkscape, Blender, etc."),r.createElement(i,{preset:"poly",title:"Loosely connected quadratic poly-Bézier",setup:this.setupQuadratic,draw:this.draw,onMouseDown:this.bufferPoints,onMouseMove:this.modelCurve}),r.createElement(i,{preset:"poly",title:"Loosely connected cubic poly-Bézier",setup:this.setupCubic,draw:this.draw,onMouseDown:this.bufferPoints,onMouseMove:this.modelCurve}),r.createElement("p",null,'Again, we see that cubic curves are now rather nice to work with, but quadratic curves have a new, very serious problem: we can move an on-curve point in such a way that we can\'t compute what needs to "happen next". Move the top point down, below the left and right points, for instance. There is no way to preserve correct control points without a kink at the bottom point. Quadratic curves: just not that good...'),r.createElement("p",null,'A final improvement is to offer fine-level control over which points behave which, so that you can have "kinks" or individually controlled segments when you need them, with nicely well-behaved curves for the rest of the path. Implementing that, is left as an excercise for the reader.'))}});e.exports=c},function(e,t,n){"use strict";var r=n(2),i=n(215),a=n(221),o=["unite","intersect","exclude","subtract"],s=r.createClass({displayName:"Shapes",getDefaultProps:function(){return{title:"Boolean shape operations"}},getInitialState:function(){return{mode:o[0]}},setMode:function(e){this.setState({mode:e})},formPath:function(e,t,n,r,i){t=t||0,n=n||0;var a=30,o=a/2;r=r||8*a,i=i||4*a;var s=r/2,l=i/2,u=s/3,c=l/3,h=e.Paper,d=h.Path,p=h.Point,f=new d;return f.moveTo(new p(t-s+2*a,n-l)),f.cubicCurveTo(new p(t-s+o,n-l+o),new p(t-s+o,n+l-o),new p(t-s+2*a,n+l)),f.cubicCurveTo(new p(t-u,n+c),new p(t+u,n+c),new p(t+s-2*a,n+l)),f.cubicCurveTo(new p(t+s-o,n+l-o),new p(t+s-o,n-l+o),new p(t+s-2*a,n-l)),f.cubicCurveTo(new p(t+u,n-c),new p(t-u,n-c),new p(t-s+2*a,n-l)),f.closePath(!0),f.strokeColor="rgb(100,100,255)",f},setup:function(e){var t=e.getPanelWidth(),n=40,r=t/2,i=t/2;e.c1=this.formPath(e,r,i),r+=n,i+=n,e.c2=this.formPath(e,r,i),this.state.mode=o[0]},onMouseMove:function(e,t){var n=e.offsetX,r=e.offsetY;t.c2.position={x:n,y:r}},draw:function(e){e.c3&&e.c3.remove();var t=e.c1,n=e.c2,r=t[this.state.mode].bind(t),i=e.c3=r(n);i.strokeColor="red",i.fillColor="rgba(255,100,100,0.4)",e.Paper.view.draw()},render:function(){var e=this;return r.createElement("section",null,r.createElement(a,this.props),r.createElement("p",null,"We can apply the topics covered so far in this primer to effect boolean shape operations: getting the union, intersection, or exclusion, between two or more shapes that involve Bézier curves. For simplicity (well.. sort of, more homogeneity), we'll be looking at Poly-Bézier shapes only, but a shape that consists of a mix of lines and Bézier curves is technically a simplification (although it does mean we need to write a definition for the class of shapes that mix lines and Bézier curves. Since poly-Bézier curves are a superset, we'll be using those in the following examples)"),r.createElement("p",null,"The procedure for performing boolean operations consists, broadly, of four steps:"),r.createElement("ol",null,r.createElement("li",null,"Find the intersection points between both shapes,"),r.createElement("li",null,"cut up the shapes into multiple sections between these intersections,"),r.createElement("li",null,"discard any section that isn't part of the desired operation's resultant shape, and"),r.createElement("li",null,"link up the remaining sections to form the new shape.")),r.createElement("p",null,"Finding all intersections between two poly-Bézier curves, or any poly-line-section shape, is similar to the iterative algorithm discussed in the section on curve/curve intersection. For each segment in the poly-Bézier curve we check whether its bounding box overlaps with any of the segment bounding boxes in the other poly-Bézier curve. If so, we run normal intersection detection."),r.createElement("p",null,"After we found all intersection points, we split up our poly-Bézier curves, making sure to record which of the newly formed poly-Bézier curves might potentially link up at the points we split the originals up at. This will let us quickly glue poly-Bézier curves back together after the next step."),r.createElement("p",null,"Once we have all the new poly-Bézier curves, we run the first step of the desired boolean operation."),r.createElement("ul",null,r.createElement("li",null,'Union: discard all poly-Bézier curves that lie "inside" our union of our shapes. E.g. if we want the union of two overlapping circles, the resulting shape is the outline.'),r.createElement("li",null,'Intersection: discard all poly-Bézier curves that lie "outside" the intersection of the two shapes. E.g. if we want the intersection of two overlapping circles, the resulting shape is the tapered ellipse where they overlap.'),r.createElement("li",null,"Exclusion: none of the sections are discarded, but we will need to link the shapes back up in a special way. Flip any section that would qualify for removal under UNION rules.")),r.createElement("table",{className:"sketch"},r.createElement("tbody",null,r.createElement("tr",null,r.createElement("td",{className:"labeled-image"},r.createElement("img",{src:"images/op_base.gif",height:"169px"}),r.createElement("p",null,"Two overlapping shapes.")),r.createElement("td",{className:"labeled-image"},r.createElement("img",{src:"images/op_union.gif",height:"169px"}),r.createElement("p",null,"The unified region.")),r.createElement("td",{className:"labeled-image"},r.createElement("img",{src:"images/op_intersection.gif",height:"169px"}),r.createElement("p",null,"Their intersection.")),r.createElement("td",{className:"labeled-image"},r.createElement("img",{src:"images/op_exclusion.gif",height:"169px"}),r.createElement("p",null,"Their exclusion regions."))))),r.createElement("p",null,'The main complication in the outlined procedure here is determining how sections qualify in terms of being "inside" and "outside" of our shapes. For this, we need to be able to perform point-in-shape detection, for which we\'ll use a classic algorithm: getting the "crossing number" by using ray casting, and then testing for "insidedness" by applying the ',r.createElement("a",{href:"http://folk.uio.no/bjornw/doc/bifrost-ref/bifrost-ref-12.html"},"even-odd rule"),': For any point and any shape, we can cast a ray from our point, to some point that we know lies outside of the shape (such as a corner of our drawing surface). We then count how many times that line crosses our shape (remember that we can perform line/curve intersection detection quite easily). If the number of times it crosses the shape\'s outline is even, the point did not actually lie inside our shape. If the number of intersections is odd, our point did lie inside out shape. With that knowledge, we can decide whether to treat a section that such a point lies on "needs removal" (under union rules), "needs preserving" (under intersection rules), or "needs flipping" (under exclusion rules).'),r.createElement("p",null,"These operations are expensive, and implementing your own code for this is generally a bad idea if there is already a geometry package available for your language of choice. In this case, for JavaScript the most excellent ",r.createElement("a",{href:"http://paperjs.org"},"Paper.js")," already comes with all the code in place to perform efficient boolean shape operations, so rather that implement an inferior version here, I can strongly recommend the Paper.js library if you intend to do any boolean shape work."),r.createElement("p",null,"The following graphic shows Paper.js doing its thing for two shapes: one static, and one that is linked to your mouse pointer. If you move the mouse around, you'll see how the shape intersections are resolved. The base shapes are outlined in blue, and the boolean result is coloured red."),r.createElement(i,{preset:"simple",title:"Boolean shape operations with Paper.js",paperjs:!0,setup:this.setup,draw:this.draw,onMouseMove:this.onMouseMove},r.createElement("br",null),o.map(function(t){var n=e.state.mode===t?"selected":null;return r.createElement("button",{className:n,key:t,onClick:function(){this.setMode(t)}.bind(e)},t)})))}});e.exports=s},function(e,t,n){"use strict";var r=n(2),i=n(215),a=n(221),o=r.createClass({displayName:"Projections",getDefaultProps:function(){return{title:"Projecting a point onto a Bézier curve"}},setup:function(e){e.setSize(320,320);var t=new e.Bezier([{x:248,y:188},{x:218,y:294},{x:45,y:290},{x:12,y:236},{x:14,y:82},{x:186,y:177},{x:221,y:90},{x:18,y:156},{x:34,y:57},{x:198,y:18}]);e.setCurve(t),e._lut=t.getLUT()},findClosest:function(e,t,n){var r,i,a=e.length,o=n(e[0],t),s=0;for(r=1;a>r;r++)i=n(e[r],t),o>i&&(s=r,o=i);return s/(a-1)},draw:function(e,t){if(e.reset(),e.drawSkeleton(t),e.drawCurve(t),e.mousePt){e.setColor("red"),e.setFill("red"),e.drawCircle(e.mousePt,3);var n=this.findClosest(e._lut,e.mousePt,e.utils.dist),r=t.get(n);e.drawLine(r,e.mousePt),e.drawCircle(r,3),e.text("t = "+e.utils.round(n,2),r,{x:10,y:3})}},onMouseMove:function(e,t){t.mousePt={x:e.offsetX,y:e.offsetY},t._lut=t.curve.getLUT()},render:function(){return r.createElement("section",null,r.createElement(a,this.props),r.createElement("p",null,"Say we have a Bézier curve and some point, not on the curve, of which we want to know which ",r.createElement("i",null,"t")," value on the curve gives us an on-curve point closest to our off-curve point. Or: say we want to find the projection of a random point onto a curve. How do we do that?"),r.createElement("p",null,"If the Bézier curve is of low enough order, we might be able to ",r.createElement("a",{href:"http://jazzros.blogspot.ca/2011/03/projecting-point-on-bezier-curve.html"},"work out the maths for how to do this"),", and get a perfect ",r.createElement("i",null,"t")," value back, but in general this is an incredibly hard problem and the easiest solution is, really, a numerical approach again. We'll be finding our ideal ",r.createElement("i",null,"t")," value using a ",r.createElement("a",{href:"https://en.wikipedia.org/wiki/Binary_search_algorithm"},"binary search"),". First, we do a coarse distance-check based on ",r.createElement("i",null,"t"),' values associated with the curve\'s "to draw" coordinates (using a lookup table, or LUT). This is pretty fast. Then we run this algorithm:'),r.createElement("ol",null,r.createElement("li",null,"with the ",r.createElement("i",null,"t")," value we found, start with some small interval around ",r.createElement("i",null,"t")," (1/length_of_LUT on either side is a reasonable start),"),r.createElement("li",null,"if the distance to ",r.createElement("i",null,"t ± interval/2")," is larger than the distance to ",r.createElement("i",null,"t"),", try again with the interval reduced to half its original length."),r.createElement("li",null,"if the distance to ",r.createElement("i",null,"t ± interval/2")," is smaller than the distance to ",r.createElement("i",null,"t"),", replace ",r.createElement("i",null,"t")," with the smaller-distance value."),r.createElement("li",null,"after reducing the interval, or changing ",r.createElement("i",null,"t"),", go back to step 1.")),r.createElement("p",null,"We keep repeating this process until the interval is small enough to claim the difference in precision found is irrelevant for the purpose we're trying to find ",r.createElement("i",null,"t")," for. In this case, I'm arbitrarily fixing it at 0.0001."),r.createElement("p",null,'The following graphic demonstrates the result of this procedure.Simply move the cursor around, and if it does not lie on top of the curve, you will see a line that projects the cursor onto the curve based on an iteratively found "ideal" ',r.createElement("i",null,"t")," value."),r.createElement(i,{preset:"simple",title:"Projecting a point onto a Bézier curve",setup:this.setup,draw:this.draw,onMouseMove:this.onMouseMove}))}});e.exports=o},function(e,t,n){"use strict";var r=n(2),i=n(215),a=n(221),o=n(224),s=r.createClass({displayName:"Offsetting",statics:{keyHandlingOptions:{propName:"distance",values:{38:1,40:-1}}},getDefaultProps:function(){return{title:"Curve offsetting"}},setup:function(e,t){e.setCurve(t),e.distance=20},setupQuadratic:function(e){var t=e.getDefaultQuadratic();this.setup(e,t)},setupCubic:function(e){var t=e.getDefaultCubic();this.setup(e,t)},draw:function(e,t){e.reset(),e.drawSkeleton(t);var n=t.reduce();n.forEach(function(t){e.setRandomColor(),e.drawCurve(t),e.drawCircle(t.points[0],1)});var r=n.slice(-1)[0];e.drawPoint(r.points[3]||r.points[2]),e.setColor("red");var i=t.offset(e.distance);i.forEach(function(t){e.drawPoint(t.points[0]),e.drawCurve(t)}),r=i.slice(-1)[0],e.drawPoint(r.points[3]||r.points[2]),e.setColor("blue"),i=t.offset(-e.distance),i.forEach(function(t){e.drawPoint(t.points[0]),e.drawCurve(t)}),r=i.slice(-1)[0],e.drawPoint(r.points[3]||r.points[2])},render:function(){return r.createElement("section",null,r.createElement(a,this.props),r.createElement("p",null,"Perhaps you are like me, and you've been writing various small programs that use Bézier curves in some way or another, and at some point you make the step to implementing path extrusion. But you don't want to do it pixel based, you want to stay in the vector world. You find that extruding lines is relatively easy, and tracing outlines is coming along nicely (although junction caps and fillets are a bit of a hassle), and then decide to do things properly and add Bézier curves to the mix. Now you have a problem."),r.createElement("p",null,"Unlike lines, you can't simply extrude a Bézier curve by taking a copy and moving it around, because of the curvatures; rather than a uniform thickness you get an extrusion that looks too thin in places, if you're lucky, but more likely will self-intersect. The trick, then, is to scale the curve, rather than simply copying it. But how do you scale a Bézier curve?"),r.createElement("p",null,"Bottom line: ",r.createElement("strong",null,"you can't"),". So you cheat. We're not going to do true curve scaling, or rather curve offsetting, because that's impossible. Instead we're going to try to generate 'looks good enough' offset curves."),r.createElement("div",{className:"note"},r.createElement("h2",null,'"What do you mean, you can\'t. Prove it."'),r.createElement("p",null,'First off, when I say "you can\'t" what I really mean is "you can\'t offset a Bézier curve with another Bézier curve". not even by using a really high order curve. You can find the function that describes the offset curve, but it won\'t be a polynomial, and as such it cannot be represented as a Bézier curve, which',r.createElement("strong",null,"has")," to be a polynomial. Let's look at why this is:"),r.createElement("p",null,"From a mathematical point of view, an offset curve ",r.createElement("i",null,"O(t)")," is a curve such that, given our original curve",r.createElement("i",null,"B(t)"),", any point on ",r.createElement("i",null,"O(t)")," is a fixed distance ",r.createElement("i",null,"d")," away from coordinate ",r.createElement("i",null,"B(t)"),". So let's math that:"),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/3aff5cef0028337bbb48ae64ad30000c4d5e238f.svg",style:{width:"7.275150000000001rem",height:"1.125rem"}})),r.createElement("p",null,"However, we're working in 2D, and ",r.createElement("i",null,"d")," is a single value, so we want to turn it into a vector. If we want a point distance ",r.createElement("i",null,"d"),' "away" from the curve ',r.createElement("i",null,"B(t)")," then what we really mean is that we want a point at ",r.createElement("i",null,"d"),' times the "normal vector" from point ',r.createElement("i",null,"B(t)"),', where the "normal" is a vector that runs perpendicular ("at a right angle") to the tangent at ',r.createElement("i",null,"B(t)"),". Easy enough:"),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/2cf48e2f8525258a3fa0fe4f10ec2acef67104b3.svg",style:{width:"10.125rem",height:"1.125rem"}})),r.createElement("p",null,"Now this still isn't very useful unless we know what the formula for ",r.createElement("i",null,"N(t)")," is, so let's find out.",r.createElement("i",null,"N(t)")," runs perpendicular to the original curve tangent, and we know that the tangent is simply",r.createElement("i",null,"B'(t)"),", so we could just rotate that 90 degrees and be done with it. However, we need to ensure that ",r.createElement("i",null,"N(t)")," has the same magnitude for every ",r.createElement("i",null,"t"),", or the offset curve won't be at a uniform distance, thus not being an offset curve at all. The easiest way to guarantee this is to make sure",r.createElement("i",null,"N(t)")," always has length 1, which we can achieve by dividing ",r.createElement("i",null,"B'(t)")," by its magnitude:"),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/664fba98ea17b358941b579115bf063edf87ae17.svg",style:{width:"9.450000000000001rem",height:"3.15rem"}})),r.createElement("p",null,"Determining the length requires computing an arc length, and this is where things get Tricky with a capital T. First off, to compute arc length from some start ",r.createElement("i",null,"a")," to end ",r.createElement("i",null,"b"),', we must use the formula we saw earlier. Noting that "length" is usually denoted with double vertical bars:'),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/f6d8c2965b02363e092acb00bbc1398cfbb170a4.svg",style:{width:"12.45015rem",height:"2.6248500000000003rem"}})),r.createElement("p",null,"So if we want the length of the tangent, we plug in ",r.createElement("i",null,"B'(t)"),", with ",r.createElement("i",null,"t = 0")," as start and",r.createElement("i",null,"t = 1")," as end:"),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/1f024282044316a9e4b3de2c855d2ceb96aff056.svg",style:{width:"15.150150000000002rem",height:"2.6248500000000003rem"}})),r.createElement("p",null,"And that's where things go wrong. It doesn't even really matter what the second derivative for ",r.createElement("i",null,"B(t)"),"is, that square root is screwing everything up, because it turns our nice polynomials into things that are no longer polynomials."),r.createElement("p",null,"There is a small class of polynomials where the square root is also a polynomial, but they're utterly useless to us: any polynomial with unweighted binomial coefficients has a square root that is also a polynomial. Now, you might think that Bézier curves are just fine because they do, but they don't; remember that only the ",r.createElement("strong",null,"base")," function has binomial coefficients. That's before we factor in our coordinates, which turn it into a non-binomial polygon. The only way to make sure the functions stay binomial is to make all our coordinates have the same value. And that's not a curve, that's a point. We can already create offset curves for points, we call them circles, and they have much simpler functions than Bézier curves."),r.createElement("p",null,"So, since the tangent length isn't a polynomial, the normalised tangent won't be a polynomial either, which means ",r.createElement("i",null,"N(t)")," won't be a polynomial, which means that ",r.createElement("i",null,"d")," times ",r.createElement("i",null,"N(t)")," won't be a polynomial, which means that, ultimately, ",r.createElement("i",null,"O(t)")," won't be a polynomial, which means that even if we can determine the function for ",r.createElement("i",null,"O(t)")," just fine (and that's far from trivial!), it simply cannot be represented as a Bézier curve."),r.createElement("p",null,"And that's one reason why Bézier curves are tricky: there are actually a ",r.createElement("i",null,"lot")," of curves that cannot be represent as a Bézier curve at all. They can't even model their own offset curves. They're weird that way. So how do all those other programs do it? Well, much like we're about to do, they cheat. We're going to approximate an offset curve in a way that will look relatively close to what the real offset curve would look like, if we could compute it.")),r.createElement("p",null,'So, you cannot offset a Bézier curve perfectly with another Bézier curve, no matter how high-order you make that other Bézier curve. However, we can chop up a curve into "safe" sub-curves (where safe means that all the control points are always on a single side of the baseline, and the midpoint of the curve at ',r.createElement("i",null,"t=0.5")," is roughly in the centre of the polygon defined by the curve coordinates) and then point-scale those sub-curves with respect to the curve's scaling origin (which is the intersection of the point normals at the start and end points)."),r.createElement("p",null,"A good way to do this reduction is to first find the curve's extreme points, as explained in the earlier section on curve extremities, and use these as initial splitting points. After this initial split, we can check each individual segment to see if it's \"safe enough\" based on where the center of the curve is. If the on-curve point for ",r.createElement("i",null,"t=0.5")," is too far off from the center, we simply split the segment down the middle. Generally this is more than enough to end up with safe segments."),r.createElement("p",null,"The following graphics show off curve offsetting, and you can use your up and down arrow keys to control the distance at which the curve gets offset. The curve first gets reduced to safe segments, each of which is then offset at the desired distance. Especially for simple curves, particularly easily set up for quadratic curves, no reduction is necessary, but the more twisty the curve gets, the more the curve needs to be reduced in order to get segments that can safely be scaled."),r.createElement(i,{preset:"simple",title:"Offsetting a quadratic Bézier curve",setup:this.setupQuadratic,draw:this.draw,onKeyDown:this.props.onKeyDown}),r.createElement(i,{preset:"simple",title:"Offsetting a cubic Bézier curve",setup:this.setupCubic,draw:this.draw,onKeyDown:this.props.onKeyDown}),r.createElement("p",null,"You may notice that this may still lead to small 'jumps' in the sub-curves when moving the curve around. This is caused by the fact that we're still performing a naive form of offsetting, moving the control points the same distance as the start and end points. If the curve is large enough, this may still lead to incorrect offsets.")); }});e.exports=o(s)},function(e,t,n){"use strict";var r=n(2),i=n(215),a=n(221),o=n(224),s=r.createClass({displayName:"GraduatedOffsetting",statics:{keyHandlingOptions:{propName:"distance",values:{38:1,40:-1}}},getDefaultProps:function(){return{title:"Graduated curve offsetting"}},setup:function(e,t){e.setCurve(t),e.distance=20},setupQuadratic:function(e){var t=e.getDefaultQuadratic();this.setup(e,t)},setupCubic:function(e){var t=e.getDefaultCubic();this.setup(e,t)},draw:function(e,t){e.reset(),e.drawSkeleton(t),e.drawCurve(t),e.setColor("blue");var n=t.outline(0,0,e.distance,e.distance);n.curves.forEach(function(t){return e.drawCurve(t)})},render:function(){return r.createElement("section",null,r.createElement(a,this.props),r.createElement("p",null,"What if we want to do graduated offsetting, starting at some distance ",r.createElement("i",null,"s")," but ending at some other distance ",r.createElement("i",null,"e"),'? well, if we can compute the length of a curve (which we can if we use the Legendre-Gauss quadrature approach) then we can also determine how far "along the line" any point on the curve is. With that knowledge, we can offset a curve so that its offset curve is not uniformly wide, but graduated between with two different offset widths at the start and end.'),r.createElement("p",null,'Like normal offsetting we cut up our curve in sub-curves, and then check at which distance along the original curve each sub-curve starts and ends, as well as to which point on the curve each of the control points map. This gives us the distance-along-the-curve for each interesting point in the sub-curve. If we call the total length of all sub-curves seen prior to seeing "the\\ current" sub-curve ',r.createElement("i",null,"S")," (and if the current sub-curve is the first one, ",r.createElement("i",null,"S")," is zero), and we call the full length of our original curve ",r.createElement("i",null,"L"),", then we get the following graduation values:"),r.createElement("ul",null,r.createElement("li",null,"start: map ",r.createElement("i",null,"S")," from interval (",r.createElement("i",null,"0,L"),") to interval ",r.createElement("i",null,"(s,e)")),r.createElement("li",null,"c1: ",r.createElement("i",null,"map(",r.createElement("strong",null,"S+d1"),", 0,L, s,e)"),", d1 = distance along curve to projection of c1"),r.createElement("li",null,"c2: ",r.createElement("i",null,"map(",r.createElement("strong",null,"S+d2"),", 0,L, s,e)"),", d2 = distance along curve to projection of c2"),r.createElement("li",null,"..."),r.createElement("li",null,"end: ",r.createElement("i",null,"map(",r.createElement("strong",null,"S+length(subcurve)"),", 0,L, s,e)"))),r.createElement("p",null,"At each of the relevant points (start, end, and the projections of the control points onto the curve) we know the curve's normal, so offsetting is simply a matter of taking our original point, and moving it along the normal vector by the offset distance for each point. Doing so will give us the following result (these have with a starting width of 0, and an end width of 40 pixels, but can be controlled with your up and down arrow keys):"),r.createElement(i,{preset:"simple",title:"Offsetting a quadratic Bézier curve",setup:this.setupQuadratic,draw:this.draw,onKeyDown:this.props.onKeyDown}),r.createElement(i,{preset:"simple",title:"Offsetting a cubic Bézier curve",setup:this.setupCubic,draw:this.draw,onKeyDown:this.props.onKeyDown}))}});e.exports=o(s)},function(e,t,n){"use strict";var r=n(2),i=n(215),a=n(221),o=Math.sin,s=Math.cos,l=r.createClass({displayName:"Circles",getDefaultProps:function(){return{title:"Circles and quadratic Bézier curves"}},setup:function(e){e.w=e.getPanelWidth(),e.h=e.getPanelHeight(),e.pad=20,e.r=e.w/2-e.pad,e.mousePt=!1,e.angle=0;var t={x:e.w-e.pad,y:e.h/2};e.setCurve(new e.Bezier(t,t,t))},draw:function(e,t){e.reset(),e.setColor("lightgrey"),e.drawGrid(1,1),e.setColor("red"),e.drawCircle({x:e.w/2,y:e.h/2},e.r),e.setColor("transparent"),e.setFill("rgba(100,255,100,0.4)");var n={x:e.w/2,y:e.h/2,r:e.r,s:e.angle<0?e.angle:0,e:e.angle<0?0:e.angle};e.drawArc(n),e.setColor("black"),e.drawSkeleton(t),e.drawCurve(t)},onMouseMove:function(e,t){var n=e.offsetX-t.w/2,r=e.offsetY-t.h/2,i=Math.atan2(r,n),a=t.curve.points,l=t.r,u=(s(i)-1)/o(i);a[1]={x:t.w/2+l*(s(i)-u*o(i)),y:t.w/2+l*(o(i)+u*s(i))},a[2]={x:t.w/2+t.r*s(i),y:t.w/2+t.r*o(i)},t.setCurve(new t.Bezier(a)),t.angle=i},render:function(){return r.createElement("section",null,r.createElement(a,this.props),r.createElement("p",null,"Circles and Bézier curves are very different beasts, and circles are infinitely easier to work with than Bézier curves. Their formula is much simpler, and they can be drawn more efficiently. But, sometimes you don't have the luxury of using circles, or ellipses, or arcs. Sometimes, all you have are Bézier curves. For instance, if you're doing font design, fonts have no concept of geometric shapes, they only know straight lines, and Bézier curves. OpenType fonts with TrueType outlines only know quadratic Bézier curves, and OpenType fonts with Type 2 outlines only know cubic Bézier curves. So how do you draw a circle, or an ellipse, or an arc?"),r.createElement("p",null,"You approximate."),r.createElement("p",null,"We already know that Bézier curves cannot model all curves that we can think of, and this includes perfect circles, as well as ellipses, and their arc counterparts. However, we can certainly approximate them to a degree that is visually acceptable. Quadratic and cubic curves offer us different curvature control, so in order to approximate a circle we will first need to figure out what the error is if we try to approximate arcs of increasing degree with quadratic and cubic curves, and where the coordinates even lie."),r.createElement("p",null,"Since arcs are mid-point-symmetrical, we need the control points to set up a symmetrical curve. For quadratic curves this means that the control point will be somewhere on a line that intersects the baseline at a right angle. And we don't get any choice on where that will be, since the derivatives at the start and end point have to line up, so our control point will lie at the intersection of the tangents at the start and end point."),r.createElement("p",null,"First, let's try to fit the quadratic curve onto a circular arc. In the following sketch you can move the mouse around over a unit circle, to see how well, or poorly, a quadratic curve can approximate the arc from (1,0) to where your mouse cursor is:"),r.createElement(i,{preset:"arcfitting",title:"Quadratic Bézier arc approximation",setup:this.setup,draw:this.draw,onMouseMove:this.onMouseMove}),r.createElement("p",null,"As you can see, things go horribly wrong quite quickly; even trying to approximate a quarter circle using a quadratic curve is a bad idea. An eighth of a turns might look okay, but how okay is okay? Let's apply some maths and find out. What we're interested in is how far off our on-curve coordinates are with respect to a circular arc, given a specific start and end angle. We'll be looking at how much space there is between the circular arc, and the quadratic curve's midpoint."),r.createElement("p",null,"We start out with our start and end point, and for convenience we will place them on a unit circle (a circle around 0,0 with radius 1), at some angle ",r.createElement("i",null,"φ"),":"),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/ef34ab8f466ed3294895135a346b55ada05d779d.svg",style:{width:"13.275rem",height:"2.6248500000000003rem"}})),r.createElement("p",null,"What we want to find is the intersection of the tangents, so we want a point C such that:"),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/5660e8512b07dbac7fcf04633de8002fa25aa962.svg",style:{width:"20.77515rem",height:"2.6248500000000003rem"}})),r.createElement("p",null,"i.e. we want a point that lies on the vertical line through A (at some distance ",r.createElement("i",null,"a"),"from A) and also lies on the tangent line through B (at some distance ",r.createElement("i",null,"b")," from B). Solving this gives us:"),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/d16e7a1c1e9686e1afb82f4ffcec07078d264565.svg",style:{width:"14.99985rem",height:"2.7rem"}})),r.createElement("p",null,"First we solve for ",r.createElement("i",null,"b"),":"),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/3128b31a874166ebe4479d3002d70f280de375a1.svg",style:{width:"39.07485rem",height:"1.125rem"}})),r.createElement("p",null,"which yields:"),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/02b158f9ef2191b970dc2fe69c0903eba2b1f8b5.svg",style:{width:"6.9750000000000005rem",height:"2.7rem"}})),r.createElement("p",null,"which we can then substitute in the expression for ",r.createElement("i",null,"a"),":"),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/e940f26afcd5f80371b6b72a8f52e217da64721d.svg",style:{width:"16.50015rem",height:"13.275rem"}})),r.createElement("p",null,"A quick check shows that plugging these values for ",r.createElement("i",null,"a")," and ",r.createElement("i",null,"b")," into the expressions for C",r.createElement("sub",null,"x")," and C",r.createElement("sub",null,"y"),' give the same x/y coordinates for both "',r.createElement("i",null,"a"),' away from A" and "',r.createElement("i",null,"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 ",r.createElement("i",null,"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:"),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/0b80423188012451e0400f473c19729eb2bad654.svg",style:{width:"13.350150000000001rem",height:"2.025rem"}})),r.createElement("p",null,"We compute T, observing that if ",r.createElement("i",null,"t=0.5"),", the polynomial values (1-t)², 2(1-t)t, and t² are 0.25, 0.5, and 0.25 respectively:"),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/bc50559ff8bd9062694a449aae5f6f85f91de909.svg",style:{width:"18.225rem",height:"2.17485rem"}})),r.createElement("p",null,"Which, worked out for the x and y components, gives:"),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/6e512d83529089b2294b45659b826bb24a598356.svg",style:{width:"29.025000000000002rem",height:"5.175rem"}})),r.createElement("p",null,"And the distance between these two is the standard Euclidean distance:"),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/d13ad085587983ba3fa6fe9051dcc2f6a3d0917c.svg",style:{width:"27.675rem",height:"9.525150000000002rem"}})),r.createElement("p",null,"So, what does this distance function look like when we plot it for a number of ranges for the angle φ, such as a half circle, quarter circle and eighth circle?"),r.createElement("table",null,r.createElement("tbody",null,r.createElement("tr",null,r.createElement("td",null,r.createElement("p",null,r.createElement("img",{src:"images/arc-q-pi.gif"})),r.createElement("p",null,"plotted for 0 ≤ φ ≤ π:")),r.createElement("td",null,r.createElement("p",null,r.createElement("img",{src:"images/arc-q-pi2.gif"})),r.createElement("p",null,"plotted for 0 ≤ φ ≤ ½π:")),r.createElement("td",null,this.props.showhref?"http://www.wolframalpha.com/input/?i=plot+sqrt%28%281%2F4+*+%28sin%28x%29+%2B+2tan%28x%2F2%29%29+-+sin%28x%2F2%29%29%5E2+%2B+%282sin%5E4%28x%2F4%29%29%5E2%29+for+0+%3C%3D+x+%3C%3D+pi%2F4":null,r.createElement("p",null,r.createElement("img",{src:"images/arc-q-pi4.gif"})),r.createElement("p",null,"plotted for 0 ≤ φ ≤ ¼π:"))))),r.createElement("p",null,"We now see why the eighth circle arc looks decent, but the quarter circle arc doesn't: an error of roughly 0.06 at ",r.createElement("i",null,"t=0.5")," means we're 6% off the mark... we will already be off by one pixel on a circle with pixel radius 17. Any decent sized quarter circle arc, say with radius 100px, will be way off if approximated by a quadratic curve! For the eighth circle arc, however, the error is only roughly 0.003, or 0.3%, which explains why it looks so close to the actual eighth circle arc. In fact, if we want a truly tiny error, like 0.001, we'll have to contend with an angle of (rounded) 0.593667, which equates to roughly 34 degrees. We'd need 11 quadratic curves to form a full circle with that precision! (technically, 10 and ten seventeenth, but we can't do partial curves, so we have to round up). That's a whole lot of curves just to get a shape that can be drawn using a simple function!"),r.createElement("p",null,"In fact, let's flip the function around, so that if we plug in the precision error, labelled ε, we get back the maximum angle for that precision:"),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/61a938fa10b77e8c41c3c064ed39bd1145d6bbcc.svg",style:{width:"18.225rem",height:"4.5rem"}})),r.createElement("p",null,"And frankly, things are starting to look a bit ridiculous at this point, we're doing way more maths than we've ever done, but thankfully this is as far as we need the maths to take us: If we plug in the precisions 0.1, 0.01, 0.001 and 0.0001 we get the radians values 1.748, 1.038, 0.594 and 0.3356; in degrees, that means we can cover roughly 100 degrees (requiring four curves), 59.5 degrees (requiring six curves), 34 degrees (requiring 11 curves), and 19.2 degrees (requiring a whopping nineteen curves). "),r.createElement("p",null,"The bottom line? ",r.createElement("strong",null,"Quadratic curves are kind of lousy")," if you want circular (or elliptical, which are circles that have been squashed in one dimension) curves. We can do better, even if it's just by raising the order of our curve once. So let's try the same thing for cubic curves."))}});e.exports=l},function(e,t,n){"use strict";var r=n(2),i=n(215),a=n(221),o=Math.sin,s=Math.cos,l=Math.tan,u=r.createClass({displayName:"CirclesCubic",getDefaultProps:function(){return{title:"Circles and cubic Bézier curves"}},setup:function(e){e.setSize(400,400),e.w=e.getPanelWidth(),e.h=e.getPanelHeight(),e.pad=80,e.r=e.w/2-e.pad,e.mousePt=!1,e.angle=0;var t={x:e.w-e.pad,y:e.h/2};e.setCurve(new e.Bezier(t,t,t,t))},guessCurve:function(e,t,n){var r={x:(e.x+n.x)/2,y:(e.y+n.y)/2},i={x:t.x+(t.x-r.x)/3,y:t.y+(t.y-r.y)/3},a=(n.x-e.x)/4,o=(n.y-e.y)/4,s={x:t.x-a,y:t.y-o},l={x:t.x+a,y:t.y+o},u={x:i.x+2*(s.x-i.x),y:i.y+2*(s.y-i.y)},c={x:i.x+2*(l.x-i.x),y:i.y+2*(l.y-i.y)},h={x:e.x+2*(u.x-e.x),y:e.y+2*(u.y-e.y)},d={x:n.x+2*(c.x-n.x),y:n.y+2*(c.y-n.y)};return[h,d]},draw:function(e,t){e.reset(),e.setColor("lightgrey"),e.drawGrid(1,1),e.setColor("rgba(255,0,0,0.4)"),e.drawCircle({x:e.w/2,y:e.h/2},e.r),e.setColor("transparent"),e.setFill("rgba(100,255,100,0.4)");var n={x:e.w/2,y:e.h/2,r:e.r,s:e.angle<0?e.angle:0,e:e.angle<0?0:e.angle};e.drawArc(n);var r={x:e.w/2+e.r*s(e.angle/2),y:e.w/2+e.r*o(e.angle/2)},i=t.points[0],a=t.points[3],l=this.guessCurve(i,r,a),u=new e.Bezier([i,l[0],l[1],a]);e.setColor("rgb(140,140,255)"),e.drawLine(u.points[0],u.points[1]),e.drawLine(u.points[1],u.points[2]),e.drawLine(u.points[2],u.points[3]),e.setColor("blue"),e.drawCurve(u),e.drawCircle(u.points[1],3),e.drawCircle(u.points[2],3),e.drawSkeleton(t),e.setColor("black"),e.drawLine(t.points[1],t.points[2]),e.drawCurve(t)},onMouseMove:function(e,t){var n=e.offsetX-t.w/2,r=e.offsetY-t.h/2;if(!(n>t.w/2)){var i=Math.atan2(r,n);0>i&&(i=2*Math.PI+i);var a=t.curve.points,u=t.r,c=4*l(i/4)/3;a[1]={x:t.w/2+u,y:t.w/2+u*c},a[2]={x:t.w/2+t.r*(s(i)+c*o(i)),y:t.w/2+t.r*(o(i)-c*s(i))},a[3]={x:t.w/2+t.r*s(i),y:t.w/2+t.r*o(i)},t.setCurve(new t.Bezier(a)),t.angle=i}},drawCircle:function(e){e.setSize(325,325),e.reset();var t=e.getPanelWidth(),n=e.getPanelHeight(),r=60,i=t/2-r,a=.55228,o={x:-r/2,y:-r/4},s=new e.Bezier([{x:t/2+i,y:n/2},{x:t/2+i,y:n/2+a*i},{x:t/2+a*i,y:n/2+i},{x:t/2,y:n/2+i}]);e.setColor("lightgrey"),e.drawLine({x:0,y:n/2},{x:t+r,y:n/2},o),e.drawLine({x:t/2,y:0},{x:t/2,y:n+r},o);var l=s.points;e.setColor("red"),e.drawPoint(l[0],o),e.drawPoint(l[1],o),e.drawPoint(l[2],o),e.drawPoint(l[3],o),e.drawCurve(s,o),e.setColor("rgb(255,160,160)"),e.drawLine(l[0],l[1],o),e.drawLine(l[1],l[2],o),e.drawLine(l[2],l[3],o),e.setFill("red"),e.text(l[0].x-t/2+","+(l[0].y-n/2),{x:l[0].x+7,y:l[0].y+3},o),e.text(l[1].x-t/2+","+(l[1].y-n/2),{x:l[1].x+7,y:l[1].y+3},o),e.text(l[2].x-t/2+","+(l[2].y-n/2),{x:l[2].x+7,y:l[2].y+7},o),e.text(l[3].x-t/2+","+(l[3].y-n/2),{x:l[3].x,y:l[3].y+13},o),l.forEach(function(e){e.x=-(e.x-t)}),e.setColor("blue"),e.drawCurve(s,o),e.drawLine(l[2],l[3],o),e.drawPoint(l[2],o),e.setFill("blue"),e.text("reflected",{x:l[2].x-r/2,y:l[2].y+13},o),e.setColor("rgb(200,200,255)"),e.drawLine(l[1],l[0],o),e.drawPoint(l[1],o),l.forEach(function(e){e.y=-(e.y-n)}),e.setColor("green"),e.drawCurve(s,o),l.forEach(function(e){e.x=-(e.x-t)}),e.setColor("purple"),e.drawCurve(s,o),e.drawLine(l[1],l[0],o),e.drawPoint(l[1],o),e.setFill("purple"),e.text("reflected",{x:l[1].x+10,y:l[1].y+3},o),e.setColor("rgb(200,200,255)"),e.drawLine(l[2],l[3],o),e.drawPoint(l[2],o),e.setColor("black"),e.setFill("black"),e.drawLine({x:t/2,y:n/2},{x:t/2+i-2,y:n/2},o),e.drawLine({x:t/2,y:n/2},{x:t/2,y:n/2+i-2},o),e.text("r = "+i,{x:t/2+i/3,y:n/2+10},o)},render:function(){return r.createElement("section",null,r.createElement(a,this.props),r.createElement("p",null,"In the previous section we tried to approximate a circular arc with a quadratic curve, and it mostly made us unhappy. Cubic curves are much better suited to this task, so what do we need to do?"),r.createElement("p",null,'For cubic curves, we basically want the curve to pass through three points on the circle: the start point, the mid point at "angle/2", and the end point at "angle". We then also need to make sure the control points are such that the start and end tangent lines line up with the circle\'s tangent lines at the start and end point.'),r.createElement("p",null,'The first thing we can do is "guess" what the curve should look like, based on the previously outlined curve-through-three-points procedure. This will give use a curve with correct start, mid and end points, but possibly incorrect derivatives at the start and end, because the control points might not be in the right spot. We can then slide the control points along the lines that connect them to their respective end point, until they effect the corrected derivative at the start and end points. However, if you look back at the section on fitting curves through three points, the rules used were such that they optimized for a near perfect hemisphere, so using the same guess won\'t be all that useful: guessing the solution based on knowing the solution is not really guessing.'),r.createElement("p",null,'So have a graphical look at a "bad" guess versus the true fit, where we\'ll be using the bad guess and the description in the second paragraph to derive the maths for the true fit:'),r.createElement(i,{preset:"arcfitting",title:"Cubic Bézier arc approximation",setup:this.setup,draw:this.draw,onMouseMove:this.onMouseMove}),r.createElement("p",null,'We see two curves here; in blue, our "guessed" curve and its control points, and in grey/black, the true curve fit, with proper control points that were shifted in, along line between our guessed control points, such that the derivatives at the start and end points are correct.'),r.createElement("p",null,'We can already seethat cubic curves are a lot better than quadratic curves, and don\'t look all that wrong until we go well past a quarter circle; ⅜th starts to hint at problems, and half a circle has an obvious "gap" between the real circle and the cubic approximation. Anything past that just looks plain ridiculous... but quarter curves actually look pretty okay!'),r.createElement("p",null,'So, maths time again: how okay is "okay"? Let\'s apply some more maths to find out.'),r.createElement("p",null,"Unlike for the quadratic curve, we can't use ",r.createElement("i",null,"t=0.5")," as our reference point because by its very nature it's one of the three points that are actually guaranteed to lie on the circular curve. Instead, we need a different ",r.createElement("i",null,"t")," value. If we run some analysis on the curve we find that the actual ",r.createElement("i",null,"t"),' value at which the curve is furthest from what it should be is 0.211325 (rounded), but we don\'t know "why", since finding this value involves root-finding, and is nearly impossible to do symbolically without pages and pages of math just to express one of the possible solutions.'),r.createElement("p",null,"So instead of walking you through the derivation for that value, let's simply take that ",r.createElement("i",null,"t")," value and see what the error is for circular arcs with an angle ranging from 0 to 2π:"),r.createElement("table",null,r.createElement("tbody",null,r.createElement("tr",null,r.createElement("td",null,r.createElement("p",null,r.createElement("img",{src:"images/arc-c-2pi.gif"})),r.createElement("p",null,"plotted for 0 ≤ φ ≤ 2π:")),r.createElement("td",null,r.createElement("p",null,r.createElement("img",{src:"images/arc-c-pi.gif"})),r.createElement("p",null,"plotted for 0 ≤ φ ≤ π:")),r.createElement("td",null,r.createElement("p",null,r.createElement("img",{src:"images/arc-c-pi2.gif"})),r.createElement("p",null,"plotted for 0 ≤ φ ≤ ½π:"))))),r.createElement("p",null,"We see that cubic Bézier curves are much better when it comes to approximating circular arcs, with an error of less than 0.027 at the two \"bulge\" points for a quarter circle (which had an error of 0.06 for quadratic curves at the mid point), and an error near 0.001 for an eighth of a circle, so we're getting less than half the error for a quarter circle, or: at a slightly lower error, we're getting twice the arc. This makes cubic curves quite useful!"),r.createElement("p",null,'In fact, the precision of a cubic curve at a quarter circle is considered "good enough" by so many people that it\'s generally considered "just fine" to use four cubic Bézier curves to fake a full circle when no circle primitives are available; generally, people won\'t notice that it\'s not a real circle unless you also happen to overlay an actual circle, so that the difference becomes obvious.'),r.createElement("p",null,'So with the error analysis out of the way, how do we actually compute the coordinates needed to get that "true fit" cubic curve? The first observation is that we already know the start and end points, because they\'re the same as for the quadratic attempt:'),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/ef34ab8f466ed3294895135a346b55ada05d779d.svg",style:{width:"13.275rem",height:"2.6248500000000003rem"}})),r.createElement("p",null,"But we now need to find two control points, rather than one. If we want the derivatives at the start and end point to match the circle, then the first control point can only lie somewhere on the vertical line through S, and the second control point can only lie somewhere on the line tangent to point E, which means:"),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/4df65dae78bc5a0e6c5f23a2faae9a9d7a8b39b3.svg",style:{width:"8.325000000000001rem",height:"2.55015rem"}})),r.createElement("p",null,'where "a" is some scaling factor, and:'),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/cb32f8f9c3ae2b264a48003c237a798d02dc8935.svg",style:{width:"11.62485rem",height:"2.6248500000000003rem"}})),r.createElement("p",null,'where "b" is also some scaling factor.'),r.createElement("p",null,"Starting with this information, we slowly maths our way to success, but I won't lie: the maths for this is pretty trig-heavy, and it's easy to get lost if you remember (or know!) some of the core trigonoetric identities, so if you just want to see the final result just skip past the next section!"),r.createElement("div",{className:"note"},r.createElement("h2",null,"Let's do this thing."),r.createElement("p",null,"Unlike for the quadratic case, we need some more information in order to compute ",r.createElement("i",null,"a")," and ",r.createElement("i",null,"b"),", since they're no longer dependent variables. First, we observe that the curve is symmetrical, so whatever values we end up finding for C",r.createElement("sub",null,"1")," will apply to C",r.createElement("sub",null,"2")," as well (rotated along its tangent), so we'll focus on finding the location of C",r.createElement("sub",null,"1")," only. So here's where we do something that you might not expect: we're going to ignore for a moment, because we're going to have a much easier time if we just solve this problem with geometry first, then move to calculus to solve a much simpler problem."),r.createElement("p",null,"If we look at the triangle that is formed between our starting point, or initial guess C",r.createElement("sub",null,"1"),"and our real C",r.createElement("sub",null,"1"),", there's something funny going on: if we treat the line ","{","start,guess","}"," as our opposite side, the line ","{","guess,real","}"," as our adjacent side, with ","{","start,real","}"," our hypothenuse, then the angle for the corner hypothenuse/adjacent is half that of the arc we're covering. Try it: if you place the end point at a quarter circle (pi/2, or 90 degrees), the angle in our triangle is half a quarter (pi/4, or 45 degrees). With that knowledge, and a knowledge of what the length of any of our lines segments are (as a function), we can determine where our control points are, and thus have everything we need to find the error distance function. Of the three lines, the one we can easiest determine is ","{","start,guess","}",", so let's find out what the guessed control point is. Again geometrically, because we have the benefit of an on-curve ",r.createElement("i",null,"t=0.5")," value."),r.createElement("p",null,"The distance from our guessed point to the start point is exactly the same as the projection distance we looked at earlier. Using ",r.createElement("i",null,"t=0.5"),' as our point "B" in the "A,B,C" projection, then we know the length of the line segment ',"{","C,A","}",", since it's d",r.createElement("sub",null,"1")," = ","{","A,B","}"," + d",r.createElement("sub",null,"2")," = ","{","B,C","}",":"),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/b15a274c1e0a6aeeaf517b5d2c8ee0a7997dd617.svg",style:{width:"27.675rem",height:"2.32515rem"}})),r.createElement("p",null,"So that just leaves us to find the distance from ",r.createElement("i",null,"t=0.5")," to the baseline for an arbitrary angle φ, which is the distance from the centre of the circle to our ",r.createElement("i",null,"t=0.5")," point, minus the distance from the centre to the line that runs from start point to end point. The first is the same as the point P we found for the quadratic curve:"),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/0b80423188012451e0400f473c19729eb2bad654.svg",style:{width:"13.350150000000001rem",height:"2.025rem"}})),r.createElement("p",null,"And the distance from the origin to the line start/end is another application of angles, since the triangle ","{","origin,start,C","}"," has known angles, and two known sides. We can find the length of the line ","{","origin,C","}",", which lets us trivially compute the coordinate for C:"),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/9be55fb38d5d30bbc6c7140afb1c7bc097bc044e.svg",style:{width:"18.675rem",height:"5.3248500000000005rem"}})),r.createElement("p",null,"With the coordinate C, and knowledge of coordinate B, we can determine coordinate A, and get a vector that is identical to the vector ","{","start,guess","}",":"),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/262f2eca63105779f30a0a5445cf76f60786039a.svg",style:{width:"27.675rem",height:"3.67515rem"}})),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/0e83ebbac13a84ef6036bf4be57b3d1b6cb316f8.svg",style:{width:"14.99985rem",height:"3.29985rem"}})),r.createElement("p",null,"Which means we can now determine the distance ","{","start,guessed","}",", which is the same as the distance","{","C,A","}",", and use that to determine the vertical distance from our start point to our C",r.createElement("sub",null,"1"),":"),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/c87e454fb11ef7f15c7386e83ca1ce41a004d8a7.svg",style:{width:"17.850150000000003rem",height:"4.64985rem"}})),r.createElement("p",null,"And after this tedious detour to find the coordinate for C",r.createElement("sub",null,"1"),", we can find C",r.createElement("sub",null,"2")," fairly simply, since it's lies at distance -C",r.createElement("sub",null,"1y")," along the end point's tangent:"),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/25f027074b6af8ca7b640e27636e3bf89c28afdb.svg",style:{width:"36.675000000000004rem",height:"6.89985rem"}})),r.createElement("p",null,"And that's it, we have all four points now for an approximation of an arbitrary circular arc with angle φ.")),r.createElement("p",null,"So, to recap, given an angle φ, the new control coordinates are:"),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/c4d82e44d1c67dda8ba26aa6da0f406d05eba618.svg",style:{width:"15.075000000000001rem",height:"2.55015rem"}})),r.createElement("p",null,"and"),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/3a4b1ee00eebb7697e5513ef9df673928913252e.svg",style:{width:"23.02515rem",height:"2.6248500000000003rem"}})),r.createElement("p",null,'And, because the "quarter curve" special case comes up so incredibly often, let\'s look at what these new control points mean for the curve coordinates of a quarter curve, by simply filling in φ = π/2:'),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/63e0936b4849d4cdbb9a2e0909181259be951e4d.svg",style:{width:"28.65015rem",height:"1.94985rem"}})),r.createElement("p",null,"Which, in decimal values, rounded to six significant digits, is:"),r.createElement("p",null,r.createElement("img",{className:"LaTeX SVG",src:"images/latex/fd12e65204a31319b66355c6ff99e6b3d9603b05.svg",style:{width:"28.65015rem",height:"1.125rem"}})),r.createElement("p",null,"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:"),r.createElement(i,{preset:"simple",title:"Cubic Bézier circle approximation",draw:this.drawCircle,"static":!0}))}});e.exports=u},function(e,t,n){"use strict";var r=n(2),i=n(215),a=n(221),o=n(224),s=Math.atan2,l=Math.PI,u=2*l,c=Math.cos,h=Math.sin,d=r.createClass({displayName:"Introduction",statics:{keyHandlingOptions:{propName:"error",values:{38:.1,40:-.1},controller:function(e){e.error<.1&&(e.error=.1)}}},getDefaultProps:function(){return{title:"Approximating Bézier curves with circular arcs"}},setupCircle:function(e){var t=new e.Bezier(70,70,140,40,240,130);e.setCurve(t)},setupQuadratic:function(e){var t=e.getDefaultQuadratic();e.setCurve(t)},setupCubic:function(e){var t=e.getDefaultCubic();e.setCurve(t),e.error=.5},getCCenter:function(e,t,n,r){var i,a=n.x-t.x,o=n.y-t.y,d=r.x-n.x,p=r.y-n.y,f=a*c(l/2)-o*h(l/2),m=a*h(l/2)+o*c(l/2),g=d*c(l/2)-p*h(l/2),v=d*h(l/2)+p*c(l/2),y=(t.x+n.x)/2,w=(t.y+n.y)/2,b=(n.x+r.x)/2,_=(n.y+r.y)/2,x=y+f,E=w+m,C=b+g,N=_+v,k=e.utils.lli8(y,w,x,E,b,_,C,N),S=e.utils.dist(k,t),P=s(t.y-k.y,t.x-k.x),O=s(n.y-k.y,n.x-k.x),D=s(r.y-k.y,r.x-k.x); -return D>P?((P>O||O>D)&&(P+=u),P>D&&(i=D,D=P,P=i)):O>D&&P>O?(i=D,D=P,P=i):D+=u,k.s=P,k.e=D,k.r=S,k},drawCircle:function(e,t){e.reset();var n=t.points,r=this.getCCenter(e,n[0],n[1],n[2]);e.setColor("grey"),e.drawCircle(r,e.utils.dist(r,n[0])),e.setColor("black"),n.forEach(function(t){return e.drawCircle(t,3)});var i;e.setColor("blue"),e.drawLine(n[0],n[1]),i={x:(n[0].x+n[1].x)/2,y:(n[0].y+n[1].y)/2},e.drawLine(i,{x:r.x+(r.x-i.x),y:r.y+(r.y-i.y)}),e.setColor("red"),e.drawLine(n[1],n[2]),i={x:(n[1].x+n[2].x)/2,y:(n[1].y+n[2].y)/2},e.drawLine(i,{x:r.x+(r.x-i.x),y:r.y+(r.y-i.y)}),e.setColor("green"),e.drawLine(n[2],n[0]),i={x:(n[2].x+n[0].x)/2,y:(n[2].y+n[0].y)/2},e.drawLine(i,{x:r.x+(r.x-i.x),y:r.y+(r.y-i.y)}),e.setColor("black"),e.drawPoint(r),e.setFill("black"),e.text("Intersection point",r,{x:-25,y:10})},drawSingleArc:function(e,t){e.reset();var n=t.arcs(e.error);e.drawSkeleton(t),e.drawCurve(t);var r=n[0];e.setColor("red"),e.setFill("rgba(255,0,0,0.2)"),e.debug=!0,e.drawArc(r),e.setFill("black"),e.text("Arc approximation with total error "+e.utils.round(e.error,1),{x:10,y:15})},drawArcs:function(e,t){e.reset();var n=t.arcs(e.error);e.drawSkeleton(t),e.drawCurve(t),n.forEach(function(t){e.setRandomColor(.3),e.setFill(e.getColor()),e.drawArc(t)}),e.setFill("black"),e.text("Arc approximation with total error "+e.utils.round(e.error,1)+" per arc segment",{x:10,y:15})},render:function(){return r.createElement("section",null,r.createElement(a,this.props),r.createElement("p",null,"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."),r.createElement("p",null,"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."),r.createElement("p",null,'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.'),r.createElement("p",null,"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 ",r.createElement("a",{href:"https://en.wikipedia.org/wiki/Chord_%28geometry%29"},"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."),r.createElement("p",null,"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."),r.createElement("p",null,"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!"),r.createElement(i,{preset:"simple",title:"Finding a circle through three points",setup:this.setupCircle,draw:this.drawCircle}),r.createElement("p",null,"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."),r.createElement("p",null,"So how can we convert a Bezier curve into a (sequence of) circular arc(s)?"),r.createElement("ul",null,r.createElement("li",null,"Start at ",r.createElement("em",null,"t=0")),r.createElement("li",null,"Pick two points further down the curve at some value ",r.createElement("em",null,"m = t + n")," and ",r.createElement("em",null,"e = t + 2n")),r.createElement("li",null,"Find the arc that these points define"),r.createElement("li",null,"Determine how close the found arc is to the curve:",r.createElement("ul",null,r.createElement("li",null,"Pick two additional points ",r.createElement("em",null,"e1 = t + n/2")," and ",r.createElement("em",null,"e2 = t + n + n/2"),"."),r.createElement("li",null,"These points, if the arc is a good approximation of the curve interval chosen, should lie ",r.createElement("em",null,"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."),r.createElement("li",null,"For point points, determine the (absolute) error between the radius of the circle, and the",r.createElement("em",null,"actual")," distance from the center of the circle to the point on the curve."),r.createElement("li",null,"If this error is too high, we consider the arc bad, and try a smaller interval.")))),r.createElement("p",null,"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 ",r.createElement("em",null,"t=0.5"),", and then we start performing a ",r.createElement("a",{href:"https://en.wikipedia.org/wiki/Binary_search_algorithm"},"Binary Search"),"."),r.createElement("ol",null,r.createElement("li",null,"We start with ",1),r.createElement("li",null,"That'll fail, so we retry with the interval halved: ",.5),r.createElement("ul",null,r.createElement("li",null,"If that arc's good, we move back up by half distance: ",.75,"."),r.createElement("li",null,"However, if the arc was still bad, we move ",r.createElement("em",null,"down")," by half the distance: ",.25,".")),r.createElement("li",null,"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")),r.createElement("p",null,"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 ",r.createElement("em",null,"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."),r.createElement(i,{preset:"simple",title:"Arc approximation of a Bézier curve",setup:this.setupCubic,draw:this.drawSingleArc,onKeyDown:this.props.onKeyDown}),r.createElement("p",null,"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 ",r.createElement("em",null,"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:"),r.createElement(i,{preset:"simple",title:"Arc approximation of a Bézier curve",setup:this.setupCubic,draw:this.drawArcs,onKeyDown:this.props.onKeyDown}),r.createElement("p",null,'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 straight-forward, 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 betwee 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!'))}});e.exports=o(d)},function(e,t,n){"use strict";var r=n(2),i=n(165),a=i.Link,o=n(212),s=Object.keys(o),l=r.createClass({displayName:"Navigation",generateNavItem:function(e,t){var n=o[e],i=n.getDefaultProps().title,s=r.createElement("a",{href:"#"+e},i);return this.props.fullNav&&(s=r.createElement(a,{to:e},i)),r.createElement("li",{key:e,"data-number":t},s)},generateNav:function(){return this.props.compact?null:r.createElement("div",{ref:"navigation"},r.createElement("navigation",{className:this.props.compact?"compact":null},r.createElement("ul",{className:"navigation"},s.map(this.generateNavItem))))},render:function(){return this.generateNav()}});e.exports=l},function(e,t,n){"use strict";var r=n(2),i=r.createClass({displayName:"Footer",render:function(){return r.createElement("footer",{className:"copyright"},'This article is © 2011-2016 to me, Mike "Pomax" Kamermans, but the text, code, and images are ',r.createElement("a",{href:"https://github.com/Pomax/bezierinfo/blob/gh-pages/LICENSE.md"},"almost no rights reserved"),". Go do something cool with it!")}});e.exports=i}]); \ No newline at end of file +return D>P?((P>O||O>D)&&(P+=u),P>D&&(i=D,D=P,P=i)):O>D&&P>O?(i=D,D=P,P=i):D+=u,k.s=P,k.e=D,k.r=S,k},drawCircle:function(e,t){e.reset();var n=t.points,r=this.getCCenter(e,n[0],n[1],n[2]);e.setColor("grey"),e.drawCircle(r,e.utils.dist(r,n[0])),e.setColor("black"),n.forEach(function(t){return e.drawCircle(t,3)});var i;e.setColor("blue"),e.drawLine(n[0],n[1]),i={x:(n[0].x+n[1].x)/2,y:(n[0].y+n[1].y)/2},e.drawLine(i,{x:r.x+(r.x-i.x),y:r.y+(r.y-i.y)}),e.setColor("red"),e.drawLine(n[1],n[2]),i={x:(n[1].x+n[2].x)/2,y:(n[1].y+n[2].y)/2},e.drawLine(i,{x:r.x+(r.x-i.x),y:r.y+(r.y-i.y)}),e.setColor("green"),e.drawLine(n[2],n[0]),i={x:(n[2].x+n[0].x)/2,y:(n[2].y+n[0].y)/2},e.drawLine(i,{x:r.x+(r.x-i.x),y:r.y+(r.y-i.y)}),e.setColor("black"),e.drawPoint(r),e.setFill("black"),e.text("Intersection point",r,{x:-25,y:10})},drawSingleArc:function(e,t){e.reset();var n=t.arcs(e.error);e.drawSkeleton(t),e.drawCurve(t);var r=n[0];e.setColor("red"),e.setFill("rgba(255,0,0,0.2)"),e.debug=!0,e.drawArc(r),e.setFill("black"),e.text("Arc approximation with total error "+e.utils.round(e.error,1),{x:10,y:15})},drawArcs:function(e,t){e.reset();var n=t.arcs(e.error);e.drawSkeleton(t),e.drawCurve(t),n.forEach(function(t){e.setRandomColor(.3),e.setFill(e.getColor()),e.drawArc(t)}),e.setFill("black"),e.text("Arc approximation with total error "+e.utils.round(e.error,1)+" per arc segment",{x:10,y:15})},render:function(){return r.createElement("section",null,r.createElement(a,this.props),r.createElement("p",null,"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."),r.createElement("p",null,"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."),r.createElement("p",null,'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.'),r.createElement("p",null,"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 ",r.createElement("a",{href:"https://en.wikipedia.org/wiki/Chord_%28geometry%29"},"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."),r.createElement("p",null,"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."),r.createElement("p",null,"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!"),r.createElement(i,{preset:"simple",title:"Finding a circle through three points",setup:this.setupCircle,draw:this.drawCircle}),r.createElement("p",null,"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."),r.createElement("p",null,"So how can we convert a Bezier curve into a (sequence of) circular arc(s)?"),r.createElement("ul",null,r.createElement("li",null,"Start at ",r.createElement("em",null,"t=0")),r.createElement("li",null,"Pick two points further down the curve at some value ",r.createElement("em",null,"m = t + n")," and ",r.createElement("em",null,"e = t + 2n")),r.createElement("li",null,"Find the arc that these points define"),r.createElement("li",null,"Determine how close the found arc is to the curve:",r.createElement("ul",null,r.createElement("li",null,"Pick two additional points ",r.createElement("em",null,"e1 = t + n/2")," and ",r.createElement("em",null,"e2 = t + n + n/2"),"."),r.createElement("li",null,"These points, if the arc is a good approximation of the curve interval chosen, should lie ",r.createElement("em",null,"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."),r.createElement("li",null,"For point points, determine the (absolute) error between the radius of the circle, and the",r.createElement("em",null,"actual")," distance from the center of the circle to the point on the curve."),r.createElement("li",null,"If this error is too high, we consider the arc bad, and try a smaller interval.")))),r.createElement("p",null,"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 ",r.createElement("em",null,"t=0.5"),", and then we start performing a ",r.createElement("a",{href:"https://en.wikipedia.org/wiki/Binary_search_algorithm"},"Binary Search"),"."),r.createElement("ol",null,r.createElement("li",null,"We start with ",1),r.createElement("li",null,"That'll fail, so we retry with the interval halved: ",.5),r.createElement("ul",null,r.createElement("li",null,"If that arc's good, we move back up by half distance: ",.75,"."),r.createElement("li",null,"However, if the arc was still bad, we move ",r.createElement("em",null,"down")," by half the distance: ",.25,".")),r.createElement("li",null,"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")),r.createElement("p",null,"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 ",r.createElement("em",null,"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."),r.createElement(i,{preset:"simple",title:"Arc approximation of a Bézier curve",setup:this.setupCubic,draw:this.drawSingleArc,onKeyDown:this.props.onKeyDown}),r.createElement("p",null,"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 ",r.createElement("em",null,"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:"),r.createElement(i,{preset:"simple",title:"Arc approximation of a Bézier curve",setup:this.setupCubic,draw:this.drawArcs,onKeyDown:this.props.onKeyDown}),r.createElement("p",null,'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 straight-forward, 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 betwee 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!'))}});e.exports=o(d)},function(e,t,n){"use strict";var r=n(2),i=n(165),a=i.Link,o=n(212),s=Object.keys(o),l=r.createClass({displayName:"Navigation",generateNavItem:function(e,t){var n=o[e],i=n.getDefaultProps().title,s=r.createElement("a",{href:"#"+e},i);return this.props.fullNav&&(s=r.createElement(a,{to:e},i)),r.createElement("li",{key:e,"data-number":t},s)},generateNav:function(){return this.props.compact?null:r.createElement("div",{ref:"navigation"},r.createElement("navigation",{className:this.props.compact?"compact":null},r.createElement("ul",{className:"navigation"},s.map(this.generateNavItem),r.createElement("li",null,r.createElement("a",{href:"#comments"},"Comments and questions")))))},render:function(){return this.generateNav()}});e.exports=l},function(e,t,n){"use strict";var r=n(2),i=r.createClass({displayName:"Footer",render:function(){return r.createElement("footer",{className:"copyright"},'This article is © 2011-2016 to me, Mike "Pomax" Kamermans, but the text, code, and images are ',r.createElement("a",{href:"https://github.com/Pomax/bezierinfo/blob/gh-pages/LICENSE.md"},"almost no rights reserved"),". Go do something cool with it!")}});e.exports=i}]); \ No newline at end of file diff --git a/components/Navigation.jsx b/components/Navigation.jsx index ecc7eebb..140b138f 100644 --- a/components/Navigation.jsx +++ b/components/Navigation.jsx @@ -22,7 +22,8 @@ var Navigation = React.createClass({
Comments and questions
+ +