SVGLoader.js 63 KB

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