SVGLoader.js 64 KB

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