LDrawLoader.js 56 KB

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