LDrawLoader.js 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263
  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.startingBuildingStep = original.startingBuildingStep;
  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 startingBuildingStep = 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. startingBuildingStep = 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. startingBuildingStep: startingBuildingStep
  688. } );
  689. startingBuildingStep = false;
  690. bfcInverted = false;
  691. break;
  692. // Line type 2: Line segment
  693. case '2':
  694. colorCode = lp.getToken();
  695. material = getLocalMaterial( colorCode );
  696. v0 = lp.getVector();
  697. v1 = lp.getVector();
  698. segment = {
  699. material: material,
  700. colorCode: colorCode,
  701. vertices: [ v0, v1 ]
  702. };
  703. lineSegments.push( segment );
  704. break;
  705. // Line type 5: Conditional Line segment
  706. case '5':
  707. colorCode = lp.getToken();
  708. material = getLocalMaterial( colorCode );
  709. v0 = lp.getVector();
  710. v1 = lp.getVector();
  711. c0 = lp.getVector();
  712. c1 = lp.getVector();
  713. segment = {
  714. material: material,
  715. colorCode: colorCode,
  716. vertices: [ v0, v1 ],
  717. controlPoints: [ c0, c1 ]
  718. };
  719. conditionalSegments.push( segment );
  720. break;
  721. // Line type 3: Triangle
  722. case '3':
  723. colorCode = lp.getToken();
  724. material = getLocalMaterial( colorCode );
  725. ccw = bfcCCW;
  726. doubleSided = ! bfcCertified || ! bfcCull;
  727. if ( ccw === true ) {
  728. v0 = lp.getVector();
  729. v1 = lp.getVector();
  730. v2 = lp.getVector();
  731. } else {
  732. v2 = lp.getVector();
  733. v1 = lp.getVector();
  734. v0 = lp.getVector();
  735. }
  736. faces.push( {
  737. material: material,
  738. colorCode: colorCode,
  739. faceNormal: null,
  740. vertices: [ v0, v1, v2 ],
  741. normals: [ null, null, null ]
  742. } );
  743. totalFaces ++;
  744. if ( doubleSided === true ) {
  745. faces.push( {
  746. material: material,
  747. colorCode: colorCode,
  748. faceNormal: null,
  749. vertices: [ v2, v1, v0 ],
  750. normals: [ null, null, null ]
  751. } );
  752. totalFaces ++;
  753. }
  754. break;
  755. // Line type 4: Quadrilateral
  756. case '4':
  757. colorCode = lp.getToken();
  758. material = getLocalMaterial( colorCode );
  759. ccw = bfcCCW;
  760. doubleSided = ! bfcCertified || ! bfcCull;
  761. if ( ccw === true ) {
  762. v0 = lp.getVector();
  763. v1 = lp.getVector();
  764. v2 = lp.getVector();
  765. v3 = lp.getVector();
  766. } else {
  767. v3 = lp.getVector();
  768. v2 = lp.getVector();
  769. v1 = lp.getVector();
  770. v0 = lp.getVector();
  771. }
  772. // specifically place the triangle diagonal in the v0 and v1 slots so we can
  773. // account for the doubling of vertices later when smoothing normals.
  774. faces.push( {
  775. material: material,
  776. colorCode: colorCode,
  777. faceNormal: null,
  778. vertices: [ v0, v1, v2, v3 ],
  779. normals: [ null, null, null, null ]
  780. } );
  781. totalFaces += 2;
  782. if ( doubleSided === true ) {
  783. faces.push( {
  784. material: material,
  785. colorCode: colorCode,
  786. faceNormal: null,
  787. vertices: [ v3, v2, v1, v0 ],
  788. normals: [ null, null, null, null ]
  789. } );
  790. totalFaces += 2;
  791. }
  792. break;
  793. default:
  794. throw new Error( 'LDrawLoader: Unknown line type "' + lineType + '"' + lp.getLineNumberString() + '.' );
  795. }
  796. }
  797. if ( parsingEmbeddedFiles ) {
  798. this.setData( currentEmbeddedFileName, currentEmbeddedText );
  799. }
  800. return {
  801. faces,
  802. conditionalSegments,
  803. lineSegments,
  804. type,
  805. category,
  806. keywords,
  807. author,
  808. subobjects,
  809. totalFaces,
  810. startingBuildingStep,
  811. materials,
  812. fileName,
  813. group: null
  814. };
  815. }
  816. // returns an (optionally cloned) instance of the data
  817. getData( fileName, clone = true ) {
  818. const key = fileName.toLowerCase();
  819. const result = this._cache[ key ];
  820. if ( result === null || result instanceof Promise ) {
  821. return null;
  822. }
  823. if ( clone ) {
  824. return this.cloneResult( result );
  825. } else {
  826. return result;
  827. }
  828. }
  829. // kicks off a fetch and parse of the requested data if it hasn't already been loaded. Returns when
  830. // the data is ready to use and can be retrieved synchronously with "getData".
  831. async ensureDataLoaded( fileName ) {
  832. const key = fileName.toLowerCase();
  833. if ( ! ( key in this._cache ) ) {
  834. // replace the promise with a copy of the parsed data for immediate processing
  835. this._cache[ key ] = this.fetchData( fileName ).then( text => {
  836. const info = this.parse( text, fileName );
  837. this._cache[ key ] = info;
  838. return info;
  839. } );
  840. }
  841. await this._cache[ key ];
  842. }
  843. // sets the data in the cache from parsed data
  844. setData( fileName, text ) {
  845. const key = fileName.toLowerCase();
  846. this._cache[ key ] = this.parse( text, fileName );
  847. }
  848. }
  849. // returns the material for an associated color code. If the color code is 16 for a face or 24 for
  850. // an edge then the passthroughColorCode is used.
  851. function getMaterialFromCode( colorCode, parentColorCode, materialHierarchy, forEdge ) {
  852. const isPassthrough = ! forEdge && colorCode === MAIN_COLOUR_CODE || forEdge && colorCode === MAIN_EDGE_COLOUR_CODE;
  853. if ( isPassthrough ) {
  854. colorCode = parentColorCode;
  855. }
  856. return materialHierarchy[ colorCode ] || null;
  857. }
  858. // Class used to parse and build LDraw parts as three.js objects and cache them if they're a "Part" type.
  859. class LDrawPartsGeometryCache {
  860. constructor( loader ) {
  861. this.loader = loader;
  862. this.parseCache = new LDrawParsedCache( loader );
  863. this._cache = {};
  864. }
  865. // Convert the given file information into a mesh by processing subobjects.
  866. async processIntoMesh( info ) {
  867. const loader = this.loader;
  868. const parseCache = this.parseCache;
  869. const faceMaterials = new Set();
  870. // Processes the part subobject information to load child parts and merge geometry onto part
  871. // piece object.
  872. const processInfoSubobjects = async ( info, subobject = null ) => {
  873. const subobjects = info.subobjects;
  874. const promises = [];
  875. // Trigger load of all subobjects. If a subobject isn't a primitive then load it as a separate
  876. // group which lets instruction steps apply correctly.
  877. for ( let i = 0, l = subobjects.length; i < l; i ++ ) {
  878. const subobject = subobjects[ i ];
  879. const promise = parseCache.ensureDataLoaded( subobject.fileName ).then( () => {
  880. const subobjectInfo = parseCache.getData( subobject.fileName, false );
  881. if ( ! isPrimitiveType( subobjectInfo.type ) ) {
  882. return this.loadModel( subobject.fileName ).catch( error => {
  883. console.warn( error );
  884. return null;
  885. } );
  886. }
  887. return processInfoSubobjects( parseCache.getData( subobject.fileName ), subobject );
  888. } );
  889. promises.push( promise );
  890. }
  891. const group = new THREE.Group();
  892. group.userData.category = info.category;
  893. group.userData.keywords = info.keywords;
  894. group.userData.author = info.author;
  895. group.userData.type = info.type;
  896. group.userData.fileName = info.fileName;
  897. info.group = group;
  898. const subobjectInfos = await Promise.all( promises );
  899. for ( let i = 0, l = subobjectInfos.length; i < l; i ++ ) {
  900. const subobject = info.subobjects[ i ];
  901. const subobjectInfo = subobjectInfos[ i ];
  902. if ( subobjectInfo === null ) {
  903. // the subobject failed to load
  904. continue;
  905. }
  906. // if the subobject was loaded as a separate group then apply the parent scopes materials
  907. if ( subobjectInfo.isGroup ) {
  908. const subobjectGroup = subobjectInfo;
  909. subobject.matrix.decompose( subobjectGroup.position, subobjectGroup.quaternion, subobjectGroup.scale );
  910. subobjectGroup.userData.startingBuildingStep = subobject.startingBuildingStep;
  911. subobjectGroup.name = subobject.fileName;
  912. loader.applyMaterialsToMesh( subobjectGroup, subobject.colorCode, info.materials );
  913. subobjectGroup.userData.colorCode = subobject.colorCode;
  914. group.add( subobjectGroup );
  915. continue;
  916. }
  917. // add the subobject group if it has children in case it has both children and primitives
  918. if ( subobjectInfo.group.children.length ) {
  919. group.add( subobjectInfo.group );
  920. }
  921. // transform the primitives into the local space of the parent piece and append them to
  922. // to the parent primitives list.
  923. const parentLineSegments = info.lineSegments;
  924. const parentConditionalSegments = info.conditionalSegments;
  925. const parentFaces = info.faces;
  926. const lineSegments = subobjectInfo.lineSegments;
  927. const conditionalSegments = subobjectInfo.conditionalSegments;
  928. const faces = subobjectInfo.faces;
  929. const matrix = subobject.matrix;
  930. const inverted = subobject.inverted;
  931. const matrixScaleInverted = matrix.determinant() < 0;
  932. const colorCode = subobject.colorCode;
  933. const lineColorCode = colorCode === MAIN_COLOUR_CODE ? MAIN_EDGE_COLOUR_CODE : colorCode;
  934. for ( let i = 0, l = lineSegments.length; i < l; i ++ ) {
  935. const ls = lineSegments[ i ];
  936. const vertices = ls.vertices;
  937. vertices[ 0 ].applyMatrix4( matrix );
  938. vertices[ 1 ].applyMatrix4( matrix );
  939. ls.colorCode = ls.colorCode === MAIN_EDGE_COLOUR_CODE ? lineColorCode : ls.colorCode;
  940. ls.material = ls.material || getMaterialFromCode( ls.colorCode, ls.colorCode, info.materials, true );
  941. parentLineSegments.push( ls );
  942. }
  943. for ( let i = 0, l = conditionalSegments.length; i < l; i ++ ) {
  944. const os = conditionalSegments[ i ];
  945. const vertices = os.vertices;
  946. const controlPoints = os.controlPoints;
  947. vertices[ 0 ].applyMatrix4( matrix );
  948. vertices[ 1 ].applyMatrix4( matrix );
  949. controlPoints[ 0 ].applyMatrix4( matrix );
  950. controlPoints[ 1 ].applyMatrix4( matrix );
  951. os.colorCode = os.colorCode === MAIN_EDGE_COLOUR_CODE ? lineColorCode : os.colorCode;
  952. os.material = os.material || getMaterialFromCode( os.colorCode, os.colorCode, info.materials, true );
  953. parentConditionalSegments.push( os );
  954. }
  955. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  956. const tri = faces[ i ];
  957. const vertices = tri.vertices;
  958. for ( let i = 0, l = vertices.length; i < l; i ++ ) {
  959. vertices[ i ].applyMatrix4( matrix );
  960. }
  961. tri.colorCode = tri.colorCode === MAIN_COLOUR_CODE ? colorCode : tri.colorCode;
  962. tri.material = tri.material || getMaterialFromCode( tri.colorCode, colorCode, info.materials, false );
  963. faceMaterials.add( tri.colorCode );
  964. // If the scale of the object is negated then the triangle winding order
  965. // needs to be flipped.
  966. if ( matrixScaleInverted !== inverted ) {
  967. vertices.reverse();
  968. }
  969. parentFaces.push( tri );
  970. }
  971. info.totalFaces += subobjectInfo.totalFaces;
  972. }
  973. // Apply the parent subobjects pass through material code to this object. This is done several times due
  974. // to material scoping.
  975. if ( subobject ) {
  976. loader.applyMaterialsToMesh( group, subobject.colorCode, info.materials );
  977. group.userData.colorCode = subobject.colorCode;
  978. }
  979. return info;
  980. };
  981. // Track material use to see if we need to use the normal smooth slow path for hard edges.
  982. for ( let i = 0, l = info.faces; i < l; i ++ ) {
  983. faceMaterials.add( info.faces[ i ].colorCode );
  984. }
  985. await processInfoSubobjects( info );
  986. if ( loader.smoothNormals ) {
  987. const checkSubSegments = faceMaterials.size > 1;
  988. generateFaceNormals( info.faces );
  989. smoothNormals( info.faces, info.lineSegments, checkSubSegments );
  990. }
  991. // Add the primitive objects and metadata.
  992. const group = info.group;
  993. if ( info.faces.length > 0 ) {
  994. group.add( createObject( info.faces, 3, false, info.totalFaces ) );
  995. }
  996. if ( info.lineSegments.length > 0 ) {
  997. group.add( createObject( info.lineSegments, 2 ) );
  998. }
  999. if ( info.conditionalSegments.length > 0 ) {
  1000. group.add( createObject( info.conditionalSegments, 2, true ) );
  1001. }
  1002. return group;
  1003. }
  1004. hasCachedModel( fileName ) {
  1005. return fileName !== null && fileName.toLowerCase() in this._cache;
  1006. }
  1007. async getCachedModel( fileName ) {
  1008. if ( fileName !== null && this.hasCachedModel( fileName ) ) {
  1009. const key = fileName.toLowerCase();
  1010. const group = await this._cache[ key ];
  1011. return group.clone();
  1012. } else {
  1013. return null;
  1014. }
  1015. }
  1016. // Loads and parses the model with the given file name. Returns a cached copy if available.
  1017. async loadModel( fileName ) {
  1018. const parseCache = this.parseCache;
  1019. const key = fileName.toLowerCase();
  1020. if ( this.hasCachedModel( fileName ) ) {
  1021. // Return cached model if available.
  1022. return this.getCachedModel( fileName );
  1023. } else {
  1024. // Otherwise parse a new model.
  1025. // Ensure the file data is loaded and pre parsed.
  1026. await parseCache.ensureDataLoaded( fileName );
  1027. const info = parseCache.getData( fileName );
  1028. const promise = this.processIntoMesh( info );
  1029. // Now that the file has loaded it's possible that another part parse has been waiting in parallel
  1030. // so check the cache again to see if it's been added since the last async operation so we don't
  1031. // do unnecessary work.
  1032. if ( this.hasCachedModel( fileName ) ) {
  1033. return this.getCachedModel( fileName );
  1034. }
  1035. // Cache object if it's a part so it can be reused later.
  1036. if ( isPartType( info.type ) ) {
  1037. this._cache[ key ] = promise;
  1038. }
  1039. // return a copy
  1040. const group = await promise;
  1041. return group.clone();
  1042. }
  1043. }
  1044. // parses the given model text into a renderable object. Returns cached copy if available.
  1045. async parseModel( text ) {
  1046. const parseCache = this.parseCache;
  1047. const info = parseCache.parse( text );
  1048. if ( isPartType( info.type ) && this.hasCachedModel( info.fileName ) ) {
  1049. return this.getCachedModel( info.fileName );
  1050. }
  1051. return this.processIntoMesh( info );
  1052. }
  1053. }
  1054. function sortByMaterial( a, b ) {
  1055. if ( a.colorCode === b.colorCode ) {
  1056. return 0;
  1057. }
  1058. if ( a.colorCode < b.colorCode ) {
  1059. return - 1;
  1060. }
  1061. return 1;
  1062. }
  1063. function createObject( elements, elementSize, isConditionalSegments = false, totalElements = null ) {
  1064. // Creates a THREE.LineSegments (elementSize = 2) or a THREE.Mesh (elementSize = 3 )
  1065. // With per face / segment material, implemented with mesh groups and materials array
  1066. // Sort the faces or line segments by color code to make later the mesh groups
  1067. elements.sort( sortByMaterial );
  1068. if ( totalElements === null ) {
  1069. totalElements = elements.length;
  1070. }
  1071. const positions = new Float32Array( elementSize * totalElements * 3 );
  1072. const normals = elementSize === 3 ? new Float32Array( elementSize * totalElements * 3 ) : null;
  1073. const materials = [];
  1074. const quadArray = new Array( 6 );
  1075. const bufferGeometry = new THREE.BufferGeometry();
  1076. let prevMaterial = null;
  1077. let index0 = 0;
  1078. let numGroupVerts = 0;
  1079. let offset = 0;
  1080. for ( let iElem = 0, nElem = elements.length; iElem < nElem; iElem ++ ) {
  1081. const elem = elements[ iElem ];
  1082. let vertices = elem.vertices;
  1083. if ( vertices.length === 4 ) {
  1084. quadArray[ 0 ] = vertices[ 0 ];
  1085. quadArray[ 1 ] = vertices[ 1 ];
  1086. quadArray[ 2 ] = vertices[ 2 ];
  1087. quadArray[ 3 ] = vertices[ 0 ];
  1088. quadArray[ 4 ] = vertices[ 2 ];
  1089. quadArray[ 5 ] = vertices[ 3 ];
  1090. vertices = quadArray;
  1091. }
  1092. for ( let j = 0, l = vertices.length; j < l; j ++ ) {
  1093. const v = vertices[ j ];
  1094. const index = offset + j * 3;
  1095. positions[ index + 0 ] = v.x;
  1096. positions[ index + 1 ] = v.y;
  1097. positions[ index + 2 ] = v.z;
  1098. }
  1099. // create the normals array if this is a set of faces
  1100. if ( elementSize === 3 ) {
  1101. if ( ! elem.faceNormal ) {
  1102. const v0 = vertices[ 0 ];
  1103. const v1 = vertices[ 1 ];
  1104. const v2 = vertices[ 2 ];
  1105. _tempVec0.subVectors( v1, v0 );
  1106. _tempVec1.subVectors( v2, v1 );
  1107. elem.faceNormal = new THREE.Vector3().crossVectors( _tempVec0, _tempVec1 ).normalize();
  1108. }
  1109. let elemNormals = elem.normals;
  1110. if ( elemNormals.length === 4 ) {
  1111. quadArray[ 0 ] = elemNormals[ 0 ];
  1112. quadArray[ 1 ] = elemNormals[ 1 ];
  1113. quadArray[ 2 ] = elemNormals[ 2 ];
  1114. quadArray[ 3 ] = elemNormals[ 0 ];
  1115. quadArray[ 4 ] = elemNormals[ 2 ];
  1116. quadArray[ 5 ] = elemNormals[ 3 ];
  1117. elemNormals = quadArray;
  1118. }
  1119. for ( let j = 0, l = elemNormals.length; j < l; j ++ ) {
  1120. // use face normal if a vertex normal is not provided
  1121. let n = elem.faceNormal;
  1122. if ( elemNormals[ j ] ) {
  1123. n = elemNormals[ j ].norm;
  1124. }
  1125. const index = offset + j * 3;
  1126. normals[ index + 0 ] = n.x;
  1127. normals[ index + 1 ] = n.y;
  1128. normals[ index + 2 ] = n.z;
  1129. }
  1130. }
  1131. if ( prevMaterial !== elem.colorCode ) {
  1132. if ( prevMaterial !== null ) {
  1133. bufferGeometry.addGroup( index0, numGroupVerts, materials.length - 1 );
  1134. }
  1135. const material = elem.material;
  1136. if ( material !== null ) {
  1137. if ( elementSize === 3 ) {
  1138. materials.push( material );
  1139. } else if ( elementSize === 2 ) {
  1140. if ( isConditionalSegments ) {
  1141. materials.push( material.userData.edgeMaterial.userData.conditionalEdgeMaterial );
  1142. } else {
  1143. materials.push( material.userData.edgeMaterial );
  1144. }
  1145. }
  1146. } else {
  1147. // If a material has not been made available yet then keep the color code string in the material array
  1148. // to save the spot for the material once a parent scopes materials are being applied to the object.
  1149. materials.push( elem.colorCode );
  1150. }
  1151. prevMaterial = elem.colorCode;
  1152. index0 = offset / 3;
  1153. numGroupVerts = vertices.length;
  1154. } else {
  1155. numGroupVerts += vertices.length;
  1156. }
  1157. offset += 3 * vertices.length;
  1158. }
  1159. if ( numGroupVerts > 0 ) {
  1160. bufferGeometry.addGroup( index0, Infinity, materials.length - 1 );
  1161. }
  1162. bufferGeometry.setAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) );
  1163. if ( normals !== null ) {
  1164. bufferGeometry.setAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) );
  1165. }
  1166. let object3d = null;
  1167. if ( elementSize === 2 ) {
  1168. if ( isConditionalSegments ) {
  1169. object3d = new ConditionalLineSegments( bufferGeometry, materials.length === 1 ? materials[ 0 ] : materials );
  1170. } else {
  1171. object3d = new THREE.LineSegments( bufferGeometry, materials.length === 1 ? materials[ 0 ] : materials );
  1172. }
  1173. } else if ( elementSize === 3 ) {
  1174. object3d = new THREE.Mesh( bufferGeometry, materials.length === 1 ? materials[ 0 ] : materials );
  1175. }
  1176. if ( isConditionalSegments ) {
  1177. object3d.isConditionalLine = true;
  1178. const controlArray0 = new Float32Array( elements.length * 3 * 2 );
  1179. const controlArray1 = new Float32Array( elements.length * 3 * 2 );
  1180. const directionArray = new Float32Array( elements.length * 3 * 2 );
  1181. for ( let i = 0, l = elements.length; i < l; i ++ ) {
  1182. const os = elements[ i ];
  1183. const vertices = os.vertices;
  1184. const controlPoints = os.controlPoints;
  1185. const c0 = controlPoints[ 0 ];
  1186. const c1 = controlPoints[ 1 ];
  1187. const v0 = vertices[ 0 ];
  1188. const v1 = vertices[ 1 ];
  1189. const index = i * 3 * 2;
  1190. controlArray0[ index + 0 ] = c0.x;
  1191. controlArray0[ index + 1 ] = c0.y;
  1192. controlArray0[ index + 2 ] = c0.z;
  1193. controlArray0[ index + 3 ] = c0.x;
  1194. controlArray0[ index + 4 ] = c0.y;
  1195. controlArray0[ index + 5 ] = c0.z;
  1196. controlArray1[ index + 0 ] = c1.x;
  1197. controlArray1[ index + 1 ] = c1.y;
  1198. controlArray1[ index + 2 ] = c1.z;
  1199. controlArray1[ index + 3 ] = c1.x;
  1200. controlArray1[ index + 4 ] = c1.y;
  1201. controlArray1[ index + 5 ] = c1.z;
  1202. directionArray[ index + 0 ] = v1.x - v0.x;
  1203. directionArray[ index + 1 ] = v1.y - v0.y;
  1204. directionArray[ index + 2 ] = v1.z - v0.z;
  1205. directionArray[ index + 3 ] = v1.x - v0.x;
  1206. directionArray[ index + 4 ] = v1.y - v0.y;
  1207. directionArray[ index + 5 ] = v1.z - v0.z;
  1208. }
  1209. bufferGeometry.setAttribute( 'control0', new THREE.BufferAttribute( controlArray0, 3, false ) );
  1210. bufferGeometry.setAttribute( 'control1', new THREE.BufferAttribute( controlArray1, 3, false ) );
  1211. bufferGeometry.setAttribute( 'direction', new THREE.BufferAttribute( directionArray, 3, false ) );
  1212. }
  1213. return object3d;
  1214. }
  1215. //
  1216. class LDrawLoader extends THREE.Loader {
  1217. constructor( manager ) {
  1218. super( manager );
  1219. // Array of THREE.Material
  1220. this.materials = [];
  1221. this.materialLibrary = {};
  1222. // This also allows to handle the embedded text files ("0 FILE" lines)
  1223. this.partsCache = new LDrawPartsGeometryCache( this );
  1224. // 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.
  1225. this.fileMap = {};
  1226. // Initializes the materials library with default materials
  1227. this.setMaterials( [] );
  1228. // If this flag is set to true the vertex normals will be smoothed.
  1229. this.smoothNormals = true;
  1230. // The path to load parts from the LDraw parts library from.
  1231. this.partsLibraryPath = '';
  1232. // Material assigned to not available colors for meshes and edges
  1233. this.missingColorMaterial = new THREE.MeshStandardMaterial( {
  1234. color: 0xFF00FF,
  1235. roughness: 0.3,
  1236. metalness: 0
  1237. } );
  1238. this.missingColorMaterial.name = 'Missing material';
  1239. this.missingEdgeColorMaterial = new THREE.LineBasicMaterial( {
  1240. color: 0xFF00FF
  1241. } );
  1242. this.missingEdgeColorMaterial.name = 'Missing material - Edge';
  1243. this.missingConditionalEdgeColorMaterial = new LDrawConditionalLineMaterial( {
  1244. fog: true,
  1245. color: 0xFF00FF
  1246. } );
  1247. this.missingConditionalEdgeColorMaterial.name = 'Missing material - Conditional Edge';
  1248. this.missingColorMaterial.userData.edgeMaterial = this.missingEdgeColorMaterial;
  1249. this.missingEdgeColorMaterial.userData.conditionalEdgeMaterial = this.missingConditionalEdgeColorMaterial;
  1250. }
  1251. setPartsLibraryPath( path ) {
  1252. this.partsLibraryPath = path;
  1253. return this;
  1254. }
  1255. async preloadMaterials( url ) {
  1256. const fileLoader = new THREE.FileLoader( this.manager );
  1257. fileLoader.setPath( this.path );
  1258. fileLoader.setRequestHeader( this.requestHeader );
  1259. fileLoader.setWithCredentials( this.withCredentials );
  1260. const text = await fileLoader.loadAsync( url );
  1261. const colorLineRegex = /^0 !COLOUR/;
  1262. const lines = text.split( /[\n\r]/g );
  1263. const materials = [];
  1264. for ( let i = 0, l = lines.length; i < l; i ++ ) {
  1265. const line = lines[ i ];
  1266. if ( colorLineRegex.test( line ) ) {
  1267. const directive = line.replace( colorLineRegex, '' );
  1268. const material = this.parseColorMetaDirective( new LineParser( directive ) );
  1269. materials.push( material );
  1270. }
  1271. }
  1272. this.setMaterials( materials );
  1273. }
  1274. load( url, onLoad, onProgress, onError ) {
  1275. const fileLoader = new THREE.FileLoader( this.manager );
  1276. fileLoader.setPath( this.path );
  1277. fileLoader.setRequestHeader( this.requestHeader );
  1278. fileLoader.setWithCredentials( this.withCredentials );
  1279. fileLoader.load( url, text => {
  1280. this.partsCache.parseModel( text, this.materialLibrary ).then( group => {
  1281. this.applyMaterialsToMesh( group, MAIN_COLOUR_CODE, this.materialLibrary, true );
  1282. this.computeBuildingSteps( group );
  1283. group.userData.fileName = url;
  1284. onLoad( group );
  1285. } ).catch( onError );
  1286. }, onProgress, onError );
  1287. }
  1288. parse( text, onLoad ) {
  1289. this.partsCache.parseModel( text, this.materialLibrary ).then( group => {
  1290. this.applyMaterialsToMesh( group, MAIN_COLOUR_CODE, this.materialLibrary, true );
  1291. this.computeBuildingSteps( group );
  1292. group.userData.fileName = '';
  1293. onLoad( group );
  1294. } );
  1295. }
  1296. setMaterials( materials ) {
  1297. this.materialLibrary = {};
  1298. this.materials = [];
  1299. for ( let i = 0, l = materials.length; i < l; i ++ ) {
  1300. this.addMaterial( materials[ i ] );
  1301. }
  1302. // Add default main triangle and line edge materials (used in pieces that can be colored with a main color)
  1303. this.addMaterial( this.parseColorMetaDirective( new LineParser( 'Main_Colour CODE 16 VALUE #FF8080 EDGE #333333' ) ) );
  1304. this.addMaterial( this.parseColorMetaDirective( new LineParser( 'Edge_Colour CODE 24 VALUE #A0A0A0 EDGE #333333' ) ) );
  1305. return this;
  1306. }
  1307. setFileMap( fileMap ) {
  1308. this.fileMap = fileMap;
  1309. return this;
  1310. }
  1311. addMaterial( material ) {
  1312. // Adds a material to the material library which is on top of the parse scopes stack. And also to the materials array
  1313. const matLib = this.materialLibrary;
  1314. if ( ! matLib[ material.userData.code ] ) {
  1315. this.materials.push( material );
  1316. matLib[ material.userData.code ] = material;
  1317. }
  1318. return this;
  1319. }
  1320. getMaterial( colorCode ) {
  1321. if ( colorCode.startsWith( '0x2' ) ) {
  1322. // Special 'direct' material value (RGB color)
  1323. const color = colorCode.substring( 3 );
  1324. return this.parseColorMetaDirective( new LineParser( 'Direct_Color_' + color + ' CODE -1 VALUE #' + color + ' EDGE #' + color + '' ) );
  1325. }
  1326. return this.materialLibrary[ colorCode ] || null;
  1327. }
  1328. // Applies the appropriate materials to a prebuilt hierarchy of geometry. Assumes that color codes are present
  1329. // in the material array if they need to be filled in.
  1330. applyMaterialsToMesh( group, parentColorCode, materialHierarchy, finalMaterialPass = false ) {
  1331. // find any missing materials as indicated by a color code string and replace it with a material from the current material lib
  1332. const loader = this;
  1333. const parentIsPassthrough = parentColorCode === MAIN_COLOUR_CODE;
  1334. group.traverse( c => {
  1335. if ( c.isMesh || c.isLineSegments ) {
  1336. if ( Array.isArray( c.material ) ) {
  1337. for ( let i = 0, l = c.material.length; i < l; i ++ ) {
  1338. if ( ! c.material[ i ].isMaterial ) {
  1339. c.material[ i ] = getMaterial( c, c.material[ i ] );
  1340. }
  1341. }
  1342. } else if ( ! c.material.isMaterial ) {
  1343. c.material = getMaterial( c, c.material );
  1344. }
  1345. }
  1346. } );
  1347. // Returns the appropriate material for the object (line or face) given color code. If the code is "pass through"
  1348. // (24 for lines, 16 for edges) then the pass through color code is used. If that is also pass through then it's
  1349. // simply returned for the subsequent material application.
  1350. function getMaterial( c, colorCode ) {
  1351. // if our parent is a passthrough color code and we don't have the current material color available then
  1352. // return early.
  1353. if ( parentIsPassthrough && ! ( colorCode in materialHierarchy ) && ! finalMaterialPass ) {
  1354. return colorCode;
  1355. }
  1356. const forEdge = c.isLineSegments || c.isConditionalLine;
  1357. const isPassthrough = ! forEdge && colorCode === MAIN_COLOUR_CODE || forEdge && colorCode === MAIN_EDGE_COLOUR_CODE;
  1358. if ( isPassthrough ) {
  1359. colorCode = parentColorCode;
  1360. }
  1361. let material = null;
  1362. if ( colorCode in materialHierarchy ) {
  1363. material = materialHierarchy[ colorCode ];
  1364. } else if ( finalMaterialPass ) {
  1365. // see if we can get the final material from from the "getMaterial" function which will attempt to
  1366. // parse the "direct" colors
  1367. material = loader.getMaterial( colorCode );
  1368. if ( material === null ) {
  1369. // otherwise throw a warning if this is final opportunity to set the material
  1370. console.warn( `LDrawLoader: Material properties for code ${colorCode} not available.` );
  1371. // And return the 'missing color' material
  1372. material = loader.missingColorMaterial;
  1373. }
  1374. } else {
  1375. return colorCode;
  1376. }
  1377. if ( c.isLineSegments ) {
  1378. material = material.userData.edgeMaterial;
  1379. if ( c.isConditionalLine ) {
  1380. material = material.userData.conditionalEdgeMaterial;
  1381. }
  1382. }
  1383. return material;
  1384. }
  1385. }
  1386. getMainMaterial() {
  1387. return this.getMaterial( MAIN_COLOUR_CODE );
  1388. }
  1389. getMainEdgeMaterial() {
  1390. const mat = this.getMaterial( MAIN_EDGE_COLOUR_CODE );
  1391. return mat ? mat.userData.edgeMaterial : null;
  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. if ( ! parseLuminance( token ) ) {
  1418. switch ( token.toUpperCase() ) {
  1419. case 'CODE':
  1420. code = lineParser.getToken();
  1421. break;
  1422. case 'VALUE':
  1423. color = lineParser.getToken();
  1424. if ( color.startsWith( '0x' ) ) {
  1425. color = '#' + color.substring( 2 );
  1426. } else if ( ! color.startsWith( '#' ) ) {
  1427. throw new Error( 'LDrawLoader: Invalid color while parsing material' + lineParser.getLineNumberString() + '.' );
  1428. }
  1429. break;
  1430. case 'EDGE':
  1431. edgeColor = lineParser.getToken();
  1432. if ( edgeColor.startsWith( '0x' ) ) {
  1433. edgeColor = '#' + edgeColor.substring( 2 );
  1434. } else if ( ! edgeColor.startsWith( '#' ) ) {
  1435. // Try to see if edge color is a color code
  1436. edgeMaterial = this.getMaterial( edgeColor );
  1437. if ( ! edgeMaterial ) {
  1438. throw new Error( 'LDrawLoader: Invalid edge color while parsing material' + lineParser.getLineNumberString() + '.' );
  1439. }
  1440. // Get the edge material for this triangle material
  1441. edgeMaterial = edgeMaterial.userData.edgeMaterial;
  1442. }
  1443. break;
  1444. case 'ALPHA':
  1445. alpha = parseInt( lineParser.getToken() );
  1446. if ( isNaN( alpha ) ) {
  1447. throw new Error( 'LDrawLoader: Invalid alpha value in material definition' + lineParser.getLineNumberString() + '.' );
  1448. }
  1449. alpha = Math.max( 0, Math.min( 1, alpha / 255 ) );
  1450. if ( alpha < 1 ) {
  1451. isTransparent = true;
  1452. }
  1453. break;
  1454. case 'LUMINANCE':
  1455. if ( ! parseLuminance( lineParser.getToken() ) ) {
  1456. throw new Error( 'LDrawLoader: Invalid luminance value in material definition' + LineParser.getLineNumberString() + '.' );
  1457. }
  1458. break;
  1459. case 'CHROME':
  1460. finishType = FINISH_TYPE_CHROME;
  1461. break;
  1462. case 'PEARLESCENT':
  1463. finishType = FINISH_TYPE_PEARLESCENT;
  1464. break;
  1465. case 'RUBBER':
  1466. finishType = FINISH_TYPE_RUBBER;
  1467. break;
  1468. case 'MATTE_METALLIC':
  1469. finishType = FINISH_TYPE_MATTE_METALLIC;
  1470. break;
  1471. case 'METAL':
  1472. finishType = FINISH_TYPE_METAL;
  1473. break;
  1474. case 'MATERIAL':
  1475. // Not implemented
  1476. lineParser.setToEnd();
  1477. break;
  1478. default:
  1479. throw new Error( 'LDrawLoader: Unknown token "' + token + '" while parsing material' + lineParser.getLineNumberString() + '.' );
  1480. }
  1481. }
  1482. }
  1483. let material = null;
  1484. switch ( finishType ) {
  1485. case FINISH_TYPE_DEFAULT:
  1486. material = new THREE.MeshStandardMaterial( {
  1487. color: color,
  1488. roughness: 0.3,
  1489. metalness: 0
  1490. } );
  1491. break;
  1492. case FINISH_TYPE_PEARLESCENT:
  1493. // Try to imitate pearlescency by making the surface glossy
  1494. material = new THREE.MeshStandardMaterial( {
  1495. color: color,
  1496. roughness: 0.3,
  1497. metalness: 0.25
  1498. } );
  1499. break;
  1500. case FINISH_TYPE_CHROME:
  1501. // Mirror finish surface
  1502. material = new THREE.MeshStandardMaterial( {
  1503. color: color,
  1504. roughness: 0,
  1505. metalness: 1
  1506. } );
  1507. break;
  1508. case FINISH_TYPE_RUBBER:
  1509. // Rubber finish
  1510. material = new THREE.MeshStandardMaterial( {
  1511. color: color,
  1512. roughness: 0.9,
  1513. metalness: 0
  1514. } );
  1515. break;
  1516. case FINISH_TYPE_MATTE_METALLIC:
  1517. // Brushed metal finish
  1518. material = new THREE.MeshStandardMaterial( {
  1519. color: color,
  1520. roughness: 0.8,
  1521. metalness: 0.4
  1522. } );
  1523. break;
  1524. case FINISH_TYPE_METAL:
  1525. // Average metal finish
  1526. material = new THREE.MeshStandardMaterial( {
  1527. color: color,
  1528. roughness: 0.2,
  1529. metalness: 0.85
  1530. } );
  1531. break;
  1532. default:
  1533. // Should not happen
  1534. break;
  1535. }
  1536. material.transparent = isTransparent;
  1537. material.premultipliedAlpha = true;
  1538. material.opacity = alpha;
  1539. material.depthWrite = ! isTransparent;
  1540. material.color.convertSRGBToLinear();
  1541. material.polygonOffset = true;
  1542. material.polygonOffsetFactor = 1;
  1543. if ( luminance !== 0 ) {
  1544. material.emissive.set( material.color ).multiplyScalar( luminance );
  1545. }
  1546. if ( ! edgeMaterial ) {
  1547. // This is the material used for edges
  1548. edgeMaterial = new THREE.LineBasicMaterial( {
  1549. color: edgeColor,
  1550. transparent: isTransparent,
  1551. opacity: alpha,
  1552. depthWrite: ! isTransparent
  1553. } );
  1554. edgeMaterial.userData.code = code;
  1555. edgeMaterial.name = name + ' - Edge';
  1556. edgeMaterial.color.convertSRGBToLinear();
  1557. // This is the material used for conditional edges
  1558. edgeMaterial.userData.conditionalEdgeMaterial = new LDrawConditionalLineMaterial( {
  1559. fog: true,
  1560. transparent: isTransparent,
  1561. depthWrite: ! isTransparent,
  1562. color: edgeColor,
  1563. opacity: alpha
  1564. } );
  1565. edgeMaterial.userData.conditionalEdgeMaterial.color.convertSRGBToLinear();
  1566. edgeMaterial.userData.conditionalEdgeMaterial.userData.code = code;
  1567. edgeMaterial.userData.conditionalEdgeMaterial.name = name + ' - Conditional Edge';
  1568. }
  1569. material.userData.code = code;
  1570. material.name = name;
  1571. material.userData.edgeMaterial = edgeMaterial;
  1572. this.addMaterial( material );
  1573. return material;
  1574. function parseLuminance( token ) {
  1575. // Returns success
  1576. let lum;
  1577. if ( token.startsWith( 'LUMINANCE' ) ) {
  1578. lum = parseInt( token.substring( 9 ) );
  1579. } else {
  1580. lum = parseInt( token );
  1581. }
  1582. if ( isNaN( lum ) ) {
  1583. return false;
  1584. }
  1585. luminance = Math.max( 0, Math.min( 1, lum / 255 ) );
  1586. return true;
  1587. }
  1588. }
  1589. computeBuildingSteps( model ) {
  1590. // Sets userdata.buildingStep number in THREE.Group objects and userData.numBuildingSteps number in the root THREE.Group object.
  1591. let stepNumber = 0;
  1592. model.traverse( c => {
  1593. if ( c.isGroup ) {
  1594. if ( c.userData.startingBuildingStep ) {
  1595. stepNumber ++;
  1596. }
  1597. c.userData.buildingStep = stepNumber;
  1598. }
  1599. } );
  1600. model.userData.numBuildingSteps = stepNumber + 1;
  1601. }
  1602. }
  1603. THREE.LDrawLoader = LDrawLoader;
  1604. } )();