SVGLoader.js 61 KB

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