SVGLoader.js 63 KB

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