SVGLoader.js 64 KB

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