SVGLoader.js 63 KB

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