SVGLoader.js 81 KB

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