SVGLoader.js 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862
  1. THREE.SVGLoader = function ( manager ) {
  2. THREE.Loader.call( this, manager );
  3. // Default dots per inch
  4. this.defaultDPI = 90;
  5. // Accepted units: 'mm', 'cm', 'in', 'pt', 'pc', 'px'
  6. this.defaultUnit = 'px';
  7. };
  8. THREE.SVGLoader.prototype = Object.assign( Object.create( THREE.Loader.prototype ), {
  9. constructor: THREE.SVGLoader,
  10. load: function ( url, onLoad, onProgress, onError ) {
  11. var scope = this;
  12. var loader = new THREE.FileLoader( scope.manager );
  13. loader.setPath( scope.path );
  14. loader.setRequestHeader( scope.requestHeader );
  15. loader.setWithCredentials( scope.withCredentials );
  16. loader.load( url, function ( text ) {
  17. try {
  18. onLoad( scope.parse( text ) );
  19. } catch ( e ) {
  20. if ( onError ) {
  21. onError( e );
  22. } else {
  23. console.error( e );
  24. }
  25. scope.manager.itemError( url );
  26. }
  27. }, onProgress, onError );
  28. },
  29. parse: function ( text ) {
  30. var scope = this;
  31. function parseNode( node, style ) {
  32. if ( node.nodeType !== 1 ) return;
  33. var transform = getNodeTransform( node );
  34. var traverseChildNodes = true;
  35. var path = null;
  36. switch ( node.nodeName ) {
  37. case 'svg':
  38. break;
  39. case 'style':
  40. parseCSSStylesheet( node );
  41. break;
  42. case 'g':
  43. style = parseStyle( node, style );
  44. break;
  45. case 'path':
  46. style = parseStyle( node, style );
  47. if ( node.hasAttribute( 'd' ) ) path = parsePathNode( node );
  48. break;
  49. case 'rect':
  50. style = parseStyle( node, style );
  51. path = parseRectNode( node );
  52. break;
  53. case 'polygon':
  54. style = parseStyle( node, style );
  55. path = parsePolygonNode( node );
  56. break;
  57. case 'polyline':
  58. style = parseStyle( node, style );
  59. path = parsePolylineNode( node );
  60. break;
  61. case 'circle':
  62. style = parseStyle( node, style );
  63. path = parseCircleNode( node );
  64. break;
  65. case 'ellipse':
  66. style = parseStyle( node, style );
  67. path = parseEllipseNode( node );
  68. break;
  69. case 'line':
  70. style = parseStyle( node, style );
  71. path = parseLineNode( node );
  72. break;
  73. case 'defs':
  74. traverseChildNodes = false;
  75. break;
  76. case 'use':
  77. style = parseStyle( node, style );
  78. var usedNodeId = node.href.baseVal.substring( 1 );
  79. var usedNode = node.viewportElement.getElementById( usedNodeId );
  80. if ( usedNode ) {
  81. parseNode( usedNode, style );
  82. } else {
  83. console.warn( 'SVGLoader: \'use node\' references non-existent node id: ' + usedNodeId );
  84. }
  85. break;
  86. default:
  87. // console.log( node );
  88. }
  89. if ( path ) {
  90. if ( style.fill !== undefined && style.fill !== 'none' ) {
  91. path.color.setStyle( style.fill );
  92. }
  93. transformPath( path, currentTransform );
  94. paths.push( path );
  95. path.userData = { node: node, style: style };
  96. }
  97. if ( traverseChildNodes ) {
  98. var nodes = node.childNodes;
  99. for ( var i = 0; i < nodes.length; i ++ ) {
  100. parseNode( nodes[ i ], style );
  101. }
  102. }
  103. if ( transform ) {
  104. transformStack.pop();
  105. if ( transformStack.length > 0 ) {
  106. currentTransform.copy( transformStack[ transformStack.length - 1 ] );
  107. } else {
  108. currentTransform.identity();
  109. }
  110. }
  111. }
  112. function parsePathNode( node ) {
  113. var path = new THREE.ShapePath();
  114. var point = new THREE.Vector2();
  115. var control = new THREE.Vector2();
  116. var firstPoint = new THREE.Vector2();
  117. var isFirstPoint = true;
  118. var doSetFirstPoint = false;
  119. var d = node.getAttribute( 'd' );
  120. // console.log( d );
  121. var commands = d.match( /[a-df-z][^a-df-z]*/ig );
  122. for ( var i = 0, l = commands.length; i < l; i ++ ) {
  123. var command = commands[ i ];
  124. var type = command.charAt( 0 );
  125. var data = command.substr( 1 ).trim();
  126. if ( isFirstPoint === true ) {
  127. doSetFirstPoint = true;
  128. isFirstPoint = false;
  129. }
  130. switch ( type ) {
  131. case 'M':
  132. var numbers = parseFloats( data );
  133. for ( var j = 0, jl = numbers.length; j < jl; j += 2 ) {
  134. point.x = numbers[ j + 0 ];
  135. point.y = numbers[ j + 1 ];
  136. control.x = point.x;
  137. control.y = point.y;
  138. if ( j === 0 ) {
  139. path.moveTo( point.x, point.y );
  140. } else {
  141. path.lineTo( point.x, point.y );
  142. }
  143. if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
  144. }
  145. break;
  146. case 'H':
  147. var numbers = parseFloats( data );
  148. for ( var j = 0, jl = numbers.length; j < jl; j ++ ) {
  149. point.x = numbers[ j ];
  150. control.x = point.x;
  151. control.y = point.y;
  152. path.lineTo( point.x, point.y );
  153. if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
  154. }
  155. break;
  156. case 'V':
  157. var numbers = parseFloats( data );
  158. for ( var j = 0, jl = numbers.length; j < jl; j ++ ) {
  159. point.y = numbers[ j ];
  160. control.x = point.x;
  161. control.y = point.y;
  162. path.lineTo( point.x, point.y );
  163. if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
  164. }
  165. break;
  166. case 'L':
  167. var numbers = parseFloats( data );
  168. for ( var j = 0, jl = numbers.length; j < jl; j += 2 ) {
  169. point.x = numbers[ j + 0 ];
  170. point.y = numbers[ j + 1 ];
  171. control.x = point.x;
  172. control.y = point.y;
  173. path.lineTo( point.x, point.y );
  174. if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
  175. }
  176. break;
  177. case 'C':
  178. var numbers = parseFloats( data );
  179. for ( var j = 0, jl = numbers.length; j < jl; j += 6 ) {
  180. path.bezierCurveTo(
  181. numbers[ j + 0 ],
  182. numbers[ j + 1 ],
  183. numbers[ j + 2 ],
  184. numbers[ j + 3 ],
  185. numbers[ j + 4 ],
  186. numbers[ j + 5 ]
  187. );
  188. control.x = numbers[ j + 2 ];
  189. control.y = numbers[ j + 3 ];
  190. point.x = numbers[ j + 4 ];
  191. point.y = numbers[ j + 5 ];
  192. if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
  193. }
  194. break;
  195. case 'S':
  196. var numbers = parseFloats( data );
  197. for ( var j = 0, jl = numbers.length; j < jl; j += 4 ) {
  198. path.bezierCurveTo(
  199. getReflection( point.x, control.x ),
  200. getReflection( point.y, control.y ),
  201. numbers[ j + 0 ],
  202. numbers[ j + 1 ],
  203. numbers[ j + 2 ],
  204. numbers[ j + 3 ]
  205. );
  206. control.x = numbers[ j + 0 ];
  207. control.y = numbers[ j + 1 ];
  208. point.x = numbers[ j + 2 ];
  209. point.y = numbers[ j + 3 ];
  210. if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
  211. }
  212. break;
  213. case 'Q':
  214. var numbers = parseFloats( data );
  215. for ( var j = 0, jl = numbers.length; j < jl; j += 4 ) {
  216. path.quadraticCurveTo(
  217. numbers[ j + 0 ],
  218. numbers[ j + 1 ],
  219. numbers[ j + 2 ],
  220. numbers[ j + 3 ]
  221. );
  222. control.x = numbers[ j + 0 ];
  223. control.y = numbers[ j + 1 ];
  224. point.x = numbers[ j + 2 ];
  225. point.y = numbers[ j + 3 ];
  226. if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
  227. }
  228. break;
  229. case 'T':
  230. var numbers = parseFloats( data );
  231. for ( var j = 0, jl = numbers.length; j < jl; j += 2 ) {
  232. var rx = getReflection( point.x, control.x );
  233. var ry = getReflection( point.y, control.y );
  234. path.quadraticCurveTo(
  235. rx,
  236. ry,
  237. numbers[ j + 0 ],
  238. numbers[ j + 1 ]
  239. );
  240. control.x = rx;
  241. control.y = ry;
  242. point.x = numbers[ j + 0 ];
  243. point.y = numbers[ j + 1 ];
  244. if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
  245. }
  246. break;
  247. case 'A':
  248. var numbers = parseFloats( data );
  249. for ( var j = 0, jl = numbers.length; j < jl; j += 7 ) {
  250. // skip command if start point == end point
  251. if ( numbers[ j + 5 ] == point.x && numbers[ j + 6 ] == point.y ) continue;
  252. var start = point.clone();
  253. point.x = numbers[ j + 5 ];
  254. point.y = numbers[ j + 6 ];
  255. control.x = point.x;
  256. control.y = point.y;
  257. parseArcCommand(
  258. path, numbers[ j ], numbers[ j + 1 ], numbers[ j + 2 ], numbers[ j + 3 ], numbers[ j + 4 ], start, point
  259. );
  260. if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
  261. }
  262. break;
  263. case 'm':
  264. var numbers = parseFloats( data );
  265. for ( var j = 0, jl = numbers.length; j < jl; j += 2 ) {
  266. point.x += numbers[ j + 0 ];
  267. point.y += numbers[ j + 1 ];
  268. control.x = point.x;
  269. control.y = point.y;
  270. if ( j === 0 ) {
  271. path.moveTo( point.x, point.y );
  272. } else {
  273. path.lineTo( point.x, point.y );
  274. }
  275. if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
  276. }
  277. break;
  278. case 'h':
  279. var numbers = parseFloats( data );
  280. for ( var j = 0, jl = numbers.length; j < jl; j ++ ) {
  281. point.x += numbers[ j ];
  282. control.x = point.x;
  283. control.y = point.y;
  284. path.lineTo( point.x, point.y );
  285. if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
  286. }
  287. break;
  288. case 'v':
  289. var numbers = parseFloats( data );
  290. for ( var j = 0, jl = numbers.length; j < jl; j ++ ) {
  291. point.y += numbers[ j ];
  292. control.x = point.x;
  293. control.y = point.y;
  294. path.lineTo( point.x, point.y );
  295. if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
  296. }
  297. break;
  298. case 'l':
  299. var numbers = parseFloats( data );
  300. for ( var j = 0, jl = numbers.length; j < jl; j += 2 ) {
  301. point.x += numbers[ j + 0 ];
  302. point.y += numbers[ j + 1 ];
  303. control.x = point.x;
  304. control.y = point.y;
  305. path.lineTo( point.x, point.y );
  306. if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
  307. }
  308. break;
  309. case 'c':
  310. var numbers = parseFloats( data );
  311. for ( var j = 0, jl = numbers.length; j < jl; j += 6 ) {
  312. path.bezierCurveTo(
  313. point.x + numbers[ j + 0 ],
  314. point.y + numbers[ j + 1 ],
  315. point.x + numbers[ j + 2 ],
  316. point.y + numbers[ j + 3 ],
  317. point.x + numbers[ j + 4 ],
  318. point.y + numbers[ j + 5 ]
  319. );
  320. control.x = point.x + numbers[ j + 2 ];
  321. control.y = point.y + numbers[ j + 3 ];
  322. point.x += numbers[ j + 4 ];
  323. point.y += numbers[ j + 5 ];
  324. if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
  325. }
  326. break;
  327. case 's':
  328. var numbers = parseFloats( data );
  329. for ( var j = 0, jl = numbers.length; j < jl; j += 4 ) {
  330. path.bezierCurveTo(
  331. getReflection( point.x, control.x ),
  332. getReflection( point.y, control.y ),
  333. point.x + numbers[ j + 0 ],
  334. point.y + numbers[ j + 1 ],
  335. point.x + numbers[ j + 2 ],
  336. point.y + numbers[ j + 3 ]
  337. );
  338. control.x = point.x + numbers[ j + 0 ];
  339. control.y = point.y + numbers[ j + 1 ];
  340. point.x += numbers[ j + 2 ];
  341. point.y += numbers[ j + 3 ];
  342. if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
  343. }
  344. break;
  345. case 'q':
  346. var numbers = parseFloats( data );
  347. for ( var j = 0, jl = numbers.length; j < jl; j += 4 ) {
  348. path.quadraticCurveTo(
  349. point.x + numbers[ j + 0 ],
  350. point.y + numbers[ j + 1 ],
  351. point.x + numbers[ j + 2 ],
  352. point.y + numbers[ j + 3 ]
  353. );
  354. control.x = point.x + numbers[ j + 0 ];
  355. control.y = point.y + numbers[ j + 1 ];
  356. point.x += numbers[ j + 2 ];
  357. point.y += numbers[ j + 3 ];
  358. if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
  359. }
  360. break;
  361. case 't':
  362. var numbers = parseFloats( data );
  363. for ( var j = 0, jl = numbers.length; j < jl; j += 2 ) {
  364. var rx = getReflection( point.x, control.x );
  365. var ry = getReflection( point.y, control.y );
  366. path.quadraticCurveTo(
  367. rx,
  368. ry,
  369. point.x + numbers[ j + 0 ],
  370. point.y + numbers[ j + 1 ]
  371. );
  372. control.x = rx;
  373. control.y = ry;
  374. point.x = point.x + numbers[ j + 0 ];
  375. point.y = point.y + numbers[ j + 1 ];
  376. if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
  377. }
  378. break;
  379. case 'a':
  380. var numbers = parseFloats( data );
  381. for ( var j = 0, jl = numbers.length; j < jl; j += 7 ) {
  382. // skip command if no displacement
  383. if ( numbers[ j + 5 ] == 0 && numbers[ j + 6 ] == 0 ) continue;
  384. var start = point.clone();
  385. point.x += numbers[ j + 5 ];
  386. point.y += numbers[ j + 6 ];
  387. control.x = point.x;
  388. control.y = point.y;
  389. parseArcCommand(
  390. path, numbers[ j ], numbers[ j + 1 ], numbers[ j + 2 ], numbers[ j + 3 ], numbers[ j + 4 ], start, point
  391. );
  392. if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
  393. }
  394. break;
  395. case 'Z':
  396. case 'z':
  397. path.currentPath.autoClose = true;
  398. if ( path.currentPath.curves.length > 0 ) {
  399. // Reset point to beginning of Path
  400. point.copy( firstPoint );
  401. path.currentPath.currentPoint.copy( point );
  402. isFirstPoint = true;
  403. }
  404. break;
  405. default:
  406. console.warn( command );
  407. }
  408. // console.log( type, parseFloats( data ), parseFloats( data ).length )
  409. doSetFirstPoint = false;
  410. }
  411. return path;
  412. }
  413. function parseCSSStylesheet( node ) {
  414. if ( ! node.sheet || ! node.sheet.cssRules || ! node.sheet.cssRules.length ) return;
  415. for ( var i = 0; i < node.sheet.cssRules.length; i ++ ) {
  416. var stylesheet = node.sheet.cssRules[ i ];
  417. if ( stylesheet.type !== 1 ) continue;
  418. var selectorList = stylesheet.selectorText
  419. .split( /,/gm )
  420. .filter( Boolean )
  421. .map( i => i.trim() );
  422. for ( var j = 0; j < selectorList.length; j ++ ) {
  423. stylesheets[ selectorList[ j ] ] = Object.assign(
  424. stylesheets[ selectorList[ j ] ] || {},
  425. stylesheet.style
  426. );
  427. }
  428. }
  429. }
  430. /**
  431. * https://www.w3.org/TR/SVG/implnote.html#ArcImplementationNotes
  432. * https://mortoray.com/2017/02/16/rendering-an-svg-elliptical-arc-as-bezier-curves/ Appendix: Endpoint to center arc conversion
  433. * From
  434. * rx ry x-axis-rotation large-arc-flag sweep-flag x y
  435. * To
  436. * aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation
  437. */
  438. function parseArcCommand( path, rx, ry, x_axis_rotation, large_arc_flag, sweep_flag, start, end ) {
  439. if ( rx == 0 || ry == 0 ) {
  440. // draw a line if either of the radii == 0
  441. path.lineTo( end.x, end.y );
  442. return;
  443. }
  444. x_axis_rotation = x_axis_rotation * Math.PI / 180;
  445. // Ensure radii are positive
  446. rx = Math.abs( rx );
  447. ry = Math.abs( ry );
  448. // Compute (x1', y1')
  449. var dx2 = ( start.x - end.x ) / 2.0;
  450. var dy2 = ( start.y - end.y ) / 2.0;
  451. var x1p = Math.cos( x_axis_rotation ) * dx2 + Math.sin( x_axis_rotation ) * dy2;
  452. var y1p = - Math.sin( x_axis_rotation ) * dx2 + Math.cos( x_axis_rotation ) * dy2;
  453. // Compute (cx', cy')
  454. var rxs = rx * rx;
  455. var rys = ry * ry;
  456. var x1ps = x1p * x1p;
  457. var y1ps = y1p * y1p;
  458. // Ensure radii are large enough
  459. var cr = x1ps / rxs + y1ps / rys;
  460. if ( cr > 1 ) {
  461. // scale up rx,ry equally so cr == 1
  462. var s = Math.sqrt( cr );
  463. rx = s * rx;
  464. ry = s * ry;
  465. rxs = rx * rx;
  466. rys = ry * ry;
  467. }
  468. var dq = ( rxs * y1ps + rys * x1ps );
  469. var pq = ( rxs * rys - dq ) / dq;
  470. var q = Math.sqrt( Math.max( 0, pq ) );
  471. if ( large_arc_flag === sweep_flag ) q = - q;
  472. var cxp = q * rx * y1p / ry;
  473. var cyp = - q * ry * x1p / rx;
  474. // Step 3: Compute (cx, cy) from (cx', cy')
  475. var cx = Math.cos( x_axis_rotation ) * cxp - Math.sin( x_axis_rotation ) * cyp + ( start.x + end.x ) / 2;
  476. var cy = Math.sin( x_axis_rotation ) * cxp + Math.cos( x_axis_rotation ) * cyp + ( start.y + end.y ) / 2;
  477. // Step 4: Compute θ1 and Δθ
  478. var theta = svgAngle( 1, 0, ( x1p - cxp ) / rx, ( y1p - cyp ) / ry );
  479. var delta = svgAngle( ( x1p - cxp ) / rx, ( y1p - cyp ) / ry, ( - x1p - cxp ) / rx, ( - y1p - cyp ) / ry ) % ( Math.PI * 2 );
  480. path.currentPath.absellipse( cx, cy, rx, ry, theta, theta + delta, sweep_flag === 0, x_axis_rotation );
  481. }
  482. function svgAngle( ux, uy, vx, vy ) {
  483. var dot = ux * vx + uy * vy;
  484. var len = Math.sqrt( ux * ux + uy * uy ) * Math.sqrt( vx * vx + vy * vy );
  485. var ang = Math.acos( Math.max( - 1, Math.min( 1, dot / len ) ) ); // floating point precision, slightly over values appear
  486. if ( ( ux * vy - uy * vx ) < 0 ) ang = - ang;
  487. return ang;
  488. }
  489. /*
  490. * According to https://www.w3.org/TR/SVG/shapes.html#RectElementRXAttribute
  491. * rounded corner should be rendered to elliptical arc, but bezier curve does the job well enough
  492. */
  493. function parseRectNode( node ) {
  494. var x = parseFloatWithUnits( node.getAttribute( 'x' ) || 0 );
  495. var y = parseFloatWithUnits( node.getAttribute( 'y' ) || 0 );
  496. var rx = parseFloatWithUnits( node.getAttribute( 'rx' ) || 0 );
  497. var ry = parseFloatWithUnits( node.getAttribute( 'ry' ) || 0 );
  498. var w = parseFloatWithUnits( node.getAttribute( 'width' ) );
  499. var h = parseFloatWithUnits( node.getAttribute( 'height' ) );
  500. var path = new THREE.ShapePath();
  501. path.moveTo( x + 2 * rx, y );
  502. path.lineTo( x + w - 2 * rx, y );
  503. if ( rx !== 0 || ry !== 0 ) path.bezierCurveTo( x + w, y, x + w, y, x + w, y + 2 * ry );
  504. path.lineTo( x + w, y + h - 2 * ry );
  505. if ( rx !== 0 || ry !== 0 ) path.bezierCurveTo( x + w, y + h, x + w, y + h, x + w - 2 * rx, y + h );
  506. path.lineTo( x + 2 * rx, y + h );
  507. if ( rx !== 0 || ry !== 0 ) {
  508. path.bezierCurveTo( x, y + h, x, y + h, x, y + h - 2 * ry );
  509. }
  510. path.lineTo( x, y + 2 * ry );
  511. if ( rx !== 0 || ry !== 0 ) {
  512. path.bezierCurveTo( x, y, x, y, x + 2 * rx, y );
  513. }
  514. return path;
  515. }
  516. function parsePolygonNode( node ) {
  517. function iterator( match, a, b ) {
  518. var x = parseFloatWithUnits( a );
  519. var y = parseFloatWithUnits( b );
  520. if ( index === 0 ) {
  521. path.moveTo( x, y );
  522. } else {
  523. path.lineTo( x, y );
  524. }
  525. index ++;
  526. }
  527. var regex = /(-?[\d\.?]+)[,|\s](-?[\d\.?]+)/g;
  528. var path = new THREE.ShapePath();
  529. var index = 0;
  530. node.getAttribute( 'points' ).replace( regex, iterator );
  531. path.currentPath.autoClose = true;
  532. return path;
  533. }
  534. function parsePolylineNode( node ) {
  535. function iterator( match, a, b ) {
  536. var x = parseFloatWithUnits( a );
  537. var y = parseFloatWithUnits( b );
  538. if ( index === 0 ) {
  539. path.moveTo( x, y );
  540. } else {
  541. path.lineTo( x, y );
  542. }
  543. index ++;
  544. }
  545. var regex = /(-?[\d\.?]+)[,|\s](-?[\d\.?]+)/g;
  546. var path = new THREE.ShapePath();
  547. var index = 0;
  548. node.getAttribute( 'points' ).replace( regex, iterator );
  549. path.currentPath.autoClose = false;
  550. return path;
  551. }
  552. function parseCircleNode( node ) {
  553. var x = parseFloatWithUnits( node.getAttribute( 'cx' ) || 0 );
  554. var y = parseFloatWithUnits( node.getAttribute( 'cy' ) || 0 );
  555. var r = parseFloatWithUnits( node.getAttribute( 'r' ) || 0 );
  556. var subpath = new THREE.Path();
  557. subpath.absarc( x, y, r, 0, Math.PI * 2 );
  558. var path = new THREE.ShapePath();
  559. path.subPaths.push( subpath );
  560. return path;
  561. }
  562. function parseEllipseNode( node ) {
  563. var x = parseFloatWithUnits( node.getAttribute( 'cx' ) || 0 );
  564. var y = parseFloatWithUnits( node.getAttribute( 'cy' ) || 0 );
  565. var rx = parseFloatWithUnits( node.getAttribute( 'rx' ) || 0 );
  566. var ry = parseFloatWithUnits( node.getAttribute( 'ry' ) || 0 );
  567. var subpath = new THREE.Path();
  568. subpath.absellipse( x, y, rx, ry, 0, Math.PI * 2 );
  569. var path = new THREE.ShapePath();
  570. path.subPaths.push( subpath );
  571. return path;
  572. }
  573. function parseLineNode( node ) {
  574. var x1 = parseFloatWithUnits( node.getAttribute( 'x1' ) || 0 );
  575. var y1 = parseFloatWithUnits( node.getAttribute( 'y1' ) || 0 );
  576. var x2 = parseFloatWithUnits( node.getAttribute( 'x2' ) || 0 );
  577. var y2 = parseFloatWithUnits( node.getAttribute( 'y2' ) || 0 );
  578. var path = new THREE.ShapePath();
  579. path.moveTo( x1, y1 );
  580. path.lineTo( x2, y2 );
  581. path.currentPath.autoClose = false;
  582. return path;
  583. }
  584. //
  585. function parseStyle( node, style ) {
  586. style = Object.assign( {}, style ); // clone style
  587. var stylesheetStyles = {};
  588. if ( node.hasAttribute( 'class' ) ) {
  589. var classSelectors = node.getAttribute( 'class' )
  590. .split( /\s/ )
  591. .filter( Boolean )
  592. .map( i => i.trim() );
  593. for ( var i = 0; i < classSelectors.length; i ++ ) {
  594. stylesheetStyles = Object.assign( stylesheetStyles, stylesheets[ '.' + classSelectors[ i ] ] );
  595. }
  596. }
  597. if ( node.hasAttribute( 'id' ) ) {
  598. stylesheetStyles = Object.assign( stylesheetStyles, stylesheets[ '#' + node.getAttribute( 'id' ) ] );
  599. }
  600. function addStyle( svgName, jsName, adjustFunction ) {
  601. if ( adjustFunction === undefined ) adjustFunction = function copy( v ) {
  602. if ( v.startsWith( 'url' ) ) console.warn( 'SVGLoader: url access in attributes is not implemented.' );
  603. return v;
  604. };
  605. if ( node.hasAttribute( svgName ) ) style[ jsName ] = adjustFunction( node.getAttribute( svgName ) );
  606. if ( stylesheetStyles[ svgName ] ) style[ jsName ] = adjustFunction( stylesheetStyles[ svgName ] );
  607. if ( node.style && node.style[ svgName ] !== '' ) style[ jsName ] = adjustFunction( node.style[ svgName ] );
  608. }
  609. function clamp( v ) {
  610. return Math.max( 0, Math.min( 1, parseFloatWithUnits( v ) ) );
  611. }
  612. function positive( v ) {
  613. return Math.max( 0, parseFloatWithUnits( v ) );
  614. }
  615. addStyle( 'fill', 'fill' );
  616. addStyle( 'fill-opacity', 'fillOpacity', clamp );
  617. addStyle( 'opacity', 'opacity', clamp );
  618. addStyle( 'stroke', 'stroke' );
  619. addStyle( 'stroke-opacity', 'strokeOpacity', clamp );
  620. addStyle( 'stroke-width', 'strokeWidth', positive );
  621. addStyle( 'stroke-linejoin', 'strokeLineJoin' );
  622. addStyle( 'stroke-linecap', 'strokeLineCap' );
  623. addStyle( 'stroke-miterlimit', 'strokeMiterLimit', positive );
  624. addStyle( 'visibility', 'visibility' );
  625. return style;
  626. }
  627. // http://www.w3.org/TR/SVG11/implnote.html#PathElementImplementationNotes
  628. function getReflection( a, b ) {
  629. return a - ( b - a );
  630. }
  631. // from https://github.com/ppvg/svg-numbers (MIT License)
  632. function parseFloats( input ) {
  633. if ( typeof input !== 'string' ) {
  634. throw new TypeError( 'Invalid input: ' + typeof input );
  635. }
  636. // Character groups
  637. var RE = {
  638. SEPARATOR: /[ \t\r\n\,.\-+]/,
  639. WHITESPACE: /[ \t\r\n]/,
  640. DIGIT: /[\d]/,
  641. SIGN: /[-+]/,
  642. POINT: /\./,
  643. COMMA: /,/,
  644. EXP: /e/i
  645. };
  646. // States
  647. var SEP = 0;
  648. var INT = 1;
  649. var FLOAT = 2;
  650. var EXP = 3;
  651. var state = SEP;
  652. var seenComma = true;
  653. var result = [], number = '', exponent = '';
  654. function throwSyntaxError( current, i, partial ) {
  655. var error = new SyntaxError( 'Unexpected character "' + current + '" at index ' + i + '.' );
  656. error.partial = partial;
  657. throw error;
  658. }
  659. function newNumber() {
  660. if ( number !== '' ) {
  661. if ( exponent === '' ) result.push( Number( number ) );
  662. else result.push( Number( number ) * Math.pow( 10, Number( exponent ) ) );
  663. }
  664. number = '';
  665. exponent = '';
  666. }
  667. var current, i = 0, length = input.length;
  668. for ( i = 0; i < length; i ++ ) {
  669. current = input[ i ];
  670. // parse until next number
  671. if ( state === SEP ) {
  672. // eat whitespace
  673. if ( RE.WHITESPACE.test( current ) ) {
  674. continue;
  675. }
  676. // start new number
  677. if ( RE.DIGIT.test( current ) || RE.SIGN.test( current ) ) {
  678. state = INT;
  679. number = current;
  680. continue;
  681. }
  682. if ( RE.POINT.test( current ) ) {
  683. state = FLOAT;
  684. number = current;
  685. continue;
  686. }
  687. // throw on double commas (e.g. "1, , 2")
  688. if ( RE.COMMA.test( current ) ) {
  689. if ( seenComma ) {
  690. throwSyntaxError( current, i, result );
  691. }
  692. seenComma = true;
  693. }
  694. }
  695. // parse integer part
  696. if ( state === INT ) {
  697. if ( RE.DIGIT.test( current ) ) {
  698. number += current;
  699. continue;
  700. }
  701. if ( RE.POINT.test( current ) ) {
  702. number += current;
  703. state = FLOAT;
  704. continue;
  705. }
  706. if ( RE.EXP.test( current ) ) {
  707. state = EXP;
  708. continue;
  709. }
  710. // throw on double signs ("-+1"), but not on sign as separator ("-1-2")
  711. if ( RE.SIGN.test( current )
  712. && number.length === 1
  713. && RE.SIGN.test( number[ 0 ] ) ) {
  714. throwSyntaxError( current, i, result );
  715. }
  716. }
  717. // parse decimal part
  718. if ( state === FLOAT ) {
  719. if ( RE.DIGIT.test( current ) ) {
  720. number += current;
  721. continue;
  722. }
  723. if ( RE.EXP.test( current ) ) {
  724. state = EXP;
  725. continue;
  726. }
  727. // throw on double decimal points (e.g. "1..2")
  728. if ( RE.POINT.test( current ) && number[ number.length - 1 ] === '.' ) {
  729. throwSyntaxError( current, i, result );
  730. }
  731. }
  732. // parse exponent part
  733. if ( state == EXP ) {
  734. if ( RE.DIGIT.test( current ) ) {
  735. exponent += current;
  736. continue;
  737. }
  738. if ( RE.SIGN.test( current ) ) {
  739. if ( exponent === '' ) {
  740. exponent += current;
  741. continue;
  742. }
  743. if ( exponent.length === 1 && RE.SIGN.test( exponent ) ) {
  744. throwSyntaxError( current, i, result );
  745. }
  746. }
  747. }
  748. // end of number
  749. if ( RE.WHITESPACE.test( current ) ) {
  750. newNumber();
  751. state = SEP;
  752. seenComma = false;
  753. } else if ( RE.COMMA.test( current ) ) {
  754. newNumber();
  755. state = SEP;
  756. seenComma = true;
  757. } else if ( RE.SIGN.test( current ) ) {
  758. newNumber();
  759. state = INT;
  760. number = current;
  761. } else if ( RE.POINT.test( current ) ) {
  762. newNumber();
  763. state = FLOAT;
  764. number = current;
  765. } else {
  766. throwSyntaxError( current, i, result );
  767. }
  768. }
  769. // add the last number found (if any)
  770. newNumber();
  771. return result;
  772. }
  773. // Units
  774. var units = [ 'mm', 'cm', 'in', 'pt', 'pc', 'px' ];
  775. // Conversion: [ fromUnit ][ toUnit ] (-1 means dpi dependent)
  776. var unitConversion = {
  777. 'mm': {
  778. 'mm': 1,
  779. 'cm': 0.1,
  780. 'in': 1 / 25.4,
  781. 'pt': 72 / 25.4,
  782. 'pc': 6 / 25.4,
  783. 'px': - 1
  784. },
  785. 'cm': {
  786. 'mm': 10,
  787. 'cm': 1,
  788. 'in': 1 / 2.54,
  789. 'pt': 72 / 2.54,
  790. 'pc': 6 / 2.54,
  791. 'px': - 1
  792. },
  793. 'in': {
  794. 'mm': 25.4,
  795. 'cm': 2.54,
  796. 'in': 1,
  797. 'pt': 72,
  798. 'pc': 6,
  799. 'px': - 1
  800. },
  801. 'pt': {
  802. 'mm': 25.4 / 72,
  803. 'cm': 2.54 / 72,
  804. 'in': 1 / 72,
  805. 'pt': 1,
  806. 'pc': 6 / 72,
  807. 'px': - 1
  808. },
  809. 'pc': {
  810. 'mm': 25.4 / 6,
  811. 'cm': 2.54 / 6,
  812. 'in': 1 / 6,
  813. 'pt': 72 / 6,
  814. 'pc': 1,
  815. 'px': - 1
  816. },
  817. 'px': {
  818. 'px': 1
  819. }
  820. };
  821. function parseFloatWithUnits( string ) {
  822. var theUnit = 'px';
  823. if ( typeof string === 'string' || string instanceof String ) {
  824. for ( var i = 0, n = units.length; i < n; i ++ ) {
  825. var u = units[ i ];
  826. if ( string.endsWith( u ) ) {
  827. theUnit = u;
  828. string = string.substring( 0, string.length - u.length );
  829. break;
  830. }
  831. }
  832. }
  833. var scale = undefined;
  834. if ( theUnit === 'px' && scope.defaultUnit !== 'px' ) {
  835. // Conversion scale from pixels to inches, then to default units
  836. scale = unitConversion[ 'in' ][ scope.defaultUnit ] / scope.defaultDPI;
  837. } else {
  838. scale = unitConversion[ theUnit ][ scope.defaultUnit ];
  839. if ( scale < 0 ) {
  840. // Conversion scale to pixels
  841. scale = unitConversion[ theUnit ][ 'in' ] * scope.defaultDPI;
  842. }
  843. }
  844. return scale * parseFloat( string );
  845. }
  846. // Transforms
  847. function getNodeTransform( node ) {
  848. if ( ! ( node.hasAttribute( 'transform' ) || ( node.nodeName === 'use' && ( node.hasAttribute( 'x' ) || node.hasAttribute( 'y' ) ) ) ) ) {
  849. return null;
  850. }
  851. var transform = parseNodeTransform( node );
  852. if ( transformStack.length > 0 ) {
  853. transform.premultiply( transformStack[ transformStack.length - 1 ] );
  854. }
  855. currentTransform.copy( transform );
  856. transformStack.push( transform );
  857. return transform;
  858. }
  859. function parseNodeTransform( node ) {
  860. var transform = new THREE.Matrix3();
  861. var currentTransform = tempTransform0;
  862. if ( node.nodeName === 'use' && ( node.hasAttribute( 'x' ) || node.hasAttribute( 'y' ) ) ) {
  863. var tx = parseFloatWithUnits( node.getAttribute( 'x' ) );
  864. var ty = parseFloatWithUnits( node.getAttribute( 'y' ) );
  865. transform.translate( tx, ty );
  866. }
  867. if ( node.hasAttribute( 'transform' ) ) {
  868. var transformsTexts = node.getAttribute( 'transform' ).split( ')' );
  869. for ( var tIndex = transformsTexts.length - 1; tIndex >= 0; tIndex -- ) {
  870. var transformText = transformsTexts[ tIndex ].trim();
  871. if ( transformText === '' ) continue;
  872. var openParPos = transformText.indexOf( '(' );
  873. var closeParPos = transformText.length;
  874. if ( openParPos > 0 && openParPos < closeParPos ) {
  875. var transformType = transformText.substr( 0, openParPos );
  876. var array = parseFloats( transformText.substr( openParPos + 1, closeParPos - openParPos - 1 ) );
  877. currentTransform.identity();
  878. switch ( transformType ) {
  879. case 'translate':
  880. if ( array.length >= 1 ) {
  881. var tx = array[ 0 ];
  882. var ty = tx;
  883. if ( array.length >= 2 ) {
  884. ty = array[ 1 ];
  885. }
  886. currentTransform.translate( tx, ty );
  887. }
  888. break;
  889. case 'rotate':
  890. if ( array.length >= 1 ) {
  891. var angle = 0;
  892. var cx = 0;
  893. var cy = 0;
  894. // Angle
  895. angle = - array[ 0 ] * Math.PI / 180;
  896. if ( array.length >= 3 ) {
  897. // Center x, y
  898. cx = array[ 1 ];
  899. cy = array[ 2 ];
  900. }
  901. // Rotate around center (cx, cy)
  902. tempTransform1.identity().translate( - cx, - cy );
  903. tempTransform2.identity().rotate( angle );
  904. tempTransform3.multiplyMatrices( tempTransform2, tempTransform1 );
  905. tempTransform1.identity().translate( cx, cy );
  906. currentTransform.multiplyMatrices( tempTransform1, tempTransform3 );
  907. }
  908. break;
  909. case 'scale':
  910. if ( array.length >= 1 ) {
  911. var scaleX = array[ 0 ];
  912. var scaleY = scaleX;
  913. if ( array.length >= 2 ) {
  914. scaleY = array[ 1 ];
  915. }
  916. currentTransform.scale( scaleX, scaleY );
  917. }
  918. break;
  919. case 'skewX':
  920. if ( array.length === 1 ) {
  921. currentTransform.set(
  922. 1, Math.tan( array[ 0 ] * Math.PI / 180 ), 0,
  923. 0, 1, 0,
  924. 0, 0, 1
  925. );
  926. }
  927. break;
  928. case 'skewY':
  929. if ( array.length === 1 ) {
  930. currentTransform.set(
  931. 1, 0, 0,
  932. Math.tan( array[ 0 ] * Math.PI / 180 ), 1, 0,
  933. 0, 0, 1
  934. );
  935. }
  936. break;
  937. case 'matrix':
  938. if ( array.length === 6 ) {
  939. currentTransform.set(
  940. array[ 0 ], array[ 2 ], array[ 4 ],
  941. array[ 1 ], array[ 3 ], array[ 5 ],
  942. 0, 0, 1
  943. );
  944. }
  945. break;
  946. }
  947. }
  948. transform.premultiply( currentTransform );
  949. }
  950. }
  951. return transform;
  952. }
  953. function transformPath( path, m ) {
  954. function transfVec2( v2 ) {
  955. tempV3.set( v2.x, v2.y, 1 ).applyMatrix3( m );
  956. v2.set( tempV3.x, tempV3.y );
  957. }
  958. var isRotated = isTransformRotated( m );
  959. var subPaths = path.subPaths;
  960. for ( var i = 0, n = subPaths.length; i < n; i ++ ) {
  961. var subPath = subPaths[ i ];
  962. var curves = subPath.curves;
  963. for ( var j = 0; j < curves.length; j ++ ) {
  964. var curve = curves[ j ];
  965. if ( curve.isLineCurve ) {
  966. transfVec2( curve.v1 );
  967. transfVec2( curve.v2 );
  968. } else if ( curve.isCubicBezierCurve ) {
  969. transfVec2( curve.v0 );
  970. transfVec2( curve.v1 );
  971. transfVec2( curve.v2 );
  972. transfVec2( curve.v3 );
  973. } else if ( curve.isQuadraticBezierCurve ) {
  974. transfVec2( curve.v0 );
  975. transfVec2( curve.v1 );
  976. transfVec2( curve.v2 );
  977. } else if ( curve.isEllipseCurve ) {
  978. if ( isRotated ) {
  979. console.warn( 'SVGLoader: Elliptic arc or ellipse rotation or skewing is not implemented.' );
  980. }
  981. tempV2.set( curve.aX, curve.aY );
  982. transfVec2( tempV2 );
  983. curve.aX = tempV2.x;
  984. curve.aY = tempV2.y;
  985. curve.xRadius *= getTransformScaleX( m );
  986. curve.yRadius *= getTransformScaleY( m );
  987. }
  988. }
  989. }
  990. }
  991. function isTransformRotated( m ) {
  992. return m.elements[ 1 ] !== 0 || m.elements[ 3 ] !== 0;
  993. }
  994. function getTransformScaleX( m ) {
  995. var te = m.elements;
  996. return Math.sqrt( te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] );
  997. }
  998. function getTransformScaleY( m ) {
  999. var te = m.elements;
  1000. return Math.sqrt( te[ 3 ] * te[ 3 ] + te[ 4 ] * te[ 4 ] );
  1001. }
  1002. //
  1003. var paths = [];
  1004. var stylesheets = {};
  1005. var transformStack = [];
  1006. var tempTransform0 = new THREE.Matrix3();
  1007. var tempTransform1 = new THREE.Matrix3();
  1008. var tempTransform2 = new THREE.Matrix3();
  1009. var tempTransform3 = new THREE.Matrix3();
  1010. var tempV2 = new THREE.Vector2();
  1011. var tempV3 = new THREE.Vector3();
  1012. var currentTransform = new THREE.Matrix3();
  1013. var xml = new DOMParser().parseFromString( text, 'image/svg+xml' ); // application/xml
  1014. parseNode( xml.documentElement, {
  1015. fill: '#000',
  1016. fillOpacity: 1,
  1017. strokeOpacity: 1,
  1018. strokeWidth: 1,
  1019. strokeLineJoin: 'miter',
  1020. strokeLineCap: 'butt',
  1021. strokeMiterLimit: 4
  1022. } );
  1023. var data = { paths: paths, xml: xml.documentElement };
  1024. // console.log( paths );
  1025. return data;
  1026. }
  1027. } );
  1028. THREE.SVGLoader.createShapes = function ( shapePath ) {
  1029. // Param shapePath: a shapepath as returned by the parse function of this class
  1030. // Returns Shape object
  1031. const BIGNUMBER = 999999999;
  1032. const IntersectionLocationType = {
  1033. ORIGIN: 0,
  1034. DESTINATION: 1,
  1035. BETWEEN: 2,
  1036. LEFT: 3,
  1037. RIGHT: 4,
  1038. BEHIND: 5,
  1039. BEYOND: 6
  1040. };
  1041. const classifyResult = {
  1042. loc: IntersectionLocationType.ORIGIN,
  1043. t: 0
  1044. };
  1045. function findEdgeIntersection( a0, a1, b0, b1 ) {
  1046. var x1 = a0.x;
  1047. var x2 = a1.x;
  1048. var x3 = b0.x;
  1049. var x4 = b1.x;
  1050. var y1 = a0.y;
  1051. var y2 = a1.y;
  1052. var y3 = b0.y;
  1053. var y4 = b1.y;
  1054. var nom1 = ( x4 - x3 ) * ( y1 - y3 ) - ( y4 - y3 ) * ( x1 - x3 );
  1055. var nom2 = ( x2 - x1 ) * ( y1 - y3 ) - ( y2 - y1 ) * ( x1 - x3 );
  1056. var denom = ( y4 - y3 ) * ( x2 - x1 ) - ( x4 - x3 ) * ( y2 - y1 );
  1057. var t1 = nom1 / denom;
  1058. var t2 = nom2 / denom;
  1059. if ( ( ( denom === 0 ) && ( nom1 !== 0 ) ) || ( t1 <= 0 ) || ( t1 >= 1 ) || ( t2 < 0 ) || ( t2 > 1 ) ) {
  1060. //1. lines are parallel or edges don't intersect
  1061. return null;
  1062. } else if ( ( nom1 === 0 ) && ( denom === 0 ) ) {
  1063. //2. lines are colinear
  1064. //check if endpoints of edge2 (b0-b1) lies on edge1 (a0-a1)
  1065. for ( var i = 0; i < 2; i ++ ) {
  1066. classifyPoint( i === 0 ? b0 : b1, a0, a1 );
  1067. //find position of this endpoints relatively to edge1
  1068. if ( classifyResult.loc == IntersectionLocationType.ORIGIN ) {
  1069. var point = ( i === 0 ? b0 : b1 );
  1070. return { x: point.x, y: point.y, t: classifyResult.t };
  1071. } else if ( classifyResult.loc == IntersectionLocationType.BETWEEN ) {
  1072. var x = + ( ( x1 + classifyResult.t * ( x2 - x1 ) ).toPrecision( 10 ) );
  1073. var y = + ( ( y1 + classifyResult.t * ( y2 - y1 ) ).toPrecision( 10 ) );
  1074. return { x: x, y: y, t: classifyResult.t, };
  1075. }
  1076. }
  1077. return null;
  1078. } else {
  1079. //3. edges intersect
  1080. for ( var i = 0; i < 2; i ++ ) {
  1081. classifyPoint( i === 0 ? b0 : b1, a0, a1 );
  1082. if ( classifyResult.loc == IntersectionLocationType.ORIGIN ) {
  1083. var point = ( i === 0 ? b0 : b1 );
  1084. return { x: point.x, y: point.y, t: classifyResult.t };
  1085. }
  1086. }
  1087. var x = + ( ( x1 + t1 * ( x2 - x1 ) ).toPrecision( 10 ) );
  1088. var y = + ( ( y1 + t1 * ( y2 - y1 ) ).toPrecision( 10 ) );
  1089. return { x: x, y: y, t: t1 };
  1090. }
  1091. }
  1092. function classifyPoint( p, edgeStart, edgeEnd ) {
  1093. var ax = edgeEnd.x - edgeStart.x;
  1094. var ay = edgeEnd.y - edgeStart.y;
  1095. var bx = p.x - edgeStart.x;
  1096. var by = p.y - edgeStart.y;
  1097. var sa = ax * by - bx * ay;
  1098. if ( ( p.x === edgeStart.x ) && ( p.y === edgeStart.y ) ) {
  1099. classifyResult.loc = IntersectionLocationType.ORIGIN;
  1100. classifyResult.t = 0;
  1101. return;
  1102. }
  1103. if ( ( p.x === edgeEnd.x ) && ( p.y === edgeEnd.y ) ) {
  1104. classifyResult.loc = IntersectionLocationType.DESTINATION;
  1105. classifyResult.t = 1;
  1106. return;
  1107. }
  1108. if ( sa < - Number.EPSILON ) {
  1109. classifyResult.loc = IntersectionLocationType.LEFT;
  1110. return;
  1111. }
  1112. if ( sa > Number.EPSILON ) {
  1113. classifyResult.loc = IntersectionLocationType.RIGHT;
  1114. return;
  1115. }
  1116. if ( ( ( ax * bx ) < 0 ) || ( ( ay * by ) < 0 ) ) {
  1117. classifyResult.loc = IntersectionLocationType.BEHIND;
  1118. return;
  1119. }
  1120. if ( ( Math.sqrt( ax * ax + ay * ay ) ) < ( Math.sqrt( bx * bx + by * by ) ) ) {
  1121. classifyResult.loc = IntersectionLocationType.BEYOND;
  1122. return;
  1123. }
  1124. var t;
  1125. if ( ax !== 0 ) {
  1126. t = bx / ax;
  1127. } else {
  1128. t = by / ay;
  1129. }
  1130. classifyResult.loc = IntersectionLocationType.BETWEEN;
  1131. classifyResult.t = t;
  1132. }
  1133. function getIntersections( path1, path2 ) {
  1134. const intersectionsRaw = [];
  1135. const intersections = [];
  1136. for ( let index = 1; index < path1.length; index ++ ) {
  1137. const path1EdgeStart = path1[ index - 1 ];
  1138. const path1EdgeEnd = path1[ index ];
  1139. for ( let index2 = 1; index2 < path2.length; index2 ++ ) {
  1140. const path2EdgeStart = path2[ index2 - 1 ];
  1141. const path2EdgeEnd = path2[ index2 ];
  1142. const intersection = findEdgeIntersection( path1EdgeStart, path1EdgeEnd, path2EdgeStart, path2EdgeEnd );
  1143. if ( intersection !== null && intersectionsRaw.find( i => i.t <= intersection.t + Number.EPSILON && i.t >= intersection.t - Number.EPSILON ) === undefined ) {
  1144. intersectionsRaw.push( intersection );
  1145. intersections.push( new THREE.Vector2( intersection.x, intersection.y ) );
  1146. }
  1147. }
  1148. }
  1149. return intersections;
  1150. }
  1151. function getScanlineIntersections( scanline, boundingBox, paths ) {
  1152. const center = new THREE.Vector2();
  1153. boundingBox.getCenter( center );
  1154. const allIntersections = [];
  1155. paths.forEach( path => {
  1156. // check if the center of the bounding box is in the bounding box of the paths.
  1157. // this is a pruning method to limit the search of intersections in paths that can't envelop of the current path.
  1158. // if a path envelops another path. The center of that oter path, has to be inside the bounding box of the enveloping path.
  1159. if ( path.boundingBox.containsPoint( center ) ) {
  1160. const intersections = getIntersections( scanline, path.points );
  1161. intersections.forEach( p => {
  1162. allIntersections.push( { identifier: path.identifier, isCW: path.isCW, point: p } );
  1163. } );
  1164. }
  1165. } );
  1166. allIntersections.sort( ( i1, i2 ) => {
  1167. return i1.point.x - i2.point.x;
  1168. } );
  1169. return allIntersections;
  1170. }
  1171. function isHoleTo( simplePath, allPaths, scanlineMinX, scanlineMaxX, _fillRule ) {
  1172. if ( _fillRule === null || _fillRule === undefined || _fillRule === '' ) {
  1173. _fillRule = 'nonzero';
  1174. }
  1175. const centerBoundingBox = new THREE.Vector2();
  1176. simplePath.boundingBox.getCenter( centerBoundingBox );
  1177. const scanline = [ new THREE.Vector2( scanlineMinX, centerBoundingBox.y ), new THREE.Vector2( scanlineMaxX, centerBoundingBox.y ) ];
  1178. const scanlineIntersections = getScanlineIntersections( scanline, simplePath.boundingBox, allPaths );
  1179. scanlineIntersections.sort( ( i1, i2 ) => {
  1180. return i1.point.x - i2.point.x;
  1181. } );
  1182. const baseIntersections = [];
  1183. const otherIntersections = [];
  1184. scanlineIntersections.forEach( i => {
  1185. if ( i.identifier === simplePath.identifier ) {
  1186. baseIntersections.push( i );
  1187. } else {
  1188. otherIntersections.push( i );
  1189. }
  1190. } );
  1191. const firstXOfPath = baseIntersections[ 0 ].point.x;
  1192. // build up the path hierarchy
  1193. const stack = [];
  1194. let i = 0;
  1195. while ( i < otherIntersections.length && otherIntersections[ i ].point.x < firstXOfPath ) {
  1196. if ( stack.length > 0 && stack[ stack.length - 1 ] === otherIntersections[ i ].identifier ) {
  1197. stack.pop();
  1198. } else {
  1199. stack.push( otherIntersections[ i ].identifier );
  1200. }
  1201. i ++;
  1202. }
  1203. stack.push( simplePath.identifier );
  1204. if ( _fillRule === 'evenodd' ) {
  1205. const isHole = stack.length % 2 === 0 ? true : false;
  1206. const isHoleFor = stack[ stack.length - 2 ];
  1207. return { identifier: simplePath.identifier, isHole: isHole, for: isHoleFor };
  1208. } else if ( _fillRule === 'nonzero' ) {
  1209. // check if path is a hole by counting the amount of paths with alternating rotations it has to cross.
  1210. let isHole = true;
  1211. let isHoleFor = null;
  1212. let lastCWValue = null;
  1213. for ( let i = 0; i < stack.length; i ++ ) {
  1214. const identifier = stack[ i ];
  1215. if ( isHole ) {
  1216. lastCWValue = allPaths[ identifier ].isCW;
  1217. isHole = false;
  1218. isHoleFor = identifier;
  1219. } else if ( lastCWValue !== allPaths[ identifier ].isCW ) {
  1220. lastCWValue = allPaths[ identifier ].isCW;
  1221. isHole = true;
  1222. }
  1223. }
  1224. return { identifier: simplePath.identifier, isHole: isHole, for: isHoleFor };
  1225. } else {
  1226. console.warn( 'fill-rule: "' + _fillRule + '" is currently not implemented.' );
  1227. }
  1228. }
  1229. // check for self intersecting paths
  1230. // TODO
  1231. // check intersecting paths
  1232. // TODO
  1233. // prepare paths for hole detection
  1234. let identifier = 0;
  1235. let scanlineMinX = BIGNUMBER;
  1236. let scanlineMaxX = - BIGNUMBER;
  1237. let simplePaths = shapePath.subPaths.map( p => {
  1238. const points = p.getPoints();
  1239. let maxY = - BIGNUMBER;
  1240. let minY = BIGNUMBER;
  1241. let maxX = - BIGNUMBER;
  1242. let minX = BIGNUMBER;
  1243. //points.forEach(p => p.y *= -1);
  1244. for ( let i = 0; i < points.length; i ++ ) {
  1245. const p = points[ i ];
  1246. if ( p.y > maxY ) {
  1247. maxY = p.y;
  1248. }
  1249. if ( p.y < minY ) {
  1250. minY = p.y;
  1251. }
  1252. if ( p.x > maxX ) {
  1253. maxX = p.x;
  1254. }
  1255. if ( p.x < minX ) {
  1256. minX = p.x;
  1257. }
  1258. }
  1259. //
  1260. if ( scanlineMaxX <= maxX ) {
  1261. scanlineMaxX = maxX + 1;
  1262. }
  1263. if ( scanlineMinX >= minX ) {
  1264. scanlineMinX = minX - 1;
  1265. }
  1266. return { points: points, isCW: THREE.ShapeUtils.isClockWise( points ), identifier: identifier ++, boundingBox: new THREE.Box2( new THREE.Vector2( minX, minY ), new THREE.Vector2( maxX, maxY ) ) };
  1267. } );
  1268. simplePaths = simplePaths.filter( sp => sp.points.length > 0 );
  1269. // check if path is solid or a hole
  1270. const isAHole = simplePaths.map( p => isHoleTo( p, simplePaths, scanlineMinX, scanlineMaxX, shapePath.userData.style.fillRule ) );
  1271. const shapesToReturn = [];
  1272. simplePaths.forEach( p => {
  1273. const amIAHole = isAHole[ p.identifier ];
  1274. if ( ! amIAHole.isHole ) {
  1275. const shape = new THREE.Shape( p.points );
  1276. const holes = isAHole.filter( h => h.isHole && h.for === p.identifier );
  1277. holes.forEach( h => {
  1278. const path = simplePaths[ h.identifier ];
  1279. shape.holes.push( new THREE.Path( path.points ) );
  1280. } );
  1281. shapesToReturn.push( shape );
  1282. }
  1283. } );
  1284. return shapesToReturn;
  1285. };
  1286. THREE.SVGLoader.getStrokeStyle = function ( width, color, lineJoin, lineCap, miterLimit ) {
  1287. // Param width: Stroke width
  1288. // Param color: As returned by THREE.Color.getStyle()
  1289. // Param lineJoin: One of "round", "bevel", "miter" or "miter-limit"
  1290. // Param lineCap: One of "round", "square" or "butt"
  1291. // Param miterLimit: Maximum join length, in multiples of the "width" parameter (join is truncated if it exceeds that distance)
  1292. // Returns style object
  1293. width = width !== undefined ? width : 1;
  1294. color = color !== undefined ? color : '#000';
  1295. lineJoin = lineJoin !== undefined ? lineJoin : 'miter';
  1296. lineCap = lineCap !== undefined ? lineCap : 'butt';
  1297. miterLimit = miterLimit !== undefined ? miterLimit : 4;
  1298. return {
  1299. strokeColor: color,
  1300. strokeWidth: width,
  1301. strokeLineJoin: lineJoin,
  1302. strokeLineCap: lineCap,
  1303. strokeMiterLimit: miterLimit
  1304. };
  1305. };
  1306. THREE.SVGLoader.pointsToStroke = function ( points, style, arcDivisions, minDistance ) {
  1307. // Generates a stroke with some witdh around the given path.
  1308. // The path can be open or closed (last point equals to first point)
  1309. // Param points: Array of Vector2D (the path). Minimum 2 points.
  1310. // Param style: Object with SVG properties as returned by SVGLoader.getStrokeStyle(), or SVGLoader.parse() in the path.userData.style object
  1311. // Params arcDivisions: Arc divisions for round joins and endcaps. (Optional)
  1312. // Param minDistance: Points closer to this distance will be merged. (Optional)
  1313. // Returns BufferGeometry with stroke triangles (In plane z = 0). UV coordinates are generated ('u' along path. 'v' across it, from left to right)
  1314. var vertices = [];
  1315. var normals = [];
  1316. var uvs = [];
  1317. if ( THREE.SVGLoader.pointsToStrokeWithBuffers( points, style, arcDivisions, minDistance, vertices, normals, uvs ) === 0 ) {
  1318. return null;
  1319. }
  1320. var geometry = new THREE.BufferGeometry();
  1321. geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( vertices, 3 ) );
  1322. geometry.setAttribute( 'normal', new THREE.Float32BufferAttribute( normals, 3 ) );
  1323. geometry.setAttribute( 'uv', new THREE.Float32BufferAttribute( uvs, 2 ) );
  1324. return geometry;
  1325. };
  1326. THREE.SVGLoader.pointsToStrokeWithBuffers = function () {
  1327. var tempV2_1 = new THREE.Vector2();
  1328. var tempV2_2 = new THREE.Vector2();
  1329. var tempV2_3 = new THREE.Vector2();
  1330. var tempV2_4 = new THREE.Vector2();
  1331. var tempV2_5 = new THREE.Vector2();
  1332. var tempV2_6 = new THREE.Vector2();
  1333. var tempV2_7 = new THREE.Vector2();
  1334. var lastPointL = new THREE.Vector2();
  1335. var lastPointR = new THREE.Vector2();
  1336. var point0L = new THREE.Vector2();
  1337. var point0R = new THREE.Vector2();
  1338. var currentPointL = new THREE.Vector2();
  1339. var currentPointR = new THREE.Vector2();
  1340. var nextPointL = new THREE.Vector2();
  1341. var nextPointR = new THREE.Vector2();
  1342. var innerPoint = new THREE.Vector2();
  1343. var outerPoint = new THREE.Vector2();
  1344. return function ( points, style, arcDivisions, minDistance, vertices, normals, uvs, vertexOffset ) {
  1345. // This function can be called to update existing arrays or buffers.
  1346. // Accepts same parameters as pointsToStroke, plus the buffers and optional offset.
  1347. // Param vertexOffset: Offset vertices to start writing in the buffers (3 elements/vertex for vertices and normals, and 2 elements/vertex for uvs)
  1348. // Returns number of written vertices / normals / uvs pairs
  1349. // if 'vertices' parameter is undefined no triangles will be generated, but the returned vertices count will still be valid (useful to preallocate the buffers)
  1350. // 'normals' and 'uvs' buffers are optional
  1351. arcDivisions = arcDivisions !== undefined ? arcDivisions : 12;
  1352. minDistance = minDistance !== undefined ? minDistance : 0.001;
  1353. vertexOffset = vertexOffset !== undefined ? vertexOffset : 0;
  1354. // First ensure there are no duplicated points
  1355. points = removeDuplicatedPoints( points );
  1356. var numPoints = points.length;
  1357. if ( numPoints < 2 ) return 0;
  1358. var isClosed = points[ 0 ].equals( points[ numPoints - 1 ] );
  1359. var currentPoint;
  1360. var previousPoint = points[ 0 ];
  1361. var nextPoint;
  1362. var strokeWidth2 = style.strokeWidth / 2;
  1363. var deltaU = 1 / ( numPoints - 1 );
  1364. var u0 = 0;
  1365. var innerSideModified;
  1366. var joinIsOnLeftSide;
  1367. var isMiter;
  1368. var initialJoinIsOnLeftSide = false;
  1369. var numVertices = 0;
  1370. var currentCoordinate = vertexOffset * 3;
  1371. var currentCoordinateUV = vertexOffset * 2;
  1372. // Get initial left and right stroke points
  1373. getNormal( points[ 0 ], points[ 1 ], tempV2_1 ).multiplyScalar( strokeWidth2 );
  1374. lastPointL.copy( points[ 0 ] ).sub( tempV2_1 );
  1375. lastPointR.copy( points[ 0 ] ).add( tempV2_1 );
  1376. point0L.copy( lastPointL );
  1377. point0R.copy( lastPointR );
  1378. for ( var iPoint = 1; iPoint < numPoints; iPoint ++ ) {
  1379. currentPoint = points[ iPoint ];
  1380. // Get next point
  1381. if ( iPoint === numPoints - 1 ) {
  1382. if ( isClosed ) {
  1383. // Skip duplicated initial point
  1384. nextPoint = points[ 1 ];
  1385. } else nextPoint = undefined;
  1386. } else {
  1387. nextPoint = points[ iPoint + 1 ];
  1388. }
  1389. // Normal of previous segment in tempV2_1
  1390. var normal1 = tempV2_1;
  1391. getNormal( previousPoint, currentPoint, normal1 );
  1392. tempV2_3.copy( normal1 ).multiplyScalar( strokeWidth2 );
  1393. currentPointL.copy( currentPoint ).sub( tempV2_3 );
  1394. currentPointR.copy( currentPoint ).add( tempV2_3 );
  1395. var u1 = u0 + deltaU;
  1396. innerSideModified = false;
  1397. if ( nextPoint !== undefined ) {
  1398. // Normal of next segment in tempV2_2
  1399. getNormal( currentPoint, nextPoint, tempV2_2 );
  1400. tempV2_3.copy( tempV2_2 ).multiplyScalar( strokeWidth2 );
  1401. nextPointL.copy( currentPoint ).sub( tempV2_3 );
  1402. nextPointR.copy( currentPoint ).add( tempV2_3 );
  1403. joinIsOnLeftSide = true;
  1404. tempV2_3.subVectors( nextPoint, previousPoint );
  1405. if ( normal1.dot( tempV2_3 ) < 0 ) {
  1406. joinIsOnLeftSide = false;
  1407. }
  1408. if ( iPoint === 1 ) initialJoinIsOnLeftSide = joinIsOnLeftSide;
  1409. tempV2_3.subVectors( nextPoint, currentPoint );
  1410. tempV2_3.normalize();
  1411. var dot = Math.abs( normal1.dot( tempV2_3 ) );
  1412. // If path is straight, don't create join
  1413. if ( dot !== 0 ) {
  1414. // Compute inner and outer segment intersections
  1415. var miterSide = strokeWidth2 / dot;
  1416. tempV2_3.multiplyScalar( - miterSide );
  1417. tempV2_4.subVectors( currentPoint, previousPoint );
  1418. tempV2_5.copy( tempV2_4 ).setLength( miterSide ).add( tempV2_3 );
  1419. innerPoint.copy( tempV2_5 ).negate();
  1420. var miterLength2 = tempV2_5.length();
  1421. var segmentLengthPrev = tempV2_4.length();
  1422. tempV2_4.divideScalar( segmentLengthPrev );
  1423. tempV2_6.subVectors( nextPoint, currentPoint );
  1424. var segmentLengthNext = tempV2_6.length();
  1425. tempV2_6.divideScalar( segmentLengthNext );
  1426. // Check that previous and next segments doesn't overlap with the innerPoint of intersection
  1427. if ( tempV2_4.dot( innerPoint ) < segmentLengthPrev && tempV2_6.dot( innerPoint ) < segmentLengthNext ) {
  1428. innerSideModified = true;
  1429. }
  1430. outerPoint.copy( tempV2_5 ).add( currentPoint );
  1431. innerPoint.add( currentPoint );
  1432. isMiter = false;
  1433. if ( innerSideModified ) {
  1434. if ( joinIsOnLeftSide ) {
  1435. nextPointR.copy( innerPoint );
  1436. currentPointR.copy( innerPoint );
  1437. } else {
  1438. nextPointL.copy( innerPoint );
  1439. currentPointL.copy( innerPoint );
  1440. }
  1441. } else {
  1442. // The segment triangles are generated here if there was overlapping
  1443. makeSegmentTriangles();
  1444. }
  1445. switch ( style.strokeLineJoin ) {
  1446. case 'bevel':
  1447. makeSegmentWithBevelJoin( joinIsOnLeftSide, innerSideModified, u1 );
  1448. break;
  1449. case 'round':
  1450. // Segment triangles
  1451. createSegmentTrianglesWithMiddleSection( joinIsOnLeftSide, innerSideModified );
  1452. // Join triangles
  1453. if ( joinIsOnLeftSide ) {
  1454. makeCircularSector( currentPoint, currentPointL, nextPointL, u1, 0 );
  1455. } else {
  1456. makeCircularSector( currentPoint, nextPointR, currentPointR, u1, 1 );
  1457. }
  1458. break;
  1459. case 'miter':
  1460. case 'miter-clip':
  1461. default:
  1462. var miterFraction = ( strokeWidth2 * style.strokeMiterLimit ) / miterLength2;
  1463. if ( miterFraction < 1 ) {
  1464. // The join miter length exceeds the miter limit
  1465. if ( style.strokeLineJoin !== 'miter-clip' ) {
  1466. makeSegmentWithBevelJoin( joinIsOnLeftSide, innerSideModified, u1 );
  1467. break;
  1468. } else {
  1469. // Segment triangles
  1470. createSegmentTrianglesWithMiddleSection( joinIsOnLeftSide, innerSideModified );
  1471. // Miter-clip join triangles
  1472. if ( joinIsOnLeftSide ) {
  1473. tempV2_6.subVectors( outerPoint, currentPointL ).multiplyScalar( miterFraction ).add( currentPointL );
  1474. tempV2_7.subVectors( outerPoint, nextPointL ).multiplyScalar( miterFraction ).add( nextPointL );
  1475. addVertex( currentPointL, u1, 0 );
  1476. addVertex( tempV2_6, u1, 0 );
  1477. addVertex( currentPoint, u1, 0.5 );
  1478. addVertex( currentPoint, u1, 0.5 );
  1479. addVertex( tempV2_6, u1, 0 );
  1480. addVertex( tempV2_7, u1, 0 );
  1481. addVertex( currentPoint, u1, 0.5 );
  1482. addVertex( tempV2_7, u1, 0 );
  1483. addVertex( nextPointL, u1, 0 );
  1484. } else {
  1485. tempV2_6.subVectors( outerPoint, currentPointR ).multiplyScalar( miterFraction ).add( currentPointR );
  1486. tempV2_7.subVectors( outerPoint, nextPointR ).multiplyScalar( miterFraction ).add( nextPointR );
  1487. addVertex( currentPointR, u1, 1 );
  1488. addVertex( tempV2_6, u1, 1 );
  1489. addVertex( currentPoint, u1, 0.5 );
  1490. addVertex( currentPoint, u1, 0.5 );
  1491. addVertex( tempV2_6, u1, 1 );
  1492. addVertex( tempV2_7, u1, 1 );
  1493. addVertex( currentPoint, u1, 0.5 );
  1494. addVertex( tempV2_7, u1, 1 );
  1495. addVertex( nextPointR, u1, 1 );
  1496. }
  1497. }
  1498. } else {
  1499. // Miter join segment triangles
  1500. if ( innerSideModified ) {
  1501. // Optimized segment + join triangles
  1502. if ( joinIsOnLeftSide ) {
  1503. addVertex( lastPointR, u0, 1 );
  1504. addVertex( lastPointL, u0, 0 );
  1505. addVertex( outerPoint, u1, 0 );
  1506. addVertex( lastPointR, u0, 1 );
  1507. addVertex( outerPoint, u1, 0 );
  1508. addVertex( innerPoint, u1, 1 );
  1509. } else {
  1510. addVertex( lastPointR, u0, 1 );
  1511. addVertex( lastPointL, u0, 0 );
  1512. addVertex( outerPoint, u1, 1 );
  1513. addVertex( lastPointL, u0, 0 );
  1514. addVertex( innerPoint, u1, 0 );
  1515. addVertex( outerPoint, u1, 1 );
  1516. }
  1517. if ( joinIsOnLeftSide ) {
  1518. nextPointL.copy( outerPoint );
  1519. } else {
  1520. nextPointR.copy( outerPoint );
  1521. }
  1522. } else {
  1523. // Add extra miter join triangles
  1524. if ( joinIsOnLeftSide ) {
  1525. addVertex( currentPointL, u1, 0 );
  1526. addVertex( outerPoint, u1, 0 );
  1527. addVertex( currentPoint, u1, 0.5 );
  1528. addVertex( currentPoint, u1, 0.5 );
  1529. addVertex( outerPoint, u1, 0 );
  1530. addVertex( nextPointL, u1, 0 );
  1531. } else {
  1532. addVertex( currentPointR, u1, 1 );
  1533. addVertex( outerPoint, u1, 1 );
  1534. addVertex( currentPoint, u1, 0.5 );
  1535. addVertex( currentPoint, u1, 0.5 );
  1536. addVertex( outerPoint, u1, 1 );
  1537. addVertex( nextPointR, u1, 1 );
  1538. }
  1539. }
  1540. isMiter = true;
  1541. }
  1542. break;
  1543. }
  1544. } else {
  1545. // The segment triangles are generated here when two consecutive points are collinear
  1546. makeSegmentTriangles();
  1547. }
  1548. } else {
  1549. // The segment triangles are generated here if it is the ending segment
  1550. makeSegmentTriangles();
  1551. }
  1552. if ( ! isClosed && iPoint === numPoints - 1 ) {
  1553. // Start line endcap
  1554. addCapGeometry( points[ 0 ], point0L, point0R, joinIsOnLeftSide, true, u0 );
  1555. }
  1556. // Increment loop variables
  1557. u0 = u1;
  1558. previousPoint = currentPoint;
  1559. lastPointL.copy( nextPointL );
  1560. lastPointR.copy( nextPointR );
  1561. }
  1562. if ( ! isClosed ) {
  1563. // Ending line endcap
  1564. addCapGeometry( currentPoint, currentPointL, currentPointR, joinIsOnLeftSide, false, u1 );
  1565. } else if ( innerSideModified && vertices ) {
  1566. // Modify path first segment vertices to adjust to the segments inner and outer intersections
  1567. var lastOuter = outerPoint;
  1568. var lastInner = innerPoint;
  1569. if ( initialJoinIsOnLeftSide !== joinIsOnLeftSide ) {
  1570. lastOuter = innerPoint;
  1571. lastInner = outerPoint;
  1572. }
  1573. if ( joinIsOnLeftSide ) {
  1574. if ( isMiter || initialJoinIsOnLeftSide ) {
  1575. lastInner.toArray( vertices, 0 * 3 );
  1576. lastInner.toArray( vertices, 3 * 3 );
  1577. if ( isMiter ) {
  1578. lastOuter.toArray( vertices, 1 * 3 );
  1579. }
  1580. }
  1581. } else {
  1582. if ( isMiter || ! initialJoinIsOnLeftSide ) {
  1583. lastInner.toArray( vertices, 1 * 3 );
  1584. lastInner.toArray( vertices, 3 * 3 );
  1585. if ( isMiter ) {
  1586. lastOuter.toArray( vertices, 0 * 3 );
  1587. }
  1588. }
  1589. }
  1590. }
  1591. return numVertices;
  1592. // -- End of algorithm
  1593. // -- Functions
  1594. function getNormal( p1, p2, result ) {
  1595. result.subVectors( p2, p1 );
  1596. return result.set( - result.y, result.x ).normalize();
  1597. }
  1598. function addVertex( position, u, v ) {
  1599. if ( vertices ) {
  1600. vertices[ currentCoordinate ] = position.x;
  1601. vertices[ currentCoordinate + 1 ] = position.y;
  1602. vertices[ currentCoordinate + 2 ] = 0;
  1603. if ( normals ) {
  1604. normals[ currentCoordinate ] = 0;
  1605. normals[ currentCoordinate + 1 ] = 0;
  1606. normals[ currentCoordinate + 2 ] = 1;
  1607. }
  1608. currentCoordinate += 3;
  1609. if ( uvs ) {
  1610. uvs[ currentCoordinateUV ] = u;
  1611. uvs[ currentCoordinateUV + 1 ] = v;
  1612. currentCoordinateUV += 2;
  1613. }
  1614. }
  1615. numVertices += 3;
  1616. }
  1617. function makeCircularSector( center, p1, p2, u, v ) {
  1618. // param p1, p2: Points in the circle arc.
  1619. // p1 and p2 are in clockwise direction.
  1620. tempV2_1.copy( p1 ).sub( center ).normalize();
  1621. tempV2_2.copy( p2 ).sub( center ).normalize();
  1622. var angle = Math.PI;
  1623. var dot = tempV2_1.dot( tempV2_2 );
  1624. if ( Math.abs( dot ) < 1 ) angle = Math.abs( Math.acos( dot ) );
  1625. angle /= arcDivisions;
  1626. tempV2_3.copy( p1 );
  1627. for ( var i = 0, il = arcDivisions - 1; i < il; i ++ ) {
  1628. tempV2_4.copy( tempV2_3 ).rotateAround( center, angle );
  1629. addVertex( tempV2_3, u, v );
  1630. addVertex( tempV2_4, u, v );
  1631. addVertex( center, u, 0.5 );
  1632. tempV2_3.copy( tempV2_4 );
  1633. }
  1634. addVertex( tempV2_4, u, v );
  1635. addVertex( p2, u, v );
  1636. addVertex( center, u, 0.5 );
  1637. }
  1638. function makeSegmentTriangles() {
  1639. addVertex( lastPointR, u0, 1 );
  1640. addVertex( lastPointL, u0, 0 );
  1641. addVertex( currentPointL, u1, 0 );
  1642. addVertex( lastPointR, u0, 1 );
  1643. addVertex( currentPointL, u1, 1 );
  1644. addVertex( currentPointR, u1, 0 );
  1645. }
  1646. function makeSegmentWithBevelJoin( joinIsOnLeftSide, innerSideModified, u ) {
  1647. if ( innerSideModified ) {
  1648. // Optimized segment + bevel triangles
  1649. if ( joinIsOnLeftSide ) {
  1650. // Path segments triangles
  1651. addVertex( lastPointR, u0, 1 );
  1652. addVertex( lastPointL, u0, 0 );
  1653. addVertex( currentPointL, u1, 0 );
  1654. addVertex( lastPointR, u0, 1 );
  1655. addVertex( currentPointL, u1, 0 );
  1656. addVertex( innerPoint, u1, 1 );
  1657. // Bevel join triangle
  1658. addVertex( currentPointL, u, 0 );
  1659. addVertex( nextPointL, u, 0 );
  1660. addVertex( innerPoint, u, 0.5 );
  1661. } else {
  1662. // Path segments triangles
  1663. addVertex( lastPointR, u0, 1 );
  1664. addVertex( lastPointL, u0, 0 );
  1665. addVertex( currentPointR, u1, 1 );
  1666. addVertex( lastPointL, u0, 0 );
  1667. addVertex( innerPoint, u1, 0 );
  1668. addVertex( currentPointR, u1, 1 );
  1669. // Bevel join triangle
  1670. addVertex( currentPointR, u, 1 );
  1671. addVertex( nextPointR, u, 0 );
  1672. addVertex( innerPoint, u, 0.5 );
  1673. }
  1674. } else {
  1675. // Bevel join triangle. The segment triangles are done in the main loop
  1676. if ( joinIsOnLeftSide ) {
  1677. addVertex( currentPointL, u, 0 );
  1678. addVertex( nextPointL, u, 0 );
  1679. addVertex( currentPoint, u, 0.5 );
  1680. } else {
  1681. addVertex( currentPointR, u, 1 );
  1682. addVertex( nextPointR, u, 0 );
  1683. addVertex( currentPoint, u, 0.5 );
  1684. }
  1685. }
  1686. }
  1687. function createSegmentTrianglesWithMiddleSection( joinIsOnLeftSide, innerSideModified ) {
  1688. if ( innerSideModified ) {
  1689. if ( joinIsOnLeftSide ) {
  1690. addVertex( lastPointR, u0, 1 );
  1691. addVertex( lastPointL, u0, 0 );
  1692. addVertex( currentPointL, u1, 0 );
  1693. addVertex( lastPointR, u0, 1 );
  1694. addVertex( currentPointL, u1, 0 );
  1695. addVertex( innerPoint, u1, 1 );
  1696. addVertex( currentPointL, u0, 0 );
  1697. addVertex( currentPoint, u1, 0.5 );
  1698. addVertex( innerPoint, u1, 1 );
  1699. addVertex( currentPoint, u1, 0.5 );
  1700. addVertex( nextPointL, u0, 0 );
  1701. addVertex( innerPoint, u1, 1 );
  1702. } else {
  1703. addVertex( lastPointR, u0, 1 );
  1704. addVertex( lastPointL, u0, 0 );
  1705. addVertex( currentPointR, u1, 1 );
  1706. addVertex( lastPointL, u0, 0 );
  1707. addVertex( innerPoint, u1, 0 );
  1708. addVertex( currentPointR, u1, 1 );
  1709. addVertex( currentPointR, u0, 1 );
  1710. addVertex( innerPoint, u1, 0 );
  1711. addVertex( currentPoint, u1, 0.5 );
  1712. addVertex( currentPoint, u1, 0.5 );
  1713. addVertex( innerPoint, u1, 0 );
  1714. addVertex( nextPointR, u0, 1 );
  1715. }
  1716. }
  1717. }
  1718. function addCapGeometry( center, p1, p2, joinIsOnLeftSide, start, u ) {
  1719. // param center: End point of the path
  1720. // param p1, p2: Left and right cap points
  1721. switch ( style.strokeLineCap ) {
  1722. case 'round':
  1723. if ( start ) {
  1724. makeCircularSector( center, p2, p1, u, 0.5 );
  1725. } else {
  1726. makeCircularSector( center, p1, p2, u, 0.5 );
  1727. }
  1728. break;
  1729. case 'square':
  1730. if ( start ) {
  1731. tempV2_1.subVectors( p1, center );
  1732. tempV2_2.set( tempV2_1.y, - tempV2_1.x );
  1733. tempV2_3.addVectors( tempV2_1, tempV2_2 ).add( center );
  1734. tempV2_4.subVectors( tempV2_2, tempV2_1 ).add( center );
  1735. // Modify already existing vertices
  1736. if ( joinIsOnLeftSide ) {
  1737. tempV2_3.toArray( vertices, 1 * 3 );
  1738. tempV2_4.toArray( vertices, 0 * 3 );
  1739. tempV2_4.toArray( vertices, 3 * 3 );
  1740. } else {
  1741. tempV2_3.toArray( vertices, 1 * 3 );
  1742. tempV2_3.toArray( vertices, 3 * 3 );
  1743. tempV2_4.toArray( vertices, 0 * 3 );
  1744. }
  1745. } else {
  1746. tempV2_1.subVectors( p2, center );
  1747. tempV2_2.set( tempV2_1.y, - tempV2_1.x );
  1748. tempV2_3.addVectors( tempV2_1, tempV2_2 ).add( center );
  1749. tempV2_4.subVectors( tempV2_2, tempV2_1 ).add( center );
  1750. var vl = vertices.length;
  1751. // Modify already existing vertices
  1752. if ( joinIsOnLeftSide ) {
  1753. tempV2_3.toArray( vertices, vl - 1 * 3 );
  1754. tempV2_4.toArray( vertices, vl - 2 * 3 );
  1755. tempV2_4.toArray( vertices, vl - 4 * 3 );
  1756. } else {
  1757. tempV2_3.toArray( vertices, vl - 2 * 3 );
  1758. tempV2_4.toArray( vertices, vl - 1 * 3 );
  1759. tempV2_4.toArray( vertices, vl - 4 * 3 );
  1760. }
  1761. }
  1762. break;
  1763. case 'butt':
  1764. default:
  1765. // Nothing to do here
  1766. break;
  1767. }
  1768. }
  1769. function removeDuplicatedPoints( points ) {
  1770. // Creates a new array if necessary with duplicated points removed.
  1771. // This does not remove duplicated initial and ending points of a closed path.
  1772. var dupPoints = false;
  1773. for ( var i = 1, n = points.length - 1; i < n; i ++ ) {
  1774. if ( points[ i ].distanceTo( points[ i + 1 ] ) < minDistance ) {
  1775. dupPoints = true;
  1776. break;
  1777. }
  1778. }
  1779. if ( ! dupPoints ) return points;
  1780. var newPoints = [];
  1781. newPoints.push( points[ 0 ] );
  1782. for ( var i = 1, n = points.length - 1; i < n; i ++ ) {
  1783. if ( points[ i ].distanceTo( points[ i + 1 ] ) >= minDistance ) {
  1784. newPoints.push( points[ i ] );
  1785. }
  1786. }
  1787. newPoints.push( points[ points.length - 1 ] );
  1788. return newPoints;
  1789. }
  1790. };
  1791. }();