diff --git a/article.ja-JP.js b/article.ja-JP.js index eb1edad6..0820e3b0 100644 --- a/article.ja-JP.js +++ b/article.ja-JP.js @@ -22,14 +22,14 @@ return this._segments[this._segments.length-1]},getCurves:function(){var e=this. _class:"PathIterator",initialize:function(e,t,n,r){function i(e,t){var n=A.getValues(e,t,r);s.push(n),a(n,e._index,0,1)}function a(e,t,r,i){if(i-r>c&&!A.isFlatEnough(e,n||.25)){var o=A.subdivide(e,.5),s=(r+i)/2;a(o[0],t,r,s),a(o[1],t,s,i)}else{var h=e[6]-e[0],d=e[7]-e[1],f=Math.sqrt(h*h+d*d);f>1e-6&&(u+=f,l.push({offset:u,value:i,index:t}))}}for(var o,s=[],l=[],u=0,c=1/(t||32),h=e._segments,d=h[0],f=1,p=h.length;f=e){this.index=t;var a=this.parts[t-1],o=a&&a.index==i.index?a.value:0,s=a?a.offset:0;return{value:o+(i.value-o)*(e-s)/(i.offset-s),index:i.index}}}var i=this.parts[this.parts.length-1];return{value:1,index:i.index}},drawPart:function(e,t,n){t=this.getParameterAt(t),n=this.getParameterAt(n);for(var r=t.index;r<=n.index;r++){var i=A.getPart(this.curves[r],r==t.index?t.value:0,r==n.index?n.value:1);r==t.index&&e.moveTo(i[0],i[1]),e.bezierCurveTo.apply(e,i.slice(2))}}},s.each(A.evaluateMethods,function(e){this[e+"At"]=function(t,n){var r=this.getParameterAt(t);return A[e](this.curves[r.index],r.value,n)}},{})),j=s.extend({initialize:function(e,t){for(var n,r=this.points=[],i=e._segments,a=0,o=i.length;a0?[new I(e[0])]:[];return t>1&&this.fitCubic(0,t-1,e[1].subtract(e[0]).normalize(),e[t-2].subtract(e[t-1]).normalize()),this.closed&&(n.shift(),n.pop()),n},fitCubic:function(e,t,n,r){if(t-e==1){var i=this.points[e],a=this.points[t],o=i.getDistance(a)/3;return void this.addCurve([i,i.add(n.normalize(o)),a.add(r.normalize(o)),a])}for(var s,l=this.chordLengthParameterize(e,t),u=Math.max(this.error,this.error*this.error),c=!0,h=0;h<=4;h++){var d=this.generateBezier(e,t,l,n,r),f=this.findMaxError(e,t,d,l);if(f.error=u)break;c=this.reparameterize(e,t,l,d),u=f.error}var p=this.points[s-1].subtract(this.points[s]),m=this.points[s].subtract(this.points[s+1]),g=p.add(m).divide(2).normalize();this.fitCubic(e,s,n,g),this.fitCubic(s,t,g.negate(),r)},addCurve:function(e){var t=this.segments[this.segments.length-1];t.setHandleOut(e[1].subtract(e[0])),this.segments.push(new I(e[3],e[2].subtract(e[3])))},generateBezier:function(e,t,n,r,i){for(var a=1e-12,o=this.points[e],s=this.points[t],l=[[0,0],[0,0]],u=[0,0],c=0,h=t-e+1;ca){var k=l[0][0]*u[1]-l[1][0]*u[0],S=u[0]*l[1][1]-u[1]*l[0][1];x=S/C,E=k/C}else{var P=l[0][0]+l[0][1],T=l[1][0]+l[1][1];x=E=Math.abs(P)>a?u[0]/P:Math.abs(T)>a?u[1]/T:0}var N,M,I=s.getDistance(o),L=a*I;if(xI*I&&(x=E=I/3,N=M=null)}return[o,o.add(N||r.normalize(x)),s.add(M||i.normalize(E)),s]},reparameterize:function(e,t,n,r){for(var i=e;i<=t;i++)n[i-e]=this.findRoot(r,this.points[i],n[i-e]);for(var i=1,a=n.length;i=a&&(a=u,i=o)}return{error:a,index:i}}}),F=C.extend({_class:"TextItem",_boundsSelected:!0,_applyMatrix:!1,_canApplyMatrix:!1,_serializeFields:{content:null},_boundsGetter:"getBounds",initialize:function(e){this._content="",this._lines=[];var t=e&&s.isPlainObject(e)&&e.x===o&&e.y===o;this._initialize(t&&e,!t&&p.read(arguments))},_equals:function(e){return this._content===e._content},_clone:function e(t,n,r){return t.setContent(this._content),e.base.call(this,t,n,r)},getContent:function(){return this._content},setContent:function(e){this._content=""+e,this._lines=this._content.split(/\r\n|\n|\r/gm),this._changed(265)},isEmpty:function(){return!this._content},getCharacterStyle:"#getStyle",setCharacterStyle:"#setStyle",getParagraphStyle:"#getStyle",setParagraphStyle:"#setStyle"}),q=F.extend({_class:"PointText",initialize:function(){F.apply(this,arguments)},clone:function(e){return this._clone(new q(C.NO_INSERT),e)},getPoint:function(){var e=this._matrix.getTranslation();return new m(e.x,e.y,this,"setPoint")},setPoint:function(){var e=p.read(arguments);this.translate(e.subtract(this._matrix.getTranslation()))},_draw:function(e){if(this._content){this._setStyles(e);var t=this._style,n=this._lines,r=t.getLeading(),i=e.shadowColor;e.font=t.getFontStyle(),e.textAlign=t.getJustification();for(var a=0,o=n.length;a1&&(l-=1),o[s]=6*l<1?a+6*(i-a)*l:2*l<1?i:3*l<2?a+(i-a)*(2/3-l)*6:a}return o},"rgb-gray":function(e,t,n){return[.2989*e+.587*t+.114*n]},"gray-rgb":function(e){return[e,e,e]},"gray-hsb":function(e){return[0,0,e]},"gray-hsl":function(e){return[0,0,e]},"gradient-rgb":function(){return[]},"rgb-gradient":function(){return[]}};return s.each(n,function(e,t){r[t]=[],s.each(e,function(e,i){var a=s.capitalize(e),o=/^(hue|saturation)$/.test(e),l=r[t][i]="gradient"===e?function(e){var t=this._components[0];return e=U.read(Array.isArray(e)?e:arguments,0,{readNull:!0}),t!==e&&(t&&t._removeOwner(this),e&&e._addOwner(this)),e}:"gradient"===t?function(){return p.read(arguments,0,{readNull:"highlight"===e,clone:!0})}:function(e){return null==e||isNaN(e)?0:e};this["get"+a]=function(){return this._type===t||o&&/^hs[bl]$/.test(this._type)?this._components[i]:this._convert(t)[i]},this["set"+a]=function(e){this._type===t||o&&/^hs[bl]$/.test(this._type)||(this._components=this._convert(t),this._properties=n[t],this._type=t),this._components[i]=l.call(this,e),this._changed()}},this)},{_class:"Color",_readIndex:!0,initialize:function t(i){var a,o,s,l,u=Array.prototype.slice,c=arguments,h=0;Array.isArray(i)&&(c=i,i=c[0]);var d=null!=i&&typeof i;if("string"===d&&i in n&&(a=i,i=c[1],Array.isArray(i)?(o=i,s=c[2]):(this.__read&&(h=1),c=u.call(c,1),d=typeof i)),!o){if(l="number"===d?c:"object"===d&&null!=i.length?i:null){a||(a=l.length>=3?"rgb":"gray");var p=n[a].length;s=l[p],this.__read&&(h+=l===arguments?p+(null!=s?1:0):1),l.length>p&&(l=u.call(l,0,p))}else if("string"===d)a="rgb",o=e(i),4===o.length&&(s=o[3],o.length--);else if("object"===d)if(i.constructor===t){if(a=i._type,o=i._components.slice(),s=i._alpha,"gradient"===a)for(var m=1,g=o.length;m1?1:e))}var n=this._convert("rgb"),r=e||null==this._alpha?1:this._alpha;return n=[t(n[0]),t(n[1]),t(n[2])],r<1&&n.push(r<0?0:r),e?"#"+((1<<24)+(n[0]<<16)+(n[1]<<8)+n[2]).toString(16).slice(1):(4==n.length?"rgba(":"rgb(")+n.join(",")+")"},toCanvasStyle:function(e){if(this._canvasStyle)return this._canvasStyle;if("gradient"!==this._type)return this._canvasStyle=this.toCSS();var t,n=this._components,r=n[0],i=r._stops,a=n[1],o=n[2];if(r._radial){var s=o.getDistance(a),l=n[3];if(l){var u=l.subtract(a);u.getLength()>s&&(l=a.add(u.normalize(s-.1)))}var c=l||a;t=e.createRadialGradient(c.x,c.y,0,a.x,a.y,s)}else t=e.createLinearGradient(a.x,a.y,o.x,o.y);for(var h=0,d=i.length;h0&&!(t instanceof D))for(var r=0,s=n.length;r0},hasShadow:function(){return!!this.getShadowColor()&&this.getShadowBlur()>0},getView:function(){return this._project.getView()},getFontStyle:function(){var e=this.getFontSize();return this.getFontWeight()+" "+e+(/[a-z]/i.test(e+"")?" ":"px ")+this.getFontFamily()},getFont:"#getFontFamily",setFont:"#setFontFamily",getLeading:function e(){var t=e.base.call(this),n=this.getFontSize();return/pt|em|%|px/.test(n)&&(n=this.getView().getPixelSize(n)),null!=t?t:1.2*n}}),H=new function(){function e(e,t,n,r){for(var i=["","webkit","moz","Moz","ms","o"],a=t[0].toUpperCase()+t.substring(1),o=0;o<6;o++){var s=i[o],l=s?s+a:t;if(l in e){if(!n)return e[l];e[l]=r;break}}}return{getStyles:function(e){var t=e&&9!==e.nodeType?e.ownerDocument:e,n=t&&t.defaultView;return n&&n.getComputedStyle(e,"")},getBounds:function(e,t){var n,r=e.ownerDocument,i=r.body,a=r.documentElement;try{n=e.getBoundingClientRect()}catch(e){n={left:0,top:0,width:0,height:0}}var o=n.left-(a.clientLeft||i.clientLeft||0),s=n.top-(a.clientTop||i.clientTop||0);if(!t){var l=r.defaultView;o+=l.pageXOffset||a.scrollLeft||i.scrollLeft,s+=l.pageYOffset||a.scrollTop||i.scrollTop}return new y(o,s,n.width,n.height)},getViewportBounds:function(e){var t=e.ownerDocument,n=t.defaultView,r=t.documentElement;return new y(0,0,n.innerWidth||r.clientWidth,n.innerHeight||r.clientHeight)},getOffset:function(e,t){return H.getBounds(e,t).getPoint()},getSize:function(e){return H.getBounds(e,!0).getSize()},isInvisible:function(e){return H.getSize(e).equals(new g(0,0))},isInView:function(e){return!H.isInvisible(e)&&H.getViewportBounds(e).intersects(H.getBounds(e,!0))},getPrefixed:function(t,n){return e(t,n)},setPrefixed:function(t,n,r){if("object"==typeof n)for(var i in n)e(t,i,!0,n[i]);else e(t,n,!0,r)}}},X={add:function(e,t){for(var n in t)for(var r=t[n],i=n.split(/[\s,]+/g),a=0,o=i.length;a=0;t--){var o=i[t],s=o[0],l=o[1];(!l||("true"==u.getAttribute(l,"keepalive")||a)&&H.isInView(l))&&(i.splice(t,1),s())}n&&(i.length?n(e):r=!1)}var t,n=H.getPrefixed(window,"requestAnimationFrame"),r=!1,i=[],a=!0;return X.add(window,{focus:function(){a=!0},blur:function(){a=!1}}),function(a,o){i.push([a,o]),n?r||(n(e),r=!0):t||(t=setInterval(e,1e3/60))}};var K=s.extend(l,{_class:"View",initialize:function e(t,n){function r(e){return n[e]||parseInt(n.getAttribute(e),10)}function i(){var e=H.getSize(n);return e.isNaN()||e.isZero()?new g(r("width"),r("height")):e}this._project=t,this._scope=t._scope,this._element=n;var a;this._pixelRatio||(this._pixelRatio=window.devicePixelRatio||1),this._id=n.getAttribute("id"),null==this._id&&n.setAttribute("id",this._id="view-"+e._id++),X.add(n,this._viewEvents);var o="none";if(H.setPrefixed(n.style,{userSelect:o,touchAction:o,touchCallout:o,contentZooming:o,userDrag:o,tapHighlightColor:"rgba(0,0,0,0)"}),u.hasAttribute(n,"resize")){var s=this;X.add(window,this._windowEvents={resize:function(){s.setViewSize(i())}})}if(this._setViewSize(a=i()),u.hasAttribute(n,"stats")&&"undefined"!=typeof Stats){this._stats=new Stats;var l=this._stats.domElement,c=l.style,h=H.getOffset(n);c.position="absolute",c.left=h.x+"px",c.top=h.y+"px",document.body.appendChild(l)}e._views.push(this),e._viewsById[this._id]=this,this._viewSize=a,(this._matrix=new b)._owner=this,this._zoom=1,e._focused||(e._focused=this),this._frameItems={},this._frameItemCount=0},remove:function(){return!!this._project&&(K._focused===this&&(K._focused=null),K._views.splice(K._views.indexOf(this),1),delete K._viewsById[this._id],this._project._view===this&&(this._project._view=null),X.remove(this._element,this._viewEvents),X.remove(window,this._windowEvents),this._element=this._project=null,this.off("frame"),this._animate=!1,this._frameItems={},!0)},_events:s.each(["onResize","onMouseDown","onMouseUp","onMouseMove"],function(e){this[e]={install:function(e){this._installEvent(e)},uninstall:function(e){this._uninstallEvent(e)}}},{onFrame:{install:function(){this.play()},uninstall:function(){this.pause()}}}),_animate:!1,_time:0,_count:0,_requestFrame:function(){var e=this;X.requestAnimationFrame(function(){e._requested=!1,e._animate&&(e._requestFrame(),e._handleFrame())},this._element),this._requested=!0},_handleFrame:function(){a=this._scope;var e=Date.now()/1e3,t=this._before?e-this._before:0;this._before=e,this._handlingFrame=!0,this.emit("frame",new s({delta:t,time:this._time+=t,count:this._count++})),this._stats&&this._stats.update(),this._handlingFrame=!1,this.update()},_animateItem:function(e,t){var n=this._frameItems;t?(n[e._id]={item:e,time:0,count:0},1===++this._frameItemCount&&this.on("frame",this._handleFrameItems)):(delete n[e._id],0===--this._frameItemCount&&this.off("frame",this._handleFrameItems))},_handleFrameItems:function(e){for(var t in this._frameItems){var n=this._frameItems[t];n.item.emit("frame",new s(e,{time:n.time+=e.delta,count:n.count++}))}},_update:function(){this._project._needsUpdate=!0,this._handlingFrame||(this._animate?this._handleFrame():this.update())},_changed:function(e){1&e&&(this._project._needsUpdate=!0)},_transform:function(e){this._matrix.concatenate(e),this._bounds=null,this._update()},getElement:function(){return this._element},getPixelRatio:function(){return this._pixelRatio},getResolution:function(){return 72*this._pixelRatio},getViewSize:function(){var e=this._viewSize;return new v(e.width,e.height,this,"setViewSize")},setViewSize:function(){var e=g.read(arguments),t=e.subtract(this._viewSize);t.isZero()||(this._viewSize.set(e.width,e.height),this._setViewSize(e),this._bounds=null,this.emit("resize",{size:e,delta:t}),this._update())},_setViewSize:function(e){var t=this._element;t.width=e.width,t.height=e.height},getBounds:function(){return this._bounds||(this._bounds=this._matrix.inverted()._transformBounds(new y(new p,this._viewSize))),this._bounds},getSize:function(){return this.getBounds().getSize()},getCenter:function(){return this.getBounds().getCenter()},setCenter:function(){var e=p.read(arguments);this.scrollBy(e.subtract(this.getCenter()))},getZoom:function(){return this._zoom},setZoom:function(e){this._transform((new b).scale(e/this._zoom,this.getCenter())),this._zoom=e},isVisible:function(){return H.isInView(this._element)},scrollBy:function(){this._transform((new b).translate(p.read(arguments).negate()))},play:function(){this._animate=!0,this._requested||this._requestFrame()},pause:function(){this._animate=!1},draw:function(){this.update()},projectToView:function(){return this._matrix._transformPoint(p.read(arguments))},viewToProject:function(){return this._matrix._inverseTransform(p.read(arguments))}},{statics:{_views:[],_viewsById:{},_id:0,create:function(e,t){return"string"==typeof t&&(t=document.getElementById(t)),new Q(e,t)}}},new function(){function e(e){var t=X.getTarget(e);return t.getAttribute&&K._viewsById[t.getAttribute("id")]}function t(e,t){return e.viewToProject(X.getOffset(t,e._element))}function n(){if(!K._focused||!K._focused.isVisible())for(var e=0,t=K._views.length;ethis._maxDistance&&(this._maxDistance=e)},getMaxDistance:function(){return this._maxDistance},setMaxDistance:function(e){this._maxDistance=e,null!=this._minDistance&&null!=e&&er)t=this._point.add(l.normalize(r));else if(o)return!1}if(a&&t.equals(this._point))return!1}switch(this._lastPoint=i&&"mousemove"==e?t:this._point,this._point=t,e){case"mousedown":this._lastPoint=this._downPoint,this._downPoint=this._point,this._downCount++;break;case"mouseup":this._lastPoint=this._downPoint}return this._count=i?0:this._count+1,!0},_fireEvent:function(e,t){var n=a.project._removeSets;if(n){"mouseup"===e&&(n.mousedrag=null);var r=n[e];if(r){for(var i in r){var o=r[i];for(var s in n){var l=n[s];l&&l!=r&&delete l[o._id]}o.remove()}n[e]=null}}return this.responds(e)&&this.emit(e,new ee(this,e,t))},_handleEvent:function(e,t,n){a=this._scope;var r=!1;switch(e){case"mousedown":this._updateEvent(e,t,null,null,!0,!1,!1),r=this._fireEvent(e,n);break;case"mousedrag":for(var i=!1,o=!1;this._updateEvent(e,t,this.minDistance,this.maxDistance,!1,i,o);)r=this._fireEvent(e,n)||r,i=!0,o=!0;break;case"mouseup":!t.equals(this._point)&&this._updateEvent("mousedrag",t,this.minDistance,this.maxDistance,!1,!1,!1)&&(r=this._fireEvent("mousedrag",n)),this._updateEvent(e,t,null,this.maxDistance,!1,!1,!1),r=this._fireEvent(e,n)||r,this._updateEvent(e,t,null,null,!0,!1,!1),this._firstMove=!0;break;case"mousemove":for(;this._updateEvent(e,t,this.minDistance,this.maxDistance,this._firstMove,!0,!1);)r=this._fireEvent(e,n)||r,this._firstMove=!1}return r&&n.preventDefault(),r}}),{request:function(e,t,n,r){r=r===o||r;var i=new(window.ActiveXObject||XMLHttpRequest)("Microsoft.XMLHTTP");return i.open(e.toUpperCase(),t,r),"overrideMimeType"in i&&i.overrideMimeType("text/plain"),i.onreadystatechange=function(){if(4===i.readyState){var e=i.status;if(0!==e&&200!==e)throw new Error("Could not load "+t+" (Error "+e+")");n.call(i,i.responseText)}},i.send(null)}}),ne={canvases:[],getCanvas:function(e,t){var n,r=!0;"object"==typeof e&&(t=e.height,e=e.width),n=this.canvases.length?this.canvases.pop():document.createElement("canvas");var i=n.getContext("2d");return n.width===e&&n.height===t?r&&i.clearRect(0,0,e+1,t+1):(n.width=e,n.height=t),i.save(),n},getContext:function(e,t){return this.getCanvas(e,t).getContext("2d")},release:function(e){var t=e.canvas?e.canvas:e;t.getContext("2d").restore(),this.canvases.push(t)}},re=new function(){function e(e,t,n){return.2989*e+.587*t+.114*n}function t(t,n,r,i){var a=i-e(t,n,r);f=t+a,p=n+a,m=r+a;var i=e(f,p,m),o=g(f,p,m),s=v(f,p,m);if(o<0){var l=i-o;f=i+(f-i)*i/l,p=i+(p-i)*i/l,m=i+(m-i)*i/l}if(s>255){var u=255-i,c=s-i;f=i+(f-i)*u/c,p=i+(p-i)*u/c,m=i+(m-i)*u/c}}function n(e,t,n){return v(e,t,n)-g(e,t,n)}function r(e,t,n,r){var i,a=[e,t,n],o=v(e,t,n),s=g(e,t,n);s=s===e?0:s===t?1:2,o=o===e?0:o===t?1:2,i=0===g(s,o)?1===v(s,o)?2:1:0,a[o]>a[s]?(a[i]=(a[i]-a[s])*r/(a[o]-a[s]),a[o]=r):a[i]=a[o]=0,a[s]=0,f=a[0],p=a[1],m=a[2]}var i,a,o,l,u,c,h,d,f,p,m,g=Math.min,v=Math.max,y=Math.abs,w={multiply:function(){f=u*i/255,p=c*a/255,m=h*o/255},screen:function(){f=u+i-u*i/255,p=c+a-c*a/255,m=h+o-h*o/255},overlay:function(){f=u<128?2*u*i/255:255-2*(255-u)*(255-i)/255,p=c<128?2*c*a/255:255-2*(255-c)*(255-a)/255,m=h<128?2*h*o/255:255-2*(255-h)*(255-o)/255},"soft-light":function(){var e=i*u/255;f=e+u*(255-(255-u)*(255-i)/255-e)/255,e=a*c/255,p=e+c*(255-(255-c)*(255-a)/255-e)/255,e=o*h/255,m=e+h*(255-(255-h)*(255-o)/255-e)/255},"hard-light":function(){f=i<128?2*i*u/255:255-2*(255-i)*(255-u)/255,p=a<128?2*a*c/255:255-2*(255-a)*(255-c)/255,m=o<128?2*o*h/255:255-2*(255-o)*(255-h)/255},"color-dodge":function(){f=0===u?0:255===i?255:g(255,255*u/(255-i)),p=0===c?0:255===a?255:g(255,255*c/(255-a)),m=0===h?0:255===o?255:g(255,255*h/(255-o))},"color-burn":function(){f=255===u?255:0===i?0:v(0,255-255*(255-u)/i),p=255===c?255:0===a?0:v(0,255-255*(255-c)/a),m=255===h?255:0===o?0:v(0,255-255*(255-h)/o)},darken:function(){f=ui?u:i,p=c>a?c:a,m=h>o?h:o},difference:function(){f=u-i,f<0&&(f=-f),p=c-a,p<0&&(p=-p),m=h-o,m<0&&(m=-m)},exclusion:function(){f=u+i*(255-u-u)/255,p=c+a*(255-c-c)/255,m=h+o*(255-h-h)/255},hue:function(){r(i,a,o,n(u,c,h)),t(f,p,m,e(u,c,h))},saturation:function(){r(u,c,h,n(i,a,o)),t(f,p,m,e(u,c,h))},luminosity:function(){t(u,c,h,e(i,a,o))},color:function(){t(i,a,o,e(u,c,h))},add:function(){f=g(u+i,255),p=g(c+a,255),m=g(h+o,255)},subtract:function(){f=v(u-i,0),p=v(c-a,0),m=v(h-o,0)},average:function(){f=(u+i)/2,p=(c+a)/2,m=(h+o)/2},negation:function(){f=255-y(255-i-u),p=255-y(255-a-c),m=255-y(255-o-h)}},b=this.nativeModes=s.each(["source-over","source-in","source-out","source-atop","destination-over","destination-in","destination-out","destination-atop","lighter","darker","copy","xor"],function(e){this[e]=!0},{}),_=ne.getContext(1,1);s.each(w,function(e,t){var n="darken"===t,r=!1;_.save();try{_.fillStyle=n?"#300":"#a00",_.fillRect(0,0,1,1),_.globalCompositeOperation=t,_.globalCompositeOperation===t&&(_.fillStyle=n?"#a00":"#300",_.fillRect(0,0,1,1),r=_.getImageData(0,0,1,1).data[0]!==n?170:51)}catch(e){}_.restore(),b[t]=r}),ne.release(_),this.process=function(e,t,n,r,s){var g=t.canvas,v="normal"===e;if(v||b[e])n.save(),n.setTransform(1,0,0,1,0,0),n.globalAlpha=r,v||(n.globalCompositeOperation=e),n.drawImage(g,s.x,s.y),n.restore();else{var y=w[e];if(!y)return;for(var _=n.getImageData(s.x,s.y,g.width,g.height),x=_.data,E=t.getImageData(0,0,g.width,g.height).data,C=0,k=x.length;C=3){s=e._closed?"polygon":"polyline";for(var c=[],h=0,d=l.length;h1||/z\S+/i.test(t)?new D(n):new z(n)}function c(n,r){var i,a=(e(n,"href",!0)||"").substring(1),o="radialgradient"===r;if(a)i=N[a].getGradient();else{for(var s=n.childNodes,l=[],u=0,c=s.length;u0&&this.weights;t.beginPath();var r=i(0,this.degree,e,this.knots,n);t.moveTo(r[0],r[1]);for(var a=.01;a<1;a+=.01)r=i(a,this.degree,e,this.knots,n),t.lineTo(r[0],r[1]);r=i(1,this.degree,e,this.knots,n),t.lineTo(r[0],r[1]),t.stroke(),t.closePath()},drawKnots:function(e){var t=this,n=this.knots,r=this.weights.length>0&&this.weights;n.forEach(function(a,o){if(!(on.length-1-t.degree)){var s=i(a,t.degree,e,n,r,!1,!0);t.circle(s[0],s[1],3)}})},drawNodes:function(e){var t,n=this;this.stroke(150),this.nodes.forEach(function(r,a){try{t=i(r,n.degree,e,n.knots,!1,!1,!0),n.line(t[0],t[1],e[a][0],e[a++][1])}catch(e){console.error(e)}})},formKnots:function(e,t){if(t=t===!0,!t)return this.formUniformKnots(e);var n,r=e.length,i=[],a=r-this.degree;for(n=1;n=0;n--)t.push(n);return t.reverse()},formNodes:function(e,t){var n,r,i,a=[this.degree,e.length-1-this.degree],o=[];for(r=0;re[a[1]]||o.push(n)}return o},formWeights:function(e){var t=[];return e.forEach(function(e){return t.push(1)}),t},setDegree:function(e){this.degree+=e,this.knots=this.formKnots(this.points),this.nodes=this.formNodes(this.knots,this.points)},near:function(e,t,n){var r=e.x-t,i=e.y-n,a=Math.sqrt(r*r+i*i);return a1&&this.setDegree(-1),this.redraw()},keyUp:function(){},keyPressed:function(){},mouseDown:function(){this.isMouseDown=!0,this.cp=this.getCurrentPoint(this.mouseX,this.mouseY),this.cp||(this.points.push({x:this.mouseX,y:this.mouseY}),this.knots=this.formKnots(this.points),this.nodes=this.formNodes(this.knots,this.points)),this.redraw()},mouseUp:function(){this.isMouseDown=!1,this.cp=!1,this.redraw()},mouseDrag:function(){this.cp&&(this.cp.x=this.mouseX,this.cp.y=this.mouseY,this.redraw())},mouseMove:function(){},scrolled:function(e){if(this.cp=this.getCurrentPoint(this.mouseX,this.mouseY),this.cp){var t=this.points.indexOf(this.cp);this.weights.length>t&&(this.weights[t]+=.1*e,this.weights[t]<0&&(this.weights[t]=0)),t=this.points.indexOf(this.cp,t+1),t!==-1&&this.weights.length>t&&(this.weights[t]+=.1*e,this.weights[t]<0&&(this.weights[t]=0)),this.redraw()}},setKeyboardValues:function(e){e.ctrlKey||e.metaKey||e.altKey||e.preventDefault(),this.key=e.key,this.keyCode=e.code},setMouseValues:function(e){var t=this.cvs.getBoundingClientRect();this.mouseX=e.clientX-t.left,this.mouseY=e.clientY-t.top},size:function(e,t){this.width=0|e,this.height=0|(t||e),this.cvs.width=this.width,this.cvs.height=this.height,this.ctx=this.cvs.getContext("2d")},redraw:function(){this.draw()},clear:function(){this.ctx.clearRect(0,0,this.width,this.height)},grid:function(e){e=(0|(e||10))+.5,this.stroke(200,200,220);for(var t=e;t-1&&{to:s[e],title:o[s[e]].getDefaultProps().title};var t=this.props.next;return t=t=s)return null;var c={type:t,min:n,max:i,step:a,value:l,onChange:function(t){var n=e.state.weights;n[u]=t.target.value,o&&u.95)&&(t.t=!1),t.redraw()},setupQuadratic:function(e){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/d351ad8dd7d1ab5c5e65f5abd78caf082fc84eb4.svg",style:{width:"12.825000000000001rem",height:"5.92515rem"}})),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/7ef64890f95db9e48258edb46a3d52d5ed143155.svg",style:{width:"16.57485rem",height:"2.77515rem"}})),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(0),i=n(4),a=new i,o="aligning",s=r.createClass({displayName:"Aligning",getDefaultProps:function(){return{title:a.getTitle(o)}},setupQuadratic:function(e){var t=e.getDefaultQuadratic();e.setCurve(t)},setupCubic:function(e){var t=e.getDefaultCubic();e.setCurve(t)},align:function(e,t){var n=t.p1.x,r=t.p1.y,i=-Math.atan2(t.p2.y-r,t.p2.x-n),a=Math.cos,o=Math.sin,s=function(e){return{x:(e.x-n)*a(i)-(e.y-r)*o(i),y:(e.x-n)*o(i)+(e.y-r)*a(i)}};return e.map(s)},draw:function(e,t){e.setPanelCount(2),e.reset(),e.drawSkeleton(t),e.drawCurve(t);var n=t.points,r={p1:n[0],p2:n[n.length-1]},i=this.align(n,r),a=new e.Bezier(i),o=e.getPanelWidth(),s=e.getPanelHeight(),l={x:o,y:0};e.setColor("black"),e.drawLine({x:0,y:0},{x:0,y:s},l),l.x+=o/4,l.y+=s/2,e.setColor("grey"),e.drawLine({x:0,y:-s/2},{x:0,y:s/2},l),e.drawLine({x:-o/4,y:0},{x:o,y:0},l),e.setFill("grey"),e.setColor("black"),e.drawSkeleton(a,l),e.drawCurve(a,l)},render:function(){return r.createElement("section",null,a.getContent(o,this))}});e.exports=s},function(e,t,n){"use strict";var r=n(0),i=n(8),a=n(6),o=n(15),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,f=r.y-n.y,p=a*c(l/2)-o*h(l/2),m=a*h(l/2)+o*c(l/2),g=d*c(l/2)-f*h(l/2),v=d*h(l/2)+f*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+p,E=w+m,C=b+g,k=_+v,S=e.utils.lli8(y,w,x,E,b,_,C,k),P=e.utils.dist(S,t),T=s(t.y-S.y,t.x-S.x),N=s(n.y-S.y,n.x-S.x),M=s(r.y-S.y,r.x-S.x);return TN||N>M)&&(T+=u),T>M&&(i=M,M=T,T=i)):M s + L - order; i--) ","{","\n"," let numerator = t - knots[i]","\n"," let denominator = knots[i - L + order] - knots[i]","\n"," let alpha = numerator / denominator","\n"," let v[i] = alpha * v[i] + (1-alpha) * v[i-1]","\n"," ","}","\n"," ","}"),r.createElement("p",null,'(A nice bit of behaviour in this code is that we work the interpolation "backwards", starting at ',r.createElement("code",null,"i=s")," at each level of the interpolation, and we stop when ",r.createElement("code",null,"i = s - order + level"),", so we always end up with a value for ",r.createElement("code",null,"i")," such that those ",r.createElement("code",null,"v[i-1]")," don't try to use an array index that doesn't exist)"),r.createElement("h2",null,"Open vs. closed paths"),r.createElement("p",null,"Much like poly-Béziers, B-Splines can be either open, running from the first point to the last point, or closed, where the first and last point are ",r.createElement("em",null,"the same point"),". However, because B-Splines are an interpolation of curves, not just point, we can't simply make the first and last point the same, we need to link a few point point: for an order ",r.createElement("code",null,"d")," B-Spline, we need to make the last ",r.createElement("code",null,"d")," point the same as the first ",r.createElement("code",null,"d")," points. And the easiest way to do this is to simply append ",r.createElement("code",null,"points.splice(0,d)")," to ",r.createElement("code",null,"points"),". Done!"),r.createElement("p",null,'Of course if we want to manipulate these kind of curves we need to make sure to mark them as "closed" so that we know the coordinate for ',r.createElement("code",null,"points[0]")," and ",r.createElement("code",null,"points[n-k]")," etc. are the same coordinate, and manipulating one will equally manipulate the other, but programming generally makes this really easy by storing references to coordinates (or other linked values such as coordinate weights, discussed in the NURBS section) rather than separate coordinate objects."),r.createElement("h2",null,"Manipulating the curve through the knot vector"),r.createElement("p",null,"The most important thing to understand when it comes to B-Splines is that they work ",r.createElement("em",null,"because"),' of the concept of a knot vector. As mentioned above, knots represent "where individual control points start/stop influencing the curve", but we never looked at the ',r.createElement("em",null,"values")," that go in the knot vector. If you look back at the N() and a() functions, you see that interpolations are based on intervals in the knot vector, rather than the actual values in the knot vector, and we can exploit this to do some pretty interesting things with clever manipulation of the knot vector. Specifically there are four things we can do that are worth looking at:"),r.createElement("ol",null,r.createElement("li",null,"we can use a uniform knot vector, with equally spaced intervals,"),r.createElement("li",null,"we can use a non-uniform knot vector, without enforcing equally spaced internvals,"),r.createElement("li",null,'we can collapse sequential knots to the same value, locally lowering curve complexity using "null" intervals, and'),r.createElement("li",null,"we can form a special case non-uniform vector, by combining (1) and (3) to for a vector with collapsed start and end knots, with a uniform vector in between.")),r.createElement("h3",null,"Uniform B-Splines"),r.createElement("p",null,"The most straightforward type of B-Spline is the uniform spline. In a uniform spline, the knots are distributed uniformly over the entire curve interval. For instance, if we have a knot vector of length twelve, then a uniform knot vector would be [0,1,2,3,...,9,10,11]. Or [4,5,6,...,13,14,15], which defines ",r.createElement("em",null,"the same intervals"),", or even [0,2,3,...,18,20,22], which also defines ",r.createElement("em",null,"the same intervals"),", just scaled by a constant factor, which becomes normalised during interpolation and so does not contribute to the curvature."),r.createElement("div",{className:"two-column"},r.createElement(o,{ref:"uniform-spline"}),r.createElement(i,{sketch:n(131),controller:function(t,n){return e.bindKnots(t,n,"uniform-spline")}})),r.createElement("p",null,"This is an important point: the intervals that the knot vector defines are ",r.createElement("em",null,"relative")," intervals, so it doesn't matter if every interval is size 1, or size 100 - the relative differences between the intervals is what shapes any particular curve."),r.createElement("p",null,"The problem with uniform knot vectors is that, as we need ",r.createElement("code",null,"order"),' control points before we have any curve with which we can perform interpolation, the curve does not "start" at the first point, nor "ends" at the last point. Instead there are "gaps". We can get rid of these, by being clever about how we apply the following uniformity-breaking approach instead...'),r.createElement("h3",null,"Reducing local curve complexity by collapsing intervals"),r.createElement("p",null,"By collapsing knot intervals by making two or more consecutive knots have the same value, we can reduce the curve complexity in the sections that are affected by the knots involved. This can have drastic effects: for ever interval collapse, the curve order goes down, and curve continuity goes down, to the point where collapsing ",r.createElement("code",null,"order"),' knots creates a situation where all continuity is lost and the curve "kinks".'),r.createElement("div",{className:"two-column"},r.createElement(o,{ref:"center-cut-bspline"}),r.createElement(i,{sketch:n(126),controller:function(t,n){return e.bindKnots(t,n,"center-cut-bspline")}})),r.createElement("h3",null,"Open-Uniform B-Splines"),r.createElement("p",null,"By combining knot interval collapsing at the start and end of the curve, with uniform knots in between, we can overcome the problem of the curve not starting and ending where we'd kind of like it to:"),r.createElement("p",null,"For any curve of degree ",r.createElement("code",null,"D")," with control points ",r.createElement("code",null,"N"),", we can define a knot vector of length ",r.createElement("code",null,"N+D+1")," in which the values ",r.createElement("code",null,"0 ... D+1")," are the same, the values ",r.createElement("code",null,"D+1 ... N+1"),' follow the "uniform" pattern, and the values ',r.createElement("code",null,"N+1 ... N+D+1"),' are the same again. For example, a cubic B-Spline with 7 control points can have a knot vector [0,0,0,0,1,2,3,4,4,4,4], or it might have the "identical" knot vector [0,0,0,0,2,4,6,8,8,8,8], etc. Again, it is the relative differences that determine the curve shape.'),r.createElement("div",{className:"two-column"},r.createElement(o,{ref:"open-uniform-bspline"}),r.createElement(i,{sketch:n(129),controller:function(t,n){return e.bindKnots(t,n,"open-uniform-bspline")}})),r.createElement("h3",null,"Non-uniform B-Splines"),r.createElement("p",null,'This is essentialy the "free form" version of a B-Spline, and also the least interesting to look at, as without any specific reason to pick specific knot intervals, there is nothing particularly interesting going on. There is one constraint to the knot vector, and that is that any value ',r.createElement("code",null,"knots[k+1]"),"should be equal to, or greater than ",r.createElement("code",null,"knots[k]"),"."),r.createElement("h2",null,"One last thing: Rational B-Splines"),r.createElement("p",null,'While it is true that this section on B-Splines is running quite long already, there is one more thing we need to talk about, and that\'s "Rational" splines, where the rationality applies to the "ratio", or relative weights, of the control points themselves. By introducing a ratio vector with weights to apply to each control point, we greatly increase our influence over the final curve shape: the more weight a control point carries, the close to that point the spline curve will lie, a bit like turning up the gravity of a control point.'),r.createElement("div",{className:"two-column"},r.createElement(s,{ref:"rational-uniform-bspline-weights"}),r.createElement(i,{scrolling:!0,sketch:n(130),controller:function(t,n,r,i){e.bindWeights(t,r,i,"rational-uniform-bspline-weights")}})),r.createElement("p",null,'Of course this brings us to the final topic that any text on B-Splines must touch on before calling it a day: the NURBS, or Non-Uniform Rational B-Spline (NURBS is not a plural, the capital S actually just stands for "spline", but a lot of people mistakenly treat it as if it is, so now you know better). NURBS are an important type of curve in computer-facilitated design, used a lot in 3D modelling (as NURBS surfaces) as well as in arbitrary-precision 2D design due to the level of control a NURBS curve offers designers.'),r.createElement("p",null,"While a true non-uniform rational B-Spline would be hard to work with, when we talk about NURBS we typically mean the Open-Uniform Rational B-Spline, or OURBS, but that doesn't roll off the tongue nearly as nicely, and so remember that when people talk about NURBS, they typically mean open-uniform, which has the useful property of starting the curve at the first control point, and ending it at the last."),r.createElement("h2",null,"Extending our implementation to cover rational splines"),r.createElement("p",null,"The algorithm for working with Rational B-Splines is virtually identical to the regular algorithm, and the extension to work in the control point weights is fairly simple: we extend each control point from a point in its original number of dimensions (2D, 3D, etc) to one dimension higher, scaling the original dimensions by the control point's weight, and then assigning that weight as its value for the extended dimension."),r.createElement("p",null,"For example, a 2D point ",r.createElement("code",null,"(x,y)")," with weight ",r.createElement("code",null,"w")," becomes a 3D point ",r.createElement("code",null,"(w * x, w * y, w)"),"."),r.createElement("p",null,"We then run the same algorithm as before, which will automaticall perform weight interpolation in addition to regular coordinate interpolation, because all we've done is pretended we have coordinates in a higher dimension. The algorithm doesn't really care about how many dimensions it needs to interpolate."),r.createElement("p",null,'In order to recover our "real" curve point, we take the final result of the point generation algorithm, and "unweigh" it: we take the final point\'s derived weight ',r.createElement("code",null,"w'")," and divide all the regular coordinate dimensions by it, then throw away the weight information."),r.createElement("p",null,"Based on our previous example, we take the final 3D point ",r.createElement("code",null,"(x', y', w')"),", which we then turn back into a 2D point by computing ",r.createElement("code",null,"(x'/w', y'/w')"),". And that's it, we're done!"))}});e.exports=l},function(e,t,n){"use strict";var r=["#C00","#CC0","#0C0","#0CC","#00C","#C0C","#600","#660","#060","#066","#006","#606"];e.exports={degree:3,activeDistance:9,cache:{N:[]},setup:function(){this.size(600,300),this.points=[{x:0,y:0},{x:100,y:-100},{x:200,y:100},{x:300,y:-100},{x:400,y:100},{x:500,y:0}],this.knots=this.formKnots(this.points),this.props.controller&&this.props.controller(this,this.knots),this.draw()},draw:function(){this.clear();var e=25;this.grid(e),this.stroke(0),this.line(e,0,e,this.height);var t=this.height-e;this.line(0,t,this.width,t);for(var n=this.degree,r=this.points.length||4,i=0;i-10&&(l.push({x:i*u,y:i*c}),e.drawLine({x:i*u,y:i*c},{x:i*o,y:i*s},a)),u=o,c=s;l.push({x:i*u,y:i*c}),e.text("Curve form has cusp →",{x:n/2-2*i,y:r/2+i/2.5}),e.setColor("#FF00FF"),e.setFill(e.getColor());var h=Math.sqrt;for(o=1;o>=0;o-=.005)l.push({x:i*u,y:i*c}),s=.5*(h(3)*h(4*o-o*o)-o),e.drawLine({x:i*u,y:i*c},{x:i*o,y:i*s},a),u=o,c=s;for(l.push({x:i*u,y:i*c}),e.text("← Curve forms a loop at t = 1",{x:n/2+i/4,y:r/2+i/1.5}),e.setColor("#3300FF"),e.setFill(e.getColor()),o=0;o>-n;o-=.01)l.push({x:i*u,y:i*c}),s=(-o*o+3*o)/3,e.drawLine({x:i*u,y:i*c},{x:i*o,y:i*s},a),u=o,c=s;l.push({x:i*u,y:i*c}),e.text("← Curve forms a loop at t = 0",{x:n/2-i+10,y:r/2-1.25*i}),e.setColor("transparent"),e.setFill("rgba(255,120,100,0.2)"),e.drawPath(l,a),l=[{x:-n/2,y:i},{x:n/2,y:i},{x:n/2,y:r},{x:-n/2,y:r}],e.setFill("rgba(0,200,0,0.2)"),e.drawPath(l,a),e.setColor("black"),e.setFill(e.getColor()),e.text("← Curve form has one inflection →",{x:n/2-i,y:r/2+1.75*i}),e.text("← Plain curve ↕",{x:n/2+i/2,y:r/6}),e.text("↕ Double inflection",{x:10,y:r/2-10}),e._map_image=e.toImage(),e._map_loaded=!0},render:function(){return r.createElement("section",null,a.getContent(o,this))}});e.exports=s},function(e,t,n){"use strict";var r=n(0),i=n(6),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(0),i=n(8),a=n(6),o=n(15),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},f=e.utils.lli4(a,s,o,{x:(h.x+d.x)/2,y:(h.y+d.y)/2});e.setColor("blue"),e.drawCircle(f,3,i),e.drawLine(t[1],f,i),e.setColor("#666"),e.drawLine(f,h,i),e.drawLine(f,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 p=new e.Bezier(this.convert(h,a,o,s)),m=new e.Bezier(this.convert(a,o,s,d));e.setColor("lightgrey"),e.drawCurve(p,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(p,i),e.drawCurve(m,i),e.drawPoints(p.points,i),e.drawPoints(m.points,i),e.setColor("lightgrey"),e.drawLine(p.points[0],p.points[1],i),e.drawLine(p.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(0),i=n(8),a=n(6),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 S (at some distance ",r.createElement("i",null,"a")," from S) and also lies on the tangent line through E (at some distance ",r.createElement("i",null,"b")," from E). 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",height:"190px"})),r.createElement("p",null,"plotted for 0 ≤ φ ≤ π:")),r.createElement("td",null,r.createElement("p",null,r.createElement("img",{src:"images/arc-q-pi2.gif",height:"187px"})),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",height:"174px"})),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(0),i=n(8),a=n(6),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);i<0&&(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,{ +c=(100*c|0)/100,e.text("Approximate length, "+e.steps+" steps: "+h+" (true: "+c+")",{x:10,y:15})},render:function(){return r.createElement("section",null,r.createElement(a,this.props),r.createElement("p",null,"Sometimes, we don't actually need the precision of a true arc length, and we can get away with simply computing the approximate arc length instead. The by far fastest way to do this is to flatten the curve and then simply calculate the linear distance from point to point. This will come with an error, but this can be made arbitrarily small by increasing the segment count."),r.createElement("p",null,"If we combine the work done in the previous sections on curve flattening and arc length computation, we can implement these with minimal effort:"),r.createElement(i,{preset:"twopanel",title:"Approximate quadratic curve arc length",setup:this.setupQuadratic,draw:this.draw,onKeyDown:this.props.onKeyDown}),r.createElement(i,{preset:"twopanel",title:"Approximate cubic curve arc length",setup:this.setupCubic,draw:this.draw,onKeyDown:this.props.onKeyDown}),r.createElement("p",null,"Try clicking on the sketch and using your up and down arrow keys to lower the number of segments for both the quadratic and cubic curve. You may notice that the error in length is actually pretty significant, even if the percentage is fairly low: if the number of segments used yields an error of 0.1% or higher, the flattened curve already looks fairly obviously flattened. And of course, the longer the curve, the more significant the error will be."))}});e.exports=o(s)},function(e,t,n){"use strict";var r=n(0),i=n(4),a=new i,o="boundingbox",s=r.createClass({displayName:"BoundingBox",getDefaultProps:function(){return{title:a.getTitle(o)}},setupQuadratic:function(e){var t=e.getDefaultQuadratic();e.setCurve(t)},setupCubic:function(e){var t=e.getDefaultCubic();e.setCurve(t)},draw:function(e,t){e.reset(),e.setColor("#00FF00"),e.drawbbox(t.bbox()),e.setColor("black"),e.drawSkeleton(t),e.drawCurve(t),e.setColor("red"),t.extrema().values.forEach(function(n){e.drawCircle(t.get(n),3)})},render:function(){return r.createElement("section",null,a.getContent(o,this))}});e.exports=s},function(e,t,n){"use strict";e.exports={degree:3,activeDistance:9,setup:function(){this.size(600,300),this.draw()},draw:function(){var e=this;this.clear(),this.grid(25);var t=this.points[0];this.points.forEach(function(n){e.stroke(200),e.line(n.x,n.y,t.x,t.y),t=n,e.stroke(0),e.circle(t.x,t.y,4)}),this.drawSplineData()},drawSplineData:function(){if(!(this.points.length<=this.degree)){var e=this.points.map(function(e){return[e.x,e.y]});this.drawCurve(e),this.drawKnots(e)}}}},function(e,t,n){"use strict";e.exports={degree:3,activeDistance:9,setup:function(){this.size(400,400);for(var e=2*Math.PI,t=0;t s + L - order; i--) {\n let numerator = t - knots[i]\n let denominator = knots[i - L + order] - knots[i]\n let alpha = numerator / denominator\n let v[i] = alpha * v[i] + (1-alpha) * v[i-1]\n }\n }"),r.createElement("p",null,'(A nice bit of behaviour in this code is that we work the interpolation "backwards", starting at ',r.createElement("code",null,"i=s")," at each level of the interpolation, and we stop when ",r.createElement("code",null,"i = s - order + level"),", so we always end up with a value for ",r.createElement("code",null,"i")," such that those ",r.createElement("code",null,"v[i-1]")," don't try to use an array index that doesn't exist)"),r.createElement("h2",null,"Open vs. closed paths"),r.createElement("p",null,"Much like poly-Béziers, B-Splines can be either open, running from the first point to the last point, or closed, where the first and last point are ",r.createElement("em",null,"the same point"),". However, because B-Splines are an interpolation of curves, not just point, we can't simply make the first and last point the same, we need to link a few point point: for an order ",r.createElement("code",null,"d")," B-Spline, we need to make the last ",r.createElement("code",null,"d")," point the same as the first ",r.createElement("code",null,"d")," points. And the easiest way to do this is to simply append ",r.createElement("code",null,"points.splice(0,d)")," to ",r.createElement("code",null,"points"),". Done!"),r.createElement("p",null,'Of course if we want to manipulate these kind of curves we need to make sure to mark them as "closed" so that we know the coordinate for ',r.createElement("code",null,"points[0]")," and ",r.createElement("code",null,"points[n-k]")," etc. are the same coordinate, and manipulating one will equally manipulate the other, but programming generally makes this really easy by storing references to coordinates (or other linked values such as coordinate weights, discussed in the NURBS section) rather than separate coordinate objects."),r.createElement("h2",null,"Manipulating the curve through the knot vector"),r.createElement("p",null,"The most important thing to understand when it comes to B-Splines is that they work ",r.createElement("em",null,"because"),' of the concept of a knot vector. As mentioned above, knots represent "where individual control points start/stop influencing the curve", but we never looked at the ',r.createElement("em",null,"values")," that go in the knot vector. If you look back at the N() and a() functions, you see that interpolations are based on intervals in the knot vector, rather than the actual values in the knot vector, and we can exploit this to do some pretty interesting things with clever manipulation of the knot vector. Specifically there are four things we can do that are worth looking at:"),r.createElement("ol",null,r.createElement("li",null,"we can use a uniform knot vector, with equally spaced intervals,"),r.createElement("li",null,"we can use a non-uniform knot vector, without enforcing equally spaced internvals,"),r.createElement("li",null,'we can collapse sequential knots to the same value, locally lowering curve complexity using "null" intervals, and'),r.createElement("li",null,"we can form a special case non-uniform vector, by combining (1) and (3) to for a vector with collapsed start and end knots, with a uniform vector in between.")),r.createElement("h3",null,"Uniform B-Splines"),r.createElement("p",null,"The most straightforward type of B-Spline is the uniform spline. In a uniform spline, the knots are distributed uniformly over the entire curve interval. For instance, if we have a knot vector of length twelve, then a uniform knot vector would be [0,1,2,3,...,9,10,11]. Or [4,5,6,...,13,14,15], which defines ",r.createElement("em",null,"the same intervals"),", or even [0,2,3,...,18,20,22], which also defines ",r.createElement("em",null,"the same intervals"),", just scaled by a constant factor, which becomes normalised during interpolation and so does not contribute to the curvature."),r.createElement("div",{className:"two-column"},r.createElement(o,{ref:"uniform-spline"}),r.createElement(i,{sketch:n(131),controller:function(t,n){return e.bindKnots(t,n,"uniform-spline")}})),r.createElement("p",null,"This is an important point: the intervals that the knot vector defines are ",r.createElement("em",null,"relative")," intervals, so it doesn't matter if every interval is size 1, or size 100 - the relative differences between the intervals is what shapes any particular curve."),r.createElement("p",null,"The problem with uniform knot vectors is that, as we need ",r.createElement("code",null,"order"),' control points before we have any curve with which we can perform interpolation, the curve does not "start" at the first point, nor "ends" at the last point. Instead there are "gaps". We can get rid of these, by being clever about how we apply the following uniformity-breaking approach instead...'),r.createElement("h3",null,"Reducing local curve complexity by collapsing intervals"),r.createElement("p",null,"By collapsing knot intervals by making two or more consecutive knots have the same value, we can reduce the curve complexity in the sections that are affected by the knots involved. This can have drastic effects: for ever interval collapse, the curve order goes down, and curve continuity goes down, to the point where collapsing ",r.createElement("code",null,"order"),' knots creates a situation where all continuity is lost and the curve "kinks".'),r.createElement("div",{className:"two-column"},r.createElement(o,{ref:"center-cut-bspline"}),r.createElement(i,{sketch:n(126),controller:function(t,n){return e.bindKnots(t,n,"center-cut-bspline")}})),r.createElement("h3",null,"Open-Uniform B-Splines"),r.createElement("p",null,"By combining knot interval collapsing at the start and end of the curve, with uniform knots in between, we can overcome the problem of the curve not starting and ending where we'd kind of like it to:"),r.createElement("p",null,"For any curve of degree ",r.createElement("code",null,"D")," with control points ",r.createElement("code",null,"N"),", we can define a knot vector of length ",r.createElement("code",null,"N+D+1")," in which the values ",r.createElement("code",null,"0 ... D+1")," are the same, the values ",r.createElement("code",null,"D+1 ... N+1"),' follow the "uniform" pattern, and the values ',r.createElement("code",null,"N+1 ... N+D+1"),' are the same again. For example, a cubic B-Spline with 7 control points can have a knot vector [0,0,0,0,1,2,3,4,4,4,4], or it might have the "identical" knot vector [0,0,0,0,2,4,6,8,8,8,8], etc. Again, it is the relative differences that determine the curve shape.'),r.createElement("div",{className:"two-column"},r.createElement(o,{ref:"open-uniform-bspline"}),r.createElement(i,{sketch:n(129),controller:function(t,n){return e.bindKnots(t,n,"open-uniform-bspline")}})),r.createElement("h3",null,"Non-uniform B-Splines"),r.createElement("p",null,'This is essentialy the "free form" version of a B-Spline, and also the least interesting to look at, as without any specific reason to pick specific knot intervals, there is nothing particularly interesting going on. There is one constraint to the knot vector, and that is that any value ',r.createElement("code",null,"knots[k+1]"),"should be equal to, or greater than ",r.createElement("code",null,"knots[k]"),"."),r.createElement("h2",null,"One last thing: Rational B-Splines"),r.createElement("p",null,'While it is true that this section on B-Splines is running quite long already, there is one more thing we need to talk about, and that\'s "Rational" splines, where the rationality applies to the "ratio", or relative weights, of the control points themselves. By introducing a ratio vector with weights to apply to each control point, we greatly increase our influence over the final curve shape: the more weight a control point carries, the close to that point the spline curve will lie, a bit like turning up the gravity of a control point.'),r.createElement("div",{className:"two-column"},r.createElement(s,{ref:"rational-uniform-bspline-weights"}),r.createElement(i,{scrolling:!0,sketch:n(130),controller:function(t,n,r,i){e.bindWeights(t,r,i,"rational-uniform-bspline-weights")}})),r.createElement("p",null,'Of course this brings us to the final topic that any text on B-Splines must touch on before calling it a day: the NURBS, or Non-Uniform Rational B-Spline (NURBS is not a plural, the capital S actually just stands for "spline", but a lot of people mistakenly treat it as if it is, so now you know better). NURBS are an important type of curve in computer-facilitated design, used a lot in 3D modelling (as NURBS surfaces) as well as in arbitrary-precision 2D design due to the level of control a NURBS curve offers designers.'),r.createElement("p",null,"While a true non-uniform rational B-Spline would be hard to work with, when we talk about NURBS we typically mean the Open-Uniform Rational B-Spline, or OURBS, but that doesn't roll off the tongue nearly as nicely, and so remember that when people talk about NURBS, they typically mean open-uniform, which has the useful property of starting the curve at the first control point, and ending it at the last."),r.createElement("h2",null,"Extending our implementation to cover rational splines"),r.createElement("p",null,"The algorithm for working with Rational B-Splines is virtually identical to the regular algorithm, and the extension to work in the control point weights is fairly simple: we extend each control point from a point in its original number of dimensions (2D, 3D, etc) to one dimension higher, scaling the original dimensions by the control point's weight, and then assigning that weight as its value for the extended dimension."),r.createElement("p",null,"For example, a 2D point ",r.createElement("code",null,"(x,y)")," with weight ",r.createElement("code",null,"w")," becomes a 3D point ",r.createElement("code",null,"(w * x, w * y, w)"),"."),r.createElement("p",null,"We then run the same algorithm as before, which will automaticall perform weight interpolation in addition to regular coordinate interpolation, because all we've done is pretended we have coordinates in a higher dimension. The algorithm doesn't really care about how many dimensions it needs to interpolate."),r.createElement("p",null,'In order to recover our "real" curve point, we take the final result of the point generation algorithm, and "unweigh" it: we take the final point\'s derived weight ',r.createElement("code",null,"w'")," and divide all the regular coordinate dimensions by it, then throw away the weight information."),r.createElement("p",null,"Based on our previous example, we take the final 3D point ",r.createElement("code",null,"(x', y', w')"),", which we then turn back into a 2D point by computing ",r.createElement("code",null,"(x'/w', y'/w')"),". And that's it, we're done!"))}});e.exports=l},function(e,t,n){"use strict";var r=["#C00","#CC0","#0C0","#0CC","#00C","#C0C","#600","#660","#060","#066","#006","#606"];e.exports={degree:3,activeDistance:9,cache:{N:[]},setup:function(){this.size(600,300),this.points=[{x:0,y:0},{x:100,y:-100},{x:200,y:100},{x:300,y:-100},{x:400,y:100},{x:500,y:0}],this.knots=this.formKnots(this.points),this.props.controller&&this.props.controller(this,this.knots),this.draw()},draw:function(){this.clear();var e=25;this.grid(e),this.stroke(0),this.line(e,0,e,this.height);var t=this.height-e;this.line(0,t,this.width,t);for(var n=this.degree,r=this.points.length||4,i=0;i-10&&(l.push({x:i*u,y:i*c}),e.drawLine({x:i*u,y:i*c},{x:i*o,y:i*s},a)),u=o,c=s;l.push({x:i*u,y:i*c}),e.text("Curve form has cusp →",{x:n/2-2*i,y:r/2+i/2.5}),e.setColor("#FF00FF"),e.setFill(e.getColor());var h=Math.sqrt;for(o=1;o>=0;o-=.005)l.push({x:i*u,y:i*c}),s=.5*(h(3)*h(4*o-o*o)-o),e.drawLine({x:i*u,y:i*c},{x:i*o,y:i*s},a),u=o,c=s;for(l.push({x:i*u,y:i*c}),e.text("← Curve forms a loop at t = 1",{x:n/2+i/4,y:r/2+i/1.5}),e.setColor("#3300FF"),e.setFill(e.getColor()),o=0;o>-n;o-=.01)l.push({x:i*u,y:i*c}),s=(-o*o+3*o)/3,e.drawLine({x:i*u,y:i*c},{x:i*o,y:i*s},a),u=o,c=s;l.push({x:i*u,y:i*c}),e.text("← Curve forms a loop at t = 0",{x:n/2-i+10,y:r/2-1.25*i}),e.setColor("transparent"),e.setFill("rgba(255,120,100,0.2)"),e.drawPath(l,a),l=[{x:-n/2,y:i},{x:n/2,y:i},{x:n/2,y:r},{x:-n/2,y:r}],e.setFill("rgba(0,200,0,0.2)"),e.drawPath(l,a),e.setColor("black"),e.setFill(e.getColor()),e.text("← Curve form has one inflection →",{x:n/2-i,y:r/2+1.75*i}),e.text("← Plain curve ↕",{x:n/2+i/2,y:r/6}),e.text("↕ Double inflection",{x:10,y:r/2-10}),e._map_image=e.toImage(),e._map_loaded=!0},render:function(){return r.createElement("section",null,a.getContent(o,this))}});e.exports=s},function(e,t,n){"use strict";var r=n(0),i=n(6),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(0),i=n(8),a=n(6),o=n(15),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},f=e.utils.lli4(a,s,o,{x:(h.x+d.x)/2,y:(h.y+d.y)/2});e.setColor("blue"),e.drawCircle(f,3,i),e.drawLine(t[1],f,i),e.setColor("#666"),e.drawLine(f,h,i),e.drawLine(f,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 p=new e.Bezier(this.convert(h,a,o,s)),m=new e.Bezier(this.convert(a,o,s,d));e.setColor("lightgrey"),e.drawCurve(p,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(p,i),e.drawCurve(m,i),e.drawPoints(p.points,i),e.drawPoints(m.points,i),e.setColor("lightgrey"),e.drawLine(p.points[0],p.points[1],i),e.drawLine(p.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(0),i=n(8),a=n(6),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 S (at some distance ",r.createElement("i",null,"a")," from S) and also lies on the tangent line through E (at some distance ",r.createElement("i",null,"b")," from E). 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",height:"190px"})),r.createElement("p",null,"plotted for 0 ≤ φ ≤ π:")),r.createElement("td",null,r.createElement("p",null,r.createElement("img",{src:"images/arc-q-pi2.gif",height:"187px"})),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",height:"174px"})),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(0),i=n(8),a=n(6),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);i<0&&(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",height:"187px"})),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",height:"187px"})),r.createElement("p",null,"plotted for 0 ≤ φ ≤ π:")),r.createElement("td",null,r.createElement("p",null,r.createElement("img",{src:"images/arc-c-pi2.gif",height:"187px"})),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(0),i={width:"calc(960px + 2em)",marginTop:0,borderTop:"1px solid rgba(255, 0, 0, 0.5)",paddingTop:"3em"},a=r.createElement("section",{id:"comments",style:i},r.createElement("h2",null,"Comments and questions"),r.createElement("p",null,"If you enjoyed this book, or you simply found it useful for something you were trying to get done, and you were wondering how to let me know you appreciated this book, you can always ",r.createElement("a",{className:"link",href:"https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=QPRDLNGDANJSW"},"buy me a coffee"),", however much a coffee is where you live. This work has grown over the years, from a small primer to a 70ish print-page-equivalent reader on the subject of Bézier curves, and a lot of coffee went into the making of it. I don't regret a minute I spent on writing it, but I can always do with some more coffee to keep on writing!"),r.createElement("div",{id:"disqus_thread"})),o=r.createClass({displayName:"CommentsAndQuestions",getDefaultProps:function(){return{title:"Comments and Questions"}},componentDidMount:function(){if("undefined"!=typeof document){var e=document.createElement("script");e.setAttribute("async","async"),e.src="lib/site/disqus.js",document.head.appendChild(e)}},render:function(){return a}});e.exports=o},function(e,t,n){"use strict";var r=n(0),i=n(4),a=new i,o="components",s=r.createClass({displayName:"Components",getDefaultProps:function(){return{title:a.getTitle(o)}},setupQuadratic:function(e){var t=e.getDefaultQuadratic();t.points[2].x=210,e.setCurve(t)},setupCubic:function(e){var t=e.getDefaultCubic();e.setCurve(t)},draw:function(e,t){e.setPanelCount(3),e.reset(),e.drawSkeleton(t),e.drawCurve(t);var n=t.order+1,r=20,i=t.points,a=e.getPanelWidth(),o=e.getPanelHeight(),s={x:a,y:0},l=JSON.parse(JSON.stringify(i)).map(function(e,t){return{x:a*t/n,y:e.x}});e.drawLine({x:0,y:0},{x:0,y:o},s),e.drawAxes(r,"t",0,1,"x",0,a,s),s.x+=r,e.drawCurve(new e.Bezier(l),s),s.x+=a-r;var u=JSON.parse(JSON.stringify(i)).map(function(e,t){return{x:a*t/n,y:e.y}});e.drawLine({x:0,y:0},{x:0,y:o},s),e.drawAxes(r,"t",0,1,"y",0,a,s),s.x+=r,e.drawCurve(new e.Bezier(u),s)},render:function(){return r.createElement("section",null,a.getContent(o,this))}});e.exports=s},function(e,t,n){"use strict";var r=n(0),i=n(4),a=new i,o="control",s=r.createClass({displayName:"Control",getDefaultProps:function(){return{title:a.getTitle(o)}},drawCubic:function(e){var t=e.getDefaultCubic();e.setCurve(t)},drawCurve:function(e,t){e.reset(),e.drawSkeleton(t),e.drawCurve(t)},drawFunction:function(e,t,n,r){e.setRandomColor(),e.drawFunction(r),e.setFill(e.getColor()),t&&e.text(t,n)},drawLerpBox:function(e,t,n,r){e.noColor(),e.setFill("rgba(0,0,100,0.2)");var i={x:r.x-5,y:n},a={x:r.x+5,y:t};e.drawRect(i,a),e.setColor("black")},drawLerpPoint:function(e,t,n,r,i){i.y=n+t*r,e.drawCircle(i,3),e.setFill("black"),e.text((1e4*t|0)/100+"%",{x:i.x+10,y:i.y+4}),e.noFill()},drawQuadraticLerp:function(e){e.reset();var t=e.getPanelWidth(),n=20,r=t-2*n;e.drawAxes(n,"t",0,1,"S","0%","100%");var i=e.hover;if(i&&i.x>=n&&i.x<=t-n){this.drawLerpBox(e,t,n,i);var a=(i.x-n)/r;this.drawLerpPoint(e,(1-a)*(1-a),n,r,i),this.drawLerpPoint(e,2*(1-a)*a,n,r,i),this.drawLerpPoint(e,a*a,n,r,i)}this.drawFunction(e,"first term",{x:2*n,y:r},function(e){return{x:n+e*r,y:n+r*(1-e)*(1-e)}}),this.drawFunction(e,"second term",{x:t/2-1.5*n,y:t/2+n},function(e){return{x:n+e*r,y:n+2*r*(1-e)*e}}),this.drawFunction(e,"third term",{x:r-2.5*n,y:r},function(e){return{x:n+e*r,y:n+r*e*e}})},drawCubicLerp:function(e){e.reset();var t=e.getPanelWidth(),n=20,r=t-2*n;e.drawAxes(n,"t",0,1,"S","0%","100%");var i=e.hover;if(i&&i.x>=n&&i.x<=t-n){this.drawLerpBox(e,t,n,i);var a=(i.x-n)/r;this.drawLerpPoint(e,(1-a)*(1-a)*(1-a),n,r,i),this.drawLerpPoint(e,3*(1-a)*(1-a)*a,n,r,i),this.drawLerpPoint(e,3*(1-a)*a*a,n,r,i),this.drawLerpPoint(e,a*a*a,n,r,i)}this.drawFunction(e,"first term",{x:2*n,y:r},function(e){return{x:n+e*r,y:n+r*(1-e)*(1-e)*(1-e)}}),this.drawFunction(e,"second term",{x:t/2-4*n,y:t/2},function(e){return{x:n+e*r,y:n+3*r*(1-e)*(1-e)*e}}),this.drawFunction(e,"third term",{x:t/2+2*n,y:t/2},function(e){return{x:n+e*r,y:n+3*r*(1-e)*e*e}}),this.drawFunction(e,"fourth term",{x:r-2.5*n,y:r},function(e){return{x:n+e*r,y:n+r*e*e*e}})},draw15thLerp:function(e){e.reset();var t=e.getPanelWidth(),n=20,r=t-2*n;e.drawAxes(n,"t",0,1,"S","0%","100%");var i,a=[1,15,105,455,1365,3003,5005,6435,6435,5005,3003,1365,455,105,15,1],o=e.hover;if(o&&o.x>=n&&o.x<=t-n)for(this.drawLerpBox(e,t,n,o),i=0;i<=15;i++){var s=(o.x-n)/r,l=a[i]*Math.pow(1-s,15-i)*Math.pow(s,i);this.drawLerpPoint(e,l,n,r,o)}for(i=0;i<=15;i++){var u=!1,c=!1;0===i&&(u="first term",c={x:n+5,y:r}),15===i&&(u="last term",c={x:t-3.5*n,y:r}),this.drawFunction(e,u,c,function(e){return{x:n+e*r,y:n+r*a[i]*Math.pow(1-e,15-i)*Math.pow(e,i)}})}},render:function(){return r.createElement("section",null,a.getContent(o,this))}});e.exports=s},function(e,t,n){"use strict";var r=n(0),i=n(8),a=n(6),o=Math.abs,s=r.createClass({displayName:"CurveIntersections",getDefaultProps:function(){return{title:"Curve/curve intersection"}},setup:function(e){this.api=e,e.setPanelCount(3);var t=new e.Bezier(10,100,90,30,40,140,220,220),n=new e.Bezier(5,150,180,20,80,250,210,190);e.setCurve(t,n),this.pairReset()},pairReset:function(){this.prevstep=0,this.step=0},draw:function(e,t){var n=this;e.reset();var r={x:0,y:0};t.forEach(function(t){e.drawSkeleton(t),e.drawCurve(t)});var i=e.getPanelWidth(),a=e.getPanelHeight();if(r.x+=i,e.drawLine({x:0,y:0},{x:0,y:a},r),0===this.step&&(this.pairs=[{c1:t[0],c2:t[1]}]),this.step!==this.prevstep){var s=this.pairs;this.pairs=[],this.finals=[],s.forEach(function(t){if(t.c1.length()<.6&&t.c2.length()<.6)return n.finals.push(t);var i=t.c1.split(.5);e.setColor("black"),e.drawCurve(t.c1,r),e.setColor("red"),e.drawbbox(i.left.bbox(),r),e.drawbbox(i.right.bbox(),r);var a=t.c2.split(.5);e.setColor("black"),e.drawCurve(t.c2,r),e.setColor("blue"),e.drawbbox(a.left.bbox(),r),e.drawbbox(a.right.bbox(),r),i.left.overlaps(a.left)&&n.pairs.push({c1:i.left,c2:a.left}),i.left.overlaps(a.right)&&n.pairs.push({c1:i.left,c2:a.right}),i.right.overlaps(a.left)&&n.pairs.push({c1:i.right,c2:a.left}),i.right.overlaps(a.right)&&n.pairs.push({c1:i.right,c2:a.right})}),this.prevstep=this.step}else this.pairs.forEach(function(t){e.setColor("black"),e.drawCurve(t.c1,r),e.drawCurve(t.c2,r),e.setColor("red"),e.drawbbox(t.c1.bbox(),r),e.setColor("blue"),e.drawbbox(t.c2.bbox(),r)});0===this.pairs.length&&(this.pairReset(),this.draw(e,t)),r.x+=i,e.setColor("black"),e.drawLine({x:0,y:0},{x:0,y:a},r);var l,u,c=t[0].intersects(t[1]).map(function(e){var t=e.split("/").map(function(e){return parseFloat(e)});return{t1:t[0],t2:t[1]}}),h=c[0],d=function(e,t){return o(e.t1-t.t1)<.01&&o(e.t2-t.t2)<.01};for(u=1;u.95)&&(e.text("t = "+Math.round(h),{x:c.x+1.25*s*Math.cos(h)-10,y:c.y+1.25*l*Math.sin(h)+5}),e.drawCircle(u,2,c))}},render:function(){return r.createElement("section",null,o.getContent(s,this))}});e.exports=i(l)},function(e,t,n){"use strict";var r=n(0),i=n(4),a=new i,o="extended",s=r.createClass({displayName:"Explanation",getDefaultProps:function(){return{title:a.getTitle(o)}},setupQuadratic:function(e){var t=new e.Bezier(70,155,20,110,100,75);e.setCurve(t)},setupCubic:function(e){var t=new e.Bezier(60,105,75,30,215,115,140,160);e.setCurve(t)},draw:function(e,t){e.reset(),e.drawSkeleton(t),e.drawCurve(t),e.setColor("lightgrey");var n,r,i=.05,a=-10,o=t.get(a-i);for(n=a;n<=i;n+=i)r=t.get(n),e.drawLine(o,r),o=r;o=t.get(1);var s=10;for(n=1+i;n<=s;n+=i)r=t.get(n),e.drawLine(o,r),o=r},render:function(){return r.createElement("section",null,a.getContent(o,this))}});e.exports=s},function(e,t,n){"use strict";var r=n(0),i=n(4),a=new i,o="extremities",s=r.createClass({displayName:"Extremities",getDefaultProps:function(){return{title:a.getTitle(o)}},setupQuadratic:function(e){var t=e.getDefaultQuadratic();t.points[2].x=210,e.setCurve(t)},setupCubic:function(e){var t=e.getDefaultCubic();e.setCurve(t)},draw:function(e,t){e.setPanelCount(3),e.reset(),e.drawSkeleton(t),e.drawCurve(t);var n=t.order+1,r=20,i=t.points,a=e.getPanelWidth(),o=e.getPanelHeight(),s={x:a,y:0},l=JSON.parse(JSON.stringify(i)).map(function(e,t){return{x:a*t/n,y:e.x}});e.setColor("black"),e.drawLine({x:0,y:0},{x:0,y:o},s),e.drawAxes(r,"t",0,1,"x",0,a,s),s.x+=r;var u=new e.Bezier(l);e.drawCurve(u,s),e.setColor("red"),u.extrema().y.forEach(function(t){var n=u.get(t);e.drawCircle(n,3,s)}),s.x+=a-r;var c=JSON.parse(JSON.stringify(i)).map(function(e,t){return{x:a*t/n,y:e.y}});e.setColor("black"),e.drawLine({x:0,y:0},{x:0,y:o},s),e.drawAxes(r,"t",0,1,"y",0,a,s),s.x+=r;var h=new e.Bezier(c);e.drawCurve(h,s),e.setColor("red"),h.extrema().y.forEach(function(t){var n=h.get(t);e.drawCircle(n,3,s)})},render:function(){return r.createElement("section",null,a.getContent(o,this))}});e.exports=s},function(e,t,n){"use strict";var r=n(0),i=n(4),a=new i,o="flattening",s=n(15),l=r.createClass({displayName:"Flattening",statics:{keyHandlingOptions:{propName:"steps",values:{38:1,40:-1},controller:function(e){e.steps<1&&(e.steps=1)}}},getDefaultProps:function(){return{title:a.getTitle(o)}},setupQuadratic:function(e){var t=e.getDefaultQuadratic();e.setCurve(t),e.steps=3},setupCubic:function(e){var t=e.getDefaultCubic();e.setCurve(t),e.steps=5},drawFlattened:function(e,t){e.reset(),e.setColor("#DDD"),e.drawSkeleton(t),e.setColor("#DDD"),e.drawCurve(t);for(var n,r=1/e.steps,i=t.points[0],a=r;a<1+r;a+=r)n=t.get(Math.min(a,1)),e.setColor("red"),e.drawLine(i,n),i=n;e.setFill("black"),e.text("Curve approximation using "+e.steps+" segments",{x:10,y:15})},values:{38:1,40:-1},onKeyDown:function(e,t){var n=this.values[e.keyCode];n&&(e.preventDefault(),t.steps+=n,t.steps<1&&(t.steps=1))},render:function(){return r.createElement("section",null,a.getContent(o,this))}});e.exports=s(l)},function(e,t,n){"use strict";var r=n(0),i=n(8),a=n(6),o=n(15),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(0),i=n(4),a=new i,o="inflections",s=r.createClass({displayName:"ABC",getDefaultProps:function(){return{title:a.getTitle(o)}},setupCubic:function(e){var t=new e.Bezier(135,25,25,135,215,75,215,240);e.setCurve(t)},draw:function(e,t){e.reset(),e.drawSkeleton(t),e.drawCurve(t),e.setColor("red"),t.inflections().forEach(function(n){e.drawCircle(t.get(n),5)})},render:function(){return r.createElement("section",null,a.getContent(o,this))}});e.exports=s},function(e,t,n){"use strict";var r=n(0),i=n(8),a=n(6),o=Math.min,s=Math.max,l=r.createClass({displayName:"Intersections",getDefaultProps:function(){return{title:"Intersections"}},setupLines:function(e){var t=new e.Bezier([50,50,150,110]),n=new e.Bezier([50,250,170,170]);e.setCurve(t,n)},drawLineIntersection:function(e,t){e.reset();var n=e.utils.lli4,r=n(t[0].points[0],t[0].points[1],t[1].points[0],t[1].points[1]),i=0;t.forEach(function(t){if(e.drawSkeleton(t),e.setColor("black"),r){var n=t.points,a=o(n[0].x,n[1].x),l=o(n[0].y,n[1].y),u=s(n[0].x,n[1].x),c=s(n[0].y,n[1].y);a<=r.x&&l<=r.y&&u>=r.x&&c>=r.y&&(e.setColor("#00FF00"),i++)}e.drawCurve(t)}),r&&(e.setColor(i<2?"red":"#00FF00"),e.drawCircle(r,3))},setupQuadratic:function(e){var t=e.getDefaultQuadratic(),n=new e.Bezier([15,250,220,20]);e.setCurve(t,n)},setupCubic:function(e){var t=new e.Bezier([100,240,30,60,210,230,160,30]),n=new e.Bezier([25,260,230,20]); -e.setCurve(t,n)},draw:function(e,t){e.reset(),t.forEach(function(t){e.drawSkeleton(t),e.drawCurve(t)});var n=e.utils,r={p1:t[1].points[0],p2:t[1].points[1]},i=n.align(t[0].points,r),a=new e.Bezier(i),o=n.roots(a.points);o.forEach(function(n){var r=t[0].get(n);e.drawCircle(r,3),e.text("t = "+n,{x:r.x+5,y:r.y+10})})},render:function(){return r.createElement("section",null,r.createElement(a,this.props),r.createElement("p",null,"Let's look at some more things we will want to do with Bézier curves. Almost immediately after figuring out how to get bounding boxes to work, people tend to run into the problem that even though the minimal bounding box (based on rotation) is tight, it's not sufficient to perform true collision detection. It's a good first step to make sure there ",r.createElement("em",null,"might")," be a collision (if there is no bounding box overlap, there can't be one), but in order to do real collision detection we need to know whether or not there's an intersection on the actual curve."),r.createElement("p",null,"We'll do this in steps, because it's a bit of a journey to get to curve/curve intersection checking. First, let's start simple, by implementing a line-line intersection checker. While we can solve this the traditional calculus way (determine the functions for both lines, then compute the intersection by equating them and solving for two unknowns), linear algebra actually offers a nicer solution."),r.createElement("h3",null,"Line-line intersections"),r.createElement("p",{id:"intersection_ll"},"if we have two line segments with two coordinates each, segments A-B and C-D, we can find the intersection of the lines these segments are an intervals on by linear algebra, using the procedure outlined in this ",r.createElement("a",{href:"http://www.topcoder.com/tc?module=Static&d1=tutorials&d2=geometry2#line_line_intersection"},"top coder")," article. Of course, we need to make sure that the intersection isn't just on the lines our line segments lie on, but also on our line segments themselves, so after we find the intersection we need to verify it lies without the bounds of our original line segments."),r.createElement("p",null),r.createElement("p",null,"The following graphic implements this intersection detection, showing a red point for an intersection on the lines our segments lie on (thus being a virtual intersection point), and a green point for an intersection that lies on both segments (being a real intersection point)."),r.createElement(i,{preset:"simple",title:"Line/line intersections",setup:this.setupLines,draw:this.drawLineIntersection}),r.createElement("div",{className:"howtocode"},r.createElement("h3",null,"Implementing line-line intersections"),r.createElement("p",null,"Let's have a look at how to implement a line-line intersection checking function. The basics are covered in the article mentioned above, but sometimes you need more function signatures, because you might not want to call your function with eight distinct parameters. Maybe you're using point structs or the line. Let's get coding:"),r.createElement("pre",null,"lli8 = function(x1,y1,x2,y2,x3,y3,x4,y4):","\n"," var nx=(x1*y2-y1*x2)*(x3-x4)-(x1-x2)*(x3*y4-y3*x4),","\n"," ny=(x1*y2-y1*x2)*(y3-y4)-(y1-y2)*(x3*y4-y3*x4),","\n"," d=(x1-x2)*(y3-y4)-(y1-y2)*(x3-x4);","\n"," if d=0:","\n"," return false","\n"," return point(nx/d, ny/d)","\n","\n","lli4 = function(p1, p2, p3, p4):","\n"," var x1 = p1.x, y1 = p1.y,","\n"," x2 = p2.x, y2 = p2.y,","\n"," x3 = p3.x, y3 = p3.y,","\n"," x4 = p4.x, y4 = p4.y;","\n"," return lli8(x1,y1,x2,y2,x3,y3,x4,y4)","\n","\n","lli = function(line1, line2):","\n"," return lli4(line1.p1, line1.p2, line2.p1, line2.p2)")),r.createElement("h3",null,"What about curve-line intersections?"),r.createElement("p",null,"Curve/line intersection is more work, but we've already seen the techniques we need to use in order to perform it: first we translate/rotate both the line and curve together, in such a way that the line coincides with the x-axis. This will position the curve in a way that makes it cross the line at points where its y-function is zero. By doing this, the problem of finding intersections between a curve and a line has now become the problem of performing root finding on our translated/rotated curve, as we already covered in the section on finding extremities."),r.createElement(i,{preset:"simple",title:"Quadratic curve/line intersections",setup:this.setupQuadratic,draw:this.draw}),r.createElement(i,{preset:"simple",title:"Cubic curve/line intersections",setup:this.setupCubic,draw:this.draw}),r.createElement("p",null,"Curve/curve intersection, however, is more complicated. Since we have no straight line to align to, we can't simply align one of the curves and be left with a simple procedure. Instead, we'll need to apply two techniques we've not covered yet: de Casteljau's algorithm, and curve splitting."))}});e.exports=l},function(e,t,n){"use strict";var r=n(0),i=n(4),a=new i,o="introduction",s=r.createClass({displayName:"Introduction",getDefaultProps:function(){return{title:a.getTitle(o)}},drawQuadratic:function(e){var t=e.getDefaultQuadratic();e.setCurve(t)},drawCubic:function(e){var t=e.getDefaultCubic();e.setCurve(t)},drawCurve:function(e,t){e.reset(),e.drawSkeleton(t),e.drawCurve(t)},render:function(){return r.createElement("section",null,a.getContent(o,this))}});e.exports=s},function(e,t,n){"use strict";var r=n(0),i=n(4),a=new i,o="matrix",s=r.createClass({displayName:"Matrix",getDefaultProps:function(){return{title:a.getTitle(o)}},render:function(){return r.createElement("section",null,a.getContent(o,this))}});e.exports=s},function(e,t,n){"use strict";var r=n(0),i=n(4),a=new i,o="matrixsplit",s=r.createClass({displayName:"MatrixSplit",getDefaultProps:function(){return{title:a.getTitle(o)}},render:function(){return r.createElement("section",null,a.getContent(o,this))}});e.exports=s},function(e,t,n){"use strict";var r=n(0),i=n(8),a=n(6),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!(n<.05||n>.95)&&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],f=t.B=c.get(n);t.db=c.derivative(n),t.C=t.utils.lli4(d,f,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},f={x:t.newA.x+(d.x-t.newA.x)/t.t,y:t.newA.y+(d.y-t.newA.y)/t.t},p={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-f.x)/(1-t.t),y:u[3].y-(u[3].y-f.y)/(1-t.t)};t.p1=c,t.p2=d,t.sc1=h,t.sc2=f,t.nc1=p,t.nc2=m,t.update=[p,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(0),i=n(8),a=n(6),o=n(15),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(0),i=n(8),a=n(6),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,f=c+h/d,p=f*(i.x-r.x)/u,m=f*(i.y-r.y)/u,g={x:a.x-p,y:a.y-m},v={x:a.x+p,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(0),i=n(4),a=new i,o="pointvectors",s=r.createClass({displayName:"PointVectors",getDefaultProps:function(){return{title:a.getTitle(o)}},setupQuadratic:function(e){var t=e.getDefaultQuadratic();e.setCurve(t)},setupCubic:function(e){var t=e.getDefaultCubic();e.setCurve(t)},draw:function(e,t){e.reset(),e.drawSkeleton(t);var n,r,i,a,o,s,l=20;for(n=0;n<=10;n++)r=n/10,i=t.get(r),a=t.derivative(r),s=Math.sqrt(a.x*a.x+a.y*a.y),a={x:a.x/s,y:a.y/s},o=t.normal(r),e.setColor("blue"),e.drawLine(i,{x:i.x+a.x*l,y:i.y+a.y*l}),e.setColor("red"),e.drawLine(i,{x:i.x+o.x*l,y:i.y+o.y*l}),e.setColor("black"),e.drawCircle(i,3)},render:function(){return r.createElement("section",null,a.getContent(o,this))}});e.exports=s},function(e,t,n){"use strict";var r=n(0),i=n(8),a=n(6),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;a<4;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+=r<0?e.lpts.length:0,n=t-2,n+=n<0?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,f=s(h*h+d*d);i.x=r.x+f*u(c),i.y=r.y+f*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+=r<0?e.lpts.length:0,n=t-2,n+=n<0?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,f=s(h*h+d*d);a.x=i.x+f*u(c),a.y=i.y+f*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(0),i=n(4),a=new i,o="preface",s=r.createClass({displayName:"Preface",getDefaultProps:function(){return{title:a.getTitle(o)}},render:function(){return r.createElement("section",null,a.getContent(o,this))}});e.exports=s},function(e,t,n){"use strict";var r=n(0),i=n(8),a=n(6),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;r1;){for(var o=0;of){r--;break}r<0&&(r=0),r===c.length&&(r=c.length-1),d.push(c[r])}for(n=0;n0;o-=e.step)a=o/100,a>1||(e.setRandomColor(),n={x:d.x+a*(f.x-d.x),y:d.y+a*(f.y-d.y)},r={x:f.x+a*(p.x-f.x),y:f.y+a*(p.y-f.y)},i={x:n.x+a*(r.x-n.x),y:n.y+a*(r.y-n.y)},m={x:0,y:0},e.drawCircle(n,3,m),e.drawCircle(r,3,m),e.setWeight(.5),e.drawLine(n,r,m),e.setWeight(1.5),e.drawLine(d,n,m),e.drawLine(f,r,m),e.setWeight(1),m.x+=c,e.drawCircle(n,3,m),e.drawCircle(r,3,m),e.setWeight(.5),e.drawLine(n,r,m),e.setWeight(1.5),e.drawLine(n,i,m),e.setWeight(1),e.drawCircle(i,3,m),m.x+=c,e.drawCircle(i,3,m),e.text(o+"%, or t = "+e.utils.round(a,2),{x:i.x+10+m.x,y:i.y+10+m.y}))},values:{38:1,40:-1},onKeyDown:function(e,t){var n=this.values[e.keyCode];n&&(e.preventDefault(),t.step+=n,t.step<1&&(t.step=1))},render:function(){return r.createElement("section",null,a.getContent(o,this))}});e.exports=s},function(e,t,n){"use strict";var r=n(0),i=n(8),a=n(6);e.exports={preface:{locale:"ja-JP",title:"まえがき",getContent:function(e){return r.createElement("section",null,r.createElement(a,{name:"preface",title:"まえがき"}),r.createElement("p",null,"2次元上になにかを描くとき、普通は線を使いますが、これは直線と曲線の2つに分類することができます。直線を描くのはとても簡単で、これをコンピュータに描かせるのも容易です。直線の始点と終点をコンピュータに与えてやれば、ポン!直線が描けました。疑問の余地もありません。"),r.createElement("p",null,"しかしながら、曲線の方はもっと大きな問題です。私たちはフリーハンドでいとも簡単に曲線を描くことができますが、コンピュータの方は少し不利です。曲線の描き方を表した数学的な関数が与えられないと、コンピュータは曲線を描くことができないのです。実際には、直線でさえも関数が必要になります。直線の関数はとても簡単なので、わたしたちはよく無視してしまいますが、コンピュータにとっては直線であれ曲線であれ、線はすべて「関数」なのです。しかしこれは、コンピュータで速く計算できて、きれいな曲線が得られるような関数を見つける必要がある、ということになります。そのような関数はたくさんありますが、多くの関心を集め続け、そしてどんな場面でも使われている、ある特定の関数に対してこの記事では焦点を絞ります。この関数は「ベジエ」曲線を描きます。"),r.createElement("p",null,"ベジエ曲線は",r.createElement("a",{href:"https://ja.wikipedia.org/wiki/ピエール・ベジェ"},"Pierre Bézier"),"から名付けられました。この曲線がデザイン作業に適していることを世界に知らしめたのが、彼なのです(ルノーに勤務し、1962年にその研究を発表しました)。ただし、この曲線を「発明」したのは彼が最初で唯一というわけではありません。数学者",r.createElement("a",{href:"https://en.wikipedia.org/wiki/Paul_de_Casteljau"},"Paul de Casteljau"),"はシトロエンで働いていた1959年、この曲線の性質について研究し、ベジエ曲線の非常にエレガントな描き方を発見しました。これが最初だと言う人もいます。しかしながら、de Casteljauは自分の成果を発表しなかったため、「誰が最初か?」という問いに答えるのがとても難しくなっています。またベジエ曲線は、核心的には",r.createElement("a",{href:"https://ja.wikipedia.org/wiki/セルゲイ・ベルンシュテイン"},"Sergei Natanovich Bernstein"),"が研究した「ベルンシュタイン多項式」という数学関数の一種ですが、こちらの公刊に関しては少なくとも1912年まで遡ることができます。いずれにせよ、これらはほとんど瑣末なことです。より注目すべきなのは、ベジエ曲線は取り扱いに便利だいうことです。たとえば複数のベジエ曲線を繋いで、1つの曲線に見えるようにすることができます。もしあなたがPhotoshopで「パス」を描いたり、FlashやIllustrator、Inkscapeのようなベクタードローイングソフトを使ったことがあるのであれば、そこで描いてきた曲線はベジエ曲線です。"),r.createElement("p",null,"では、これを自分でプログラムしなければならないとなったらどうでしょう?ハマりどころは何でしょうか?どうやってベジエ曲線を描くのでしょう?バウンディングボックスとは何で、どうやって交点を求め、どうやったら曲線を押し出せるのでしょうか?つまるところ、ベジエ曲線に対して行いたいあらゆる操作は、どのようにすればいいのでしょう?このページはそれに答えるためにあります。数学にとりかかりましょう!"),r.createElement("p",null,"—Pomax (Twitter上では",r.createElement("a",{href:"https://twitter.com/TheRealPomax"},"@TheRealPomax"),")"),r.createElement("div",{ -className:"note"},r.createElement("h2",{id:"-"},"注:ベジエの図はすべてインタラクティブになっています。"),r.createElement("p",null,"このページでは",r.createElement("a",{href:"http://pomax.github.io/bezierjs"},"Bezier.js"),"を活用し、インタラクティブな例示を行っています。また、",r.createElement("a",{href:"http://mathjax.org"},"MathJax"),"というすばらしいライブラリによって、(LaTeX式の)「本物」の数学組版を行っています。このページはWebpackを使い、Reactアプリケーションとしてオフラインで生成されていますが、このために「ソースを表示」オプションを追加することがかなり難しくなってしまいました。これをどうやって追加すべきかは今もまだ考え中ですが、かといって、数年ぶりとなる今回の更新を延期したくはありませんでした。"),r.createElement("h2",{id:"-"},"本書はオープンソースです。"),r.createElement("p",null,"この本はオープンソースソフトウェアのプロジェクトで、2つのGitHubリポジトリ上に存在しています。1つ目の",r.createElement("a",{href:"https://github.com/pomax/bezierinfo"},"https://github.com/pomax/bezierinfo"),"は表示のためだけに用意されたバージョンで、あなたが今読んでいるものです。もう一方の",r.createElement("a",{href:"https://github.com/pomax/BezierInfo-2"},"https://github.com/pomax/BezierInfo-2"),"は開発版で、すべてのHTML・JavaScript・CSSが含まれています。どちらのリポジトリもフォークすることができますし、あなたの好きなように使ってかまいません。ただし、これを自分の成果だと騙って売ることはもちろん除きます。=)"),r.createElement("h2",{id:"-"},"数学はどこまで難しくなりますか?"),r.createElement("p",null,"この入門に出てくる数学は、大半が高校初年度程度です。基本的な計算を理解していて、英語の読み方が分かっていれば、こなすことができるはずです。時には",r.createElement("em",null,"ずっと"),"難しい数学も出てきますが、もし理解できないように感じたら、そこは読み飛ばしても大丈夫です。節の中の「詳細欄」を飛ばしてもいいですし、厄介そうな数学があれば節の最後まで読み飛ばしてもかまいません。各節の最後にはたいてい結論を並べてありますので、これを直に利用することもできます。"),r.createElement("h2",{id:"-"},"質問・コメント:"),r.createElement("p",null,"新しい節の提案があれば、",r.createElement("a",{href:"https://github.com/pomax/BezierInfo-2/issues"},"GitHubのissueトラッカー"),"をクリックしてください(右上にあるリポジトリのリンクからでもたどり着けます)。改訂中のため、現在はこのページにはコメント欄がありませんが、内容に関する質問がある場合にもissueトラッカーを使ってかまいません。改訂が完了したら、総合的なコメント欄を復活させる予定です。あるいは、「質問対象の節を選択して『質問』ボタンをクリック」するような項目別のシステムになるかもしれません。いずれわかります。"),r.createElement("h2",{id:"-"},"コーヒーをおごってくれませんか?"),r.createElement("p",null,"この本が気に入った場合や、取り組んでいたことに役に立つと思った場合、あるいは、この本への感謝をわたしに伝えるにはどうすればいいのかわからない場合。そのような場合には、",r.createElement("a",{href:"https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=QPRDLNGDANJSW"},"わたしにコーヒーをおごってください"),"。あなたが住んでいるところのコーヒー1杯の値段でかまいません。この本は小さな入門からはじまり、印刷で70ページほどに相当するようなベジエ曲線の読み物へと、年々成長してきています。そして、多くのコーヒーが執筆に費やされてきました。わたしは執筆に使った時間が惜しいとは思いませんが、もう少しコーヒーがあれば、ずっと書き続けることができるのです!")))}},introduction:{locale:"ja-JP",title:"バッとした導入",getContent:function(e){return r.createElement("section",null,r.createElement(a,{name:"introduction",title:"バッとした導入",number:"1"}),r.createElement("p",null,"まずは良い例から始めましょう。ベジエ曲線というのは、下の図に表示されているもののことです。ベジエ曲線はある始点からある終点へと延びており、その曲率は1個以上の「中間」制御点に左右されています。さて、このページの図はどれもインタラクティブになっていますので、ここで曲線をちょっと操作してみましょう。点をドラッグしたとき、曲線の形がそれに応じてどう変化するのか、確かめてみてください。"),r.createElement("div",{className:"figure"},r.createElement(i,{inline:!0,title:"2次のベジエ曲線",setup:e.drawQuadratic,draw:e.drawCurve}),r.createElement(i,{inline:!0,title:"3次のベジエ曲線",setup:e.drawCubic,draw:e.drawCurve})),r.createElement("p",null,"ベジエ曲線は、CAD(computer aided designやCAM(computer aided manufacturing)のアプリケーションで多用されています。もちろん、Adobe Illustrator・Photoshop・Inkscape・Gimp などのグラフィックデザインアプリケーションや、SVG(scalable vector graphics)・OpenTypeフォント(otf/ttf)のようなグラフィック技術でも利用されています。ベジエ曲線はたくさんのものに使われていますので、これについてもっと詳しく学びたいのであれば……さあ、準備しましょう!"))}},whatis:{locale:"ja-JP",title:"ではベジエ曲線はどうやってできるのでしょう?",getContent:function(e){return r.createElement("section",null,r.createElement(a,{name:"whatis",title:"ではベジエ曲線はどうやってできるのでしょう?",number:"2"}),r.createElement("p",null,"ベジエ曲線がどのように動くのか、点を触ってみて感覚が摑めたかもしれません。では、実際のところベジエ曲線",r.createElement("em",null,"とは"),"いったい何でしょうか?これを説明する方法は2通りありますが、どちらの説明でも行き着く先はまったく同じです。一方は複雑な数学を使うのに対し、もう一方はとても簡単です。というわけで……簡単な説明の方から始めましょう。"),r.createElement("p",null,"ベジエ曲線は、",r.createElement("a",{href:"https://ja.wikipedia.org/wiki/%E7%B7%9A%E5%BD%A2%E8%A3%9C%E9%96%93"},"線形補間"),"の結果です。というと難しそうに聞こえますが、誰でも幼い頃から線形補間をやってきています。例えば、何か2つのものの間を指し示すときには、いつも線形補間を行っています。線形補間とは、単純に「2点の間から点を得る」ことなのです。"),r.createElement("p",null,"例えば、2点間の距離がわかっているとして、一方の点から距離の20%だけ離れた(すなわち、もう一方の点から80%離れた)新しい点を求めたい場合、次のようにとても簡単に計算できます。"),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/75bb049d813d8ee084b076531823f2109cc1660f.svg",style:{width:"36.750150000000005rem",height:"6.37515rem"}}),r.createElement("p",null,"では、実際に見てみましょう。下の図はインタラクティブになっています。上下キーで補間の比率が増減しますので、どうなるか確かめてみましょう。最初に3点があり、それを結んで2本の直線が引かれています。この直線の上でそれぞれ線形補間を行うと、2つの点が得られます。この2点の間でさらに線形補間を行うと、1つの点を得ることができます。そして、あらゆる比率に対して同様に点を求め、それをすべて集めると、このようにベジエ曲線ができるのです。"),r.createElement(i,{title:"線形補間でベジエ曲線を得る",setup:e.setup,draw:e.draw,onKeyDown:e.onKeyDown}),r.createElement("p",null,"また、これが複雑な方の数学につながっていきます。微積分です。"),r.createElement("p",null,"いま上で行ったものとは似つかないように思えますが、実はあれは2次曲線を描いていたのです。ただし一発で描きあげるのではなく、手順を追って描いていきました。ベジエ曲線は多項式関数で表現できますが、その一方で、とても単純な補間の補間の補間の……というふうにも説明できます。これがベジエ曲線のおもしろいところです。これはまた、ベジェ曲線は「本当の数学」で見る(関数を調べたり微分を調べたり、あらゆる方法で)ことも可能ですし、「機械的」な組み立て操作として見る(例えば、ベジエ曲線は組み立てに使う点の間からは決してはみ出ないということがわかります)ことも可能だということを意味しています。"),r.createElement("p",null,"それでは、もう少し詳しくベジエ曲線を見ていきましょう。数学的な表現やそこから導かれる性質、さらには、ベジエ曲線に対して/ベジエ曲線を使ってできるさまざまな内容についてです。"))}},explanation:{locale:"en-GB",title:"The mathematics of Bézier curves",getContent:function(e){return r.createElement("section",null,r.createElement(a,{name:"explanation",title:"The mathematics of Bézier curves",number:"3"}),r.createElement("p",null,'Bézier curves are a form of "parametric" function. Mathematically speaking, parametric functions are cheats: a "function" is actually a well defined term representing a mapping from any number of inputs to a ',r.createElement("strong",null,"single")," output. Numbers go in, a single number comes out. Change the numbers that go in, and the number that comes out is still a single number. Parametric functions cheat. They basically say \"alright, well, we want multiple values coming out, so we'll just use more than one function\". An illustration: Let's say we have a function that maps some value, let's call it ",r.createElement("i",null,"x"),", to some other value, using some kind of number manipulation:"),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/785e792c343b71d4e674ac94d8800940b30917ac.svg",style:{width:"6.22485rem",height:"1.125rem"}}),r.createElement("p",null,"The notation ",r.createElement("i",null,"f(x)")," is the standard way to show that it's a function (by convention called ",r.createElement("i",null,"f")," if we're only listing one) and its output changes based on one variable (in this case, ",r.createElement("i",null,"x"),"). Change ",r.createElement("i",null,"x"),", and the output for ",r.createElement("i",null,"f(x)")," changes."),r.createElement("p",null,"So far so good. Now, let's look at parametric functions, and how they cheat. Let's take the following two functions:"),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/0dfe7562b43441e72201ff4cdd2e8b6e2e3ecb2d.svg",style:{width:"6.525rem",height:"2.6248500000000003rem"}}),r.createElement("p",null,"There's nothing really remarkable about them, they're just a sine and cosine function, but you'll notice the inputs have different names. If we change the value for ",r.createElement("i",null,"a"),", we're not going to change the output value for ",r.createElement("i",null,"f(b)"),", since ",r.createElement("i",null,"a")," isn't used in that function. Parametric functions cheat by changing that. In a parametric function all the different functions share a variable, like this:"),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/ed6f533530199d1e99b3319ba137c1327b0459c0.svg",style:{width:"7.349849999999999rem",height:"2.6248500000000003rem"}}),r.createElement("p",null,"Multiple functions, but only one variable. If we change the value for ",r.createElement("i",null,"t"),", we change the outcome of both ",r.createElement("i",null,"f",r.createElement("sub",null,"a"),"(t)")," and ",r.createElement("i",null,"f",r.createElement("sub",null,"b"),"(t)"),". You might wonder how that's useful, and the answer is actually pretty simple: if we change the labels ",r.createElement("i",null,"f",r.createElement("sub",null,"a"),"(t)")," and ",r.createElement("i",null,"f",r.createElement("sub",null,"b"),"(t)")," with what we usually mean with them for parametric curves, things might be a lot more obvious:"),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/ea632ea75d6a2aeb6fe69c07feb6e76f81884746.svg",style:{width:"5.77485rem",height:"2.6248500000000003rem"}}),r.createElement("p",null,"There we go. ",r.createElement("i",null,"x"),"/",r.createElement("i",null,"y")," coordinates, linked through some mystery value ",r.createElement("i",null,"t"),"."),r.createElement("p",null,"So, parametric curves don't define a ",r.createElement("i",null,"y")," coordinate in terms of an ",r.createElement("i",null,"x"),' coordinate, like normal functions do, but they instead link the values to a "control" variable. If we vary the value of ',r.createElement("i",null,"t"),", then with every change we get ",r.createElement("strong",null,"two")," values, which we can use as (",r.createElement("i",null,"x"),",",r.createElement("i",null,"y"),") coordinates in a graph. The above set of functions, for instance, generates points on a circle: We can range ",r.createElement("i",null,"t")," from negative to positive infinity, and the resulting (",r.createElement("i",null,"x"),",",r.createElement("i",null,"y"),") coordinates will always lie on a circle with radius 1 around the origin (0,0). If we plot it for ",r.createElement("i",null,"t")," from 0 to 5, we get this (use your up and down arrow keys to change the plot end value):"),r.createElement(i,{preset:"empty",title:"A (partial) circle: x=sin(t), y=cos(t)",static:!0,setup:e.setup,draw:e.draw,onKeyDown:e.props.onKeyDown}),r.createElement("p",null,"Bézier curves are (one in many classes of) parametric functions, and are characterised by using the same base function for all its dimensions. Unlike the above example, where the ",r.createElement("i",null,"x")," and ",r.createElement("i",null,"y"),' values use different functions (one uses a sine, the other a cosine), Bézier curves use the "binomial polynomial" for both ',r.createElement("i",null,"x")," and ",r.createElement("i",null,"y"),". So what are binomial polynomials?"),r.createElement("p",null,"You may remember polynomials from high school, where they're those sums that look like:"),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/3e8b26cf8833db7089d65e9c6b3953a3140bb19f.svg",style:{width:"14.32485rem",height:"1.20015rem"}}),r.createElement("p",null,"If they have a highest order term ",r.createElement("i",null,"x³")," they're called \"cubic\" polynomials, if it's ",r.createElement("i",null,"x²")," it's a \"square\" polynomial, if it's just ",r.createElement("i",null,"x")," it's a line (and if there aren't even any terms with ",r.createElement("i",null,"x")," it's not a polynomial!)"),r.createElement("p",null,"Bézier curves are polynomials of ",r.createElement("i",null,"t"),", rather than ",r.createElement("i",null,"x"),", with the value for ",r.createElement("i",null,"t")," fixed being between 0 and 1, with coefficients ",r.createElement("i",null,"a"),", ",r.createElement("i",null,"b"),' etc. taking the "binomial" form, which sounds fancy but is actually a pretty simple description for mixing values:'),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/24e915ab4c69b85951f1ea9018b0ece9e52a10dd.svg",style:{width:"24.89985rem",height:"4.1998500000000005rem"}}),r.createElement("p",null,"I know what you're thinking: that doesn't look too simple, but if we remove ",r.createElement("i",null,"t"),' and add in "times one", things suddenly look pretty easy. Check out these binomial terms:'),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/448d10d21afd49135055cf685fedf6c494984b53.svg",style:{width:"14.475150000000001rem",height:"5.175rem"}}),r.createElement("p",null,'Notice that 2 is the same as 1+1, and 3 is 2+1 and 1+2, and 6 is 3+3... As you can see, each time we go up a dimension, we simply start and end with 1, and everything in between is just "the two numbers above it, added together". Now ',r.createElement("i",null,"that's")," easy to remember."),r.createElement("p",null,"There's an equally simple way to figure out how the polynomial terms work: if we rename ",r.createElement("i",null,"(1-t)")," to ",r.createElement("i",null,"a")," and ",r.createElement("i",null,"t")," to ",r.createElement("i",null,"b"),", and remove the weights for a moment, we get this:"),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/87c7f5294b902def4ea56e8f6cf24265a37143b6.svg",style:{width:"20.84985rem",height:"3.825rem"}}),r.createElement("p",null,"It's basically just a sum of \"every combination of ",r.createElement("i",null,"a")," and ",r.createElement("i",null,"b"),'", progressively replacing ',r.createElement("i",null,"a"),"'s with ",r.createElement("i",null,"b"),"'s after every + sign. So that's actually pretty simple too. So now you know binomial polynomials, and just for completeness I'm going to show you the generic function for this:"),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/d79bf595a0911c17e2ac86d8806a0a8ab6ba7dfe.svg",style:{width:"20.39985rem",height:"3.90015rem"}}),r.createElement("p",null,"And that's the full description for Bézier curves. Σ in this function indicates that this is a series of additions (using the variable listed below the Σ, starting at ...= and ending at the value listed on top of the Σ)."),r.createElement("div",{className:"howtocode"},r.createElement("h3",{id:"how-to-implement-the-basis-function"},"How to implement the basis function"),r.createElement("p",null,"We could naively implement the basis function as a mathematical construct, using the function as our guide, like this:"),r.createElement("pre",null,"function Bezier(n,t):","\n"," sum = 0","\n"," for(k=0; k<n; k++):","\n"," sum += n!/(k!*(n-k)!) * (1-t)^(n-k) * t^(k)","\n"," return sum","\n"),r.createElement("p",null,"I say we could, because we're not going to: the factorial function is ",r.createElement("em",null,"incredibly"),' expensive. And, as we can see from the above explanation, we can actually create Pascal\'s triangle quite easily without it: just start at [1], then [1,1], then [1,2,1], then [1,3,3,1], and so on, with each next row fitting 1 more number than the previous row, starting and ending with "1", with all the numbers in between being the sum of the previous row\'s elements on either side "above" the one we\'re computing.'),r.createElement("p",null,"We can generate this as a list of lists lightning fast, and then never have to compute the binomial terms because we have a lookup table:"),r.createElement("pre",null,"lut = [ [1], // n=0","\n"," [1,1], // n=1","\n"," [1,2,1], // n=2","\n"," [1,3,3,1], // n=3","\n"," [1,4,6,4,1], // n=4","\n"," [1,5,10,10,5,1], // n=5","\n"," [1,6,15,20,15,6,1]] // n=6","\n","\n","binomial(n,k):","\n"," while(n >= lut.length):","\n"," s = lut.length","\n"," nextRow = new array(size=s+1)","\n"," nextRow[0] = 1","\n"," for(i=1, prev=s-1; i<prev; i++):","\n"," nextRow[i] = lut[prev][i-1] + lut[prev][i]","\n"," nextRow[s] = 1","\n"," lut.add(nextRow)","\n"," return lut[n][k]","\n"),r.createElement("p",null,"So what's going on here? First, we declare a lookup table with a size that's reasonably large enough to accommodate most lookups. Then, we declare a function to get us the values we need, and we make sure that if an n/k pair is requested that isn't in the LUT yet, we expand it first. Our basis function now looks like this:"),r.createElement("pre",null,"function Bezier(n,t):","\n"," sum = 0","\n"," for(k=0; k<=n; k++):","\n"," sum += binomial(n,k) * (1-t)^(n-k) * t^(k)","\n"," return sum","\n"),r.createElement("p",null,"Perfect. Of course, we can optimize further. For most computer graphics purposes, we don't need arbitrary curves. We need quadratic and cubic curves (this primer actually does do arbitrary curves, so you'll find code similar to shown here), which means we can drastically simplify the code:"),r.createElement("pre",null,"function Bezier(2,t):","\n"," t2 = t * t","\n"," mt = 1-t","\n"," mt2 = mt * mt","\n"," return mt2 + 2*mt*t + t2","\n","\n","function Bezier(3,t):","\n"," t2 = t * t","\n"," t3 = t2 * t","\n"," mt = 1-t","\n"," mt2 = mt * mt","\n"," mt3 = mt2 * mt","\n"," return mt3 + 3*mt2*t + 3*mt*t2 + t3","\n"),r.createElement("p",null,"And now we know how to program the basis function. Exellent.")),r.createElement("p",null,"So, now we know what the base function(s) look(s) like, time to add in the magic that makes Bézier curves so special: control points."))}},control:{locale:"en-GB",title:"Controlling Bézier curvatures",getContent:function(e){return r.createElement("section",null,r.createElement(a,{name:"control",title:"Controlling Bézier curvatures",number:"4"}),r.createElement("p",null,'Bézier curves are (like all "splines") interpolation functions, meaning they take a set of points, and generate values somewhere "between" those points. (One of the consequences of this is that you\'ll never be able to generate a point that lies outside the outline for the control points, commonly called the "hull" for the curve. Useful information!). In fact, we can visualize how each point contributes to the value generated by the function, so we can see which points are important, where, in the curve.'),r.createElement("p",null,'The following graphs show the interpolation functions for quadratic and cubic curves, with "S" being the strength of a point\'s contribution to the total sum of the Bézier function. Click or click-drag to see the interpolation percentages for each curve-defining point at a specific ',r.createElement("i",null,"t")," value."),r.createElement("div",{className:"figure"},r.createElement(i,{inline:!0,preset:"simple",title:"Quadratic interpolations",draw:e.drawQuadraticLerp}),r.createElement(i,{inline:!0,preset:"simple",title:"Cubic interpolations",draw:e.drawCubicLerp}),r.createElement(i,{inline:!0,preset:"simple",title:"15th order interpolations",draw:e.draw15thLerp})),r.createElement("p",null,"Also shown is the interpolation function for a 15",r.createElement("sup",null,"th")," order Bézier function. As you can see, the start and end point contribute considerably more to the curve's shape than any other point in the control point set."),r.createElement("p",null,'If we want to change the curve, we need to change the weights of each point, effectively changing the interpolations. The way to do this is about as straight forward as possible: just multiply each point with a value that changes its strength. These values are conventionally called "Weights", and we can add them to our original Bézier function:'),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/b98618f8061e9e58289abccc06a624a14561d40f.svg",style:{width:"23.70015rem",height:"3.90015rem"}}),r.createElement("p",null,'That looks complicated, but as it so happens, the "weights" are actually just the coordinate values we want our curve to have: for an ',r.createElement("i",null,"n",r.createElement("sup",null,"th"))," order curve, w",r.createElement("sub",null,"0")," is our start coordinate, w",r.createElement("sub",null,"n")," is our last coordinate, and everything in between is a controlling coordinate. Say we want a cubic curve that starts at (120,160), is controlled by (35,200) and (220,260) and ends at (220,40), we use this Bézier curve:"),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/853858526831a7ef3eb170efe49de397bb4913a1.svg",style:{width:"32.025150000000004rem",height:"2.77515rem"}}),r.createElement("p",null,"Which gives us the curve we saw at the top of the article:"),r.createElement(i,{preset:"simple",title:"Our cubic Bézier curve",setup:e.drawCubic,draw:e.drawCurve}),r.createElement("p",null,"What else can we do with Bézier curves? Quite a lot, actually. The rest of this article covers a multitude of possible operations and algorithms that we can apply, and the tasks they achieve."),r.createElement("div",{className:"howtocode"},r.createElement("h3",{id:"how-to-implement-the-weighted-basis-function"},"How to implement the weighted basis function"),r.createElement("p",null,"Given that we already know how to implement basis function, adding in the control points is remarkably easy:"),r.createElement("pre",null,"function Bezier(n,t,w[]):","\n"," sum = 0","\n"," for(k=0; k<n; k++):","\n"," sum += w[k] * binomial(n,k) * (1-t)^(n-k) * t^(k)","\n"," return sum","\n"),r.createElement("p",null,"And for the extremely optimized versions:"),r.createElement("pre",null,"function Bezier(2,t,w[]):","\n"," t2 = t * t","\n"," mt = 1-t","\n"," mt2 = mt * mt","\n"," return w[0]*mt2 + w[1]*2*mt*t + w[2]*t2","\n","\n","function Bezier(3,t,w[]):","\n"," t2 = t * t","\n"," t3 = t2 * t","\n"," mt = 1-t","\n"," mt2 = mt * mt","\n"," mt3 = mt2 * mt","\n"," return w[0]*mt3 + 3*w[1]*mt2*t + 3*w[2]*mt*t2 + w[3]*t3","\n"),r.createElement("p",null,"And now we know how to program the weighted basis function.")))}},extended:{locale:"en-GB",title:"The Bézier interval [0,1]",getContent:function(e){return r.createElement("section",null,r.createElement(a,{name:"extended",title:"The Bézier interval [0,1]",number:"5"}),r.createElement("p",null,"Now that we know the mathematics behind Bézier curves, there's one curious thing that you may have noticed: they always run from ",r.createElement("code",null,"t=0")," to ",r.createElement("code",null,"t=1"),". Why that particular interval?"),r.createElement("p",null,'It all has to do with how we run from "the start" of our curve to "the end" of our curve. If we have a value that is a mixture of two other values, then the general formula for this is:'),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/7f5ebb8489a8d04beb28f47c8aac2632b78ae764.svg",style:{width:"14.99985rem",height:"0.9rem"}}),r.createElement("p",null,"The obvious start and end values here need to be ",r.createElement("code",null,"a=1, b=0"),", so that the mixed value is 100% value 1, and 0% value 2, and ",r.createElement("code",null,"a=0, b=1"),', so that the mixed value is 0% value 1 and 100% value 2. Additionally, we don\'t want "a" and "b" to be independent: if they are, then we could just pick whatever values we like, and end up with a mixed value that is, for example, 100% value 1 ',r.createElement("strong",null,"and")," 100% value 2. In principle that's fine, but for Bézier curves we always want mixed values ",r.createElement("em",null,"between"),' the start and end point, so we need to make sure we can never set "a" and "b" to some values that lead to a mix value that sums to more than 100%. And that\'s easy:'),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/d326c8f323ccd2da00d998b533ac26a1c04fcfba.svg",style:{width:"14.774849999999999rem",height:"1.125rem"}}),r.createElement("p",null,"With this we can guarantee that we never sum above 100%. By restricting ",r.createElement("code",null,"a")," to values in the interval [0,1], we will always be somewhere between our two values (inclusively), and we will always sum to a 100% mix."),r.createElement("p",null,'But... what if we use this form, used in the assumption that we will only ever use values between 0 and 1, and instead use values outside of that interval? Do things go horribly wrong? Well... not really, but we get to "see more".'),r.createElement("p",null,'In the case of Bézier curves, extending the interval simply makes our curve "keep going". Bézier curves are simply segments on some polynomial curve, so if we pick a wider interval we simply get to see more of the curve. So what do they look like?'),r.createElement("p",null,'The following two graphics show you Bézier curves rendered "the usual way", as well as the curves they "lie on" if we were to extend the ',r.createElement("code",null,"t"),' values much further. As you can see, there\'s a lot more "shape" hidden in the rest of the curve, and we can model those parts by moving the curve points around.'),r.createElement(i,{preset:"simple",title:"Quadratic infinite interval Bézier curve",setup:e.setupQuadratic,draw:e.draw}),r.createElement(i,{preset:"simple",title:"Cubic infinite interval Bézier curve",setup:e.setupCubic,draw:e.draw}),r.createElement("p",null,"In fact, there are curves used in graphics design and computer modelling that do the opposite of Bézier curves, where rather than fixing the interval, and giving you free coordinates, they fix the coordinates, but give you freedom over the interval. A great example of this is the ",r.createElement("a",{href:"http://levien.com/phd/phd.html"},'"Spiro" curve'),", which is a curve based on part of a ",r.createElement("a",{href:"https://en.wikipedia.org/wiki/Euler_spiral"},"Cornu Spiral, also known as Euler's Spiral"),". It's a very aesthetically pleasing curve and you'll find it in quite a few graphics packages like ",r.createElement("a",{href:"https://fontforge.github.io"},"FontForge")," and ",r.createElement("a",{href:"https://inkscape.org"},"Inkscape"),", having even been used in font design (such as for the Inconsolata font)."))}},matrix:{locale:"en-GB",title:"Bézier curvatures as matrix operations",getContent:function(e){return r.createElement("section",null,r.createElement(a,{name:"matrix",title:"Bézier curvatures as matrix operations",number:"6"}),r.createElement("p",null,"We can also represent Bézier as matrix operations, by expressing the Bézier formula as a polynomial basis function, the weight matrix, and the actual coordinates as matrix. Let's look at what this means for the cubic curve:"),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/d961171d6d1dfc22bb1756901e79102147914360.svg",style:{width:"31.12515rem",height:"1.20015rem"}}),r.createElement("p",null,"Disregarding our actual coordinates for a moment, we have:"),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/f925c339011e6c38e47b9c3a571e02fca80eb5c3.svg",style:{width:"23.475150000000003rem",height:"1.20015rem"}}),r.createElement("p",null,"We can write this as a sum of four expressions:"),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/30d76165668bf15f62986503bea100f39c5b9fec.svg",style:{width:"10.42515rem",height:"5.8500000000000005rem"}}),r.createElement("p",null,"And we can expand these expressions:"),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/7ca5abe1124ba1e51b7f12e0469cb4b1407593b8.svg",style:{width:"27.82485rem",height:"5.8500000000000005rem"}}),r.createElement("p",null,"Furthermore, we can make all the 1 and 0 factors explicit:"),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/bccbb94942e3ff79579e4719106f4701c157727e.svg",style:{width:"15.67485rem",height:"5.625rem"}}),r.createElement("p",null,"And ",r.createElement("em",null,"that"),", we can view as a series of four matrix operations:"),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/d5f85d80fbbc62e1e8d58621b76f3d0224876b62.svg",style:{width:"45.225rem",height:"5.47515rem"}}),r.createElement("p",null,"If we compact this into a single matrix operation, we get:"),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/7140be48f45b2e7190fa8dffef5c05c47c038ab0.svg",style:{width:"16.875rem",height:"5.47515rem"}}),r.createElement("p",null,"This kind of polynomial basis representation is generally written with the bases in increasing order, which means we need to flip our ",r.createElement("code",null,"t"),' matrix horizontally, and our big "mixing" matrix upside down:'),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/4e1849950a5c13f5135aa3412e0ee634cdc67301.svg",style:{width:"16.875rem",height:"5.47515rem"}}),r.createElement("p",null,"And then finally, we can add in our original coordinates as a single third matrix:"),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/5910e25a46d9e86ab34513017f1274628a40e5a7.svg",style:{width:"23.925150000000002rem",height:"5.47515rem"}}),r.createElement("p",null,"We can perform the same trick for the quadratic curve, in which case we end up with:"),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/e56e78e406d625c2a5ec584216f79a5fee00d8ea.svg",style:{width:"19.65015rem",height:"3.97485rem"}}),r.createElement("p",null,"If we plug in a ",r.createElement("code",null,"t")," value, and then multiply the matrices, we will get exactly the same values as when we evaluate the original polynomial function, or as when we evaluate the curve using progessive linear interpolation."),r.createElement("p",null,r.createElement("strong",null,"So: why would we bother with matrices?")," Matrix representations allow us to discover things about functions that would otherwise be hard to tell. It turns out that the curves form ",r.createElement("a",{href:"https://en.wikipedia.org/wiki/Triangular_matrix"},"triangular matrices"),", and they have a determinant equal to the product of the actual coordinates we use for our curve. It's also invertible, which means there's ",r.createElement("a",{href:"https://en.wikipedia.org/wiki/Invertible_matrix#The_invertible_matrix_theorem"},"a ton of properties")," that are all satisfied. Of course, the main question is: \"Why is this useful to us, now?\", and the answer to that is that it's not immediately useful, but you'll be seeing some instances where certain curve properties can be either computed via function manipulation, or via clever use of matrices, and sometimes the matrix approach can be (drastically) faster."),r.createElement("p",null,"So for now, just remember that we can represent curves this way, and let's move on."))}},decasteljau:{locale:"en-GB",title:"de Casteljau's algorithm",getContent:function(e){return r.createElement("section",null,r.createElement(a,{name:"decasteljau",title:"de Casteljau's algorithm",number:"7"}),r.createElement("p",null,"If we want to draw Bézier curves we can run through all values of ",r.createElement("code",null,"t")," from 0 to 1 and then compute the weighted basis function, getting the ",r.createElement("code",null,"x/y"),' values we need to plot, but the more complex the curve gets, the more expensive this becomes. Instead, we can use "de Casteljau\'s algorithm" to draw curves, which is a geometric approach to drawing curves, and really easy to implement. So easy, in fact, you can do it by hand with a pencil and ruler.'),r.createElement("p",null,"Rather than using our calculus function to find ",r.createElement("code",null,"x/y")," values for ",r.createElement("code",null,"t"),", let's do this instead:"),r.createElement("ul",null,r.createElement("li",null,"treat ",r.createElement("code",null,"t")," as a ratio (which it is). t=0 is 0% along a line, t=1 is 100% along a line."),r.createElement("li",null,"Take all lines between the curve's defining points. For an order ",r.createElement("code",null,"n")," curve, that's ",r.createElement("code",null,"n")," lines."),r.createElement("li",null,"Place markers along each of these line, at distance ",r.createElement("code",null,"t"),". So if ",r.createElement("code",null,"t")," is 0.2, place the mark at 20% from the start, 80% from the end."),r.createElement("li",null,"Now form lines between ",r.createElement("code",null,"those")," points. This gives ",r.createElement("code",null,"n-1")," lines."),r.createElement("li",null,"Place markers along each of these line at distance ",r.createElement("code",null,"t"),"."),r.createElement("li",null,"Form lines between ",r.createElement("code",null,"those")," points. This'll be ",r.createElement("code",null,"n-2")," lines."),r.createElement("li",null,"place markers, form lines, place markers, etc."),r.createElement("li",null,"repeat this until you have only one line left. The point ",r.createElement("code",null,"t")," on that line coincides with the original curve point at ",r.createElement("code",null,"t"),".")),r.createElement("div",{className:"howtocode"},r.createElement("h3",{id:"how-to-implement-de-casteljau-s-algorithm"},"How to implement de Casteljau's algorithm"),r.createElement("p",null,"Let's just use the algorithm we just specified, and implement that:"),r.createElement("pre",null,"function drawCurve(points[], t):","\n"," if(points.length==1):","\n"," draw(points[0])","\n"," else:","\n"," newpoints=array(points.size-1)","\n"," for(i=0; i<newpoints.length; i++):","\n"," newpoints[i] = (1-t) * points[i] + t * points[i+1]","\n"," drawCurve(newpoints, t)","\n"),r.createElement("p",null,"And done, that's the algorithm implemented. Except usually you don't get the luxury of overloading the \"+\" operator, so let's also give the code for when you need to work with ",r.createElement("code",null,"x")," and ",r.createElement("code",null,"y")," values:"),r.createElement("pre",null,"function drawCurve(points[], t):","\n"," if(points.length==1):","\n"," draw(points[0])","\n"," else:","\n"," newpoints=array(points.size-1)","\n"," for(i=0; i<newpoints.length; i++):","\n"," x = (1-t) * points[i].x + t * points[i+1].x","\n"," y = (1-t) * points[i].y + t * points[i+1].y","\n"," newpoints[i] = new point(x,y)","\n"," drawCurve(newpoints, t)","\n"),r.createElement("p",null,"So what does this do? This draws a point, if the passed list of points is only 1 point long. Otherwise it will create a new list of points that sit at the ",r.createElement("i",null,"t"),' ratios (i.e. the "markers" outlined in the above algorithm), and then call the draw function for this new list.')),r.createElement("p",null,"To see this in action, mouse-over the following sketch. Moving the mouse changes which curve point is explicitly evaluated using de Casteljau's algorithm, moving the cursor left-to-right (or, of course, right-to-left), shows you how a curve is generated using this approach."),r.createElement(i,{ -preset:"simple",title:"Traversing a curve using de Casteljau's algorithm",setup:e.setup,draw:e.draw}))}},flattening:{locale:"en-GB",title:"Simplified drawing",getContent:function(e){return r.createElement("section",null,r.createElement(a,{name:"flattening",title:"Simplified drawing",number:"8"}),r.createElement("p",null,'We can also simplify the drawing process by "sampling" the curve at certain points, and then joining those points up with straight lines, a process known as "flattening", as we are reducing a curve to a simple sequence of straight, "flat" lines.'),r.createElement("p",null,'We can do this is by saying "we want X segments", and then sampling the curve at intervals that are spaced such that we end up with the number of segments we wanted. The advantage of this method is that it\'s fast: instead of evaluating 100 or even 1000 curve coordinates, we can sample a much lower number and still end up with a curve that sort-of-kind-of looks good enough. The disadvantage of course is that we lose the precision of working with "the real curve", so we usually can\'t use the flattened for for doing true intersection detection, or curvature alignment.'),r.createElement(i,{preset:"twopanel",title:"Flattening a quadratic curve",setup:e.setupQuadratic,draw:e.drawFlattened,onKeyDown:e.onKeyDown}),r.createElement(i,{preset:"twopanel",title:"Flattening a cubic curve",setup:e.setupCubic,draw:e.drawFlattened,onKeyDown:e.onKeyDown}),r.createElement("p",null,"Try clicking on the sketch and using your up and down arrow keys to lower the number of segments for both the quadratic and cubic curve. You'll notice that for certain curvatures, a low number of segments works quite well, but for more complex curvatures (try this for the cubic curve), a higher number is required to capture the curvature changes properly."),r.createElement("div",{className:"howtocode"},r.createElement("h3",{id:"how-to-implement-curve-flattening"},"How to implement curve flattening"),r.createElement("p",null,"Let's just use the algorithm we just specified, and implement that:"),r.createElement("pre",null,"function flattenCurve(curve, segmentCount):","\n"," step = 1/segmentCount;","\n"," coordinates = [curve.getXValue(0), curve.getYValue(0)]","\n"," for(i=1; i <= segmentCount; i++):","\n"," t = i*step;","\n"," coordinates.push[curve.getXValue(t), curve.getYValue(t)]","\n"," return coordinates;","\n"),r.createElement("p",null,'And done, that\'s the algorithm implemented. That just leaves drawing the resulting "curve" as a sequence of lines:'),r.createElement("pre",null,"function drawFlattenedCurve(curve, segmentCount):","\n"," coordinates = flattenCurve(curve, segmentCount)","\n"," coord = coordinates[0], _coords;","\n"," for(i=1; i < coordinates.length; i++):","\n"," _coords = coordinates[i]","\n"," line(coords, _coords)","\n"," coords = _coords","\n"),r.createElement("p",null,"We start with the first coordinate as reference point, and then just draw lines between each point and its next point.")))}},splitting:{locale:"en-GB",title:"Splitting curves",getContent:function(e){return r.createElement("section",null,r.createElement(a,{name:"splitting",title:"Splitting curves",number:"9"}),r.createElement("p",null,"With de Casteljau's algorithm we also find all the points we need to split up a Bézier curve into two, smaller curves, which taken together form the original curve. When we construct de Casteljau's skeleton for some value ",r.createElement("code",null,"t"),", the procedure gives us all the points we need to split a curve at that ",r.createElement("code",null,"t")," value: one curve is defined by all the inside skeleton points found prior to our on-curve point, with the other curve being defined by all the inside skeleton points after our on-curve point."),r.createElement(i,{title:"Splitting a curve",setup:e.setupCubic,draw:e.drawSplit}),r.createElement("div",{className:"howtocode"},r.createElement("h3",{id:"implementing-curve-splitting"},"implementing curve splitting"),r.createElement("p",null,"We can implement curve splitting by bolting some extra logging onto the de Casteljau function:"),r.createElement("pre",null,"left=[]","\n","right=[]","\n","function drawCurve(points[], t):","\n"," if(points.length==1):","\n"," left.add(points[0])","\n"," right.add(points[0])","\n"," draw(points[0])","\n"," else:","\n"," newpoints=array(points.size-1)","\n"," for(i=0; i<newpoints.length; i++):","\n"," if(i==0):","\n"," left.add(points[i])","\n"," if(i==newpoints.length-1):","\n"," right.add(points[i+1])","\n"," newpoints[i] = (1-t) * points[i] + t * points[i+1]","\n"," drawCurve(newpoints, t)","\n"),r.createElement("p",null,"After running this function for some value ",r.createElement("code",null,"t"),", the ",r.createElement("code",null,"left")," and ",r.createElement("code",null,"right"),' arrays will contain all the coordinates for two new curves - one to the "left" of our ',r.createElement("code",null,"t"),' value, the other on the "right", of the same order as the original curve, and overlayed exactly on the original curve.')),r.createElement("p",null,"This is best illustrated with an animated graphic (click to play/pause):"),r.createElement(i,{preset:"threepanel",title:"Bézier curve splitting",setup:e.setupCubic,draw:e.drawAnimated,onClick:e.togglePlay}))}},matrixsplit:{locale:"en-GB",title:"Splitting curves using matrices",getContent:function(e){return r.createElement("section",null,r.createElement(a,{name:"matrixsplit",title:"Splitting curves using matrices",number:"10"}),r.createElement("p",null,"Another way to split curves is to exploit the matrix representation of a Bézier curve. In ",r.createElement("a",{href:"#matrix"},"the section on matrices")," we saw that we can represent curves as matrix multiplications. Specifically, we saw these two forms for the quadratic, and cubic curves, respectively (using the reversed Bézier coefficients vector for legibility):"),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/e56e78e406d625c2a5ec584216f79a5fee00d8ea.svg",style:{width:"19.65015rem",height:"3.97485rem"}}),r.createElement("p",null,"and"),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/01ea4f74c4785a19bedf18034b51510c5ce2ad8f.svg",style:{width:"23.925150000000002rem",height:"5.47515rem"}}),r.createElement("p",null,"Let's say we want to split the curve at some point ",r.createElement("code",null,"t = z"),', forming two new (obviously smaller) Bézier curves. To find the coordinates for these two Bézier curves, we can use the matrix representation and some linear algebra. First, we split out the the actual "point on the curve" information as a new matrix multiplication:'),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/d6fa091a86782480968c232ef86513c578030004.svg",style:{width:"48.07485rem",height:"4.05rem"}}),r.createElement("p",null,"and"),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/d487e1e0181420995be49b25bc6595c9d0360435.svg",style:{width:"60.82515rem",height:"5.54985rem"}}),r.createElement("p",null,"If we could compact these matrices back to a form ",r.createElement("strong",null,"[t values] · [bezier matrix] · [column matrix]"),", with the first two staying the same, then that column matrix on the right would be the coordinates of a new Bézier curve that describes the first segment, from ",r.createElement("code",null,"t = 0")," to ",r.createElement("code",null,"t = z"),". As it turns out, we can do this quite easily, by exploiting some simple rules of linear algebra (and if you don't care about the derivations, just skip to the end of the box for the results!)."),r.createElement("div",{className:"note"},r.createElement("h2",{id:"deriving-new-hull-coordinates"},"Deriving new hull coordinates"),r.createElement("p",null,"Deriving the two segments upon splitting a curve takes a few steps, and the higher the curve order, the more work it is, so let's look at the quadratic curve first:"),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/d4b8355c3f1f80aacfc2766423a30151c5180a02.svg",style:{width:"26.24985rem",height:"4.05rem"}}),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/fe5f623585a9bbb836f54164aecaadd3fc4ec953.svg",style:{width:"17.62515rem",height:"3.97485rem"}}),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/1eb9833685c9189c64d9cbdfdbb24a94e70e493f.svg",style:{width:"17.69985rem",height:"3.97485rem"}}),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/55f9d31b32a3e8855f2d28c3253201c8963eefd1.svg",style:{width:"17.69985rem",height:"4.05rem"}}),r.createElement("p",null,"We do this, because [",r.createElement("em",null,"M · M",r.createElement("sup",null,"-1")),"] is the identity matrix (a bit like multiplying something by x/x in calculus. It doesn't do anything to the function, but it does allow you to rewrite it to something that may be easier to work with, or can be broken up differently). Adding that as matrix multiplication has no effect on the total formula, but it does allow us to change the matrix sequence [",r.createElement("em",null,"something · M"),"] to a sequence [",r.createElement("em",null,"M · something"),"], and that makes a world of difference: if we know what [",r.createElement("em",null,"M",r.createElement("sup",null,"-1")," · Z · M"),"] is, we can apply that to our coordinates, and be left with a proper matrix representation of a quadratic Bézier curve (which is [",r.createElement("em",null,"T · M · P"),"]), with a new set of coordinates that represent the curve from ",r.createElement("em",null,"t = 0")," to ",r.createElement("em",null,"t = z"),". So let's get computing:"),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/1dbabc115128a85389cbbcc75fbced48e5a2ca25.svg",style:{width:"45.9rem",height:"4.35015rem"}}),r.createElement("p",null,"Excellent! Now we can form our new quadratic curve:"),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/2972cd74dab6560ea68189c2e53f247287cbefae.svg",style:{width:"30.45015rem",height:"3.97485rem"}}),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/39b64e07c41ef6d734064f017036f6391321e924.svg",style:{width:"35.17515rem",height:"4.1998500000000005rem"}}),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/d615960f862664749c54858520c364efeb4a4c5a.svg",style:{width:"34.79985rem",height:"4.1998500000000005rem"}}),r.createElement("p",null,r.createElement("strong",null,r.createElement("em",null,"Brilliant")),": if we want a subcurve from ",r.createElement("code",null,"t = 0")," to ",r.createElement("code",null,"t = z"),", we can keep the first coordinate the same (which makes sense), our control point becomes a z-ratio mixture of the original control point and the start point, and the new end point is a mixture that looks oddly similar to a bernstein polynomial of degree two, except it uses (z-1) rather than (1-z)... These new coordinates are actually really easy to compute directly!"),r.createElement("p",null,"Of course, that's only one of the two curves. Getting the section from ",r.createElement("code",null,"t = z")," to ",r.createElement("code",null,"t = 1")," requires doing this again. We first observe what what we just did is actually evaluate the general interval [0,",r.createElement("code",null,"z"),"], which we wrote down simplified becuase of that zero, but we actually evaluated this:"),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/a51e64df3cb31acf32d0ad5814c8c6cff41ae611.svg",style:{width:"27.45rem",height:"3.97485rem"}}),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/0b50cdfed6656e681d5885a14a3af3e67efa4ccb.svg",style:{width:"23.99985rem",height:"4.05rem"}}),r.createElement("p",null,"If we want the interval [",r.createElement("em",null,"z"),",1], we will be evaluating this instead:"),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/eca8cfda9b7a3f0819ec38acc53f95af67bb26bb.svg",style:{width:"32.625rem",height:"3.97485rem"}}),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/e8c983a3efd47356c971fe46add4d0cdf103cced.svg",style:{width:"30.45015rem",height:"4.1998500000000005rem"}}),r.createElement("p",null,"We're going to do the same trick, to turn ",r.createElement("code",null,"[something · M]")," into ",r.createElement("code",null,"[M · something]"),":"),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/a28b6dcc1335de19a065b6a04d8bb45d86122bb7.svg",style:{width:"52.72515rem",height:"4.35015rem"}}),r.createElement("p",null,"So, our final second curve looks like:"),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/5851c9191acb59456e3706a8f6f1a0f85e691eda.svg",style:{width:"30.74985rem",height:"3.97485rem"}}),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/0333e63f50b3d43067dc299280f70e9eb98711bb.svg",style:{width:"34.875rem",height:"4.1998500000000005rem"}}),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/00a133860115d7a4db4ddf62781b5ae2bffef088.svg",style:{width:"34.79985rem",height:"4.1998500000000005rem"}}),r.createElement("p",null,r.createElement("strong",null,r.createElement("em",null,"Nice")),": we see the same as before; can keep the last coordinate the same (which makes sense), our control point becomes a z-ratio mixture of the original control point and the end point, and the new start point is a mixture that looks oddly similar to a bernstein polynomial of degree two, except it uses (z-1) rather than (1-z). These new coordinates are ",r.createElement("em",null,"also")," really easy to compute directly!")),r.createElement("p",null,"So, using linear algebra rather than de Casteljau's algorithm, we have determined that for any quadratic curve split at some value ",r.createElement("code",null,"t = z"),", we get two subcurves that are described as Bézier curves with simple-to-derive coordinates."),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/5769f44aea3344c32c497a3a77d236f524222b95.svg",style:{width:"40.57515rem",height:"4.1998500000000005rem"}}),r.createElement("p",null,"and"),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/1fdde935dc357642358bdf5e632d6539c9d4debd.svg",style:{width:"40.275rem",height:"4.1998500000000005rem"}}),r.createElement("p",null,"We can do the same for cubic curves. However, I'll spare you the actual derivation (don't let that stop you from writing that out yourself, though) and simply show you the resulting new coordinate sets:"),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/44db09290062827525a9b23cbaf91e65063d86d7.svg",style:{width:"58.87485rem",height:"5.70015rem"}}),r.createElement("p",null,"and"),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/d6b1abe72bac1b55d184f2c4254769404371d06f.svg",style:{width:"59.025150000000004rem",height:"5.70015rem"}}),r.createElement("p",null,"So, looking at our matrices, did we really need to compute the second segment matrix? No, we didn't. Actually having one segment's matrix means we implicitly have the other: push the values of each row in the matrix ",r.createElement("strong",null,r.createElement("em",null,"Q")),' to the right, with zeroes getting pushed off the right edge and appearing back on the left, and then flip the matrix vertically. Presto, you just "calculated" ',r.createElement("strong",null,r.createElement("em",null,"Q'")),"."),r.createElement("p",null,"Implementing curve splitting this way requires less recursion, and is just straight arithmetic with cached values, so can be cheaper on systems were recursion is expensive. If you're doing computation with devices that are good at matrix multiplication, chopping up a Bézier curve with this method will be a lot faster than applying de Casteljau."))}},reordering:{locale:"en-GB",title:"Lowering and elevating curve order",getContent:function(e){return r.createElement("section",null,r.createElement(a,{name:"reordering",title:"Lowering and elevating curve order",number:"11"}),r.createElement("p",null,"One interesting property of Bézier curves is that an ",r.createElement("em",null,"n",r.createElement("sup",null,"th"))," order curve can always be perfectly represented by an ",r.createElement("em",null,"(n+1)",r.createElement("sup",null,"th"))," order curve, by giving the higher order curve specific control points."),r.createElement("p",null,'If we have a curve with three points, then we can create a four point curve that exactly reproduce the original curve as long as we give it the same start and end points, and for its two control points we pick "1/3',r.createElement("sup",null,"rd")," start + 2/3",r.createElement("sup",null,"rd"),' control" and "2/3',r.createElement("sup",null,"rd")," control + 1/3",r.createElement("sup",null,"rd"),' end", and now we have exactly the same curve as before, except represented as a cubic curve, rather than a quadratic curve.'),r.createElement("p",null,"The general rule for raising an ",r.createElement("em",null,"n",r.createElement("sup",null,"th"))," order curve to an ",r.createElement("em",null,"(n+1)",r.createElement("sup",null,"th"))," order curve is as follows (observing that the start and end weights are the same as the start and end weights for the old curve):"),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/339fbe6b94d4580c7be2a43b8c575188c6a2ce58.svg",style:{width:"52.875rem",height:"4.42485rem"}}),r.createElement("p",null,"However, this rule also has as direct consequence that you ",r.createElement("strong",null,"cannot")," generally safely lower a curve from ",r.createElement("em",null,"n",r.createElement("sup",null,"th"))," order to ",r.createElement("em",null,"(n-1)",r.createElement("sup",null,"th")),' order, because the control points cannot be "pulled apart" cleanly. We can try to, but the resulting curve will not be identical to the original, and may in fact look completely different.'),r.createElement("p",null,"We can apply this to a (semi) random curve, as is done in the following graphic. Select the sketch and press your up and down arrow keys to elevate or lower the curve order."),r.createElement(i,{preset:"simple",title:"A "+e.getOrder()+" order Bézier curve",setup:e.setup,draw:e.draw,onKeyDown:e.props.onKeyDown}),r.createElement("p",null,"There is a good, if mathematical, explanation on the matrices necessary for optimal reduction over on ",r.createElement("a",{href:"http://www.sirver.net/blog/2011/08/23/degree-reduction-of-bezier-curves"},"Sirver's Castle"),", which given time will find its way in a more direct description into this article."))}},derivatives:{locale:"en-GB",title:"Derivatives",getContent:function(e){return r.createElement("section",null,r.createElement(a,{name:"derivatives",title:"Derivatives",number:"12"}),r.createElement("p",null,"There's a number of useful things that you can do with Bézier curves based on their derivative, and one of the more amusing observations about Bézier curves is that their derivatives are, in fact, also Bézier curves. In fact, the derivation of a Bézier curve is relatively straight forward, although we do need a bit of math. First, let's look at the derivative rule for Bézier curves, which is:"),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/ff6d9fc6f1697ca0b1e599a4e8ce43f9bd1f17da.svg",style:{width:"23.09985rem",height:"3.15rem"}}),r.createElement("p",null,"which we can also write (observing that ",r.createElement("i",null,"b")," in this formula is the same as our ",r.createElement("i",null,"w")," weights, and that ",r.createElement("i",null,"n")," times a summation is the same as a summation where each term is multiplied by ",r.createElement("i",null,"n"),") as:"),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/3437e732e8a61ec6badcfe292b6258f6ea6535c9.svg",style:{width:"23.85rem",height:"3.15rem"}}),r.createElement("p",null,"Or, in plain text: the derivative of an n",r.createElement("sup",null,"th")," degree Bézier curve is an (n-1)",r.createElement("sup",null,"th")," degree Bézier curve, with one fewer term, and new weights w'",r.createElement("sub",null,"0"),"...w'",r.createElement("sub",null,"n-1")," derived from the original weights as n(w",r.createElement("sub",null,"i+1")," - w",r.createElement("sub",null,"i"),"), so for a 3rd degree curve, with four weights, the derivative has three new weights w'",r.createElement("sub",null,"0")," = 3(w",r.createElement("sub",null,"1"),"-w",r.createElement("sub",null,"0"),"), w'",r.createElement("sub",null,"1")," = 3(w",r.createElement("sub",null,"2"),"-w",r.createElement("sub",null,"1"),") and w'",r.createElement("sub",null,"2")," = 3(w",r.createElement("sub",null,"3"),"-w",r.createElement("sub",null,"2"),")."),r.createElement("div",{className:"note"},r.createElement("h3",{id:"-slow-down-why-is-that-true-"},'"Slow down, why is that true?"'),r.createElement("p",null,"Sometimes just being told \"this is the derivative\" is nice, but you might want to see why this is indeed the case. As such, let's have a look at the proof for this derivative. First off, the weights are independent of the full Bézier function, so the derivative involves only the derivative of the polynomial basis function. So, let's find that:"),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/1f8148ecaac6af494a8bb96d2f96f7a96f85d9e0.svg",style:{width:"14.625rem",height:"2.32515rem"}}),r.createElement("p",null,"Applying the ",r.createElement("a",{href:"http://en.wikipedia.org/wiki/Product_rule"},"product")," and ",r.createElement("a",{href:"http://en.wikipedia.org/wiki/Chain_rule"},"chain")," rules gives us:"),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/02ecde09cea052e99e92b062e70cd724467f0e38.svg",style:{width:"28.425150000000002rem",height:"1.27485rem"}}),r.createElement("p",null,"Which is hard to work with, so let's expand that properly:"),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/c67d5c6165c04b4bba3e9c8f7b8362300153d00d.svg",style:{width:"24.075rem",height:"1.94985rem"}}),r.createElement("p",null,'Now, the trick is to turn this expression into something that has binomial coefficients again, so we want to end up with things that look like "x! over y!(x-y)!". If we can do that in a way that involves terms of ',r.createElement("i",null,"n-1")," and ",r.createElement("i",null,"k-1"),", we'll be on the right track."),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/cf675f8434c96397a548f91aae8150d99d8587a2.svg",style:{width:"36.525150000000004rem",height:"6.60015rem"}}),r.createElement("p",null,"And that's the first part done: the two components inside the parentheses are actually regular, lower order Bezier expressions:"),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/33bbfd279ee71b319a9a93598607c687b00636af.svg",style:{width:"37.42515rem",height:"3.6rem"}}),r.createElement("p",null,"Now to apply this to our weighted Bezier curves. We'll write out the plain curve formula that we saw earlier, and then work our way through to its derivative:"),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/88bc44a562fcdfb6b263970c252d149d7b473a39.svg",style:{width:"36.14985rem",height:"9.225rem"}}),r.createElement("p",null,"If we expand this (with some color to show how terms line up), and reorder the terms by increasing values for ",r.createElement("i",null,"k")," we see the following:"),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/833a6e9be84cd27fdaff1a7a3757411f8a356c95.svg",style:{width:"20.62485rem",height:"8.850150000000001rem"}}),r.createElement("p",null,"Two of these terms fall way: the first term falls away because there is no -1",r.createElement("sup",null,"st"),' term in a summation. As such, it always contributes "nothing", so we can safely completely ignore it for the purpose of finding the derivative function. The other term is the very last term in this expansion: one involving ',r.createElement("i",null,"B",r.createElement("sub",null,"n-1,n")),". This term would have a binomial coefficient of [",r.createElement("i",null,"i")," choose ",r.createElement("i",null,"i+1"),'], which is a non-existent binomial coefficient. Again, this term would contribute "nothing", so we can ignore it, too. This means we\'re left with:'),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/eac65797eafbe2732babcfc335733cbdf363693a.svg",style:{width:"20.39985rem",height:"5.77485rem"}}),r.createElement("p",null,"And that's just a summation of lower order curves:"),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/7cfbe72b898fcbf054564e8b0813acb0e5d7c26d.svg",style:{width:"48.15rem",height:"2.25rem"}}),r.createElement("p",null,"We can rewrite this as a normal summation, and we're done:"),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/418b48749012978b0f3e58cbb56c1049b977270e.svg",style:{width:"36.525150000000004rem",height:"3.67515rem"}})),r.createElement("p",null,"Let's rewrite that in a form similar to our original formula, so we can see the difference. We will first list our original formula for Bézier curves, and then the derivative:"),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/b98618f8061e9e58289abccc06a624a14561d40f.svg",style:{width:"23.70015rem",height:"3.90015rem"}}),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/52947a49ac9e3a189ed56b89a018eff6288435f5.svg",style:{width:"36.45rem",height:"4.05rem"}}),r.createElement("p",null,"What are the differences? In terms of the actual Bézier curve, virtually nothing! We lowered the order (rather than ",r.createElement("i",null,"n"),", it's now ",r.createElement("i",null,"n-1"),"), but it's still the same Bézier function. The only real difference is in how the weights change when we derive the curve's function. If we have four points A, B, C, and D, then the derivative will have three points, the second derivative two, and the third derivative one:"),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/6df1b35ac11dc089a02db4f6d04bc3fa17f03e39.svg",style:{width:"37.125rem",height:"5.99985rem"}}),r.createElement("p",null,"We can keep performing this trick for as long as we have more than one weight. Once we have one weight left, the next step will see ",r.createElement("i",null,"k = 0"),', and the result of our "Bézier function" summation is zero, because we\'re not adding anything at all. As such, a quadratic curve has no second derivative, a cubic curve has no third derivative, and generalized: an ',r.createElement("i",null,"n",r.createElement("sup",null,"th"))," order curve has ",r.createElement("i",null,"n-1")," (meaningful) derivatives, with any further derivative being zero."))}},pointvectors:{locale:"en-GB",title:"Tangents and normals",getContent:function(e){return r.createElement("section",null,r.createElement(a,{name:"pointvectors",title:"Tangents and normals",number:"13"}),r.createElement("p",null,'If you want to move objects along a curve, or "away from" a curve, the two vectors you\'re most interested in are the tangent vector and normal vector for curve points. These are actually really easy to find. For moving, and orienting, along a curve we use the tangent, which indicates the direction travel at specific points, and is literally just the first derivative of our curve:'),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/2271ae26977a681a1695d14ea8255564e716916e.svg",style:{width:"10.35rem",height:"2.77515rem"}}),r.createElement("p",null,"This gives us the directional vector we want. We can normalize it to give us uniform directional vectors (having a length of 1.0) at each point, and then do whatever it is we want to do based on those directions:"),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/3cb2c4f5806142e83c66e1312520d0783d15201c.svg",style:{width:"17.62515rem",height:"2.025rem"}}),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/72826b8f5053c299dbb2082678191e3564bb50a6.svg",style:{width:"20.62485rem",height:"4.7250000000000005rem"}}),r.createElement("p",null,"The tangent is very useful for moving along a line, but what if we want to move away from the curve instead, perpendicular to the curve at some point ",r.createElement("i",null,"t"),'? In that case we want the "normal" vector. This vector runs at a right angle to the direction of the curve, and is typically of length 1.0, so all we have to do is rotate the normalized directional vector and we\'re done:'),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/6cb29c325e059e236343bdd448c149ecc6d8795f.svg",style:{width:"22.800150000000002rem",height:"4.57515rem"}}),r.createElement("div",{className:"note"},r.createElement("p",null,'Rotating coordinates is actually very easy, if you know the rule for it. You might find it explained as "applying a ',r.createElement("a",{href:"https://en.wikipedia.org/wiki/Rotation_matrix"},"rotation matrix"),', which is what we\'ll look at here, too. Essentially, the idea is to take the circles over which we can rotate, and simply "sliding the coordinates" over these circles by the desired angle. If we want a quarter circle turn, we take the coordinate, slide it along the cirle by a quarter turn, and done.'),r.createElement("p",null,"To turn any point ",r.createElement("i",null,"(x,y)")," into a rotated point ",r.createElement("i",null,"(x',y')")," (over 0,0) by some angle φ, we apply this nicely easy computation:"),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/d3932ac925ad9f238029d888dc5432f6678f6491.svg",style:{width:"12.225150000000001rem",height:"2.84985rem"}}),r.createElement("p",null,'Which is the "long" version of the following matrix transformation:'),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/7297632eb150a8f5f37178612f71e5d0f2c367b1.svg",style:{width:"15.150150000000002rem",height:"2.77515rem"}}),r.createElement("p",null,"And that's all we need to rotate any coordinate. Note that for quarter, half and three quarter turns these functions become even easier, since ",r.createElement("em",null,"sin")," and ",r.createElement("em",null,"cos")," for these angles are, respectively: 0 and 1, -1 and 0, and 0 and -1."),r.createElement("p",null,"But ",r.createElement("strong",null,r.createElement("em",null,"why"))," does this work? Why this matrix multiplication? ",r.createElement("a",{href:"http://en.wikipedia.org/wiki/Rotation_matrix#Decomposition_into_shears"},"Wikipedia")," (Technically, Thomas Herter and Klaus Lott) tells us that a rotation matrix can be treated as a sequence of three (elementary) shear operations. When we combine this into a single matrix operation (because all matrix multiplications can be collapsed), we get the matrix that you see above. ",r.createElement("a",{href:"http://datagenetics.com/blog/august32013/index.html"},"DataGenetics")," have an excellent article about this very thing: it's really quite cool, and I strongly recommend taking a quick break from this primer to read that article.")),r.createElement("p",null,"The following two graphics show the tangent and normal along a quadratic and cubic curve, with the direction vector coloured blue, and the normal vector coloured red (the markers are spaced out evenly as ",r.createElement("em",null,"t"),"-intervals, not spaced equidistant)."),r.createElement("div",{className:"figure"},r.createElement(i,{preset:"simple",title:"Quadratic Bézier tangents and normals",inline:!0,setup:e.setupQuadratic,draw:e.draw}),r.createElement(i,{preset:"simple",title:"Cubic Bézier tangents and normals",inline:!0,setup:e.setupCubic,draw:e.draw})))}},components:{locale:"en-GB",title:"Component functions",getContent:function(e){return r.createElement("section",null,r.createElement(a,{name:"components",title:"Component functions",number:"14"}),r.createElement("p",null,'One of the first things people run into when they start using Bézier curves in their own programs is "I know how to draw the curve, but how do I determine the bounding box?". It\'s actually reasonably straight forward to do so, but it requires having some knowledge on exploiting math to get the values we need. For bounding boxes, we aren\'t actually interested in the curve itself, but only in its "extremities": the minimum and maximum values the curve has for its x- and y-axis values. If you remember your calculus (provided you ever took calculus, otherwise it\'s going to be hard to remember) we can determine function extremities using the first derivative of that function, but this poses a problem, since our function is parametric: every axis has its own function.'),r.createElement("p",null,"The solution: compute the derivative for each axis separately, and then fit them back together in the same way we do for the original."),r.createElement("p",null,'Let\'s look at how a parametric Bézier curve "splits up" into two normal functions, one for the x-axis and one for the y-axis. Note the left-most figure is again an interactive curve, without labeled axes (you get coordinates in the graph instead). The center and right-most figures are the component functions for computing the x-axis value, given a value for ',r.createElement("i",null,"t")," (between 0 and 1 inclusive), and the y-axis value, respectively."),r.createElement("p",null,"If you move points in a curve sideways, you should only see the middle graph change; likely, moving points vertically should only show a change in the right graph."),r.createElement(i,{ -preset:"simple",title:"Quadratic Bézier curve components",setup:e.setupQuadratic,draw:e.draw}),r.createElement(i,{preset:"simple",title:"Cubic Bézier curve components",setup:e.setupCubic,draw:e.draw}))}},extremities:{locale:"en-GB",title:"Finding extremities: root finding",getContent:function(e){return r.createElement("section",null,r.createElement(a,{name:"extremities",title:"Finding extremities: root finding",number:"15"}),r.createElement("p",null,"Now that we understand (well, superficially anyway) the component functions, we can find the extremities of our Bézier curve by finding maxima and minima on the component functions, by solving the equations B'(t) = 0 and B''(t) = 0. Although, in the case of quadratic curves there is no B''(t), so we only need to compute B'(t) = 0. So, how do we compute the first and second derivatives? Fairly easily, actually, until our derivatives are 4th order or higher... then things get really hard. But let's start simple:"),r.createElement("h3",{id:"quadratic-curves-linear-derivatives-"},"Quadratic curves: linear derivatives."),r.createElement("p",null,'Finding the solution for "where is this line 0" should be trivial:'),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/9929fd19d54366db382b7d453491d90f894352a7.svg",style:{width:"9.450000000000001rem",height:"6.37515rem"}}),r.createElement("p",null,"Done. And quadratic curves have no meaningful second derivative, so we're ",r.createElement("em",null,"really")," done."),r.createElement("h3",{id:"cubic-curves-the-quadratic-formula-"},"Cubic curves: the quadratic formula."),r.createElement("p",null,"The derivative of a cubic curve is a quadratic curve, and finding the roots for a quadratic Bézier curve means we can apply the ",r.createElement("a",{href:"https://en.wikipedia.org/wiki/Quadratic_formula"},"Quadratic formula"),". If you've seen it before, you'll remember it, and if you haven't, it looks like this:"),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/d5882cc83b002196c8e701ad273ced103e2b4484.svg",style:{width:"28.72485rem",height:"2.475rem"}}),r.createElement("p",null,"So, if we can express a Bézier component function as a plain polynomial, we're done: we just plug in the values into the quadratic formula, check if that square root is negative or not (if it is, there are no roots) and then just compute the two values that come out (because of that plus/minus sign we get two). Any value between 0 and 1 is a root that matters for Bézier curves, anything below or above that is irrelevant (because Bézier curves are only defined over the interval [0,1]). So, how do we convert?"),r.createElement("p",null,"First we turn our cubic Bézier function into a quadratic one, by following the rule mentioned at the end of the ",r.createElement("a",{href:"#derivatives"},"derivatives section"),":"),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/1fc5a3c637460213133bb4576b292e206d67b36f.svg",style:{width:"37.20015rem",height:"2.7rem"}}),r.createElement("p",null,"And then, using these ",r.createElement("em",null,"v")," values, we can find out what our ",r.createElement("em",null,"a"),", ",r.createElement("em",null,"b"),", and ",r.createElement("em",null,"c")," should be:"),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/c638a85a950ffb535fbf2056958bed5f44be5067.svg",style:{width:"21.375rem",height:"7.2rem"}}),r.createElement("p",null,"This gives us thee coefficients ",r.createElement("em",null,"a"),", ",r.createElement("em",null,"b"),", and ",r.createElement("em",null,"c")," that are expressed in terms of ",r.createElement("em",null,"v")," values, where the ",r.createElement("em",null,"v")," values are just convenient expressions of our original ",r.createElement("em",null,"p")," values, so we can do some trivial substitution to get:"),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/076b74a0f2bcb43a3b2d39fdc52c58c6f89ce33a.svg",style:{width:"20.84985rem",height:"3.97485rem"}}),r.createElement("p",null,"Easy peasy. We can now almost trivially find the roots by plugging those values into the quadratic formula. We also note that the second derivative of a cubic curve means computing the first derivative of a quadratic curve, and we just saw how to do that in the section above."),r.createElement("h3",{id:"quartic-curves-cardano-s-algorithm-"},"Quartic curves: Cardano's algorithm."),r.createElement("p",null,"Quartic—fourth degree—curves have a cubic function as derivative. Now, cubic functions are a bit of a problem because they're really hard to solve. But, way back in the 16",r.createElement("sup",null,"th")," century, ",r.createElement("a",{href:"https://en.wikipedia.org/wiki/Gerolamo_Cardano"},"Gerolamo Cardano"),' figured out that even if the general cubic function is really hard to solve, it can be rewritten to a form for which finding the roots is "easy", and then the only hard part is figuring out how to go from that form to the generic form. So:'),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/a16a0da87e138b1307973397275c296eb475b1b1.svg",style:{width:"45rem",height:"2.77515rem"}}),r.createElement("p",null,'This is easier because for the "easier formula" we can use ',r.createElement("a",{href:"http://www.wolframalpha.com/input/?i=t^3+%2B+pt+%2B+q"},"regular calculus")," to find the roots (as a cubic function, however, it can have up to three roots, but two of those can be complex. For the purpose of Bézier curve extremities, we can completely ignore those complex roots, since our ",r.createElement("em",null,"t")," is a plain real number from 0 to 1)."),r.createElement("p",null,"So, the trick is to figure out how to turn the first formula into the second formula, and to then work out the maths that gives us the roots. This is explained in detail over at ",r.createElement("a",{href:"http://www.trans4mind.com/personal_development/mathematics/polynomials/cubicAlgebra.htm"},"Ken J. Ward's page")," for solving the cubic equation, so instead of showing the maths, I'm simply going to show the programming code for solving the cubic equation, with the complex roots getting totally ignored."),r.createElement("div",{className:"howtocode"},r.createElement("h3",{id:"implementing-cardano-s-algorithm-for-finding-all-real-roots"},"Implementing Cardano's algorithm for finding all real roots"),r.createElement("p",null,'The "real roots" part is fairly important, because while you cannot take a square, cube, etc. root of a negative number in the "real" number space (denoted with ℝ), this is perfectly fine in the ',r.createElement("a",{href:"https://en.wikipedia.org/wiki/Complex_number"},'"complex" number')," space (denoted with ℂ). And, as it so happens, Cardano is also attributed as the first mathematician in history to have made use of complex numbers in his calculations. For this very algorithm!"),r.createElement("pre",null,"// A helper function to filter for values in the [0,1] interval:","\n","function accept(t) ","{","\n"," return 0<=t && t <=1;","\n","}","\n","\n","// A real-cuberoots-only function:","\n","function crt(v) ","{","\n"," if(v<0) return -Math.pow(-v,1/3);","\n"," return Math.pow(v,1/3);","\n","}","\n","\n","// Now then: given cubic coordinates ","{","pa, pb, pc, pd","}"," find all roots.","\n","function getCubicRoots(pa, pb, pc, pd) ","{","\n"," var d = (-pa + 3*pb - 3*pc + pd),","\n"," a = (3*pa - 6*pb + 3*pc) / d,","\n"," b = (-3*pa + 3*pb) / d,","\n"," c = pa / d;","\n","\n"," var p = (3*b - a*a)/3,","\n"," p3 = p/3,","\n"," q = (2*a*a*a - 9*a*b + 27*c)/27,","\n"," q2 = q/2,","\n"," discriminant = q2*q2 + p3*p3*p3;","\n","\n"," // and some variables we're going to use later on:","\n"," var u1,v1,root1,root2,root3;","\n","\n"," // three possible real roots:","\n"," if (discriminant < 0) ","{","\n"," var mp3 = -p/3,","\n"," mp33 = mp3*mp3*mp3,","\n"," r = sqrt( mp33 ),","\n"," t = -q / (2*r),","\n"," cosphi = t<-1 ? -1 : t>1 ? 1 : t,","\n"," phi = acos(cosphi),","\n"," crtr = cuberoot(r),","\n"," t1 = 2*crtr;","\n"," root1 = t1 * cos(phi/3) - a/3;","\n"," root2 = t1 * cos((phi+2*pi)/3) - a/3;","\n"," root3 = t1 * cos((phi+4*pi)/3) - a/3;","\n"," return [root1, root2, root3].filter(accept);","\n"," ","}","\n","\n"," // three real roots, but two of them are equal:","\n"," if(discriminant === 0) ","{","\n"," u1 = q2 < 0 ? cuberoot(-q2) : -cuberoot(q2);","\n"," root1 = 2*u1 - a/3;","\n"," root2 = -u1 - a/3;","\n"," return [root1, root2].filter(accept);","\n"," ","}","\n","\n"," // one real root, two complex roots","\n"," var sd = sqrt(discriminant);","\n"," u1 = cuberoot(sd - q2);","\n"," v1 = cuberoot(sd + q2);","\n"," root1 = u1 - v1 - a/3;","\n"," return [root1].filter(accept);","\n","}","\n")),r.createElement("p",null,'And that\'s it. The maths is complicated, but the code is pretty much just "follow the maths, while caching as many values as we can to reduce recomputing things as much as possible" and now we have a way to find all roots for a cubic function and can just move on with using that to find extremities of our curves.'),r.createElement("h3",{id:"quintic-and-higher-order-curves-finding-numerical-solutions"},"Quintic and higher order curves: finding numerical solutions"),r.createElement("p",null,"The problem with this is that as the order of the curve goes up, we can't actually solve those equations the normal way. We can't take the function, and then work out what the solutions are. Not to mention that even solving a third order derivative (for a fourth order curve) is already a royal pain in the backside. We need a better solution. We need numerical approaches."),r.createElement("p",null,'That\'s a fancy word for saying "rather than solve the function, treat the problem as a sequence of identical operations, the performing of which gets us closer and closer to the real answer". As it turns out, there is a really nice numerical root finding algorithm, called the ',r.createElement("a",{href:"http://en.wikipedia.org/wiki/Newton-Raphson"},"Newton-Raphson")," root finding method (yes, after ",r.createElement("em",null,r.createElement("a",{href:"https://en.wikipedia.org/wiki/Isaac_Newton"},"that"))," Newton), which we can make use of."),r.createElement("p",null,"The Newton-Raphson approach consists of picking a value ",r.createElement("em",null,"t")," (any will do), and getting the corresponding value at that ",r.createElement("em",null,"t")," value. For normal functions, we can treat that value as a height. If the height is zero, we're done, we have found a root. If it's not, we take the tangent of the curve at that point, and extend it until it passes the x-axis, which will be at some new point ",r.createElement("em",null,"t"),". We then repeat the procedure with this new value, and we keep doing this until we find our root."),r.createElement("p",null,"Mathematically, this means that for some ",r.createElement("em",null,"t"),", at step ",r.createElement("em",null,"n=1"),", we perform the following calculation until ",r.createElement("em",null,"f",r.createElement("sub",null,"y")),"(",r.createElement("em",null,"t"),") is zero, so that the next ",r.createElement("em",null,"t")," is the same as the one we already have:"),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/b563256be7016370365935944308cf878cdbc29c.svg",style:{width:"8.625150000000001rem",height:"2.9250000000000003rem"}}),r.createElement("p",null,"(The wikipedia article has a decent animation for this process, so I'm not adding a sketch for that here unless there are requests for it)"),r.createElement("p",null,"Now, this works well only if we can pick good starting points, and our curve is continuously differentiable and doesn't have oscillations. Glossing over the exact meaning of those terms, the curves we're dealing with conform to those constraints, so as long as we pick good starting points, this will work. So the question is: which starting points do we pick?"),r.createElement("p",null,"As it turns out, Newton-Raphson is so blindingly fast, so we could get away with just not picking: we simply run the algorithm from ",r.createElement("em",null,"t=0")," to ",r.createElement("em",null,"t=1")," at small steps (say, 1/200",r.createElement("sup",null,"th"),") and the result will be all the roots we want. Of course, this may pose problems for high order Bézier curves: 200 steps for a 200",r.createElement("sup",null,"th")," order Bézier curve is going to go wrong, but that's okay: there is no reason, ever, to use Bézier curves of crazy high orders. You might use a fifth order curve to get the \"nicest still remotely workable\" approximation of a full circle with a single Bézier curve, that's pretty much as high as you'll ever need to go."),r.createElement("h3",{id:"in-conclusion-"},"In conclusion:"),r.createElement("p",null,"So now that we know how to do root finding, we can determine the first and second derivative roots for our Bézier curves, and show those roots overlaid on the previous graphics:"),r.createElement(i,{preset:"simple",title:"Quadratic Bézier curve extremities",setup:e.setupQuadratic,draw:e.draw}),r.createElement(i,{preset:"simple",title:"Cubic Bézier curve extremities",setup:e.setupCubic,draw:e.draw}))}},boundingbox:{locale:"en-GB",title:"Bounding boxes",getContent:function(e){return r.createElement("section",null,r.createElement(a,{name:"boundingbox",title:"Bounding boxes",number:"16"}),r.createElement("p",null,"If we have the extremities, and the start/end points, a simple for loop that tests for min/max values for x and y means we have the four values we need to box in our curve:"),r.createElement("p",null,r.createElement("em",null,"Computing the bounding box for a Bézier curve"),":"),r.createElement("ol",null,r.createElement("li",null,"Find all ",r.createElement("em",null,"t")," value(s) for the curve derivative's x- and y-roots."),r.createElement("li",null,"Discard any ",r.createElement("em",null,"t")," value that's lower than 0 or higher than 1, because Bézier curves only use the interval [0,1]."),r.createElement("li",null,"Determine the lowest and highest value when plugging the values ",r.createElement("em",null,"t=0"),", ",r.createElement("em",null,"t=1")," and each of the found roots into the original functions: the lowest value is the lower bound, and the highest value is the upper bound for the bounding box we want to construct.")),r.createElement("p",null,"Applying this approach to our previous root finding, we get the following bounding boxes (with all curve extremity points shown on the curve):"),r.createElement(i,{preset:"simple",title:"Quadratic Bézier bounding box",setup:e.setupQuadratic,draw:e.draw}),r.createElement(i,{preset:"simple",title:"Cubic Bézier bounding box",setup:e.setupCubic,draw:e.draw}),r.createElement("p",null,"We can construct even nicer boxes by aligning them along our curve, rather than along the x- and y-axis, but in order to do so we first need to look at how aligning works."))}},aligning:{locale:"en-GB",title:"Aligning curves",getContent:function(e){return r.createElement("section",null,r.createElement(a,{name:"aligning",title:"Aligning curves",number:"17"}),r.createElement("p",null,'While there are an incredible number of curves we can define by varying the x- and y-coordinates for the control points, not all curves are actually distinct. For instance, if we define a curve, and then rotate it 90 degrees, it\'s still the same curve, and we\'ll find its extremities in the same spots, just at different draw coordinates. As such, one way to make sure we\'re working with a "unique" curve is to "axis-align" it.'),r.createElement("p",null,"Aligning also simplifies a curve's functions. We can translate (move) the curve so that the first point lies on (0,0), which turns our ",r.createElement("em",null,"n")," term polynomial functions into ",r.createElement("em",null,"n-1")," term functions. The order stays the same, but we have less terms. Then, we can rotate the curves so that the last point always lies on the x-axis, too, making its coordinate (...,0). This further simplifies the function for the y-component to an ",r.createElement("em",null,"n-2")," term function. For instance, if we have a cubic curve such as this:"),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/d253dc7ff011a8ae46f3351975f1d4beedd7a794.svg",style:{width:"34.12485rem",height:"2.77515rem"}}),r.createElement("p",null,"Then translating it so that the first coordinate lies on (0,0), moving all ",r.createElement("em",null,"x")," coordinates by -120, and all ",r.createElement("em",null,"y")," coordinates by -160, gives us:"),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/b3ec747086a146c1b2c682afea6b1eae016c9a7a.svg",style:{width:"33.075rem",height:"2.77515rem"}}),r.createElement("p",null,"If we then rotate the curve so that its end point lies on the x-axis, the coordinates (integer-rounded for illustrative purposes here) become:"),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/fd82fad845da25b074dff33bbc4aa563d5f367a7.svg",style:{width:"32.54985rem",height:"2.77515rem"}}),r.createElement("p",null,"If we drop all the zero-terms, this gives us:"),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/b4d6e220358b2d00f0cf516f433fbe5ecb58f25d.svg",style:{width:"25.79985rem",height:"2.77515rem"}}),r.createElement("p",null,"We can see that our original curve definition has been simplified considerably. The following graphics illustrate the result of aligning our example curves to the x-axis, with the cubic case using the coordinates that were just used in the example formulae:"),r.createElement(i,{preset:"twopanel",title:"Aligning a quadratic curve",setup:e.setupQuadratic,draw:e.draw}),r.createElement(i,{preset:"twopanel",title:"Aligning a cubic curve",setup:e.setupCubic,draw:e.draw}))}},tightbounds:{locale:"en-GB",title:"Tight boxes",getContent:function(e){return r.createElement("section",null,r.createElement(a,{name:"tightbounds",title:"Tight boxes",number:"18"}),r.createElement("p",null,'With our knowledge of bounding boxes, and curve alignment, We can now form the "tight" bounding box for curves. We first align our curve, recording the translation we performed, "T", and the rotation angle we used, "R". We then determine the aligned curve\'s normal bounding box. Once we have that, we can map that bounding box back to our original curve by rotating it by -R, and then translating it by -T. We now have nice tight bounding boxes for our curves:'),r.createElement(i,{preset:"twopanel",title:"Aligning a quadratic curve",setup:e.setupQuadratic,draw:e.draw}),r.createElement(i,{preset:"twopanel",title:"Aligning a cubic curve",setup:e.setupCubic,draw:e.draw}),r.createElement("p",null,"These are, strictly speaking, not necessarily the tightest possible bounding boxes. It is possible to compute the optimal bounding box by determining which spanning lines we need to effect a minimal box area, but because of the parametric nature of Bézier curves this is actually a rather costly operation, and the gain in bounding precision is often not worth it. If there is high demand for it, I'll add a section on how to precisely compute the best fit bounding box, but the maths is fairly gruelling and just not really worth spending time on."))}},inflections:{locale:"en-GB",title:"Curve inflections",getContent:function(e){return r.createElement("section",null,r.createElement(a,{name:"inflections",title:"Curve inflections",number:"19"}),r.createElement("p",null,"Now that we know how to align a curve, there's one more thing we can calculate: inflection points. Imagine we have a variable size circle that we can slide up against our curve. We place it against the curve and adjust its radius so that where it touches the curve, the curvatures of the curve and the circle are the same, and then we start to slide the circle along the curve - for quadratic curves, we can always do this without the circle behaving oddly: we might have to change the radius of the circle as we slide it along, but it'll always sit against the same side of the curve."),r.createElement("p",null,'But what happens with cubic curves? Imagine we have an S curve and we place our circle at the start of the curve, and start sliding it along. For a while we can simply adjust the radius and things will be fine, but once we get to the midpoint of that S, something odd happens: the circle "flips" from one side of the curve to the other side, in order for the curvatures to keep matching. This is called an inflection, and we can find out where those happen relatively easily.'),r.createElement("p",null,"What we need to do is solve a simple equation:"),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/b039194e01b6081628efaf4aa169a4c50fa4aae4.svg",style:{width:"3.90015rem",height:"1.125rem"}}),r.createElement("p",null,"What we're saying here is that given the curvature function ",r.createElement("em",null,"C(t)"),", we want to know for which values of ",r.createElement("em",null,"t"),' this function is zero, meaning there is no "curvature", which will be exactly at the point between our circle being on one side of the curve, and our circle being on the other side of the curve. So what does ',r.createElement("em",null,"C(t)")," look like? Actually something that seems not too hard:"),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/2488885d57cfc55b50b1c8ad808180e50337b411.svg",style:{width:"27.37485rem",height:"1.125rem"}}),r.createElement("p",null,"So the function ",r.createElement("em",null,"C(t)")," is wholly defined by the first and second derivative functions for the parametric dimensions of our curve. And as already shown, derivatives of Bézier curves are just simpler Bézier curves, with very easy to compute new coefficients, so this should be pretty easy."),r.createElement("p",null,"However as we've seen in the section on aligning, aligning lets us simplify things ",r.createElement("em",null,"a lot"),", by completely removing the contributions of the first coordinate from most mathematical evaluations, and removing the last ",r.createElement("em",null,"y")," coordinate as well by virtue of the last point lying on the x-axis. So, while we can evaluate ",r.createElement("em",null,"C(t) = 0")," for our curve, it'll be much easier to first axis-align the curve and ",r.createElement("em",null,"then")," evalutating the curvature function."),r.createElement("div",{className:"note"},r.createElement("h3",{id:"let-s-derive-the-full-formula-anyway"},"Let's derive the full formula anyway"),r.createElement("p",null,"Of course, before we do our aligned check, let's see what happens if we compute the curvature function without axis-aligning. We start with the first and second derivatives, given our basis functions:"),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/462664d174062cec5f7252d5912057210783776c.svg",style:{width:"41.250150000000005rem",height:"4.35015rem"}}),r.createElement("p",null,"And of course the same functions for ",r.createElement("em",null,"y"),":"),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/9390cb8ff4f3a9471db41c033b415a0a90b69404.svg",style:{width:"27rem",height:"4.35015rem"}}),r.createElement("p",null,"Asking a computer to now compose the ",r.createElement("em",null,"C(t)")," function for us (and to expand it to a readable form of simple terms) gives us this rather overly complicated set of arithmetic expressions:"),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/92350c75ebfba40fcab87d091f1f46e4c01be720.svg",style:{width:"29.62485rem",height:"7.12485rem"}}),r.createElement("p",null,"That is... unwieldy. So, we note that there are a lot of terms that involve multiplications involving x1, y1, and y4, which would all disappear if we axis-align our curve, which is why aligning is a great idea.")),r.createElement("p",null,"Aligning our curve so that three of the eight coefficients become zero, we end up with the following simple term function for ",r.createElement("em",null,"C(t)"),":"),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/f61c01094f0de8ca4c7f26a229f0206d54b13930.svg",style:{width:"37.49985rem",height:"1.35rem"}}),r.createElement("p",null,"That's a lot easier to work with: we see a fair number of terms that we can compute and then cache, giving us the following simplification:"),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/c1e427616a8a2502abf3cf46415971d0df9a273c.svg",style:{width:"34.72515rem",height:"5.54985rem"}}),r.createElement("p",null,"This is a plain quadratic curve, and we know how to solve ",r.createElement("em",null,"C(t) = 0"),"; we use the quadratic formula:"),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/368099657b735b0d17becbbe7be915e88e8c04c5.svg",style:{width:"30.675150000000002rem",height:"4.1998500000000005rem"}}),r.createElement("p",null,"We can easily compute this value ",r.createElement("em",null,"if")," the descriminator isn't a negative number (because we only want real roots, not complex roots), and ",r.createElement("em",null,"if")," ",r.createElement("em",null,"x")," is not zero, because divisions by zero are rather useless."),r.createElement("p",null,"Taking that into account, we compute ",r.createElement("em",null,"t"),", we disregard any ",r.createElement("em",null,"t")," value that isn't in the Bézier interval [0,1], and we now know at which ",r.createElement("em",null,"t")," value(s) our curve will inflect."),r.createElement(i,{title:"Finding cubic Bézier curve inflections",setup:e.setupCubic,draw:e.draw}))}},canonical:{locale:"en-GB",title:"Canonical form (for cubic curves)",getContent:function(e){return r.createElement("section",null,r.createElement(a,{name:"canonical",title:"Canonical form (for cubic curves)",number:"20"}),r.createElement("p",null,"While quadratic curves are relatively simple curves to analyze, the same cannot be said of the cubic curve. As a curvature controlled by more than one control points, it exhibits all kinds of features like loops, cusps, odd colinear features, and up to two inflection points because the curvature can change direction up to three times. Now, knowing what kind of curve we're dealing with means that some algorithms can be run more efficiently than if we have to implement them as generic solvers, so is there a way to determine the curve type without lots of work?"),r.createElement("p",null,"As it so happens, the answer is yes and the solution we're going to look at was presented by Maureen C. Stone from Xerox PARC and Tony D. deRose from the University of Washington in their joint paper ",r.createElement("a",{href:"http://graphics.pixar.com/people/derose/publications/CubicClassification/paper.pdf"},'"A Geometric Characterization of Parametric Cubic curves"'),'. It was published in 1989, and defines curves as having a "canonical" form (i.e. a form that all curves can be reduced to) from which we can immediately tell which features a curve will have. So how does it work?'),r.createElement("p",null,'The first observation that makes things work is that if we have a cubic curve with four points, we can apply a linear transformation to these points such that three of the points end up on (0,0), (0,1) and (1,1), with the last point then being "somewhere". After applying that transformation, the location of that last point can then tell us what kind of curve we\'re dealing with. Specifically, we see the following breakdown:'),r.createElement(i,{static:!0,preset:"simple",title:"The canonical curve map",setup:e.setup,draw:e.drawBase}),r.createElement("p",null,"This is a fairly funky image, so let's see how it breaks down. We see the three fixed points at (0,0), (0,1) and (1,1), and then the fourth point is somewhere. Depending on where it is, our curve will have certain features. Namely, if the fourth point is..."),r.createElement("ol",null,r.createElement("li",null,"anywhere on and in the red zone, the curve will be self-intersecting, yielding either a cusp or a loop. Anywhere inside the the red zone, this will be a loop. We won't know ",r.createElement("i",null,"where")," that loop is (in terms of ",r.createElement("i",null,"t")," values), but we are guaranteed that there is one."),r.createElement("li",null,"on the left (red) edge, the curve will have a cusp. We again don't know ",r.createElement("em",null,"where"),", just that it has one. This edge is described by the function:")),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/ae5a63e86bb367e6266a394962387344d0a92b10.svg",style:{width:"12.45015rem",height:"2.3998500000000003rem"}}),r.createElement("ol",null,r.createElement("li",null,"on the lower right (pink) edge, the curve will have a loop at t=1, so we know the end coordinate of the curve also lies ",r.createElement("em",null,"on")," the curve. This edge is described by the function:")),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/d389fcde05a773be99f84db5fc9ed7ef043bf406.svg",style:{width:"16.050150000000002rem",height:"2.6248500000000003rem"}}),r.createElement("ol",null,r.createElement("li",null,"on the top (blue) edge, the curve will have a loop at t=0, so we know the start coordinate of the curve also lies ",r.createElement("em",null,"on")," the curve. This edge is described by the function:")),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/d97181a9d0ada19862a0ff2cebb08bdee00868d7.svg",style:{width:"10.650150000000002rem",height:"2.3998500000000003rem"}}),r.createElement("ol",null,r.createElement("li",null,"inside the green zone, the curve will have a single inflection, switching concave/convex once."),r.createElement("li",null,"between the red and green zones, the curve has two inflections, meaning its curvature switches between concave/convex form twice."),r.createElement("li",null,"anywhere on the right of the red zone, the curve will have no inflections. It'll just be a well-behaved arch.")),r.createElement("p",null,"Of course, this map is fairly small, but the regions extend to infinity, with well defined boundaries."),r.createElement("div",{className:"note"},r.createElement("h3",{id:"wait-where-do-those-lines-come-from-"},"Wait, where do those lines come from?"),r.createElement("p",null,'Without repeating the paper mentioned at the top of this section, the loop-boundaries come from rewriting the curve into canonical form, and then solving the formulae for which constraints must hold for which possible curve properties. In the paper these functions yield formulae for where you will find cusp points, or loops where we know t=0 or t=1, but those functions are derived for the full cubic expression, meaning they apply to t=-∞ to t=∞... For Bézier curves we only care about the "clipped interval" t=0 to t=1, so some of the properties that apply when you look at the curve over an infinite interval simply don\'t apply to the Bézier curve interval.'),r.createElement("p",null,'The right bound for the loop region, indicating where the curve switches from "having inflections" to "having a loop", for the general cubic curve, is actually mirrored over x=1, but for Bézier curves this right half doesn\'t apply, so we don\'t need to pay attention to it. Similarly, the boundaries for t=0 and t=1 loops are also nice clean curves but get "cut off" when we only look at what the general curve does over the interval t=0 to t=1.'),r.createElement("p",null,'For the full details, head over to the paper and read through sections 3 and 4. If you still remember your high school precalculus, you can probably follow along with this paper, although you might have to read it a few times before all the bits "click".')),r.createElement("p",null,"So now the question becomes: how do we manipulate our curve so that it fits this canonical form, with three fixed points, and one \"free\" point? Enter linear algerba. Don't worry, I'll be doing all the math for you, as well as show you what the effect is on our curves, but basically we're going to be using linear algebra, rather than calculus, because \"it's way easier\". Sometimes a calculus approach is very hard to work with, when the equivalent geometrical solution is super obvious."),r.createElement("p",null,"The approach is going to start with a curve that doesn't have all-colinear points (so we need to make sure the points don't all fall on a straight line), and then applying four graphics operations that you will probably have heard of: translation (moving all points by some fixed x- and y-distance), scaling (multiplying all points by some x and y scale factor), and shearing (an operation that turns rectangles into parallelograms)."),r.createElement("p",null,"Step 1: we translate any curve by -p1.x and -p1.y, so that the curve starts at (0,0). We're going to make use of an interesting trick here, by pretending our 2D coordinates are 3D, with the ",r.createElement("i",null,"z")," coordinate simply always being 1. This is an old trick in graphics to overcome the limitations of 2D transformations: without it, we can only turn (x,y) coordinates into new coordinates of the form (ax + by, cx + dy), which means we can't do translation, since that requires we end up with some kind of (x + a, y + b). If we add a bogus ",r.createElement("i",null,"z")," coordinate that is always 1, then we can suddenly add arbitrary values. For example:"),r.createElement("img",{ +e.setCurve(t,n)},draw:function(e,t){e.reset(),t.forEach(function(t){e.drawSkeleton(t),e.drawCurve(t)});var n=e.utils,r={p1:t[1].points[0],p2:t[1].points[1]},i=n.align(t[0].points,r),a=new e.Bezier(i),o=n.roots(a.points);o.forEach(function(n){var r=t[0].get(n);e.drawCircle(r,3),e.text("t = "+n,{x:r.x+5,y:r.y+10})})},render:function(){return r.createElement("section",null,r.createElement(a,this.props),r.createElement("p",null,"Let's look at some more things we will want to do with Bézier curves. Almost immediately after figuring out how to get bounding boxes to work, people tend to run into the problem that even though the minimal bounding box (based on rotation) is tight, it's not sufficient to perform true collision detection. It's a good first step to make sure there ",r.createElement("em",null,"might")," be a collision (if there is no bounding box overlap, there can't be one), but in order to do real collision detection we need to know whether or not there's an intersection on the actual curve."),r.createElement("p",null,"We'll do this in steps, because it's a bit of a journey to get to curve/curve intersection checking. First, let's start simple, by implementing a line-line intersection checker. While we can solve this the traditional calculus way (determine the functions for both lines, then compute the intersection by equating them and solving for two unknowns), linear algebra actually offers a nicer solution."),r.createElement("h3",null,"Line-line intersections"),r.createElement("p",{id:"intersection_ll"},"if we have two line segments with two coordinates each, segments A-B and C-D, we can find the intersection of the lines these segments are an intervals on by linear algebra, using the procedure outlined in this ",r.createElement("a",{href:"http://www.topcoder.com/tc?module=Static&d1=tutorials&d2=geometry2#line_line_intersection"},"top coder")," article. Of course, we need to make sure that the intersection isn't just on the lines our line segments lie on, but also on our line segments themselves, so after we find the intersection we need to verify it lies without the bounds of our original line segments."),r.createElement("p",null),r.createElement("p",null,"The following graphic implements this intersection detection, showing a red point for an intersection on the lines our segments lie on (thus being a virtual intersection point), and a green point for an intersection that lies on both segments (being a real intersection point)."),r.createElement(i,{preset:"simple",title:"Line/line intersections",setup:this.setupLines,draw:this.drawLineIntersection}),r.createElement("div",{className:"howtocode"},r.createElement("h3",null,"Implementing line-line intersections"),r.createElement("p",null,"Let's have a look at how to implement a line-line intersection checking function. The basics are covered in the article mentioned above, but sometimes you need more function signatures, because you might not want to call your function with eight distinct parameters. Maybe you're using point structs or the line. Let's get coding:"),r.createElement("pre",null,"lli8 = function(x1,y1,x2,y2,x3,y3,x4,y4):\n var nx=(x1*y2-y1*x2)*(x3-x4)-(x1-x2)*(x3*y4-y3*x4),\n ny=(x1*y2-y1*x2)*(y3-y4)-(y1-y2)*(x3*y4-y3*x4),\n d=(x1-x2)*(y3-y4)-(y1-y2)*(x3-x4);\n if d=0:\n return false\n return point(nx/d, ny/d)\n\nlli4 = function(p1, p2, p3, p4):\n var x1 = p1.x, y1 = p1.y,\n x2 = p2.x, y2 = p2.y,\n x3 = p3.x, y3 = p3.y,\n x4 = p4.x, y4 = p4.y;\n return lli8(x1,y1,x2,y2,x3,y3,x4,y4)\n\nlli = function(line1, line2):\n return lli4(line1.p1, line1.p2, line2.p1, line2.p2)")),r.createElement("h3",null,"What about curve-line intersections?"),r.createElement("p",null,"Curve/line intersection is more work, but we've already seen the techniques we need to use in order to perform it: first we translate/rotate both the line and curve together, in such a way that the line coincides with the x-axis. This will position the curve in a way that makes it cross the line at points where its y-function is zero. By doing this, the problem of finding intersections between a curve and a line has now become the problem of performing root finding on our translated/rotated curve, as we already covered in the section on finding extremities."),r.createElement(i,{preset:"simple",title:"Quadratic curve/line intersections",setup:this.setupQuadratic,draw:this.draw}),r.createElement(i,{preset:"simple",title:"Cubic curve/line intersections",setup:this.setupCubic,draw:this.draw}),r.createElement("p",null,"Curve/curve intersection, however, is more complicated. Since we have no straight line to align to, we can't simply align one of the curves and be left with a simple procedure. Instead, we'll need to apply two techniques we've not covered yet: de Casteljau's algorithm, and curve splitting."))}});e.exports=l},function(e,t,n){"use strict";var r=n(0),i=n(4),a=new i,o="introduction",s=r.createClass({displayName:"Introduction",getDefaultProps:function(){return{title:a.getTitle(o)}},drawQuadratic:function(e){var t=e.getDefaultQuadratic();e.setCurve(t)},drawCubic:function(e){var t=e.getDefaultCubic();e.setCurve(t)},drawCurve:function(e,t){e.reset(),e.drawSkeleton(t),e.drawCurve(t)},render:function(){return r.createElement("section",null,a.getContent(o,this))}});e.exports=s},function(e,t,n){"use strict";var r=n(0),i=n(4),a=new i,o="matrix",s=r.createClass({displayName:"Matrix",getDefaultProps:function(){return{title:a.getTitle(o)}},render:function(){return r.createElement("section",null,a.getContent(o,this))}});e.exports=s},function(e,t,n){"use strict";var r=n(0),i=n(4),a=new i,o="matrixsplit",s=r.createClass({displayName:"MatrixSplit",getDefaultProps:function(){return{title:a.getTitle(o)}},render:function(){return r.createElement("section",null,a.getContent(o,this))}});e.exports=s},function(e,t,n){"use strict";var r=n(0),i=n(8),a=n(6),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!(n<.05||n>.95)&&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],f=t.B=c.get(n);t.db=c.derivative(n),t.C=t.utils.lli4(d,f,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},f={x:t.newA.x+(d.x-t.newA.x)/t.t,y:t.newA.y+(d.y-t.newA.y)/t.t},p={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-f.x)/(1-t.t),y:u[3].y-(u[3].y-f.y)/(1-t.t)};t.p1=c,t.p2=d,t.sc1=h,t.sc2=f,t.nc1=p,t.nc2=m,t.update=[p,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(0),i=n(8),a=n(6),o=n(15),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(0),i=n(8),a=n(6),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,f=c+h/d,p=f*(i.x-r.x)/u,m=f*(i.y-r.y)/u,g={x:a.x-p,y:a.y-m},v={x:a.x+p,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(0),i=n(4),a=new i,o="pointvectors",s=r.createClass({displayName:"PointVectors",getDefaultProps:function(){return{title:a.getTitle(o)}},setupQuadratic:function(e){var t=e.getDefaultQuadratic();e.setCurve(t)},setupCubic:function(e){var t=e.getDefaultCubic();e.setCurve(t)},draw:function(e,t){e.reset(),e.drawSkeleton(t);var n,r,i,a,o,s,l=20;for(n=0;n<=10;n++)r=n/10,i=t.get(r),a=t.derivative(r),s=Math.sqrt(a.x*a.x+a.y*a.y),a={x:a.x/s,y:a.y/s},o=t.normal(r),e.setColor("blue"),e.drawLine(i,{x:i.x+a.x*l,y:i.y+a.y*l}),e.setColor("red"),e.drawLine(i,{x:i.x+o.x*l,y:i.y+o.y*l}),e.setColor("black"),e.drawCircle(i,3)},render:function(){return r.createElement("section",null,a.getContent(o,this))}});e.exports=s},function(e,t,n){"use strict";var r=n(0),i=n(8),a=n(6),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;a<4;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+=r<0?e.lpts.length:0,n=t-2,n+=n<0?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,f=s(h*h+d*d);i.x=r.x+f*u(c),i.y=r.y+f*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+=r<0?e.lpts.length:0,n=t-2,n+=n<0?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,f=s(h*h+d*d);a.x=i.x+f*u(c),a.y=i.y+f*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(0),i=n(4),a=new i,o="preface",s=r.createClass({displayName:"Preface",getDefaultProps:function(){return{title:a.getTitle(o)}},render:function(){return r.createElement("section",null,a.getContent(o,this))}});e.exports=s},function(e,t,n){"use strict";var r=n(0),i=n(8),a=n(6),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;r1;){for(var o=0;of){r--;break}r<0&&(r=0),r===c.length&&(r=c.length-1),d.push(c[r])}for(n=0;n0;o-=e.step)a=o/100,a>1||(e.setRandomColor(),n={x:d.x+a*(f.x-d.x),y:d.y+a*(f.y-d.y)},r={x:f.x+a*(p.x-f.x),y:f.y+a*(p.y-f.y)},i={x:n.x+a*(r.x-n.x),y:n.y+a*(r.y-n.y)},m={x:0,y:0},e.drawCircle(n,3,m),e.drawCircle(r,3,m),e.setWeight(.5),e.drawLine(n,r,m),e.setWeight(1.5),e.drawLine(d,n,m),e.drawLine(f,r,m),e.setWeight(1),m.x+=c,e.drawCircle(n,3,m),e.drawCircle(r,3,m),e.setWeight(.5),e.drawLine(n,r,m),e.setWeight(1.5),e.drawLine(n,i,m),e.setWeight(1),e.drawCircle(i,3,m),m.x+=c,e.drawCircle(i,3,m),e.text(o+"%, or t = "+e.utils.round(a,2),{x:i.x+10+m.x,y:i.y+10+m.y}))},values:{38:1,40:-1},onKeyDown:function(e,t){var n=this.values[e.keyCode];n&&(e.preventDefault(),t.step+=n,t.step<1&&(t.step=1))},render:function(){return r.createElement("section",null,a.getContent(o,this))}});e.exports=s},function(e,t,n){"use strict";var r=n(0),i=n(8),a=n(6);e.exports={preface:{locale:"ja-JP",title:"まえがき",getContent:function(e){return r.createElement("section",null,r.createElement(a,{name:"preface",title:"まえがき"}),r.createElement("p",null,"2次元上になにかを描くとき、普通は線を使いますが、これは直線と曲線の2つに分類することができます。直線を描くのはとても簡単で、これをコンピュータに描かせるのも容易です。直線の始点と終点をコンピュータに与えてやれば、ポン!直線が描けました。疑問の余地もありません。"),r.createElement("p",null,"しかしながら、曲線の方はもっと大きな問題です。私たちはフリーハンドでいとも簡単に曲線を描くことができますが、コンピュータの方は少し不利です。曲線の描き方を表した数学的な関数が与えられないと、コンピュータは曲線を描くことができないのです。実際には、直線でさえも関数が必要になります。直線の関数はとても簡単なので、わたしたちはよく無視してしまいますが、コンピュータにとっては直線であれ曲線であれ、線はすべて「関数」なのです。しかしこれは、コンピュータで速く計算できて、きれいな曲線が得られるような関数を見つける必要がある、ということになります。そのような関数はたくさんありますが、多くの関心を集め続け、そしてどんな場面でも使われている、ある特定の関数に対してこの記事では焦点を絞ります。この関数は「ベジエ」曲線を描きます。"),r.createElement("p",null,"ベジエ曲線は",r.createElement("a",{href:"https://ja.wikipedia.org/wiki/ピエール・ベジェ"},"Pierre Bézier"),"から名付けられました。この曲線がデザイン作業に適していることを世界に知らしめたのが、彼なのです(ルノーに勤務し、1962年にその研究を発表しました)。ただし、この曲線を「発明」したのは彼が最初で唯一というわけではありません。数学者",r.createElement("a",{href:"https://en.wikipedia.org/wiki/Paul_de_Casteljau"},"Paul de Casteljau"),"はシトロエンで働いていた1959年、この曲線の性質について研究し、ベジエ曲線の非常にエレガントな描き方を発見しました。これが最初だと言う人もいます。しかしながら、de Casteljauは自分の成果を発表しなかったため、「誰が最初か?」という問いに答えるのがとても難しくなっています。またベジエ曲線は、核心的には",r.createElement("a",{href:"https://ja.wikipedia.org/wiki/セルゲイ・ベルンシュテイン"},"Sergei Natanovich Bernstein"),"が研究した「ベルンシュタイン多項式」という数学関数の一種ですが、こちらの公刊に関しては少なくとも1912年まで遡ることができます。いずれにせよ、これらはほとんど瑣末なことです。より注目すべきなのは、ベジエ曲線は取り扱いに便利だいうことです。たとえば複数のベジエ曲線を繋いで、1つの曲線に見えるようにすることができます。もしあなたがPhotoshopで「パス」を描いたり、FlashやIllustrator、Inkscapeのようなベクタードローイングソフトを使ったことがあるのであれば、そこで描いてきた曲線はベジエ曲線です。"),r.createElement("p",null,"では、これを自分でプログラムしなければならないとなったらどうでしょう?ハマりどころは何でしょうか?どうやってベジエ曲線を描くのでしょう?バウンディングボックスとは何で、どうやって交点を求め、どうやったら曲線を押し出せるのでしょうか?つまるところ、ベジエ曲線に対して行いたいあらゆる操作は、どのようにすればいいのでしょう?このページはそれに答えるためにあります。数学にとりかかりましょう!"),r.createElement("p",null,"—Pomax (Twitter上では",r.createElement("a",{href:"https://twitter.com/TheRealPomax"},"@TheRealPomax"),")"),r.createElement("div",{className:"note"},r.createElement("h2",{id:"-"},"注:ベジエの図はすべてインタラクティブになっています。"),r.createElement("p",null,"このページでは",r.createElement("a",{ +href:"http://pomax.github.io/bezierjs"},"Bezier.js"),"を活用し、インタラクティブな例示を行っています。また、",r.createElement("a",{href:"http://mathjax.org"},"MathJax"),"というすばらしいライブラリによって、(LaTeX式の)「本物」の数学組版を行っています。このページはWebpackを使い、Reactアプリケーションとしてオフラインで生成されていますが、このために「ソースを表示」オプションを追加することがかなり難しくなってしまいました。これをどうやって追加すべきかは今もまだ考え中ですが、かといって、数年ぶりとなる今回の更新を延期したくはありませんでした。"),r.createElement("h2",{id:"-"},"本書はオープンソースです。"),r.createElement("p",null,"この本はオープンソースソフトウェアのプロジェクトで、2つのGitHubリポジトリ上に存在しています。1つ目の",r.createElement("a",{href:"https://github.com/pomax/bezierinfo"},"https://github.com/pomax/bezierinfo"),"は表示のためだけに用意されたバージョンで、あなたが今読んでいるものです。もう一方の",r.createElement("a",{href:"https://github.com/pomax/BezierInfo-2"},"https://github.com/pomax/BezierInfo-2"),"は開発版で、すべてのHTML・JavaScript・CSSが含まれています。どちらのリポジトリもフォークすることができますし、あなたの好きなように使ってかまいません。ただし、これを自分の成果だと騙って売ることはもちろん除きます。=)"),r.createElement("h2",{id:"-"},"数学はどこまで難しくなりますか?"),r.createElement("p",null,"この入門に出てくる数学は、大半が高校初年度程度です。基本的な計算を理解していて、英語の読み方が分かっていれば、こなすことができるはずです。時には",r.createElement("em",null,"ずっと"),"難しい数学も出てきますが、もし理解できないように感じたら、そこは読み飛ばしても大丈夫です。節の中の「詳細欄」を飛ばしてもいいですし、厄介そうな数学があれば節の最後まで読み飛ばしてもかまいません。各節の最後にはたいてい結論を並べてありますので、これを直に利用することもできます。"),r.createElement("h2",{id:"-"},"質問・コメント:"),r.createElement("p",null,"新しい節の提案があれば、",r.createElement("a",{href:"https://github.com/pomax/BezierInfo-2/issues"},"GitHubのissueトラッカー"),"をクリックしてください(右上にあるリポジトリのリンクからでもたどり着けます)。改訂中のため、現在はこのページにはコメント欄がありませんが、内容に関する質問がある場合にもissueトラッカーを使ってかまいません。改訂が完了したら、総合的なコメント欄を復活させる予定です。あるいは、「質問対象の節を選択して『質問』ボタンをクリック」するような項目別のシステムになるかもしれません。いずれわかります。"),r.createElement("h2",{id:"-"},"コーヒーをおごってくれませんか?"),r.createElement("p",null,"この本が気に入った場合や、取り組んでいたことに役に立つと思った場合、あるいは、この本への感謝をわたしに伝えるにはどうすればいいのかわからない場合。そのような場合には、",r.createElement("a",{href:"https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=QPRDLNGDANJSW"},"わたしにコーヒーをおごってください"),"。あなたが住んでいるところのコーヒー1杯の値段でかまいません。この本は小さな入門からはじまり、印刷で70ページほどに相当するようなベジエ曲線の読み物へと、年々成長してきています。そして、多くのコーヒーが執筆に費やされてきました。わたしは執筆に使った時間が惜しいとは思いませんが、もう少しコーヒーがあれば、ずっと書き続けることができるのです!")))}},introduction:{locale:"ja-JP",title:"バッとした導入",getContent:function(e){return r.createElement("section",null,r.createElement(a,{name:"introduction",title:"バッとした導入",number:"1"}),r.createElement("p",null,"まずは良い例から始めましょう。ベジエ曲線というのは、下の図に表示されているもののことです。ベジエ曲線はある始点からある終点へと延びており、その曲率は1個以上の「中間」制御点に左右されています。さて、このページの図はどれもインタラクティブになっていますので、ここで曲線をちょっと操作してみましょう。点をドラッグしたとき、曲線の形がそれに応じてどう変化するのか、確かめてみてください。"),r.createElement("div",{className:"figure"},r.createElement(i,{inline:!0,title:"2次のベジエ曲線",setup:e.drawQuadratic,draw:e.drawCurve}),r.createElement(i,{inline:!0,title:"3次のベジエ曲線",setup:e.drawCubic,draw:e.drawCurve})),r.createElement("p",null,"ベジエ曲線は、CAD(computer aided designやCAM(computer aided manufacturing)のアプリケーションで多用されています。もちろん、Adobe Illustrator・Photoshop・Inkscape・Gimp などのグラフィックデザインアプリケーションや、SVG(scalable vector graphics)・OpenTypeフォント(otf/ttf)のようなグラフィック技術でも利用されています。ベジエ曲線はたくさんのものに使われていますので、これについてもっと詳しく学びたいのであれば……さあ、準備しましょう!"))}},whatis:{locale:"ja-JP",title:"ではベジエ曲線はどうやってできるのでしょう?",getContent:function(e){return r.createElement("section",null,r.createElement(a,{name:"whatis",title:"ではベジエ曲線はどうやってできるのでしょう?",number:"2"}),r.createElement("p",null,"ベジエ曲線がどのように動くのか、点を触ってみて感覚が摑めたかもしれません。では、実際のところベジエ曲線",r.createElement("em",null,"とは"),"いったい何でしょうか?これを説明する方法は2通りありますが、どちらの説明でも行き着く先はまったく同じです。一方は複雑な数学を使うのに対し、もう一方はとても簡単です。というわけで……簡単な説明の方から始めましょう。"),r.createElement("p",null,"ベジエ曲線は、",r.createElement("a",{href:"https://ja.wikipedia.org/wiki/%E7%B7%9A%E5%BD%A2%E8%A3%9C%E9%96%93"},"線形補間"),"の結果です。というと難しそうに聞こえますが、誰でも幼い頃から線形補間をやってきています。例えば、何か2つのものの間を指し示すときには、いつも線形補間を行っています。線形補間とは、単純に「2点の間から点を得る」ことなのです。"),r.createElement("p",null,"例えば、2点間の距離がわかっているとして、一方の点から距離の20%だけ離れた(すなわち、もう一方の点から80%離れた)新しい点を求めたい場合、次のようにとても簡単に計算できます。"),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/75bb049d813d8ee084b076531823f2109cc1660f.svg",style:{width:"36.750150000000005rem",height:"6.37515rem"}}),r.createElement("p",null,"では、実際に見てみましょう。下の図はインタラクティブになっています。上下キーで補間の比率が増減しますので、どうなるか確かめてみましょう。最初に3点があり、それを結んで2本の直線が引かれています。この直線の上でそれぞれ線形補間を行うと、2つの点が得られます。この2点の間でさらに線形補間を行うと、1つの点を得ることができます。そして、あらゆる比率に対して同様に点を求め、それをすべて集めると、このようにベジエ曲線ができるのです。"),r.createElement(i,{title:"線形補間でベジエ曲線を得る",setup:e.setup,draw:e.draw,onKeyDown:e.onKeyDown}),r.createElement("p",null,"また、これが複雑な方の数学につながっていきます。微積分です。"),r.createElement("p",null,"いま上で行ったものとは似つかないように思えますが、実はあれは2次曲線を描いていたのです。ただし一発で描きあげるのではなく、手順を追って描いていきました。ベジエ曲線は多項式関数で表現できますが、その一方で、とても単純な補間の補間の補間の……というふうにも説明できます。これがベジエ曲線のおもしろいところです。これはまた、ベジェ曲線は「本当の数学」で見る(関数を調べたり微分を調べたり、あらゆる方法で)ことも可能ですし、「機械的」な組み立て操作として見る(例えば、ベジエ曲線は組み立てに使う点の間からは決してはみ出ないということがわかります)ことも可能だということを意味しています。"),r.createElement("p",null,"それでは、もう少し詳しくベジエ曲線を見ていきましょう。数学的な表現やそこから導かれる性質、さらには、ベジエ曲線に対して/ベジエ曲線を使ってできるさまざまな内容についてです。"))}},explanation:{locale:"en-GB",title:"The mathematics of Bézier curves",getContent:function(e){return r.createElement("section",null,r.createElement(a,{name:"explanation",title:"The mathematics of Bézier curves",number:"3"}),r.createElement("p",null,'Bézier curves are a form of "parametric" function. Mathematically speaking, parametric functions are cheats: a "function" is actually a well defined term representing a mapping from any number of inputs to a ',r.createElement("strong",null,"single")," output. Numbers go in, a single number comes out. Change the numbers that go in, and the number that comes out is still a single number. Parametric functions cheat. They basically say \"alright, well, we want multiple values coming out, so we'll just use more than one function\". An illustration: Let's say we have a function that maps some value, let's call it ",r.createElement("i",null,"x"),", to some other value, using some kind of number manipulation:"),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/785e792c343b71d4e674ac94d8800940b30917ac.svg",style:{width:"6.22485rem",height:"1.125rem"}}),r.createElement("p",null,"The notation ",r.createElement("i",null,"f(x)")," is the standard way to show that it's a function (by convention called ",r.createElement("i",null,"f")," if we're only listing one) and its output changes based on one variable (in this case, ",r.createElement("i",null,"x"),"). Change ",r.createElement("i",null,"x"),", and the output for ",r.createElement("i",null,"f(x)")," changes."),r.createElement("p",null,"So far so good. Now, let's look at parametric functions, and how they cheat. Let's take the following two functions:"),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/0dfe7562b43441e72201ff4cdd2e8b6e2e3ecb2d.svg",style:{width:"6.525rem",height:"2.6248500000000003rem"}}),r.createElement("p",null,"There's nothing really remarkable about them, they're just a sine and cosine function, but you'll notice the inputs have different names. If we change the value for ",r.createElement("i",null,"a"),", we're not going to change the output value for ",r.createElement("i",null,"f(b)"),", since ",r.createElement("i",null,"a")," isn't used in that function. Parametric functions cheat by changing that. In a parametric function all the different functions share a variable, like this:"),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/ed6f533530199d1e99b3319ba137c1327b0459c0.svg",style:{width:"7.349849999999999rem",height:"2.6248500000000003rem"}}),r.createElement("p",null,"Multiple functions, but only one variable. If we change the value for ",r.createElement("i",null,"t"),", we change the outcome of both ",r.createElement("i",null,"f",r.createElement("sub",null,"a"),"(t)")," and ",r.createElement("i",null,"f",r.createElement("sub",null,"b"),"(t)"),". You might wonder how that's useful, and the answer is actually pretty simple: if we change the labels ",r.createElement("i",null,"f",r.createElement("sub",null,"a"),"(t)")," and ",r.createElement("i",null,"f",r.createElement("sub",null,"b"),"(t)")," with what we usually mean with them for parametric curves, things might be a lot more obvious:"),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/ea632ea75d6a2aeb6fe69c07feb6e76f81884746.svg",style:{width:"5.77485rem",height:"2.6248500000000003rem"}}),r.createElement("p",null,"There we go. ",r.createElement("i",null,"x"),"/",r.createElement("i",null,"y")," coordinates, linked through some mystery value ",r.createElement("i",null,"t"),"."),r.createElement("p",null,"So, parametric curves don't define a ",r.createElement("i",null,"y")," coordinate in terms of an ",r.createElement("i",null,"x"),' coordinate, like normal functions do, but they instead link the values to a "control" variable. If we vary the value of ',r.createElement("i",null,"t"),", then with every change we get ",r.createElement("strong",null,"two")," values, which we can use as (",r.createElement("i",null,"x"),",",r.createElement("i",null,"y"),") coordinates in a graph. The above set of functions, for instance, generates points on a circle: We can range ",r.createElement("i",null,"t")," from negative to positive infinity, and the resulting (",r.createElement("i",null,"x"),",",r.createElement("i",null,"y"),") coordinates will always lie on a circle with radius 1 around the origin (0,0). If we plot it for ",r.createElement("i",null,"t")," from 0 to 5, we get this (use your up and down arrow keys to change the plot end value):"),r.createElement(i,{preset:"empty",title:"A (partial) circle: x=sin(t), y=cos(t)",static:!0,setup:e.setup,draw:e.draw,onKeyDown:e.props.onKeyDown}),r.createElement("p",null,"Bézier curves are (one in many classes of) parametric functions, and are characterised by using the same base function for all its dimensions. Unlike the above example, where the ",r.createElement("i",null,"x")," and ",r.createElement("i",null,"y"),' values use different functions (one uses a sine, the other a cosine), Bézier curves use the "binomial polynomial" for both ',r.createElement("i",null,"x")," and ",r.createElement("i",null,"y"),". So what are binomial polynomials?"),r.createElement("p",null,"You may remember polynomials from high school, where they're those sums that look like:"),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/3e8b26cf8833db7089d65e9c6b3953a3140bb19f.svg",style:{width:"14.32485rem",height:"1.20015rem"}}),r.createElement("p",null,"If they have a highest order term ",r.createElement("i",null,"x³")," they're called \"cubic\" polynomials, if it's ",r.createElement("i",null,"x²")," it's a \"square\" polynomial, if it's just ",r.createElement("i",null,"x")," it's a line (and if there aren't even any terms with ",r.createElement("i",null,"x")," it's not a polynomial!)"),r.createElement("p",null,"Bézier curves are polynomials of ",r.createElement("i",null,"t"),", rather than ",r.createElement("i",null,"x"),", with the value for ",r.createElement("i",null,"t")," fixed being between 0 and 1, with coefficients ",r.createElement("i",null,"a"),", ",r.createElement("i",null,"b"),' etc. taking the "binomial" form, which sounds fancy but is actually a pretty simple description for mixing values:'),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/24e915ab4c69b85951f1ea9018b0ece9e52a10dd.svg",style:{width:"24.89985rem",height:"4.1998500000000005rem"}}),r.createElement("p",null,"I know what you're thinking: that doesn't look too simple, but if we remove ",r.createElement("i",null,"t"),' and add in "times one", things suddenly look pretty easy. Check out these binomial terms:'),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/448d10d21afd49135055cf685fedf6c494984b53.svg",style:{width:"14.475150000000001rem",height:"5.175rem"}}),r.createElement("p",null,'Notice that 2 is the same as 1+1, and 3 is 2+1 and 1+2, and 6 is 3+3... As you can see, each time we go up a dimension, we simply start and end with 1, and everything in between is just "the two numbers above it, added together". Now ',r.createElement("i",null,"that's")," easy to remember."),r.createElement("p",null,"There's an equally simple way to figure out how the polynomial terms work: if we rename ",r.createElement("i",null,"(1-t)")," to ",r.createElement("i",null,"a")," and ",r.createElement("i",null,"t")," to ",r.createElement("i",null,"b"),", and remove the weights for a moment, we get this:"),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/87c7f5294b902def4ea56e8f6cf24265a37143b6.svg",style:{width:"20.84985rem",height:"3.825rem"}}),r.createElement("p",null,"It's basically just a sum of \"every combination of ",r.createElement("i",null,"a")," and ",r.createElement("i",null,"b"),'", progressively replacing ',r.createElement("i",null,"a"),"'s with ",r.createElement("i",null,"b"),"'s after every + sign. So that's actually pretty simple too. So now you know binomial polynomials, and just for completeness I'm going to show you the generic function for this:"),r.createElement("img",{className:"LaTeX SVG",src:"images/latex/d79bf595a0911c17e2ac86d8806a0a8ab6ba7dfe.svg",style:{width:"20.39985rem",height:"3.90015rem"}}),r.createElement("p",null,"And that's the full description for Bézier curves. Σ in this function indicates that this is a series of additions (using the variable listed below the Σ, starting at ...= and ending at the value listed on top of the Σ)."),r.createElement("div",{className:"howtocode"},r.createElement("h3",{id:"how-to-implement-the-basis-function"},"How to implement the basis function"),r.createElement("p",null,"We could naively implement the basis function as a mathematical construct, using the function as our guide, like this:"),r.createElement("pre",null,"function Bezier(n,t):\n sum = 0\n for(k=0; k= lut.length):\n s = lut.length\n nextRow = new array(size=s+1)\n nextRow[0] = 1\n for(i=1, prev=s-1; i