LDrawLoader.js 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409
  1. import {
  2. BufferAttribute,
  3. BufferGeometry,
  4. Color,
  5. FileLoader,
  6. Group,
  7. LineBasicMaterial,
  8. LineSegments,
  9. Loader,
  10. Matrix4,
  11. Mesh,
  12. MeshStandardMaterial,
  13. ShaderMaterial,
  14. UniformsLib,
  15. UniformsUtils,
  16. Vector3,
  17. Ray
  18. } from 'three';
  19. // Special surface finish tag types.
  20. // Note: "MATERIAL" tag (e.g. GLITTER, SPECKLE) is not implemented
  21. const FINISH_TYPE_DEFAULT = 0;
  22. const FINISH_TYPE_CHROME = 1;
  23. const FINISH_TYPE_PEARLESCENT = 2;
  24. const FINISH_TYPE_RUBBER = 3;
  25. const FINISH_TYPE_MATTE_METALLIC = 4;
  26. const FINISH_TYPE_METAL = 5;
  27. // State machine to search a subobject path.
  28. // The LDraw standard establishes these various possible subfolders.
  29. const FILE_LOCATION_AS_IS = 0;
  30. const FILE_LOCATION_TRY_PARTS = 1;
  31. const FILE_LOCATION_TRY_P = 2;
  32. const FILE_LOCATION_TRY_MODELS = 3;
  33. const FILE_LOCATION_TRY_RELATIVE = 4;
  34. const FILE_LOCATION_TRY_ABSOLUTE = 5;
  35. const FILE_LOCATION_NOT_FOUND = 6;
  36. const MAIN_COLOUR_CODE = '16';
  37. const MAIN_EDGE_COLOUR_CODE = '24';
  38. const _tempVec0 = new Vector3();
  39. const _tempVec1 = new Vector3();
  40. class LDrawConditionalLineMaterial extends ShaderMaterial {
  41. constructor( parameters ) {
  42. super( {
  43. uniforms: UniformsUtils.merge( [
  44. UniformsLib.fog,
  45. {
  46. diffuse: {
  47. value: new Color()
  48. },
  49. opacity: {
  50. value: 1.0
  51. }
  52. }
  53. ] ),
  54. vertexShader: /* glsl */`
  55. attribute vec3 control0;
  56. attribute vec3 control1;
  57. attribute vec3 direction;
  58. varying float discardFlag;
  59. #include <common>
  60. #include <color_pars_vertex>
  61. #include <fog_pars_vertex>
  62. #include <logdepthbuf_pars_vertex>
  63. #include <clipping_planes_pars_vertex>
  64. void main() {
  65. #include <color_vertex>
  66. vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );
  67. gl_Position = projectionMatrix * mvPosition;
  68. // Transform the line segment ends and control points into camera clip space
  69. vec4 c0 = projectionMatrix * modelViewMatrix * vec4( control0, 1.0 );
  70. vec4 c1 = projectionMatrix * modelViewMatrix * vec4( control1, 1.0 );
  71. vec4 p0 = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  72. vec4 p1 = projectionMatrix * modelViewMatrix * vec4( position + direction, 1.0 );
  73. c0.xy /= c0.w;
  74. c1.xy /= c1.w;
  75. p0.xy /= p0.w;
  76. p1.xy /= p1.w;
  77. // Get the direction of the segment and an orthogonal vector
  78. vec2 dir = p1.xy - p0.xy;
  79. vec2 norm = vec2( -dir.y, dir.x );
  80. // Get control point directions from the line
  81. vec2 c0dir = c0.xy - p1.xy;
  82. vec2 c1dir = c1.xy - p1.xy;
  83. // If the vectors to the controls points are pointed in different directions away
  84. // from the line segment then the line should not be drawn.
  85. float d0 = dot( normalize( norm ), normalize( c0dir ) );
  86. float d1 = dot( normalize( norm ), normalize( c1dir ) );
  87. discardFlag = float( sign( d0 ) != sign( d1 ) );
  88. #include <logdepthbuf_vertex>
  89. #include <clipping_planes_vertex>
  90. #include <fog_vertex>
  91. }
  92. `,
  93. fragmentShader: /* glsl */`
  94. uniform vec3 diffuse;
  95. uniform float opacity;
  96. varying float discardFlag;
  97. #include <common>
  98. #include <color_pars_fragment>
  99. #include <fog_pars_fragment>
  100. #include <logdepthbuf_pars_fragment>
  101. #include <clipping_planes_pars_fragment>
  102. void main() {
  103. if ( discardFlag > 0.5 ) discard;
  104. #include <clipping_planes_fragment>
  105. vec3 outgoingLight = vec3( 0.0 );
  106. vec4 diffuseColor = vec4( diffuse, opacity );
  107. #include <logdepthbuf_fragment>
  108. #include <color_fragment>
  109. outgoingLight = diffuseColor.rgb; // simple shader
  110. gl_FragColor = vec4( outgoingLight, diffuseColor.a );
  111. #include <tonemapping_fragment>
  112. #include <encodings_fragment>
  113. #include <fog_fragment>
  114. #include <premultiplied_alpha_fragment>
  115. }
  116. `,
  117. } );
  118. Object.defineProperties( this, {
  119. opacity: {
  120. get: function () {
  121. return this.uniforms.opacity.value;
  122. },
  123. set: function ( value ) {
  124. this.uniforms.opacity.value = value;
  125. }
  126. },
  127. color: {
  128. get: function () {
  129. return this.uniforms.diffuse.value;
  130. }
  131. }
  132. } );
  133. this.setValues( parameters );
  134. this.isLDrawConditionalLineMaterial = true;
  135. }
  136. }
  137. class ConditionalLineSegments extends LineSegments {
  138. constructor( geometry, material ) {
  139. super( geometry, material );
  140. this.isConditionalLine = true;
  141. }
  142. }
  143. function generateFaceNormals( faces ) {
  144. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  145. const face = faces[ i ];
  146. const vertices = face.vertices;
  147. const v0 = vertices[ 0 ];
  148. const v1 = vertices[ 1 ];
  149. const v2 = vertices[ 2 ];
  150. _tempVec0.subVectors( v1, v0 );
  151. _tempVec1.subVectors( v2, v1 );
  152. face.faceNormal = new Vector3()
  153. .crossVectors( _tempVec0, _tempVec1 )
  154. .normalize();
  155. }
  156. }
  157. const _ray = new Ray();
  158. function smoothNormals( faces, lineSegments, checkSubSegments = false ) {
  159. // NOTE: 1e2 is pretty coarse but was chosen to quantize the resulting value because
  160. // it allows edges to be smoothed as expected (see minifig arms).
  161. // --
  162. // And the vector values are initialize multiplied by 1 + 1e-10 to account for floating
  163. // point errors on vertices along quantization boundaries. Ie after matrix multiplication
  164. // vertices that should be merged might be set to "1.7" and "1.6999..." meaning they won't
  165. // get merged. This added epsilon attempts to push these error values to the same quantized
  166. // value for the sake of hashing. See "AT-ST mini" dishes. See mrdoob/three#23169.
  167. const hashMultiplier = ( 1 + 1e-10 ) * 1e2;
  168. function hashVertex( v ) {
  169. const x = ~ ~ ( v.x * hashMultiplier );
  170. const y = ~ ~ ( v.y * hashMultiplier );
  171. const z = ~ ~ ( v.z * hashMultiplier );
  172. return `${ x },${ y },${ z }`;
  173. }
  174. function hashEdge( v0, v1 ) {
  175. return `${ hashVertex( v0 ) }_${ hashVertex( v1 ) }`;
  176. }
  177. // converts the two vertices to a ray with a normalized direction and origin of 0, 0, 0 projected
  178. // onto the original line.
  179. function toNormalizedRay( v0, v1, targetRay ) {
  180. targetRay.direction.subVectors( v1, v0 ).normalize();
  181. const scalar = v0.dot( targetRay.direction );
  182. targetRay.origin.copy( v0 ).addScaledVector( targetRay.direction, - scalar );
  183. return targetRay;
  184. }
  185. function hashRay( ray ) {
  186. return hashEdge( ray.origin, ray.direction );
  187. }
  188. const hardEdges = new Set();
  189. const hardEdgeRays = new Map();
  190. const halfEdgeList = {};
  191. const normals = [];
  192. // Save the list of hard edges by hash
  193. for ( let i = 0, l = lineSegments.length; i < l; i ++ ) {
  194. const ls = lineSegments[ i ];
  195. const vertices = ls.vertices;
  196. const v0 = vertices[ 0 ];
  197. const v1 = vertices[ 1 ];
  198. hardEdges.add( hashEdge( v0, v1 ) );
  199. hardEdges.add( hashEdge( v1, v0 ) );
  200. // only generate the hard edge ray map if we're checking subsegments because it's more expensive to check
  201. // and requires more memory.
  202. if ( checkSubSegments ) {
  203. // add both ray directions to the map
  204. const ray = toNormalizedRay( v0, v1, new Ray() );
  205. const rh1 = hashRay( ray );
  206. if ( ! hardEdgeRays.has( rh1 ) ) {
  207. toNormalizedRay( v1, v0, ray );
  208. const rh2 = hashRay( ray );
  209. const info = {
  210. ray,
  211. distances: [],
  212. };
  213. hardEdgeRays.set( rh1, info );
  214. hardEdgeRays.set( rh2, info );
  215. }
  216. // store both segments ends in min, max order in the distances array to check if a face edge is a
  217. // subsegment later.
  218. const info = hardEdgeRays.get( rh1 );
  219. let d0 = info.ray.direction.dot( v0 );
  220. let d1 = info.ray.direction.dot( v1 );
  221. if ( d0 > d1 ) {
  222. [ d0, d1 ] = [ d1, d0 ];
  223. }
  224. info.distances.push( d0, d1 );
  225. }
  226. }
  227. // track the half edges associated with each triangle
  228. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  229. const tri = faces[ i ];
  230. const vertices = tri.vertices;
  231. const vertCount = vertices.length;
  232. for ( let i2 = 0; i2 < vertCount; i2 ++ ) {
  233. const index = i2;
  234. const next = ( i2 + 1 ) % vertCount;
  235. const v0 = vertices[ index ];
  236. const v1 = vertices[ next ];
  237. const hash = hashEdge( v0, v1 );
  238. // don't add the triangle if the edge is supposed to be hard
  239. if ( hardEdges.has( hash ) ) {
  240. continue;
  241. }
  242. // if checking subsegments then check to see if this edge lies on a hard edge ray and whether its within any ray bounds
  243. if ( checkSubSegments ) {
  244. toNormalizedRay( v0, v1, _ray );
  245. const rayHash = hashRay( _ray );
  246. if ( hardEdgeRays.has( rayHash ) ) {
  247. const info = hardEdgeRays.get( rayHash );
  248. const { ray, distances } = info;
  249. let d0 = ray.direction.dot( v0 );
  250. let d1 = ray.direction.dot( v1 );
  251. if ( d0 > d1 ) {
  252. [ d0, d1 ] = [ d1, d0 ];
  253. }
  254. // return early if the face edge is found to be a subsegment of a line edge meaning the edge will have "hard" normals
  255. let found = false;
  256. for ( let i = 0, l = distances.length; i < l; i += 2 ) {
  257. if ( d0 >= distances[ i ] && d1 <= distances[ i + 1 ] ) {
  258. found = true;
  259. break;
  260. }
  261. }
  262. if ( found ) {
  263. continue;
  264. }
  265. }
  266. }
  267. const info = {
  268. index: index,
  269. tri: tri
  270. };
  271. halfEdgeList[ hash ] = info;
  272. }
  273. }
  274. // Iterate until we've tried to connect all faces to share normals
  275. while ( true ) {
  276. // Stop if there are no more faces left
  277. let halfEdge = null;
  278. for ( const key in halfEdgeList ) {
  279. halfEdge = halfEdgeList[ key ];
  280. break;
  281. }
  282. if ( halfEdge === null ) {
  283. break;
  284. }
  285. // Exhaustively find all connected faces
  286. const queue = [ halfEdge ];
  287. while ( queue.length > 0 ) {
  288. // initialize all vertex normals in this triangle
  289. const tri = queue.pop().tri;
  290. const vertices = tri.vertices;
  291. const vertNormals = tri.normals;
  292. const faceNormal = tri.faceNormal;
  293. // Check if any edge is connected to another triangle edge
  294. const vertCount = vertices.length;
  295. for ( let i2 = 0; i2 < vertCount; i2 ++ ) {
  296. const index = i2;
  297. const next = ( i2 + 1 ) % vertCount;
  298. const v0 = vertices[ index ];
  299. const v1 = vertices[ next ];
  300. // delete this triangle from the list so it won't be found again
  301. const hash = hashEdge( v0, v1 );
  302. delete halfEdgeList[ hash ];
  303. const reverseHash = hashEdge( v1, v0 );
  304. const otherInfo = halfEdgeList[ reverseHash ];
  305. if ( otherInfo ) {
  306. const otherTri = otherInfo.tri;
  307. const otherIndex = otherInfo.index;
  308. const otherNormals = otherTri.normals;
  309. const otherVertCount = otherNormals.length;
  310. const otherFaceNormal = otherTri.faceNormal;
  311. // NOTE: If the angle between faces is > 67.5 degrees then assume it's
  312. // hard edge. There are some cases where the line segments do not line up exactly
  313. // with or span multiple triangle edges (see Lunar Vehicle wheels).
  314. if ( Math.abs( otherTri.faceNormal.dot( tri.faceNormal ) ) < 0.25 ) {
  315. continue;
  316. }
  317. // if this triangle has already been traversed then it won't be in
  318. // the halfEdgeList. If it has not then add it to the queue and delete
  319. // it so it won't be found again.
  320. if ( reverseHash in halfEdgeList ) {
  321. queue.push( otherInfo );
  322. delete halfEdgeList[ reverseHash ];
  323. }
  324. // share the first normal
  325. const otherNext = ( otherIndex + 1 ) % otherVertCount;
  326. if (
  327. vertNormals[ index ] && otherNormals[ otherNext ] &&
  328. vertNormals[ index ] !== otherNormals[ otherNext ]
  329. ) {
  330. otherNormals[ otherNext ].norm.add( vertNormals[ index ].norm );
  331. vertNormals[ index ].norm = otherNormals[ otherNext ].norm;
  332. }
  333. let sharedNormal1 = vertNormals[ index ] || otherNormals[ otherNext ];
  334. if ( sharedNormal1 === null ) {
  335. // it's possible to encounter an edge of a triangle that has already been traversed meaning
  336. // both edges already have different normals defined and shared. To work around this we create
  337. // a wrapper object so when those edges are merged the normals can be updated everywhere.
  338. sharedNormal1 = { norm: new Vector3() };
  339. normals.push( sharedNormal1.norm );
  340. }
  341. if ( vertNormals[ index ] === null ) {
  342. vertNormals[ index ] = sharedNormal1;
  343. sharedNormal1.norm.add( faceNormal );
  344. }
  345. if ( otherNormals[ otherNext ] === null ) {
  346. otherNormals[ otherNext ] = sharedNormal1;
  347. sharedNormal1.norm.add( otherFaceNormal );
  348. }
  349. // share the second normal
  350. if (
  351. vertNormals[ next ] && otherNormals[ otherIndex ] &&
  352. vertNormals[ next ] !== otherNormals[ otherIndex ]
  353. ) {
  354. otherNormals[ otherIndex ].norm.add( vertNormals[ next ].norm );
  355. vertNormals[ next ].norm = otherNormals[ otherIndex ].norm;
  356. }
  357. let sharedNormal2 = vertNormals[ next ] || otherNormals[ otherIndex ];
  358. if ( sharedNormal2 === null ) {
  359. sharedNormal2 = { norm: new Vector3() };
  360. normals.push( sharedNormal2.norm );
  361. }
  362. if ( vertNormals[ next ] === null ) {
  363. vertNormals[ next ] = sharedNormal2;
  364. sharedNormal2.norm.add( faceNormal );
  365. }
  366. if ( otherNormals[ otherIndex ] === null ) {
  367. otherNormals[ otherIndex ] = sharedNormal2;
  368. sharedNormal2.norm.add( otherFaceNormal );
  369. }
  370. }
  371. }
  372. }
  373. }
  374. // The normals of each face have been added up so now we average them by normalizing the vector.
  375. for ( let i = 0, l = normals.length; i < l; i ++ ) {
  376. normals[ i ].normalize();
  377. }
  378. }
  379. function isPartType( type ) {
  380. return type === 'Part' || type === 'Unofficial_Part';
  381. }
  382. function isPrimitiveType( type ) {
  383. return /primitive/i.test( type ) || type === 'Subpart';
  384. }
  385. class LineParser {
  386. constructor( line, lineNumber ) {
  387. this.line = line;
  388. this.lineLength = line.length;
  389. this.currentCharIndex = 0;
  390. this.currentChar = ' ';
  391. this.lineNumber = lineNumber;
  392. }
  393. seekNonSpace() {
  394. while ( this.currentCharIndex < this.lineLength ) {
  395. this.currentChar = this.line.charAt( this.currentCharIndex );
  396. if ( this.currentChar !== ' ' && this.currentChar !== '\t' ) {
  397. return;
  398. }
  399. this.currentCharIndex ++;
  400. }
  401. }
  402. getToken() {
  403. const pos0 = this.currentCharIndex ++;
  404. // Seek space
  405. while ( this.currentCharIndex < this.lineLength ) {
  406. this.currentChar = this.line.charAt( this.currentCharIndex );
  407. if ( this.currentChar === ' ' || this.currentChar === '\t' ) {
  408. break;
  409. }
  410. this.currentCharIndex ++;
  411. }
  412. const pos1 = this.currentCharIndex;
  413. this.seekNonSpace();
  414. return this.line.substring( pos0, pos1 );
  415. }
  416. getVector() {
  417. return new Vector3( parseFloat( this.getToken() ), parseFloat( this.getToken() ), parseFloat( this.getToken() ) );
  418. }
  419. getRemainingString() {
  420. return this.line.substring( this.currentCharIndex, this.lineLength );
  421. }
  422. isAtTheEnd() {
  423. return this.currentCharIndex >= this.lineLength;
  424. }
  425. setToEnd() {
  426. this.currentCharIndex = this.lineLength;
  427. }
  428. getLineNumberString() {
  429. return this.lineNumber >= 0 ? ' at line ' + this.lineNumber : '';
  430. }
  431. }
  432. // Fetches and parses an intermediate representation of LDraw parts files.
  433. class LDrawParsedCache {
  434. constructor( loader ) {
  435. this.loader = loader;
  436. this._cache = {};
  437. }
  438. cloneResult( original ) {
  439. const result = {};
  440. // vertices are transformed and normals computed before being converted to geometry
  441. // so these pieces must be cloned.
  442. result.faces = original.faces.map( face => {
  443. return {
  444. colorCode: face.colorCode,
  445. material: face.material,
  446. vertices: face.vertices.map( v => v.clone() ),
  447. normals: face.normals.map( () => null ),
  448. faceNormal: null
  449. };
  450. } );
  451. result.conditionalSegments = original.conditionalSegments.map( face => {
  452. return {
  453. colorCode: face.colorCode,
  454. material: face.material,
  455. vertices: face.vertices.map( v => v.clone() ),
  456. controlPoints: face.controlPoints.map( v => v.clone() )
  457. };
  458. } );
  459. result.lineSegments = original.lineSegments.map( face => {
  460. return {
  461. colorCode: face.colorCode,
  462. material: face.material,
  463. vertices: face.vertices.map( v => v.clone() )
  464. };
  465. } );
  466. // none if this is subsequently modified
  467. result.type = original.type;
  468. result.category = original.category;
  469. result.keywords = original.keywords;
  470. result.subobjects = original.subobjects;
  471. result.totalFaces = original.totalFaces;
  472. result.startingConstructionStep = original.startingConstructionStep;
  473. result.materials = original.materials;
  474. result.group = null;
  475. return result;
  476. }
  477. async fetchData( fileName ) {
  478. let triedLowerCase = false;
  479. let locationState = FILE_LOCATION_AS_IS;
  480. while ( locationState !== FILE_LOCATION_NOT_FOUND ) {
  481. let subobjectURL = fileName;
  482. switch ( locationState ) {
  483. case FILE_LOCATION_AS_IS:
  484. locationState = locationState + 1;
  485. break;
  486. case FILE_LOCATION_TRY_PARTS:
  487. subobjectURL = 'parts/' + subobjectURL;
  488. locationState = locationState + 1;
  489. break;
  490. case FILE_LOCATION_TRY_P:
  491. subobjectURL = 'p/' + subobjectURL;
  492. locationState = locationState + 1;
  493. break;
  494. case FILE_LOCATION_TRY_MODELS:
  495. subobjectURL = 'models/' + subobjectURL;
  496. locationState = locationState + 1;
  497. break;
  498. case FILE_LOCATION_TRY_RELATIVE:
  499. subobjectURL = fileName.substring( 0, fileName.lastIndexOf( '/' ) + 1 ) + subobjectURL;
  500. locationState = locationState + 1;
  501. break;
  502. case FILE_LOCATION_TRY_ABSOLUTE:
  503. if ( triedLowerCase ) {
  504. // Try absolute path
  505. locationState = FILE_LOCATION_NOT_FOUND;
  506. } else {
  507. // Next attempt is lower case
  508. fileName = fileName.toLowerCase();
  509. subobjectURL = fileName;
  510. triedLowerCase = true;
  511. locationState = FILE_LOCATION_AS_IS;
  512. }
  513. break;
  514. }
  515. const loader = this.loader;
  516. const fileLoader = new FileLoader( loader.manager );
  517. fileLoader.setPath( loader.partsLibraryPath );
  518. fileLoader.setRequestHeader( loader.requestHeader );
  519. fileLoader.setWithCredentials( loader.withCredentials );
  520. try {
  521. const text = await fileLoader.loadAsync( subobjectURL );
  522. return text;
  523. } catch {
  524. continue;
  525. }
  526. }
  527. throw new Error( 'LDrawLoader: Subobject "' + fileName + '" could not be loaded.' );
  528. }
  529. parse( text, fileName = null ) {
  530. const loader = this.loader;
  531. // final results
  532. const faces = [];
  533. const lineSegments = [];
  534. const conditionalSegments = [];
  535. const subobjects = [];
  536. const materials = {};
  537. const getLocalMaterial = colorCode => {
  538. return materials[ colorCode ] || null;
  539. };
  540. let type = 'Model';
  541. let category = null;
  542. let keywords = null;
  543. let totalFaces = 0;
  544. // split into lines
  545. if ( text.indexOf( '\r\n' ) !== - 1 ) {
  546. // This is faster than String.split with regex that splits on both
  547. text = text.replace( /\r\n/g, '\n' );
  548. }
  549. const lines = text.split( '\n' );
  550. const numLines = lines.length;
  551. let parsingEmbeddedFiles = false;
  552. let currentEmbeddedFileName = null;
  553. let currentEmbeddedText = null;
  554. let bfcCertified = false;
  555. let bfcCCW = true;
  556. let bfcInverted = false;
  557. let bfcCull = true;
  558. let startingConstructionStep = false;
  559. // Parse all line commands
  560. for ( let lineIndex = 0; lineIndex < numLines; lineIndex ++ ) {
  561. const line = lines[ lineIndex ];
  562. if ( line.length === 0 ) continue;
  563. if ( parsingEmbeddedFiles ) {
  564. if ( line.startsWith( '0 FILE ' ) ) {
  565. // Save previous embedded file in the cache
  566. this.setData( currentEmbeddedFileName, currentEmbeddedText );
  567. // New embedded text file
  568. currentEmbeddedFileName = line.substring( 7 );
  569. currentEmbeddedText = '';
  570. } else {
  571. currentEmbeddedText += line + '\n';
  572. }
  573. continue;
  574. }
  575. const lp = new LineParser( line, lineIndex + 1 );
  576. lp.seekNonSpace();
  577. if ( lp.isAtTheEnd() ) {
  578. // Empty line
  579. continue;
  580. }
  581. // Parse the line type
  582. const lineType = lp.getToken();
  583. let material;
  584. let colorCode;
  585. let segment;
  586. let ccw;
  587. let doubleSided;
  588. let v0, v1, v2, v3, c0, c1;
  589. switch ( lineType ) {
  590. // Line type 0: Comment or META
  591. case '0':
  592. // Parse meta directive
  593. const meta = lp.getToken();
  594. if ( meta ) {
  595. switch ( meta ) {
  596. case '!LDRAW_ORG':
  597. type = lp.getToken();
  598. break;
  599. case '!COLOUR':
  600. material = loader.parseColorMetaDirective( lp );
  601. if ( material ) {
  602. materials[ material.userData.code ] = material;
  603. } else {
  604. console.warn( 'LDrawLoader: Error parsing material' + lp.getLineNumberString() );
  605. }
  606. break;
  607. case '!CATEGORY':
  608. category = lp.getToken();
  609. break;
  610. case '!KEYWORDS':
  611. const newKeywords = lp.getRemainingString().split( ',' );
  612. if ( newKeywords.length > 0 ) {
  613. if ( ! keywords ) {
  614. keywords = [];
  615. }
  616. newKeywords.forEach( function ( keyword ) {
  617. keywords.push( keyword.trim() );
  618. } );
  619. }
  620. break;
  621. case 'FILE':
  622. if ( lineIndex > 0 ) {
  623. // Start embedded text files parsing
  624. parsingEmbeddedFiles = true;
  625. currentEmbeddedFileName = lp.getRemainingString();
  626. currentEmbeddedText = '';
  627. bfcCertified = false;
  628. bfcCCW = true;
  629. }
  630. break;
  631. case 'BFC':
  632. // Changes to the backface culling state
  633. while ( ! lp.isAtTheEnd() ) {
  634. const token = lp.getToken();
  635. switch ( token ) {
  636. case 'CERTIFY':
  637. case 'NOCERTIFY':
  638. bfcCertified = token === 'CERTIFY';
  639. bfcCCW = true;
  640. break;
  641. case 'CW':
  642. case 'CCW':
  643. bfcCCW = token === 'CCW';
  644. break;
  645. case 'INVERTNEXT':
  646. bfcInverted = true;
  647. break;
  648. case 'CLIP':
  649. case 'NOCLIP':
  650. bfcCull = token === 'CLIP';
  651. break;
  652. default:
  653. console.warn( 'THREE.LDrawLoader: BFC directive "' + token + '" is unknown.' );
  654. break;
  655. }
  656. }
  657. break;
  658. case 'STEP':
  659. startingConstructionStep = true;
  660. break;
  661. default:
  662. // Other meta directives are not implemented
  663. break;
  664. }
  665. }
  666. break;
  667. // Line type 1: Sub-object file
  668. case '1':
  669. colorCode = lp.getToken();
  670. material = getLocalMaterial( colorCode );
  671. const posX = parseFloat( lp.getToken() );
  672. const posY = parseFloat( lp.getToken() );
  673. const posZ = parseFloat( lp.getToken() );
  674. const m0 = parseFloat( lp.getToken() );
  675. const m1 = parseFloat( lp.getToken() );
  676. const m2 = parseFloat( lp.getToken() );
  677. const m3 = parseFloat( lp.getToken() );
  678. const m4 = parseFloat( lp.getToken() );
  679. const m5 = parseFloat( lp.getToken() );
  680. const m6 = parseFloat( lp.getToken() );
  681. const m7 = parseFloat( lp.getToken() );
  682. const m8 = parseFloat( lp.getToken() );
  683. const matrix = new Matrix4().set(
  684. m0, m1, m2, posX,
  685. m3, m4, m5, posY,
  686. m6, m7, m8, posZ,
  687. 0, 0, 0, 1
  688. );
  689. let fileName = lp.getRemainingString().trim().replace( /\\/g, '/' );
  690. if ( loader.fileMap[ fileName ] ) {
  691. // Found the subobject path in the preloaded file path map
  692. fileName = loader.fileMap[ fileName ];
  693. } else {
  694. // Standardized subfolders
  695. if ( fileName.startsWith( 's/' ) ) {
  696. fileName = 'parts/' + fileName;
  697. } else if ( fileName.startsWith( '48/' ) ) {
  698. fileName = 'p/' + fileName;
  699. }
  700. }
  701. subobjects.push( {
  702. material: material,
  703. colorCode: colorCode,
  704. matrix: matrix,
  705. fileName: fileName,
  706. inverted: bfcInverted,
  707. startingConstructionStep: startingConstructionStep
  708. } );
  709. bfcInverted = false;
  710. break;
  711. // Line type 2: Line segment
  712. case '2':
  713. colorCode = lp.getToken();
  714. material = getLocalMaterial( colorCode );
  715. v0 = lp.getVector();
  716. v1 = lp.getVector();
  717. segment = {
  718. material: material,
  719. colorCode: colorCode,
  720. vertices: [ v0, v1 ],
  721. };
  722. lineSegments.push( segment );
  723. break;
  724. // Line type 5: Conditional Line segment
  725. case '5':
  726. colorCode = lp.getToken();
  727. material = getLocalMaterial( colorCode );
  728. v0 = lp.getVector();
  729. v1 = lp.getVector();
  730. c0 = lp.getVector();
  731. c1 = lp.getVector();
  732. segment = {
  733. material: material,
  734. colorCode: colorCode,
  735. vertices: [ v0, v1 ],
  736. controlPoints: [ c0, c1 ],
  737. };
  738. conditionalSegments.push( segment );
  739. break;
  740. // Line type 3: Triangle
  741. case '3':
  742. colorCode = lp.getToken();
  743. material = getLocalMaterial( colorCode );
  744. ccw = bfcCCW;
  745. doubleSided = ! bfcCertified || ! bfcCull;
  746. if ( ccw === true ) {
  747. v0 = lp.getVector();
  748. v1 = lp.getVector();
  749. v2 = lp.getVector();
  750. } else {
  751. v2 = lp.getVector();
  752. v1 = lp.getVector();
  753. v0 = lp.getVector();
  754. }
  755. faces.push( {
  756. material: material,
  757. colorCode: colorCode,
  758. faceNormal: null,
  759. vertices: [ v0, v1, v2 ],
  760. normals: [ null, null, null ],
  761. } );
  762. totalFaces ++;
  763. if ( doubleSided === true ) {
  764. faces.push( {
  765. material: material,
  766. colorCode: colorCode,
  767. faceNormal: null,
  768. vertices: [ v2, v1, v0 ],
  769. normals: [ null, null, null ],
  770. } );
  771. totalFaces ++;
  772. }
  773. break;
  774. // Line type 4: Quadrilateral
  775. case '4':
  776. colorCode = lp.getToken();
  777. material = getLocalMaterial( colorCode );
  778. ccw = bfcCCW;
  779. doubleSided = ! bfcCertified || ! bfcCull;
  780. if ( ccw === true ) {
  781. v0 = lp.getVector();
  782. v1 = lp.getVector();
  783. v2 = lp.getVector();
  784. v3 = lp.getVector();
  785. } else {
  786. v3 = lp.getVector();
  787. v2 = lp.getVector();
  788. v1 = lp.getVector();
  789. v0 = lp.getVector();
  790. }
  791. // specifically place the triangle diagonal in the v0 and v1 slots so we can
  792. // account for the doubling of vertices later when smoothing normals.
  793. faces.push( {
  794. material: material,
  795. colorCode: colorCode,
  796. faceNormal: null,
  797. vertices: [ v0, v1, v2, v3 ],
  798. normals: [ null, null, null, null ],
  799. } );
  800. totalFaces += 2;
  801. if ( doubleSided === true ) {
  802. faces.push( {
  803. material: material,
  804. colorCode: colorCode,
  805. faceNormal: null,
  806. vertices: [ v3, v2, v1, v0 ],
  807. normals: [ null, null, null, null ],
  808. } );
  809. totalFaces += 2;
  810. }
  811. break;
  812. default:
  813. throw new Error( 'LDrawLoader: Unknown line type "' + lineType + '"' + lp.getLineNumberString() + '.' );
  814. }
  815. }
  816. if ( parsingEmbeddedFiles ) {
  817. this.setData( currentEmbeddedFileName, currentEmbeddedText );
  818. }
  819. return {
  820. faces,
  821. conditionalSegments,
  822. lineSegments,
  823. type,
  824. category,
  825. keywords,
  826. subobjects,
  827. totalFaces,
  828. startingConstructionStep,
  829. materials,
  830. fileName,
  831. group: null
  832. };
  833. }
  834. // returns an (optionally cloned) instance of the data
  835. getData( fileName, clone = true ) {
  836. const key = fileName.toLowerCase();
  837. const result = this._cache[ key ];
  838. if ( result === null || result instanceof Promise ) {
  839. return null;
  840. }
  841. if ( clone ) {
  842. return this.cloneResult( result );
  843. } else {
  844. return result;
  845. }
  846. }
  847. // kicks off a fetch and parse of the requested data if it hasn't already been loaded. Returns when
  848. // the data is ready to use and can be retrieved synchronously with "getData".
  849. async ensureDataLoaded( fileName ) {
  850. const key = fileName.toLowerCase();
  851. if ( ! ( key in this._cache ) ) {
  852. // replace the promise with a copy of the parsed data for immediate processing
  853. this._cache[ key ] = this.fetchData( fileName ).then( text => {
  854. const info = this.parse( text, fileName );
  855. this._cache[ key ] = info;
  856. return info;
  857. } );
  858. }
  859. await this._cache[ key ];
  860. }
  861. // sets the data in the cache from parsed data
  862. setData( fileName, text ) {
  863. const key = fileName.toLowerCase();
  864. this._cache[ key ] = this.parse( text, fileName );
  865. }
  866. }
  867. // returns the material for an associated color code. If the color code is 16 for a face or 24 for
  868. // an edge then the passthroughColorCode is used.
  869. function getMaterialFromCode( colorCode, parentColorCode, materialHierarchy, forEdge ) {
  870. const isPassthrough = ! forEdge && colorCode === MAIN_COLOUR_CODE || forEdge && colorCode === MAIN_EDGE_COLOUR_CODE;
  871. if ( isPassthrough ) {
  872. colorCode = parentColorCode;
  873. }
  874. return materialHierarchy[ colorCode ] || null;
  875. }
  876. // Class used to parse and build LDraw parts as three.js objects and cache them if they're a "Part" type.
  877. class LDrawPartsGeometryCache {
  878. constructor( loader ) {
  879. this.loader = loader;
  880. this.parseCache = new LDrawParsedCache( loader );
  881. this._cache = {};
  882. }
  883. // Convert the given file information into a mesh by processing subobjects.
  884. async processIntoMesh( info ) {
  885. const loader = this.loader;
  886. const parseCache = this.parseCache;
  887. const faceMaterials = new Set();
  888. // Processes the part subobject information to load child parts and merge geometry onto part
  889. // piece object.
  890. const processInfoSubobjects = async ( info, subobject = null ) => {
  891. const subobjects = info.subobjects;
  892. const promises = [];
  893. // Trigger load of all subobjects. If a subobject isn't a primitive then load it as a separate
  894. // group which lets instruction steps apply correctly.
  895. for ( let i = 0, l = subobjects.length; i < l; i ++ ) {
  896. const subobject = subobjects[ i ];
  897. const promise = parseCache.ensureDataLoaded( subobject.fileName ).then( () => {
  898. const subobjectInfo = parseCache.getData( subobject.fileName, false );
  899. if ( ! isPrimitiveType( subobjectInfo.type ) ) {
  900. return this.loadModel( subobject.fileName ).catch( error => {
  901. console.warn( error );
  902. return null;
  903. } );
  904. }
  905. return processInfoSubobjects( parseCache.getData( subobject.fileName ), subobject );
  906. } );
  907. promises.push( promise );
  908. }
  909. const group = new Group();
  910. group.userData.category = info.category;
  911. group.userData.keywords = info.keywords;
  912. info.group = group;
  913. const subobjectInfos = await Promise.all( promises );
  914. for ( let i = 0, l = subobjectInfos.length; i < l; i ++ ) {
  915. const subobject = info.subobjects[ i ];
  916. const subobjectInfo = subobjectInfos[ i ];
  917. if ( subobjectInfo === null ) {
  918. // the subobject failed to load
  919. continue;
  920. }
  921. // if the subobject was loaded as a separate group then apply the parent scopes materials
  922. if ( subobjectInfo.isGroup ) {
  923. const subobjectGroup = subobjectInfo;
  924. subobject.matrix.decompose( subobjectGroup.position, subobjectGroup.quaternion, subobjectGroup.scale );
  925. subobjectGroup.userData.startingConstructionStep = subobject.startingConstructionStep;
  926. subobjectGroup.name = subobject.fileName;
  927. loader.applyMaterialsToMesh( subobjectGroup, subobject.colorCode, info.materials );
  928. group.add( subobjectGroup );
  929. continue;
  930. }
  931. // add the subobject group if it has children in case it has both children and primitives
  932. if ( subobjectInfo.group.children.length ) {
  933. group.add( subobjectInfo.group );
  934. }
  935. // transform the primitives into the local space of the parent piece and append them to
  936. // to the parent primitives list.
  937. const parentLineSegments = info.lineSegments;
  938. const parentConditionalSegments = info.conditionalSegments;
  939. const parentFaces = info.faces;
  940. const lineSegments = subobjectInfo.lineSegments;
  941. const conditionalSegments = subobjectInfo.conditionalSegments;
  942. const faces = subobjectInfo.faces;
  943. const matrix = subobject.matrix;
  944. const inverted = subobject.inverted;
  945. const matrixScaleInverted = matrix.determinant() < 0;
  946. const colorCode = subobject.colorCode;
  947. const lineColorCode = colorCode === MAIN_COLOUR_CODE ? MAIN_EDGE_COLOUR_CODE : colorCode;
  948. for ( let i = 0, l = lineSegments.length; i < l; i ++ ) {
  949. const ls = lineSegments[ i ];
  950. const vertices = ls.vertices;
  951. vertices[ 0 ].applyMatrix4( matrix );
  952. vertices[ 1 ].applyMatrix4( matrix );
  953. ls.colorCode = ls.colorCode === MAIN_EDGE_COLOUR_CODE ? lineColorCode : ls.colorCode;
  954. ls.material = ls.material || getMaterialFromCode( ls.colorCode, ls.colorCode, info.materials, true );
  955. parentLineSegments.push( ls );
  956. }
  957. for ( let i = 0, l = conditionalSegments.length; i < l; i ++ ) {
  958. const os = conditionalSegments[ i ];
  959. const vertices = os.vertices;
  960. const controlPoints = os.controlPoints;
  961. vertices[ 0 ].applyMatrix4( matrix );
  962. vertices[ 1 ].applyMatrix4( matrix );
  963. controlPoints[ 0 ].applyMatrix4( matrix );
  964. controlPoints[ 1 ].applyMatrix4( matrix );
  965. os.colorCode = os.colorCode === MAIN_EDGE_COLOUR_CODE ? lineColorCode : os.colorCode;
  966. os.material = os.material || getMaterialFromCode( os.colorCode, os.colorCode, info.materials, true );
  967. parentConditionalSegments.push( os );
  968. }
  969. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  970. const tri = faces[ i ];
  971. const vertices = tri.vertices;
  972. for ( let i = 0, l = vertices.length; i < l; i ++ ) {
  973. vertices[ i ].applyMatrix4( matrix );
  974. }
  975. tri.colorCode = tri.colorCode === MAIN_COLOUR_CODE ? colorCode : tri.colorCode;
  976. tri.material = tri.material || getMaterialFromCode( tri.colorCode, colorCode, info.materials, false );
  977. faceMaterials.add( tri.colorCode );
  978. // If the scale of the object is negated then the triangle winding order
  979. // needs to be flipped.
  980. if ( matrixScaleInverted !== inverted ) {
  981. vertices.reverse();
  982. }
  983. parentFaces.push( tri );
  984. }
  985. info.totalFaces += subobjectInfo.totalFaces;
  986. }
  987. // Apply the parent subobjects pass through material code to this object. This is done several times due
  988. // to material scoping.
  989. if ( subobject ) {
  990. loader.applyMaterialsToMesh( group, subobject.colorCode, info.materials );
  991. }
  992. return info;
  993. };
  994. // Track material use to see if we need to use the normal smooth slow path for hard edges.
  995. for ( let i = 0, l = info.faces; i < l; i ++ ) {
  996. faceMaterials.add( info.faces[ i ].colorCode );
  997. }
  998. await processInfoSubobjects( info );
  999. if ( loader.smoothNormals ) {
  1000. const checkSubSegments = faceMaterials.size > 1;
  1001. generateFaceNormals( info.faces );
  1002. smoothNormals( info.faces, info.lineSegments, checkSubSegments );
  1003. }
  1004. // Add the primitive objects and metadata.
  1005. const group = info.group;
  1006. if ( info.faces.length > 0 ) {
  1007. group.add( createObject( info.faces, 3, false, info.totalFaces ) );
  1008. }
  1009. if ( info.lineSegments.length > 0 ) {
  1010. group.add( createObject( info.lineSegments, 2 ) );
  1011. }
  1012. if ( info.conditionalSegments.length > 0 ) {
  1013. group.add( createObject( info.conditionalSegments, 2, true ) );
  1014. }
  1015. return group;
  1016. }
  1017. hasCachedModel( fileName ) {
  1018. return fileName !== null && fileName.toLowerCase() in this._cache;
  1019. }
  1020. async getCachedModel( fileName ) {
  1021. if ( fileName !== null && this.hasCachedModel( fileName ) ) {
  1022. const key = fileName.toLowerCase();
  1023. const group = await this._cache[ key ];
  1024. return group.clone();
  1025. } else {
  1026. return null;
  1027. }
  1028. }
  1029. // Loads and parses the model with the given file name. Returns a cached copy if available.
  1030. async loadModel( fileName ) {
  1031. const parseCache = this.parseCache;
  1032. const key = fileName.toLowerCase();
  1033. if ( this.hasCachedModel( fileName ) ) {
  1034. // Return cached model if available.
  1035. return this.getCachedModel( fileName );
  1036. } else {
  1037. // Otherwise parse a new model.
  1038. // Ensure the file data is loaded and pre parsed.
  1039. await parseCache.ensureDataLoaded( fileName );
  1040. const info = parseCache.getData( fileName );
  1041. const promise = this.processIntoMesh( info );
  1042. // Now that the file has loaded it's possible that another part parse has been waiting in parallel
  1043. // so check the cache again to see if it's been added since the last async operation so we don't
  1044. // do unnecessary work.
  1045. if ( this.hasCachedModel( fileName ) ) {
  1046. return this.getCachedModel( fileName );
  1047. }
  1048. // Cache object if it's a part so it can be reused later.
  1049. if ( isPartType( info.type ) ) {
  1050. this._cache[ key ] = promise;
  1051. }
  1052. // return a copy
  1053. const group = await promise;
  1054. return group.clone();
  1055. }
  1056. }
  1057. // parses the given model text into a renderable object. Returns cached copy if available.
  1058. async parseModel( text ) {
  1059. const parseCache = this.parseCache;
  1060. const info = parseCache.parse( text );
  1061. if ( isPartType( info.type ) && this.hasCachedModel( info.fileName ) ) {
  1062. return this.getCachedModel( info.fileName );
  1063. }
  1064. return this.processIntoMesh( info );
  1065. }
  1066. }
  1067. function sortByMaterial( a, b ) {
  1068. if ( a.colorCode === b.colorCode ) {
  1069. return 0;
  1070. }
  1071. if ( a.colorCode < b.colorCode ) {
  1072. return - 1;
  1073. }
  1074. return 1;
  1075. }
  1076. function createObject( elements, elementSize, isConditionalSegments = false, totalElements = null ) {
  1077. // Creates a LineSegments (elementSize = 2) or a Mesh (elementSize = 3 )
  1078. // With per face / segment material, implemented with mesh groups and materials array
  1079. // Sort the faces or line segments by color code to make later the mesh groups
  1080. elements.sort( sortByMaterial );
  1081. if ( totalElements === null ) {
  1082. totalElements = elements.length;
  1083. }
  1084. const positions = new Float32Array( elementSize * totalElements * 3 );
  1085. const normals = elementSize === 3 ? new Float32Array( elementSize * totalElements * 3 ) : null;
  1086. const materials = [];
  1087. const quadArray = new Array( 6 );
  1088. const bufferGeometry = new BufferGeometry();
  1089. let prevMaterial = null;
  1090. let index0 = 0;
  1091. let numGroupVerts = 0;
  1092. let offset = 0;
  1093. for ( let iElem = 0, nElem = elements.length; iElem < nElem; iElem ++ ) {
  1094. const elem = elements[ iElem ];
  1095. let vertices = elem.vertices;
  1096. if ( vertices.length === 4 ) {
  1097. quadArray[ 0 ] = vertices[ 0 ];
  1098. quadArray[ 1 ] = vertices[ 1 ];
  1099. quadArray[ 2 ] = vertices[ 2 ];
  1100. quadArray[ 3 ] = vertices[ 0 ];
  1101. quadArray[ 4 ] = vertices[ 2 ];
  1102. quadArray[ 5 ] = vertices[ 3 ];
  1103. vertices = quadArray;
  1104. }
  1105. for ( let j = 0, l = vertices.length; j < l; j ++ ) {
  1106. const v = vertices[ j ];
  1107. const index = offset + j * 3;
  1108. positions[ index + 0 ] = v.x;
  1109. positions[ index + 1 ] = v.y;
  1110. positions[ index + 2 ] = v.z;
  1111. }
  1112. // create the normals array if this is a set of faces
  1113. if ( elementSize === 3 ) {
  1114. if ( ! elem.faceNormal ) {
  1115. const v0 = vertices[ 0 ];
  1116. const v1 = vertices[ 1 ];
  1117. const v2 = vertices[ 2 ];
  1118. _tempVec0.subVectors( v1, v0 );
  1119. _tempVec1.subVectors( v2, v1 );
  1120. elem.faceNormal = new Vector3()
  1121. .crossVectors( _tempVec0, _tempVec1 )
  1122. .normalize();
  1123. }
  1124. let elemNormals = elem.normals;
  1125. if ( elemNormals.length === 4 ) {
  1126. quadArray[ 0 ] = elemNormals[ 0 ];
  1127. quadArray[ 1 ] = elemNormals[ 1 ];
  1128. quadArray[ 2 ] = elemNormals[ 2 ];
  1129. quadArray[ 3 ] = elemNormals[ 0 ];
  1130. quadArray[ 4 ] = elemNormals[ 2 ];
  1131. quadArray[ 5 ] = elemNormals[ 3 ];
  1132. elemNormals = quadArray;
  1133. }
  1134. for ( let j = 0, l = elemNormals.length; j < l; j ++ ) {
  1135. // use face normal if a vertex normal is not provided
  1136. let n = elem.faceNormal;
  1137. if ( elemNormals[ j ] ) {
  1138. n = elemNormals[ j ].norm;
  1139. }
  1140. const index = offset + j * 3;
  1141. normals[ index + 0 ] = n.x;
  1142. normals[ index + 1 ] = n.y;
  1143. normals[ index + 2 ] = n.z;
  1144. }
  1145. }
  1146. if ( prevMaterial !== elem.colorCode ) {
  1147. if ( prevMaterial !== null ) {
  1148. bufferGeometry.addGroup( index0, numGroupVerts, materials.length - 1 );
  1149. }
  1150. const material = elem.material;
  1151. if ( material !== null ) {
  1152. if ( elementSize === 3 ) {
  1153. materials.push( material );
  1154. } else if ( elementSize === 2 ) {
  1155. if ( material !== null ) {
  1156. if ( isConditionalSegments ) {
  1157. materials.push( material.userData.edgeMaterial.userData.conditionalEdgeMaterial );
  1158. } else {
  1159. materials.push( material.userData.edgeMaterial );
  1160. }
  1161. } else {
  1162. materials.push( null );
  1163. }
  1164. }
  1165. } else {
  1166. // If a material has not been made available yet then keep the color code string in the material array
  1167. // to save the spot for the material once a parent scopes materials are being applied to the object.
  1168. materials.push( elem.colorCode );
  1169. }
  1170. prevMaterial = elem.colorCode;
  1171. index0 = offset / 3;
  1172. numGroupVerts = vertices.length;
  1173. } else {
  1174. numGroupVerts += vertices.length;
  1175. }
  1176. offset += 3 * vertices.length;
  1177. }
  1178. if ( numGroupVerts > 0 ) {
  1179. bufferGeometry.addGroup( index0, Infinity, materials.length - 1 );
  1180. }
  1181. bufferGeometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  1182. if ( normals !== null ) {
  1183. bufferGeometry.setAttribute( 'normal', new BufferAttribute( normals, 3 ) );
  1184. }
  1185. let object3d = null;
  1186. if ( elementSize === 2 ) {
  1187. if ( isConditionalSegments ) {
  1188. object3d = new ConditionalLineSegments( bufferGeometry, materials.length === 1 ? materials[ 0 ] : materials );
  1189. } else {
  1190. object3d = new LineSegments( bufferGeometry, materials.length === 1 ? materials[ 0 ] : materials );
  1191. }
  1192. } else if ( elementSize === 3 ) {
  1193. object3d = new Mesh( bufferGeometry, materials.length === 1 ? materials[ 0 ] : materials );
  1194. }
  1195. if ( isConditionalSegments ) {
  1196. object3d.isConditionalLine = true;
  1197. const controlArray0 = new Float32Array( elements.length * 3 * 2 );
  1198. const controlArray1 = new Float32Array( elements.length * 3 * 2 );
  1199. const directionArray = new Float32Array( elements.length * 3 * 2 );
  1200. for ( let i = 0, l = elements.length; i < l; i ++ ) {
  1201. const os = elements[ i ];
  1202. const vertices = os.vertices;
  1203. const controlPoints = os.controlPoints;
  1204. const c0 = controlPoints[ 0 ];
  1205. const c1 = controlPoints[ 1 ];
  1206. const v0 = vertices[ 0 ];
  1207. const v1 = vertices[ 1 ];
  1208. const index = i * 3 * 2;
  1209. controlArray0[ index + 0 ] = c0.x;
  1210. controlArray0[ index + 1 ] = c0.y;
  1211. controlArray0[ index + 2 ] = c0.z;
  1212. controlArray0[ index + 3 ] = c0.x;
  1213. controlArray0[ index + 4 ] = c0.y;
  1214. controlArray0[ index + 5 ] = c0.z;
  1215. controlArray1[ index + 0 ] = c1.x;
  1216. controlArray1[ index + 1 ] = c1.y;
  1217. controlArray1[ index + 2 ] = c1.z;
  1218. controlArray1[ index + 3 ] = c1.x;
  1219. controlArray1[ index + 4 ] = c1.y;
  1220. controlArray1[ index + 5 ] = c1.z;
  1221. directionArray[ index + 0 ] = v1.x - v0.x;
  1222. directionArray[ index + 1 ] = v1.y - v0.y;
  1223. directionArray[ index + 2 ] = v1.z - v0.z;
  1224. directionArray[ index + 3 ] = v1.x - v0.x;
  1225. directionArray[ index + 4 ] = v1.y - v0.y;
  1226. directionArray[ index + 5 ] = v1.z - v0.z;
  1227. }
  1228. bufferGeometry.setAttribute( 'control0', new BufferAttribute( controlArray0, 3, false ) );
  1229. bufferGeometry.setAttribute( 'control1', new BufferAttribute( controlArray1, 3, false ) );
  1230. bufferGeometry.setAttribute( 'direction', new BufferAttribute( directionArray, 3, false ) );
  1231. }
  1232. return object3d;
  1233. }
  1234. //
  1235. class LDrawLoader extends Loader {
  1236. constructor( manager ) {
  1237. super( manager );
  1238. // Array of THREE.Material
  1239. this.materials = [];
  1240. this.materialLibrary = {};
  1241. // This also allows to handle the embedded text files ("0 FILE" lines)
  1242. this.partsCache = new LDrawPartsGeometryCache( this );
  1243. // This object is a map from file names to paths. It agilizes the paths search. If it is not set then files will be searched by trial and error.
  1244. this.fileMap = {};
  1245. // Initializes the materials library with default materials
  1246. this.setMaterials( [] );
  1247. // If this flag is set to true the vertex normals will be smoothed.
  1248. this.smoothNormals = true;
  1249. // The path to load parts from the LDraw parts library from.
  1250. this.partsLibraryPath = '';
  1251. }
  1252. setPartsLibraryPath( path ) {
  1253. this.partsLibraryPath = path;
  1254. return this;
  1255. }
  1256. async preloadMaterials( url ) {
  1257. const fileLoader = new FileLoader( this.manager );
  1258. fileLoader.setPath( this.path );
  1259. fileLoader.setRequestHeader( this.requestHeader );
  1260. fileLoader.setWithCredentials( this.withCredentials );
  1261. const text = await fileLoader.loadAsync( url );
  1262. const colorLineRegex = /^0 !COLOUR/;
  1263. const lines = text.split( /[\n\r]/g );
  1264. const materials = [];
  1265. for ( let i = 0, l = lines.length; i < l; i ++ ) {
  1266. const line = lines[ i ];
  1267. if ( colorLineRegex.test( line ) ) {
  1268. const directive = line.replace( colorLineRegex, '' );
  1269. const material = this.parseColorMetaDirective( new LineParser( directive ) );
  1270. materials.push( material );
  1271. }
  1272. }
  1273. this.setMaterials( materials );
  1274. }
  1275. load( url, onLoad, onProgress, onError ) {
  1276. const fileLoader = new FileLoader( this.manager );
  1277. fileLoader.setPath( this.path );
  1278. fileLoader.setRequestHeader( this.requestHeader );
  1279. fileLoader.setWithCredentials( this.withCredentials );
  1280. fileLoader.load( url, text => {
  1281. this.partsCache
  1282. .parseModel( text, this.materialLibrary )
  1283. .then( group => {
  1284. this.applyMaterialsToMesh( group, MAIN_COLOUR_CODE, this.materialLibrary, true );
  1285. this.computeConstructionSteps( group );
  1286. onLoad( group );
  1287. } )
  1288. .catch( onError );
  1289. }, onProgress, onError );
  1290. }
  1291. parse( text, onLoad ) {
  1292. this.partsCache
  1293. .parseModel( text, this.materialLibrary )
  1294. .then( group => {
  1295. this.computeConstructionSteps( group );
  1296. onLoad( group );
  1297. } );
  1298. }
  1299. setMaterials( materials ) {
  1300. this.materialLibrary = {};
  1301. this.materials = [];
  1302. for ( let i = 0, l = materials.length; i < l; i ++ ) {
  1303. this.addMaterial( materials[ i ] );
  1304. }
  1305. // Add default main triangle and line edge materials (used in pieces that can be colored with a main color)
  1306. this.addMaterial( this.parseColorMetaDirective( new LineParser( 'Main_Colour CODE 16 VALUE #FF8080 EDGE #333333' ) ) );
  1307. this.addMaterial( this.parseColorMetaDirective( new LineParser( 'Edge_Colour CODE 24 VALUE #A0A0A0 EDGE #333333' ) ) );
  1308. return this;
  1309. }
  1310. setFileMap( fileMap ) {
  1311. this.fileMap = fileMap;
  1312. return this;
  1313. }
  1314. addMaterial( material ) {
  1315. // Adds a material to the material library which is on top of the parse scopes stack. And also to the materials array
  1316. const matLib = this.materialLibrary;
  1317. if ( ! matLib[ material.userData.code ] ) {
  1318. this.materials.push( material );
  1319. matLib[ material.userData.code ] = material;
  1320. }
  1321. return this;
  1322. }
  1323. getMaterial( colorCode ) {
  1324. if ( colorCode.startsWith( '0x2' ) ) {
  1325. // Special 'direct' material value (RGB color)
  1326. const color = colorCode.substring( 3 );
  1327. return this.parseColorMetaDirective( new LineParser( 'Direct_Color_' + color + ' CODE -1 VALUE #' + color + ' EDGE #' + color + '' ) );
  1328. }
  1329. return this.materialLibrary[ colorCode ] || null;
  1330. }
  1331. // Applies the appropriate materials to a prebuilt hierarchy of geometry. Assumes that color codes are present
  1332. // in the material array if they need to be filled in.
  1333. applyMaterialsToMesh( group, parentColorCode, materialHierarchy, finalMaterialPass = false ) {
  1334. // find any missing materials as indicated by a color code string and replace it with a material from the current material lib
  1335. const loader = this;
  1336. const parentIsPassthrough = parentColorCode === MAIN_COLOUR_CODE;
  1337. group.traverse( c => {
  1338. if ( c.isMesh || c.isLineSegments ) {
  1339. if ( Array.isArray( c.material ) ) {
  1340. for ( let i = 0, l = c.material.length; i < l; i ++ ) {
  1341. if ( ! c.material[ i ].isMaterial ) {
  1342. c.material[ i ] = getMaterial( c, c.material[ i ] );
  1343. }
  1344. }
  1345. } else if ( ! c.material.isMaterial ) {
  1346. c.material = getMaterial( c, c.material );
  1347. }
  1348. }
  1349. } );
  1350. // Returns the appropriate material for the object (line or face) given color code. If the code is "pass through"
  1351. // (24 for lines, 16 for edges) then the pass through color code is used. If that is also pass through then it's
  1352. // simply returned for the subsequent material application.
  1353. function getMaterial( c, colorCode ) {
  1354. // if our parent is a passthrough color code and we don't have the current material color available then
  1355. // return early.
  1356. if ( parentIsPassthrough && ! ( colorCode in materialHierarchy ) && ! finalMaterialPass ) {
  1357. return colorCode;
  1358. }
  1359. const forEdge = c.isLineSegments || c.isConditionalLine;
  1360. const isPassthrough = ! forEdge && colorCode === MAIN_COLOUR_CODE || forEdge && colorCode === MAIN_EDGE_COLOUR_CODE;
  1361. if ( isPassthrough ) {
  1362. colorCode = parentColorCode;
  1363. }
  1364. let material = null;
  1365. if ( colorCode in materialHierarchy ) {
  1366. material = materialHierarchy[ colorCode ];
  1367. } else if ( finalMaterialPass ) {
  1368. // see if we can get the final material from from the "getMaterial" function which will attempt to
  1369. // parse the "direct" colors
  1370. material = loader.getMaterial( colorCode );
  1371. if ( material === null ) {
  1372. // otherwise throw an error if this is final opportunity to set the material
  1373. throw new Error( `LDrawLoader: Material properties for code ${ colorCode } not available.` );
  1374. }
  1375. } else {
  1376. return colorCode;
  1377. }
  1378. if ( c.isLineSegments ) {
  1379. material = material.userData.edgeMaterial;
  1380. if ( c.isConditionalLine ) {
  1381. material = material.userData.conditionalEdgeMaterial;
  1382. }
  1383. }
  1384. return material;
  1385. }
  1386. }
  1387. getMainMaterial() {
  1388. return this.getMaterial( MAIN_COLOUR_CODE );
  1389. }
  1390. getMainEdgeMaterial() {
  1391. return this.getMaterial( MAIN_EDGE_COLOUR_CODE );
  1392. }
  1393. parseColorMetaDirective( lineParser ) {
  1394. // Parses a color definition and returns a THREE.Material
  1395. let code = null;
  1396. // Triangle and line colors
  1397. let color = 0xFF00FF;
  1398. let edgeColor = 0xFF00FF;
  1399. // Transparency
  1400. let alpha = 1;
  1401. let isTransparent = false;
  1402. // Self-illumination:
  1403. let luminance = 0;
  1404. let finishType = FINISH_TYPE_DEFAULT;
  1405. let edgeMaterial = null;
  1406. const name = lineParser.getToken();
  1407. if ( ! name ) {
  1408. throw new Error( 'LDrawLoader: Material name was expected after "!COLOUR tag' + lineParser.getLineNumberString() + '.' );
  1409. }
  1410. // Parse tag tokens and their parameters
  1411. let token = null;
  1412. while ( true ) {
  1413. token = lineParser.getToken();
  1414. if ( ! token ) {
  1415. break;
  1416. }
  1417. switch ( token.toUpperCase() ) {
  1418. case 'CODE':
  1419. code = lineParser.getToken();
  1420. break;
  1421. case 'VALUE':
  1422. color = lineParser.getToken();
  1423. if ( color.startsWith( '0x' ) ) {
  1424. color = '#' + color.substring( 2 );
  1425. } else if ( ! color.startsWith( '#' ) ) {
  1426. throw new Error( 'LDrawLoader: Invalid color while parsing material' + lineParser.getLineNumberString() + '.' );
  1427. }
  1428. break;
  1429. case 'EDGE':
  1430. edgeColor = lineParser.getToken();
  1431. if ( edgeColor.startsWith( '0x' ) ) {
  1432. edgeColor = '#' + edgeColor.substring( 2 );
  1433. } else if ( ! edgeColor.startsWith( '#' ) ) {
  1434. // Try to see if edge color is a color code
  1435. edgeMaterial = this.getMaterial( edgeColor );
  1436. if ( ! edgeMaterial ) {
  1437. throw new Error( 'LDrawLoader: Invalid edge color while parsing material' + lineParser.getLineNumberString() + '.' );
  1438. }
  1439. // Get the edge material for this triangle material
  1440. edgeMaterial = edgeMaterial.userData.edgeMaterial;
  1441. }
  1442. break;
  1443. case 'ALPHA':
  1444. alpha = parseInt( lineParser.getToken() );
  1445. if ( isNaN( alpha ) ) {
  1446. throw new Error( 'LDrawLoader: Invalid alpha value in material definition' + lineParser.getLineNumberString() + '.' );
  1447. }
  1448. alpha = Math.max( 0, Math.min( 1, alpha / 255 ) );
  1449. if ( alpha < 1 ) {
  1450. isTransparent = true;
  1451. }
  1452. break;
  1453. case 'LUMINANCE':
  1454. luminance = parseInt( lineParser.getToken() );
  1455. if ( isNaN( luminance ) ) {
  1456. throw new Error( 'LDrawLoader: Invalid luminance value in material definition' + LineParser.getLineNumberString() + '.' );
  1457. }
  1458. luminance = Math.max( 0, Math.min( 1, luminance / 255 ) );
  1459. break;
  1460. case 'CHROME':
  1461. finishType = FINISH_TYPE_CHROME;
  1462. break;
  1463. case 'PEARLESCENT':
  1464. finishType = FINISH_TYPE_PEARLESCENT;
  1465. break;
  1466. case 'RUBBER':
  1467. finishType = FINISH_TYPE_RUBBER;
  1468. break;
  1469. case 'MATTE_METALLIC':
  1470. finishType = FINISH_TYPE_MATTE_METALLIC;
  1471. break;
  1472. case 'METAL':
  1473. finishType = FINISH_TYPE_METAL;
  1474. break;
  1475. case 'MATERIAL':
  1476. // Not implemented
  1477. lineParser.setToEnd();
  1478. break;
  1479. default:
  1480. throw new Error( 'LDrawLoader: Unknown token "' + token + '" while parsing material' + lineParser.getLineNumberString() + '.' );
  1481. }
  1482. }
  1483. let material = null;
  1484. switch ( finishType ) {
  1485. case FINISH_TYPE_DEFAULT:
  1486. material = new MeshStandardMaterial( { color: color, roughness: 0.3, metalness: 0 } );
  1487. break;
  1488. case FINISH_TYPE_PEARLESCENT:
  1489. // Try to imitate pearlescency by making the surface glossy
  1490. material = new MeshStandardMaterial( { color: color, roughness: 0.3, metalness: 0.25 } );
  1491. break;
  1492. case FINISH_TYPE_CHROME:
  1493. // Mirror finish surface
  1494. material = new MeshStandardMaterial( { color: color, roughness: 0, metalness: 1 } );
  1495. break;
  1496. case FINISH_TYPE_RUBBER:
  1497. // Rubber finish
  1498. material = new MeshStandardMaterial( { color: color, roughness: 0.9, metalness: 0 } );
  1499. break;
  1500. case FINISH_TYPE_MATTE_METALLIC:
  1501. // Brushed metal finish
  1502. material = new MeshStandardMaterial( { color: color, roughness: 0.8, metalness: 0.4 } );
  1503. break;
  1504. case FINISH_TYPE_METAL:
  1505. // Average metal finish
  1506. material = new MeshStandardMaterial( { color: color, roughness: 0.2, metalness: 0.85 } );
  1507. break;
  1508. default:
  1509. // Should not happen
  1510. break;
  1511. }
  1512. material.transparent = isTransparent;
  1513. material.premultipliedAlpha = true;
  1514. material.opacity = alpha;
  1515. material.depthWrite = ! isTransparent;
  1516. material.color.convertSRGBToLinear();
  1517. material.polygonOffset = true;
  1518. material.polygonOffsetFactor = 1;
  1519. if ( luminance !== 0 ) {
  1520. material.emissive.set( material.color ).multiplyScalar( luminance );
  1521. }
  1522. if ( ! edgeMaterial ) {
  1523. // This is the material used for edges
  1524. edgeMaterial = new LineBasicMaterial( {
  1525. color: edgeColor,
  1526. transparent: isTransparent,
  1527. opacity: alpha,
  1528. depthWrite: ! isTransparent
  1529. } );
  1530. edgeMaterial.userData.code = code;
  1531. edgeMaterial.name = name + ' - Edge';
  1532. edgeMaterial.color.convertSRGBToLinear();
  1533. // This is the material used for conditional edges
  1534. edgeMaterial.userData.conditionalEdgeMaterial = new LDrawConditionalLineMaterial( {
  1535. fog: true,
  1536. transparent: isTransparent,
  1537. depthWrite: ! isTransparent,
  1538. color: edgeColor,
  1539. opacity: alpha,
  1540. } );
  1541. edgeMaterial.userData.conditionalEdgeMaterial.color.convertSRGBToLinear();
  1542. }
  1543. material.userData.code = code;
  1544. material.name = name;
  1545. material.userData.edgeMaterial = edgeMaterial;
  1546. this.addMaterial( material );
  1547. return material;
  1548. }
  1549. computeConstructionSteps( model ) {
  1550. // Sets userdata.constructionStep number in Group objects and userData.numConstructionSteps number in the root Group object.
  1551. let stepNumber = 0;
  1552. model.traverse( c => {
  1553. if ( c.isGroup ) {
  1554. if ( c.userData.startingConstructionStep ) {
  1555. stepNumber ++;
  1556. }
  1557. c.userData.constructionStep = stepNumber;
  1558. }
  1559. } );
  1560. model.userData.numConstructionSteps = stepNumber + 1;
  1561. }
  1562. }
  1563. export { LDrawLoader };