SVGLoader.js 62 KB

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