LDrawLoader.js 56 KB

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