SVGLoader.js 64 KB

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