Path.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748
  1. /**
  2. * @author zz85 / http://www.lab4games.net/zz85/blog
  3. * Creates free form 2d path using series of points, lines or curves.
  4. *
  5. **/
  6. THREE.Path = function ( points ) {
  7. THREE.CurvePath.call( this );
  8. this.actions = [];
  9. if ( points ) {
  10. this.fromPoints( points );
  11. }
  12. };
  13. THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );
  14. THREE.Path.prototype.constructor = THREE.Path;
  15. THREE.PathActions = {
  16. MOVE_TO: 'moveTo',
  17. LINE_TO: 'lineTo',
  18. QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
  19. BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve
  20. CSPLINE_THRU: 'splineThru', // Catmull-Rom spline
  21. ARC: 'arc', // Circle
  22. ELLIPSE: 'ellipse'
  23. };
  24. // TODO Clean up PATH API
  25. // Create path using straight lines to connect all points
  26. // - vectors: array of Vector2
  27. THREE.Path.prototype.fromPoints = function ( vectors ) {
  28. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  29. for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) {
  30. this.lineTo( vectors[ v ].x, vectors[ v ].y );
  31. }
  32. };
  33. // startPath() endPath()?
  34. THREE.Path.prototype.moveTo = function ( x, y ) {
  35. var args = Array.prototype.slice.call( arguments );
  36. this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );
  37. };
  38. THREE.Path.prototype.lineTo = function ( x, y ) {
  39. var args = Array.prototype.slice.call( arguments );
  40. var lastargs = this.actions[ this.actions.length - 1 ].args;
  41. var x0 = lastargs[ lastargs.length - 2 ];
  42. var y0 = lastargs[ lastargs.length - 1 ];
  43. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  44. this.curves.push( curve );
  45. this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } );
  46. };
  47. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  48. var args = Array.prototype.slice.call( arguments );
  49. var lastargs = this.actions[ this.actions.length - 1 ].args;
  50. var x0 = lastargs[ lastargs.length - 2 ];
  51. var y0 = lastargs[ lastargs.length - 1 ];
  52. var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ),
  53. new THREE.Vector2( aCPx, aCPy ),
  54. new THREE.Vector2( aX, aY ) );
  55. this.curves.push( curve );
  56. this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } );
  57. };
  58. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
  59. aCP2x, aCP2y,
  60. aX, aY ) {
  61. var args = Array.prototype.slice.call( arguments );
  62. var lastargs = this.actions[ this.actions.length - 1 ].args;
  63. var x0 = lastargs[ lastargs.length - 2 ];
  64. var y0 = lastargs[ lastargs.length - 1 ];
  65. var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ),
  66. new THREE.Vector2( aCP1x, aCP1y ),
  67. new THREE.Vector2( aCP2x, aCP2y ),
  68. new THREE.Vector2( aX, aY ) );
  69. this.curves.push( curve );
  70. this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } );
  71. };
  72. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  73. var args = Array.prototype.slice.call( arguments );
  74. var lastargs = this.actions[ this.actions.length - 1 ].args;
  75. var x0 = lastargs[ lastargs.length - 2 ];
  76. var y0 = lastargs[ lastargs.length - 1 ];
  77. //---
  78. var npts = [ new THREE.Vector2( x0, y0 ) ];
  79. Array.prototype.push.apply( npts, pts );
  80. var curve = new THREE.SplineCurve( npts );
  81. this.curves.push( curve );
  82. this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } );
  83. };
  84. // FUTURE: Change the API or follow canvas API?
  85. THREE.Path.prototype.arc = function ( aX, aY, aRadius,
  86. aStartAngle, aEndAngle, aClockwise ) {
  87. var lastargs = this.actions[ this.actions.length - 1 ].args;
  88. var x0 = lastargs[ lastargs.length - 2 ];
  89. var y0 = lastargs[ lastargs.length - 1 ];
  90. this.absarc( aX + x0, aY + y0, aRadius,
  91. aStartAngle, aEndAngle, aClockwise );
  92. };
  93. THREE.Path.prototype.absarc = function ( aX, aY, aRadius,
  94. aStartAngle, aEndAngle, aClockwise ) {
  95. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  96. };
  97. THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius,
  98. aStartAngle, aEndAngle, aClockwise, aRotation ) {
  99. var lastargs = this.actions[ this.actions.length - 1 ].args;
  100. var x0 = lastargs[ lastargs.length - 2 ];
  101. var y0 = lastargs[ lastargs.length - 1 ];
  102. this.absellipse( aX + x0, aY + y0, xRadius, yRadius,
  103. aStartAngle, aEndAngle, aClockwise, aRotation );
  104. };
  105. THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius,
  106. aStartAngle, aEndAngle, aClockwise, aRotation ) {
  107. var args = [
  108. aX, aY,
  109. xRadius, yRadius,
  110. aStartAngle, aEndAngle,
  111. aClockwise,
  112. aRotation || 0 // aRotation is optional.
  113. ];
  114. var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius,
  115. aStartAngle, aEndAngle, aClockwise, aRotation );
  116. this.curves.push( curve );
  117. var lastPoint = curve.getPoint( 1 );
  118. args.push( lastPoint.x );
  119. args.push( lastPoint.y );
  120. this.actions.push( { action: THREE.PathActions.ELLIPSE, args: args } );
  121. };
  122. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  123. if ( ! divisions ) divisions = 40;
  124. var points = [];
  125. for ( var i = 0; i < divisions; i ++ ) {
  126. points.push( this.getPoint( i / divisions ) );
  127. //if ( !this.getPoint( i / divisions ) ) throw "DIE";
  128. }
  129. // if ( closedPath ) {
  130. //
  131. // points.push( points[ 0 ] );
  132. //
  133. // }
  134. return points;
  135. };
  136. /* Return an array of vectors based on contour of the path */
  137. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  138. if ( this.useSpacedPoints ) {
  139. return this.getSpacedPoints( divisions, closedPath );
  140. }
  141. divisions = divisions || 12;
  142. var points = [];
  143. var i, il, item, action, args;
  144. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  145. laste, j,
  146. t, tx, ty;
  147. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  148. item = this.actions[ i ];
  149. action = item.action;
  150. args = item.args;
  151. switch ( action ) {
  152. case THREE.PathActions.MOVE_TO:
  153. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  154. break;
  155. case THREE.PathActions.LINE_TO:
  156. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  157. break;
  158. case THREE.PathActions.QUADRATIC_CURVE_TO:
  159. cpx = args[ 2 ];
  160. cpy = args[ 3 ];
  161. cpx1 = args[ 0 ];
  162. cpy1 = args[ 1 ];
  163. if ( points.length > 0 ) {
  164. laste = points[ points.length - 1 ];
  165. cpx0 = laste.x;
  166. cpy0 = laste.y;
  167. } else {
  168. laste = this.actions[ i - 1 ].args;
  169. cpx0 = laste[ laste.length - 2 ];
  170. cpy0 = laste[ laste.length - 1 ];
  171. }
  172. for ( j = 1; j <= divisions; j ++ ) {
  173. t = j / divisions;
  174. tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  175. ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  176. points.push( new THREE.Vector2( tx, ty ) );
  177. }
  178. break;
  179. case THREE.PathActions.BEZIER_CURVE_TO:
  180. cpx = args[ 4 ];
  181. cpy = args[ 5 ];
  182. cpx1 = args[ 0 ];
  183. cpy1 = args[ 1 ];
  184. cpx2 = args[ 2 ];
  185. cpy2 = args[ 3 ];
  186. if ( points.length > 0 ) {
  187. laste = points[ points.length - 1 ];
  188. cpx0 = laste.x;
  189. cpy0 = laste.y;
  190. } else {
  191. laste = this.actions[ i - 1 ].args;
  192. cpx0 = laste[ laste.length - 2 ];
  193. cpy0 = laste[ laste.length - 1 ];
  194. }
  195. for ( j = 1; j <= divisions; j ++ ) {
  196. t = j / divisions;
  197. tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  198. ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  199. points.push( new THREE.Vector2( tx, ty ) );
  200. }
  201. break;
  202. case THREE.PathActions.CSPLINE_THRU:
  203. laste = this.actions[ i - 1 ].args;
  204. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  205. var spts = [ last ];
  206. var n = divisions * args[ 0 ].length;
  207. spts = spts.concat( args[ 0 ] );
  208. var spline = new THREE.SplineCurve( spts );
  209. for ( j = 1; j <= n; j ++ ) {
  210. points.push( spline.getPointAt( j / n ) );
  211. }
  212. break;
  213. case THREE.PathActions.ARC:
  214. var aX = args[ 0 ], aY = args[ 1 ],
  215. aRadius = args[ 2 ],
  216. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  217. aClockwise = !! args[ 5 ];
  218. var deltaAngle = aEndAngle - aStartAngle;
  219. var angle;
  220. var tdivisions = divisions * 2;
  221. for ( j = 1; j <= tdivisions; j ++ ) {
  222. t = j / tdivisions;
  223. if ( ! aClockwise ) {
  224. t = 1 - t;
  225. }
  226. angle = aStartAngle + t * deltaAngle;
  227. tx = aX + aRadius * Math.cos( angle );
  228. ty = aY + aRadius * Math.sin( angle );
  229. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  230. points.push( new THREE.Vector2( tx, ty ) );
  231. }
  232. //console.log(points);
  233. break;
  234. case THREE.PathActions.ELLIPSE:
  235. var aX = args[ 0 ], aY = args[ 1 ],
  236. xRadius = args[ 2 ],
  237. yRadius = args[ 3 ],
  238. aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
  239. aClockwise = !! args[ 6 ],
  240. aRotation = args[ 7 ];
  241. var deltaAngle = aEndAngle - aStartAngle;
  242. var angle;
  243. var tdivisions = divisions * 2;
  244. var cos, sin;
  245. if ( aRotation !== 0 ) {
  246. cos = Math.cos( aRotation );
  247. sin = Math.sin( aRotation );
  248. }
  249. for ( j = 1; j <= tdivisions; j ++ ) {
  250. t = j / tdivisions;
  251. if ( ! aClockwise ) {
  252. t = 1 - t;
  253. }
  254. angle = aStartAngle + t * deltaAngle;
  255. tx = aX + xRadius * Math.cos( angle );
  256. ty = aY + yRadius * Math.sin( angle );
  257. if ( aRotation !== 0 ) {
  258. var x = tx, y = ty;
  259. // Rotate the point about the center of the ellipse.
  260. tx = ( x - aX ) * cos - ( y - aY ) * sin + aX;
  261. ty = ( x - aX ) * sin + ( y - aY ) * cos + aY;
  262. }
  263. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  264. points.push( new THREE.Vector2( tx, ty ) );
  265. }
  266. //console.log(points);
  267. break;
  268. } // end switch
  269. }
  270. // Normalize to remove the closing point by default.
  271. var lastPoint = points[ points.length - 1 ];
  272. var EPSILON = 0.0000000001;
  273. if ( Math.abs( lastPoint.x - points[ 0 ].x ) < EPSILON &&
  274. Math.abs( lastPoint.y - points[ 0 ].y ) < EPSILON )
  275. points.splice( points.length - 1, 1 );
  276. if ( closedPath ) {
  277. points.push( points[ 0 ] );
  278. }
  279. return points;
  280. };
  281. //
  282. // Breaks path into shapes
  283. //
  284. // Assumptions (if parameter isCCW==true the opposite holds):
  285. // - solid shapes are defined clockwise (CW)
  286. // - holes are defined counterclockwise (CCW)
  287. //
  288. // If parameter noHoles==true:
  289. // - all subPaths are regarded as solid shapes
  290. // - definition order CW/CCW has no relevance
  291. //
  292. THREE.Path.prototype.toShapes = function( isCCW, noHoles ) {
  293. function extractSubpaths( inActions ) {
  294. var i, il, item, action, args;
  295. var subPaths = [], lastPath = new THREE.Path();
  296. for ( i = 0, il = inActions.length; i < il; i ++ ) {
  297. item = inActions[ i ];
  298. args = item.args;
  299. action = item.action;
  300. if ( action === THREE.PathActions.MOVE_TO ) {
  301. if ( lastPath.actions.length !== 0 ) {
  302. subPaths.push( lastPath );
  303. lastPath = new THREE.Path();
  304. }
  305. }
  306. lastPath[ action ].apply( lastPath, args );
  307. }
  308. if ( lastPath.actions.length !== 0 ) {
  309. subPaths.push( lastPath );
  310. }
  311. // console.log(subPaths);
  312. return subPaths;
  313. }
  314. function toShapesNoHoles( inSubpaths ) {
  315. var shapes = [];
  316. for ( var i = 0, il = inSubpaths.length; i < il; i ++ ) {
  317. var tmpPath = inSubpaths[ i ];
  318. var tmpShape = new THREE.Shape();
  319. tmpShape.actions = tmpPath.actions;
  320. tmpShape.curves = tmpPath.curves;
  321. shapes.push( tmpShape );
  322. }
  323. //console.log("shape", shapes);
  324. return shapes;
  325. }
  326. function isPointInsidePolygon( inPt, inPolygon ) {
  327. var EPSILON = 0.0000000001;
  328. var polyLen = inPolygon.length;
  329. // inPt on polygon contour => immediate success or
  330. // toggling of inside/outside at every single! intersection point of an edge
  331. // with the horizontal line through inPt, left of inPt
  332. // not counting lowerY endpoints of edges and whole edges on that line
  333. var inside = false;
  334. for ( var p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  335. var edgeLowPt = inPolygon[ p ];
  336. var edgeHighPt = inPolygon[ q ];
  337. var edgeDx = edgeHighPt.x - edgeLowPt.x;
  338. var edgeDy = edgeHighPt.y - edgeLowPt.y;
  339. if ( Math.abs( edgeDy ) > EPSILON ) {
  340. // not parallel
  341. if ( edgeDy < 0 ) {
  342. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  343. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  344. }
  345. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  346. if ( inPt.y === edgeLowPt.y ) {
  347. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  348. // continue; // no intersection or edgeLowPt => doesn't count !!!
  349. } else {
  350. var perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  351. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  352. if ( perpEdge < 0 ) continue;
  353. inside = ! inside; // true intersection left of inPt
  354. }
  355. } else {
  356. // parallel or collinear
  357. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  358. // edge lies on the same horizontal line as inPt
  359. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  360. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  361. // continue;
  362. }
  363. }
  364. return inside;
  365. }
  366. var subPaths = extractSubpaths( this.actions );
  367. if ( subPaths.length === 0 ) return [];
  368. if ( noHoles === true ) return toShapesNoHoles( subPaths );
  369. var solid, tmpPath, tmpShape, shapes = [];
  370. if ( subPaths.length === 1 ) {
  371. tmpPath = subPaths[ 0 ];
  372. tmpShape = new THREE.Shape();
  373. tmpShape.actions = tmpPath.actions;
  374. tmpShape.curves = tmpPath.curves;
  375. shapes.push( tmpShape );
  376. return shapes;
  377. }
  378. var holesFirst = ! THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
  379. holesFirst = isCCW ? ! holesFirst : holesFirst;
  380. // console.log("Holes first", holesFirst);
  381. var betterShapeHoles = [];
  382. var newShapes = [];
  383. var newShapeHoles = [];
  384. var mainIdx = 0;
  385. var tmpPoints;
  386. newShapes[ mainIdx ] = undefined;
  387. newShapeHoles[ mainIdx ] = [];
  388. var i, il;
  389. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  390. tmpPath = subPaths[ i ];
  391. tmpPoints = tmpPath.getPoints();
  392. solid = THREE.Shape.Utils.isClockWise( tmpPoints );
  393. solid = isCCW ? ! solid : solid;
  394. if ( solid ) {
  395. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  396. newShapes[ mainIdx ] = { s: new THREE.Shape(), p: tmpPoints };
  397. newShapes[ mainIdx ].s.actions = tmpPath.actions;
  398. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  399. if ( holesFirst ) mainIdx ++;
  400. newShapeHoles[ mainIdx ] = [];
  401. //console.log('cw', i);
  402. } else {
  403. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  404. //console.log('ccw', i);
  405. }
  406. }
  407. // only Holes? -> probably all Shapes with wrong orientation
  408. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  409. if ( newShapes.length > 1 ) {
  410. var ambiguous = false;
  411. var toChange = [];
  412. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  413. betterShapeHoles[ sIdx ] = [];
  414. }
  415. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  416. var sho = newShapeHoles[ sIdx ];
  417. for ( var hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  418. var ho = sho[ hIdx ];
  419. var hole_unassigned = true;
  420. for ( var s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  421. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  422. if ( sIdx !== s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } );
  423. if ( hole_unassigned ) {
  424. hole_unassigned = false;
  425. betterShapeHoles[ s2Idx ].push( ho );
  426. } else {
  427. ambiguous = true;
  428. }
  429. }
  430. }
  431. if ( hole_unassigned ) {
  432. betterShapeHoles[ sIdx ].push( ho );
  433. }
  434. }
  435. }
  436. // console.log("ambiguous: ", ambiguous);
  437. if ( toChange.length > 0 ) {
  438. // console.log("to change: ", toChange);
  439. if ( ! ambiguous ) newShapeHoles = betterShapeHoles;
  440. }
  441. }
  442. var tmpHoles, j, jl;
  443. for ( i = 0, il = newShapes.length; i < il; i ++ ) {
  444. tmpShape = newShapes[ i ].s;
  445. shapes.push( tmpShape );
  446. tmpHoles = newShapeHoles[ i ];
  447. for ( j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  448. tmpShape.holes.push( tmpHoles[ j ].h );
  449. }
  450. }
  451. //console.log("shape", shapes);
  452. return shapes;
  453. };