SVGLoader.js 64 KB

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