LDrawLoader.js 57 KB

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