SVGLoader.js 71 KB

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