1
0

SVGLoader.js 68 KB

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