LDrawLoader.js 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942
  1. ( function () {
  2. // Note: "MATERIAL" tag (e.g. GLITTER, SPECKLE) is not implemented
  3. const FINISH_TYPE_DEFAULT = 0;
  4. const FINISH_TYPE_CHROME = 1;
  5. const FINISH_TYPE_PEARLESCENT = 2;
  6. const FINISH_TYPE_RUBBER = 3;
  7. const FINISH_TYPE_MATTE_METALLIC = 4;
  8. const FINISH_TYPE_METAL = 5; // State machine to search a subobject path.
  9. // The LDraw standard establishes these various possible subfolders.
  10. const FILE_LOCATION_AS_IS = 0;
  11. const FILE_LOCATION_TRY_PARTS = 1;
  12. const FILE_LOCATION_TRY_P = 2;
  13. const FILE_LOCATION_TRY_MODELS = 3;
  14. const FILE_LOCATION_TRY_RELATIVE = 4;
  15. const FILE_LOCATION_TRY_ABSOLUTE = 5;
  16. const FILE_LOCATION_NOT_FOUND = 6;
  17. const _tempVec0 = new THREE.Vector3();
  18. const _tempVec1 = new THREE.Vector3();
  19. class LDrawConditionalLineMaterial extends THREE.ShaderMaterial {
  20. constructor( parameters ) {
  21. super( {
  22. uniforms: THREE.UniformsUtils.merge( [ THREE.UniformsLib.fog, {
  23. diffuse: {
  24. value: new THREE.Color()
  25. },
  26. opacity: {
  27. value: 1.0
  28. }
  29. } ] ),
  30. vertexShader:
  31. /* glsl */
  32. `
  33. attribute vec3 control0;
  34. attribute vec3 control1;
  35. attribute vec3 direction;
  36. varying float discardFlag;
  37. #include <common>
  38. #include <color_pars_vertex>
  39. #include <fog_pars_vertex>
  40. #include <logdepthbuf_pars_vertex>
  41. #include <clipping_planes_pars_vertex>
  42. void main() {
  43. #include <color_vertex>
  44. vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );
  45. gl_Position = projectionMatrix * mvPosition;
  46. // Transform the line segment ends and control points into camera clip space
  47. vec4 c0 = projectionMatrix * modelViewMatrix * vec4( control0, 1.0 );
  48. vec4 c1 = projectionMatrix * modelViewMatrix * vec4( control1, 1.0 );
  49. vec4 p0 = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  50. vec4 p1 = projectionMatrix * modelViewMatrix * vec4( position + direction, 1.0 );
  51. c0.xy /= c0.w;
  52. c1.xy /= c1.w;
  53. p0.xy /= p0.w;
  54. p1.xy /= p1.w;
  55. // Get the direction of the segment and an orthogonal vector
  56. vec2 dir = p1.xy - p0.xy;
  57. vec2 norm = vec2( -dir.y, dir.x );
  58. // Get control point directions from the line
  59. vec2 c0dir = c0.xy - p1.xy;
  60. vec2 c1dir = c1.xy - p1.xy;
  61. // If the vectors to the controls points are pointed in different directions away
  62. // from the line segment then the line should not be drawn.
  63. float d0 = dot( normalize( norm ), normalize( c0dir ) );
  64. float d1 = dot( normalize( norm ), normalize( c1dir ) );
  65. discardFlag = float( sign( d0 ) != sign( d1 ) );
  66. #include <logdepthbuf_vertex>
  67. #include <clipping_planes_vertex>
  68. #include <fog_vertex>
  69. }
  70. `,
  71. fragmentShader:
  72. /* glsl */
  73. `
  74. uniform vec3 diffuse;
  75. uniform float opacity;
  76. varying float discardFlag;
  77. #include <common>
  78. #include <color_pars_fragment>
  79. #include <fog_pars_fragment>
  80. #include <logdepthbuf_pars_fragment>
  81. #include <clipping_planes_pars_fragment>
  82. void main() {
  83. if ( discardFlag > 0.5 ) discard;
  84. #include <clipping_planes_fragment>
  85. vec3 outgoingLight = vec3( 0.0 );
  86. vec4 diffuseColor = vec4( diffuse, opacity );
  87. #include <logdepthbuf_fragment>
  88. #include <color_fragment>
  89. outgoingLight = diffuseColor.rgb; // simple shader
  90. gl_FragColor = vec4( outgoingLight, diffuseColor.a );
  91. #include <tonemapping_fragment>
  92. #include <encodings_fragment>
  93. #include <fog_fragment>
  94. #include <premultiplied_alpha_fragment>
  95. }
  96. `
  97. } );
  98. Object.defineProperties( this, {
  99. opacity: {
  100. get: function () {
  101. return this.uniforms.opacity.value;
  102. },
  103. set: function ( value ) {
  104. this.uniforms.opacity.value = value;
  105. }
  106. },
  107. color: {
  108. get: function () {
  109. return this.uniforms.diffuse.value;
  110. }
  111. }
  112. } );
  113. this.setValues( parameters );
  114. this.isLDrawConditionalLineMaterial = true;
  115. }
  116. }
  117. function generateFaceNormals( faces ) {
  118. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  119. const face = faces[ i ];
  120. const vertices = face.vertices;
  121. const v0 = vertices[ 0 ];
  122. const v1 = vertices[ 1 ];
  123. const v2 = vertices[ 2 ];
  124. _tempVec0.subVectors( v1, v0 );
  125. _tempVec1.subVectors( v2, v1 );
  126. face.faceNormal = new THREE.Vector3().crossVectors( _tempVec0, _tempVec1 ).normalize();
  127. }
  128. }
  129. function smoothNormals( faces, lineSegments ) {
  130. function hashVertex( v ) {
  131. // NOTE: 1e2 is pretty coarse but was chosen because it allows edges
  132. // to be smoothed as expected (see minifig arms). The errors between edges
  133. // could be due to matrix multiplication.
  134. const x = ~ ~ ( v.x * 1e2 );
  135. const y = ~ ~ ( v.y * 1e2 );
  136. const z = ~ ~ ( v.z * 1e2 );
  137. return `${x},${y},${z}`;
  138. }
  139. function hashEdge( v0, v1 ) {
  140. return `${hashVertex( v0 )}_${hashVertex( v1 )}`;
  141. }
  142. const hardEdges = new Set();
  143. const halfEdgeList = {};
  144. const normals = []; // Save the list of hard edges by hash
  145. for ( let i = 0, l = lineSegments.length; i < l; i ++ ) {
  146. const ls = lineSegments[ i ];
  147. const vertices = ls.vertices;
  148. const v0 = vertices[ 0 ];
  149. const v1 = vertices[ 1 ];
  150. hardEdges.add( hashEdge( v0, v1 ) );
  151. hardEdges.add( hashEdge( v1, v0 ) );
  152. } // track the half edges associated with each triangle
  153. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  154. const tri = faces[ i ];
  155. const vertices = tri.vertices;
  156. const vertCount = vertices.length;
  157. for ( let i2 = 0; i2 < vertCount; i2 ++ ) {
  158. const index = i2;
  159. const next = ( i2 + 1 ) % vertCount;
  160. const v0 = vertices[ index ];
  161. const v1 = vertices[ next ];
  162. const hash = hashEdge( v0, v1 ); // don't add the triangle if the edge is supposed to be hard
  163. if ( hardEdges.has( hash ) ) continue;
  164. const info = {
  165. index: index,
  166. tri: tri
  167. };
  168. halfEdgeList[ hash ] = info;
  169. }
  170. } // Iterate until we've tried to connect all faces to share normals
  171. while ( true ) {
  172. // Stop if there are no more faces left
  173. let halfEdge = null;
  174. for ( const key in halfEdgeList ) {
  175. halfEdge = halfEdgeList[ key ];
  176. break;
  177. }
  178. if ( halfEdge === null ) {
  179. break;
  180. } // Exhaustively find all connected faces
  181. const queue = [ halfEdge ];
  182. while ( queue.length > 0 ) {
  183. // initialize all vertex normals in this triangle
  184. const tri = queue.pop().tri;
  185. const vertices = tri.vertices;
  186. const vertNormals = tri.normals;
  187. const faceNormal = tri.faceNormal; // Check if any edge is connected to another triangle edge
  188. const vertCount = vertices.length;
  189. for ( let i2 = 0; i2 < vertCount; i2 ++ ) {
  190. const index = i2;
  191. const next = ( i2 + 1 ) % vertCount;
  192. const v0 = vertices[ index ];
  193. const v1 = vertices[ next ]; // delete this triangle from the list so it won't be found again
  194. const hash = hashEdge( v0, v1 );
  195. delete halfEdgeList[ hash ];
  196. const reverseHash = hashEdge( v1, v0 );
  197. const otherInfo = halfEdgeList[ reverseHash ];
  198. if ( otherInfo ) {
  199. const otherTri = otherInfo.tri;
  200. const otherIndex = otherInfo.index;
  201. const otherNormals = otherTri.normals;
  202. const otherVertCount = otherNormals.length;
  203. const otherFaceNormal = otherTri.faceNormal; // NOTE: If the angle between faces is > 67.5 degrees then assume it's
  204. // hard edge. There are some cases where the line segments do not line up exactly
  205. // with or span multiple triangle edges (see Lunar Vehicle wheels).
  206. if ( Math.abs( otherTri.faceNormal.dot( tri.faceNormal ) ) < 0.25 ) {
  207. continue;
  208. } // if this triangle has already been traversed then it won't be in
  209. // the halfEdgeList. If it has not then add it to the queue and delete
  210. // it so it won't be found again.
  211. if ( reverseHash in halfEdgeList ) {
  212. queue.push( otherInfo );
  213. delete halfEdgeList[ reverseHash ];
  214. } // share the first normal
  215. const otherNext = ( otherIndex + 1 ) % otherVertCount;
  216. if ( vertNormals[ index ] && otherNormals[ otherNext ] && vertNormals[ index ] !== otherNormals[ otherNext ] ) {
  217. otherNormals[ otherNext ].norm.add( vertNormals[ index ].norm );
  218. vertNormals[ index ].norm = otherNormals[ otherNext ].norm;
  219. }
  220. let sharedNormal1 = vertNormals[ index ] || otherNormals[ otherNext ];
  221. if ( sharedNormal1 === null ) {
  222. // it's possible to encounter an edge of a triangle that has already been traversed meaning
  223. // both edges already have different normals defined and shared. To work around this we create
  224. // a wrapper object so when those edges are merged the normals can be updated everywhere.
  225. sharedNormal1 = {
  226. norm: new THREE.Vector3()
  227. };
  228. normals.push( sharedNormal1.norm );
  229. }
  230. if ( vertNormals[ index ] === null ) {
  231. vertNormals[ index ] = sharedNormal1;
  232. sharedNormal1.norm.add( faceNormal );
  233. }
  234. if ( otherNormals[ otherNext ] === null ) {
  235. otherNormals[ otherNext ] = sharedNormal1;
  236. sharedNormal1.norm.add( otherFaceNormal );
  237. } // share the second normal
  238. if ( vertNormals[ next ] && otherNormals[ otherIndex ] && vertNormals[ next ] !== otherNormals[ otherIndex ] ) {
  239. otherNormals[ otherIndex ].norm.add( vertNormals[ next ].norm );
  240. vertNormals[ next ].norm = otherNormals[ otherIndex ].norm;
  241. }
  242. let sharedNormal2 = vertNormals[ next ] || otherNormals[ otherIndex ];
  243. if ( sharedNormal2 === null ) {
  244. sharedNormal2 = {
  245. norm: new THREE.Vector3()
  246. };
  247. normals.push( sharedNormal2.norm );
  248. }
  249. if ( vertNormals[ next ] === null ) {
  250. vertNormals[ next ] = sharedNormal2;
  251. sharedNormal2.norm.add( faceNormal );
  252. }
  253. if ( otherNormals[ otherIndex ] === null ) {
  254. otherNormals[ otherIndex ] = sharedNormal2;
  255. sharedNormal2.norm.add( otherFaceNormal );
  256. }
  257. }
  258. }
  259. }
  260. } // The normals of each face have been added up so now we average them by normalizing the vector.
  261. for ( let i = 0, l = normals.length; i < l; i ++ ) {
  262. normals[ i ].normalize();
  263. }
  264. }
  265. function isPartType( type ) {
  266. return type === 'Part';
  267. }
  268. function isModelType( type ) {
  269. return type === 'Model' || type === 'Unofficial_Model';
  270. }
  271. function isPrimitiveType( type ) {
  272. return /primitive/i.test( type ) || type === 'Subpart';
  273. }
  274. class LineParser {
  275. constructor( line, lineNumber ) {
  276. this.line = line;
  277. this.lineLength = line.length;
  278. this.currentCharIndex = 0;
  279. this.currentChar = ' ';
  280. this.lineNumber = lineNumber;
  281. }
  282. seekNonSpace() {
  283. while ( this.currentCharIndex < this.lineLength ) {
  284. this.currentChar = this.line.charAt( this.currentCharIndex );
  285. if ( this.currentChar !== ' ' && this.currentChar !== '\t' ) {
  286. return;
  287. }
  288. this.currentCharIndex ++;
  289. }
  290. }
  291. getToken() {
  292. const pos0 = this.currentCharIndex ++; // Seek space
  293. while ( this.currentCharIndex < this.lineLength ) {
  294. this.currentChar = this.line.charAt( this.currentCharIndex );
  295. if ( this.currentChar === ' ' || this.currentChar === '\t' ) {
  296. break;
  297. }
  298. this.currentCharIndex ++;
  299. }
  300. const pos1 = this.currentCharIndex;
  301. this.seekNonSpace();
  302. return this.line.substring( pos0, pos1 );
  303. }
  304. getRemainingString() {
  305. return this.line.substring( this.currentCharIndex, this.lineLength );
  306. }
  307. isAtTheEnd() {
  308. return this.currentCharIndex >= this.lineLength;
  309. }
  310. setToEnd() {
  311. this.currentCharIndex = this.lineLength;
  312. }
  313. getLineNumberString() {
  314. return this.lineNumber >= 0 ? ' at line ' + this.lineNumber : '';
  315. }
  316. }
  317. class LDrawFileCache {
  318. constructor( loader ) {
  319. this.cache = {};
  320. this.loader = loader;
  321. }
  322. setData( key, contents ) {
  323. this.cache[ key.toLowerCase() ] = contents;
  324. }
  325. async loadData( fileName ) {
  326. const key = fileName.toLowerCase();
  327. if ( key in this.cache ) {
  328. return this.cache[ key ];
  329. }
  330. this.cache[ fileName ] = new Promise( async ( resolve, reject ) => {
  331. let triedLowerCase = false;
  332. let locationState = FILE_LOCATION_AS_IS;
  333. while ( locationState !== FILE_LOCATION_NOT_FOUND ) {
  334. let subobjectURL = fileName;
  335. switch ( locationState ) {
  336. case FILE_LOCATION_AS_IS:
  337. locationState = locationState + 1;
  338. break;
  339. case FILE_LOCATION_TRY_PARTS:
  340. subobjectURL = 'parts/' + subobjectURL;
  341. locationState = locationState + 1;
  342. break;
  343. case FILE_LOCATION_TRY_P:
  344. subobjectURL = 'p/' + subobjectURL;
  345. locationState = locationState + 1;
  346. break;
  347. case FILE_LOCATION_TRY_MODELS:
  348. subobjectURL = 'models/' + subobjectURL;
  349. locationState = locationState + 1;
  350. break;
  351. case FILE_LOCATION_TRY_RELATIVE:
  352. subobjectURL = fileName.substring( 0, fileName.lastIndexOf( '/' ) + 1 ) + subobjectURL;
  353. locationState = locationState + 1;
  354. break;
  355. case FILE_LOCATION_TRY_ABSOLUTE:
  356. if ( triedLowerCase ) {
  357. // Try absolute path
  358. locationState = FILE_LOCATION_NOT_FOUND;
  359. } else {
  360. // Next attempt is lower case
  361. fileName = fileName.toLowerCase();
  362. subobjectURL = fileName;
  363. triedLowerCase = true;
  364. locationState = FILE_LOCATION_AS_IS;
  365. }
  366. break;
  367. }
  368. const loader = this.loader;
  369. const fileLoader = new THREE.FileLoader( loader.manager );
  370. fileLoader.setPath( loader.partsLibraryPath );
  371. fileLoader.setRequestHeader( loader.requestHeader );
  372. fileLoader.setWithCredentials( loader.withCredentials );
  373. try {
  374. const text = await fileLoader.loadAsync( subobjectURL );
  375. this.setData( fileName, text );
  376. resolve( text );
  377. return;
  378. } catch {
  379. continue;
  380. }
  381. }
  382. reject();
  383. } );
  384. return this.cache[ fileName ];
  385. }
  386. }
  387. function sortByMaterial( a, b ) {
  388. if ( a.colourCode === b.colourCode ) {
  389. return 0;
  390. }
  391. if ( a.colourCode < b.colourCode ) {
  392. return - 1;
  393. }
  394. return 1;
  395. }
  396. function createObject( elements, elementSize, isConditionalSegments = false, totalElements = null ) {
  397. // Creates a THREE.LineSegments (elementSize = 2) or a THREE.Mesh (elementSize = 3 )
  398. // With per face / segment material, implemented with mesh groups and materials array
  399. // Sort the faces or line segments by colour code to make later the mesh groups
  400. elements.sort( sortByMaterial );
  401. if ( totalElements === null ) {
  402. totalElements = elements.length;
  403. }
  404. const positions = new Float32Array( elementSize * totalElements * 3 );
  405. const normals = elementSize === 3 ? new Float32Array( elementSize * totalElements * 3 ) : null;
  406. const materials = [];
  407. const quadArray = new Array( 6 );
  408. const bufferGeometry = new THREE.BufferGeometry();
  409. let prevMaterial = null;
  410. let index0 = 0;
  411. let numGroupVerts = 0;
  412. let offset = 0;
  413. for ( let iElem = 0, nElem = elements.length; iElem < nElem; iElem ++ ) {
  414. const elem = elements[ iElem ];
  415. let vertices = elem.vertices;
  416. if ( vertices.length === 4 ) {
  417. quadArray[ 0 ] = vertices[ 0 ];
  418. quadArray[ 1 ] = vertices[ 1 ];
  419. quadArray[ 2 ] = vertices[ 2 ];
  420. quadArray[ 3 ] = vertices[ 0 ];
  421. quadArray[ 4 ] = vertices[ 2 ];
  422. quadArray[ 5 ] = vertices[ 3 ];
  423. vertices = quadArray;
  424. }
  425. for ( let j = 0, l = vertices.length; j < l; j ++ ) {
  426. const v = vertices[ j ];
  427. const index = offset + j * 3;
  428. positions[ index + 0 ] = v.x;
  429. positions[ index + 1 ] = v.y;
  430. positions[ index + 2 ] = v.z;
  431. } // create the normals array if this is a set of faces
  432. if ( elementSize === 3 ) {
  433. if ( ! elem.faceNormal ) {
  434. const v0 = vertices[ 0 ];
  435. const v1 = vertices[ 1 ];
  436. const v2 = vertices[ 2 ];
  437. _tempVec0.subVectors( v1, v0 );
  438. _tempVec1.subVectors( v2, v1 );
  439. elem.faceNormal = new THREE.Vector3().crossVectors( _tempVec0, _tempVec1 ).normalize();
  440. }
  441. let elemNormals = elem.normals;
  442. if ( elemNormals.length === 4 ) {
  443. quadArray[ 0 ] = elemNormals[ 0 ];
  444. quadArray[ 1 ] = elemNormals[ 1 ];
  445. quadArray[ 2 ] = elemNormals[ 2 ];
  446. quadArray[ 3 ] = elemNormals[ 0 ];
  447. quadArray[ 4 ] = elemNormals[ 2 ];
  448. quadArray[ 5 ] = elemNormals[ 3 ];
  449. elemNormals = quadArray;
  450. }
  451. for ( let j = 0, l = elemNormals.length; j < l; j ++ ) {
  452. // use face normal if a vertex normal is not provided
  453. let n = elem.faceNormal;
  454. if ( elemNormals[ j ] ) {
  455. n = elemNormals[ j ].norm;
  456. }
  457. const index = offset + j * 3;
  458. normals[ index + 0 ] = n.x;
  459. normals[ index + 1 ] = n.y;
  460. normals[ index + 2 ] = n.z;
  461. }
  462. }
  463. if ( prevMaterial !== elem.material ) {
  464. if ( prevMaterial !== null ) {
  465. bufferGeometry.addGroup( index0, numGroupVerts, materials.length - 1 );
  466. }
  467. materials.push( elem.material );
  468. prevMaterial = elem.material;
  469. index0 = offset / 3;
  470. numGroupVerts = vertices.length;
  471. } else {
  472. numGroupVerts += vertices.length;
  473. }
  474. offset += 3 * vertices.length;
  475. }
  476. if ( numGroupVerts > 0 ) {
  477. bufferGeometry.addGroup( index0, Infinity, materials.length - 1 );
  478. }
  479. bufferGeometry.setAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) );
  480. if ( normals !== null ) {
  481. bufferGeometry.setAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) );
  482. }
  483. let object3d = null;
  484. if ( elementSize === 2 ) {
  485. object3d = new THREE.LineSegments( bufferGeometry, materials.length === 1 ? materials[ 0 ] : materials );
  486. } else if ( elementSize === 3 ) {
  487. object3d = new THREE.Mesh( bufferGeometry, materials.length === 1 ? materials[ 0 ] : materials );
  488. }
  489. if ( isConditionalSegments ) {
  490. object3d.isConditionalLine = true;
  491. const controlArray0 = new Float32Array( elements.length * 3 * 2 );
  492. const controlArray1 = new Float32Array( elements.length * 3 * 2 );
  493. const directionArray = new Float32Array( elements.length * 3 * 2 );
  494. for ( let i = 0, l = elements.length; i < l; i ++ ) {
  495. const os = elements[ i ];
  496. const vertices = os.vertices;
  497. const controlPoints = os.controlPoints;
  498. const c0 = controlPoints[ 0 ];
  499. const c1 = controlPoints[ 1 ];
  500. const v0 = vertices[ 0 ];
  501. const v1 = vertices[ 1 ];
  502. const index = i * 3 * 2;
  503. controlArray0[ index + 0 ] = c0.x;
  504. controlArray0[ index + 1 ] = c0.y;
  505. controlArray0[ index + 2 ] = c0.z;
  506. controlArray0[ index + 3 ] = c0.x;
  507. controlArray0[ index + 4 ] = c0.y;
  508. controlArray0[ index + 5 ] = c0.z;
  509. controlArray1[ index + 0 ] = c1.x;
  510. controlArray1[ index + 1 ] = c1.y;
  511. controlArray1[ index + 2 ] = c1.z;
  512. controlArray1[ index + 3 ] = c1.x;
  513. controlArray1[ index + 4 ] = c1.y;
  514. controlArray1[ index + 5 ] = c1.z;
  515. directionArray[ index + 0 ] = v1.x - v0.x;
  516. directionArray[ index + 1 ] = v1.y - v0.y;
  517. directionArray[ index + 2 ] = v1.z - v0.z;
  518. directionArray[ index + 3 ] = v1.x - v0.x;
  519. directionArray[ index + 4 ] = v1.y - v0.y;
  520. directionArray[ index + 5 ] = v1.z - v0.z;
  521. }
  522. bufferGeometry.setAttribute( 'control0', new THREE.BufferAttribute( controlArray0, 3, false ) );
  523. bufferGeometry.setAttribute( 'control1', new THREE.BufferAttribute( controlArray1, 3, false ) );
  524. bufferGeometry.setAttribute( 'direction', new THREE.BufferAttribute( directionArray, 3, false ) );
  525. }
  526. return object3d;
  527. } //
  528. class LDrawLoader extends THREE.Loader {
  529. constructor( manager ) {
  530. super( manager ); // Array of THREE.Material
  531. this.materials = []; // Not using THREE.Cache here because it returns the previous HTML error response instead of calling onError()
  532. // This also allows to handle the embedded text files ("0 FILE" lines)
  533. this.cache = new LDrawFileCache( this ); // 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.
  534. this.fileMap = {};
  535. this.rootParseScope = this.newParseScopeLevel(); // Add default main triangle and line edge materials (used in pieces that can be coloured with a main color)
  536. this.setMaterials( [ this.parseColourMetaDirective( new LineParser( 'Main_Colour CODE 16 VALUE #FF8080 EDGE #333333' ) ), this.parseColourMetaDirective( new LineParser( 'Edge_Colour CODE 24 VALUE #A0A0A0 EDGE #333333' ) ) ] ); // If this flag is set to true, each subobject will be a Object.
  537. // If not (the default), only one object which contains all the merged primitives will be created.
  538. this.separateObjects = false; // If this flag is set to true the vertex normals will be smoothed.
  539. this.smoothNormals = true; // The path to load parts from the LDraw parts library from.
  540. this.partsLibraryPath = '';
  541. }
  542. setPartsLibraryPath( path ) {
  543. this.partsLibraryPath = path;
  544. return this;
  545. }
  546. async preloadMaterials( url ) {
  547. const fileLoader = new THREE.FileLoader( this.manager );
  548. fileLoader.setPath( this.path );
  549. fileLoader.setRequestHeader( this.requestHeader );
  550. fileLoader.setWithCredentials( this.withCredentials );
  551. const text = await fileLoader.loadAsync( url );
  552. const colorLineRegex = /^0 !COLOUR/;
  553. const lines = text.split( /[\n\r]/g );
  554. const materials = [];
  555. for ( let i = 0, l = lines.length; i < l; i ++ ) {
  556. const line = lines[ i ];
  557. if ( colorLineRegex.test( line ) ) {
  558. const directive = line.replace( colorLineRegex, '' );
  559. const material = this.parseColourMetaDirective( new LineParser( directive ) );
  560. materials.push( material );
  561. }
  562. }
  563. this.setMaterials( materials );
  564. }
  565. load( url, onLoad, onProgress, onError ) {
  566. const fileLoader = new THREE.FileLoader( this.manager );
  567. fileLoader.setPath( this.path );
  568. fileLoader.setRequestHeader( this.requestHeader );
  569. fileLoader.setWithCredentials( this.withCredentials );
  570. fileLoader.load( url, text => {
  571. this.processObject( text, null, url, this.rootParseScope ).then( function ( result ) {
  572. onLoad( result.groupObject );
  573. } );
  574. }, onProgress, onError );
  575. }
  576. parse( text, path, onLoad ) {
  577. // Async parse. This function calls onParse with the parsed THREE.Object3D as parameter
  578. this.processObject( text, null, path, this.rootParseScope ).then( function ( result ) {
  579. onLoad( result.groupObject );
  580. } );
  581. }
  582. setMaterials( materials ) {
  583. // Clears parse scopes stack, adds new scope with material library
  584. this.rootParseScope = this.newParseScopeLevel( materials );
  585. this.rootParseScope.isFromParse = false;
  586. this.materials = materials;
  587. return this;
  588. }
  589. setFileMap( fileMap ) {
  590. this.fileMap = fileMap;
  591. return this;
  592. }
  593. newParseScopeLevel( materials = null, parentScope = null ) {
  594. // Adds a new scope level, assign materials to it and returns it
  595. const matLib = {};
  596. if ( materials ) {
  597. for ( let i = 0, n = materials.length; i < n; i ++ ) {
  598. const material = materials[ i ];
  599. matLib[ material.userData.code ] = material;
  600. }
  601. }
  602. const newParseScope = {
  603. parentScope: parentScope,
  604. lib: matLib,
  605. url: null,
  606. // Subobjects
  607. subobjects: null,
  608. numSubobjects: 0,
  609. subobjectIndex: 0,
  610. inverted: false,
  611. category: null,
  612. keywords: null,
  613. // Current subobject
  614. currentFileName: null,
  615. mainColourCode: parentScope ? parentScope.mainColourCode : '16',
  616. mainEdgeColourCode: parentScope ? parentScope.mainEdgeColourCode : '24',
  617. currentMatrix: new THREE.Matrix4(),
  618. matrix: new THREE.Matrix4(),
  619. type: 'Model',
  620. groupObject: null,
  621. // If false, it is a root material scope previous to parse
  622. isFromParse: true,
  623. faces: [],
  624. lineSegments: [],
  625. conditionalSegments: [],
  626. totalFaces: 0,
  627. // If true, this object is the start of a construction step
  628. startingConstructionStep: false
  629. };
  630. return newParseScope;
  631. }
  632. addMaterial( material, parseScope ) {
  633. // Adds a material to the material library which is on top of the parse scopes stack. And also to the materials array
  634. const matLib = parseScope.lib;
  635. if ( ! matLib[ material.userData.code ] ) {
  636. this.materials.push( material );
  637. }
  638. matLib[ material.userData.code ] = material;
  639. return this;
  640. }
  641. getMaterial( colourCode, parseScope = this.rootParseScope ) {
  642. // Given a colour code search its material in the parse scopes stack
  643. if ( colourCode.startsWith( '0x2' ) ) {
  644. // Special 'direct' material value (RGB colour)
  645. const colour = colourCode.substring( 3 );
  646. return this.parseColourMetaDirective( new LineParser( 'Direct_Color_' + colour + ' CODE -1 VALUE #' + colour + ' EDGE #' + colour + '' ) );
  647. }
  648. while ( parseScope ) {
  649. const material = parseScope.lib[ colourCode ];
  650. if ( material ) {
  651. return material;
  652. } else {
  653. parseScope = parseScope.parentScope;
  654. }
  655. } // Material was not found
  656. return null;
  657. }
  658. parseColourMetaDirective( lineParser ) {
  659. // Parses a colour definition and returns a THREE.Material
  660. let code = null; // Triangle and line colours
  661. let colour = 0xFF00FF;
  662. let edgeColour = 0xFF00FF; // Transparency
  663. let alpha = 1;
  664. let isTransparent = false; // Self-illumination:
  665. let luminance = 0;
  666. let finishType = FINISH_TYPE_DEFAULT;
  667. let edgeMaterial = null;
  668. const name = lineParser.getToken();
  669. if ( ! name ) {
  670. throw new Error( 'LDrawLoader: Material name was expected after "!COLOUR tag' + lineParser.getLineNumberString() + '.' );
  671. } // Parse tag tokens and their parameters
  672. let token = null;
  673. while ( true ) {
  674. token = lineParser.getToken();
  675. if ( ! token ) {
  676. break;
  677. }
  678. switch ( token.toUpperCase() ) {
  679. case 'CODE':
  680. code = lineParser.getToken();
  681. break;
  682. case 'VALUE':
  683. colour = lineParser.getToken();
  684. if ( colour.startsWith( '0x' ) ) {
  685. colour = '#' + colour.substring( 2 );
  686. } else if ( ! colour.startsWith( '#' ) ) {
  687. throw new Error( 'LDrawLoader: Invalid colour while parsing material' + lineParser.getLineNumberString() + '.' );
  688. }
  689. break;
  690. case 'EDGE':
  691. edgeColour = lineParser.getToken();
  692. if ( edgeColour.startsWith( '0x' ) ) {
  693. edgeColour = '#' + edgeColour.substring( 2 );
  694. } else if ( ! edgeColour.startsWith( '#' ) ) {
  695. // Try to see if edge colour is a colour code
  696. edgeMaterial = this.getMaterial( edgeColour );
  697. if ( ! edgeMaterial ) {
  698. throw new Error( 'LDrawLoader: Invalid edge colour while parsing material' + lineParser.getLineNumberString() + '.' );
  699. } // Get the edge material for this triangle material
  700. edgeMaterial = edgeMaterial.userData.edgeMaterial;
  701. }
  702. break;
  703. case 'ALPHA':
  704. alpha = parseInt( lineParser.getToken() );
  705. if ( isNaN( alpha ) ) {
  706. throw new Error( 'LDrawLoader: Invalid alpha value in material definition' + lineParser.getLineNumberString() + '.' );
  707. }
  708. alpha = Math.max( 0, Math.min( 1, alpha / 255 ) );
  709. if ( alpha < 1 ) {
  710. isTransparent = true;
  711. }
  712. break;
  713. case 'LUMINANCE':
  714. luminance = parseInt( lineParser.getToken() );
  715. if ( isNaN( luminance ) ) {
  716. throw new Error( 'LDrawLoader: Invalid luminance value in material definition' + LineParser.getLineNumberString() + '.' );
  717. }
  718. luminance = Math.max( 0, Math.min( 1, luminance / 255 ) );
  719. break;
  720. case 'CHROME':
  721. finishType = FINISH_TYPE_CHROME;
  722. break;
  723. case 'PEARLESCENT':
  724. finishType = FINISH_TYPE_PEARLESCENT;
  725. break;
  726. case 'RUBBER':
  727. finishType = FINISH_TYPE_RUBBER;
  728. break;
  729. case 'MATTE_METALLIC':
  730. finishType = FINISH_TYPE_MATTE_METALLIC;
  731. break;
  732. case 'METAL':
  733. finishType = FINISH_TYPE_METAL;
  734. break;
  735. case 'MATERIAL':
  736. // Not implemented
  737. lineParser.setToEnd();
  738. break;
  739. default:
  740. throw new Error( 'LDrawLoader: Unknown token "' + token + '" while parsing material' + lineParser.getLineNumberString() + '.' );
  741. }
  742. }
  743. let material = null;
  744. switch ( finishType ) {
  745. case FINISH_TYPE_DEFAULT:
  746. material = new THREE.MeshStandardMaterial( {
  747. color: colour,
  748. roughness: 0.3,
  749. metalness: 0
  750. } );
  751. break;
  752. case FINISH_TYPE_PEARLESCENT:
  753. // Try to imitate pearlescency by making the surface glossy
  754. material = new THREE.MeshStandardMaterial( {
  755. color: colour,
  756. roughness: 0.3,
  757. metalness: 0.25
  758. } );
  759. break;
  760. case FINISH_TYPE_CHROME:
  761. // Mirror finish surface
  762. material = new THREE.MeshStandardMaterial( {
  763. color: colour,
  764. roughness: 0,
  765. metalness: 1
  766. } );
  767. break;
  768. case FINISH_TYPE_RUBBER:
  769. // Rubber finish
  770. material = new THREE.MeshStandardMaterial( {
  771. color: colour,
  772. roughness: 0.9,
  773. metalness: 0
  774. } );
  775. break;
  776. case FINISH_TYPE_MATTE_METALLIC:
  777. // Brushed metal finish
  778. material = new THREE.MeshStandardMaterial( {
  779. color: colour,
  780. roughness: 0.8,
  781. metalness: 0.4
  782. } );
  783. break;
  784. case FINISH_TYPE_METAL:
  785. // Average metal finish
  786. material = new THREE.MeshStandardMaterial( {
  787. color: colour,
  788. roughness: 0.2,
  789. metalness: 0.85
  790. } );
  791. break;
  792. default:
  793. // Should not happen
  794. break;
  795. }
  796. material.transparent = isTransparent;
  797. material.premultipliedAlpha = true;
  798. material.opacity = alpha;
  799. material.depthWrite = ! isTransparent;
  800. material.polygonOffset = true;
  801. material.polygonOffsetFactor = 1;
  802. if ( luminance !== 0 ) {
  803. material.emissive.set( material.color ).multiplyScalar( luminance );
  804. }
  805. if ( ! edgeMaterial ) {
  806. // This is the material used for edges
  807. edgeMaterial = new THREE.LineBasicMaterial( {
  808. color: edgeColour,
  809. transparent: isTransparent,
  810. opacity: alpha,
  811. depthWrite: ! isTransparent
  812. } );
  813. edgeMaterial.userData.code = code;
  814. edgeMaterial.name = name + ' - Edge'; // This is the material used for conditional edges
  815. edgeMaterial.userData.conditionalEdgeMaterial = new LDrawConditionalLineMaterial( {
  816. fog: true,
  817. transparent: isTransparent,
  818. depthWrite: ! isTransparent,
  819. color: edgeColour,
  820. opacity: alpha
  821. } );
  822. }
  823. material.userData.code = code;
  824. material.name = name;
  825. material.userData.edgeMaterial = edgeMaterial;
  826. return material;
  827. } //
  828. objectParse( text, parseScope ) {
  829. // Retrieve data from the parent parse scope
  830. const currentParseScope = parseScope;
  831. const parentParseScope = currentParseScope.parentScope; // Main colour codes passed to this subobject (or default codes 16 and 24 if it is the root object)
  832. const mainColourCode = currentParseScope.mainColourCode;
  833. const mainEdgeColourCode = currentParseScope.mainEdgeColourCode; // Parse result variables
  834. let faces;
  835. let lineSegments;
  836. let conditionalSegments;
  837. const subobjects = [];
  838. let category = null;
  839. let keywords = null;
  840. if ( text.indexOf( '\r\n' ) !== - 1 ) {
  841. // This is faster than String.split with regex that splits on both
  842. text = text.replace( /\r\n/g, '\n' );
  843. }
  844. const lines = text.split( '\n' );
  845. const numLines = lines.length;
  846. let parsingEmbeddedFiles = false;
  847. let currentEmbeddedFileName = null;
  848. let currentEmbeddedText = null;
  849. let bfcCertified = false;
  850. let bfcCCW = true;
  851. let bfcInverted = false;
  852. let bfcCull = true;
  853. let type = '';
  854. let startingConstructionStep = false;
  855. const parseColourCode = ( lineParser, forEdge ) => {
  856. // Parses next colour code and returns a THREE.Material
  857. let colourCode = lineParser.getToken();
  858. if ( ! forEdge && colourCode === '16' ) {
  859. colourCode = mainColourCode;
  860. }
  861. if ( forEdge && colourCode === '24' ) {
  862. colourCode = mainEdgeColourCode;
  863. }
  864. const material = this.getMaterial( colourCode, currentParseScope );
  865. if ( ! material ) {
  866. throw new Error( 'LDrawLoader: Unknown colour code "' + colourCode + '" is used' + lineParser.getLineNumberString() + ' but it was not defined previously.' );
  867. }
  868. return material;
  869. };
  870. const parseVector = lp => {
  871. const v = new THREE.Vector3( parseFloat( lp.getToken() ), parseFloat( lp.getToken() ), parseFloat( lp.getToken() ) );
  872. if ( ! this.separateObjects ) {
  873. v.applyMatrix4( currentParseScope.currentMatrix );
  874. }
  875. return v;
  876. }; // Parse all line commands
  877. for ( let lineIndex = 0; lineIndex < numLines; lineIndex ++ ) {
  878. const line = lines[ lineIndex ];
  879. if ( line.length === 0 ) continue;
  880. if ( parsingEmbeddedFiles ) {
  881. if ( line.startsWith( '0 FILE ' ) ) {
  882. // Save previous embedded file in the cache
  883. this.cache.setData( currentEmbeddedFileName.toLowerCase(), currentEmbeddedText ); // New embedded text file
  884. currentEmbeddedFileName = line.substring( 7 );
  885. currentEmbeddedText = '';
  886. } else {
  887. currentEmbeddedText += line + '\n';
  888. }
  889. continue;
  890. }
  891. const lp = new LineParser( line, lineIndex + 1 );
  892. lp.seekNonSpace();
  893. if ( lp.isAtTheEnd() ) {
  894. // Empty line
  895. continue;
  896. } // Parse the line type
  897. const lineType = lp.getToken();
  898. let material;
  899. let segment;
  900. let inverted;
  901. let ccw;
  902. let doubleSided;
  903. let v0, v1, v2, v3, c0, c1;
  904. switch ( lineType ) {
  905. // Line type 0: Comment or META
  906. case '0':
  907. // Parse meta directive
  908. const meta = lp.getToken();
  909. if ( meta ) {
  910. switch ( meta ) {
  911. case '!LDRAW_ORG':
  912. type = lp.getToken();
  913. currentParseScope.type = type; // If the scale of the object is negated then the triangle winding order
  914. // needs to be flipped.
  915. if ( currentParseScope.matrix.determinant() < 0 && ( this.separateObjects && isPrimitiveType( type ) || ! this.separateObjects ) ) {
  916. currentParseScope.inverted = ! currentParseScope.inverted;
  917. }
  918. faces = currentParseScope.faces;
  919. lineSegments = currentParseScope.lineSegments;
  920. conditionalSegments = currentParseScope.conditionalSegments;
  921. break;
  922. case '!COLOUR':
  923. material = this.parseColourMetaDirective( lp );
  924. if ( material ) {
  925. this.addMaterial( material, parseScope );
  926. } else {
  927. console.warn( 'LDrawLoader: Error parsing material' + lp.getLineNumberString() );
  928. }
  929. break;
  930. case '!CATEGORY':
  931. category = lp.getToken();
  932. break;
  933. case '!KEYWORDS':
  934. const newKeywords = lp.getRemainingString().split( ',' );
  935. if ( newKeywords.length > 0 ) {
  936. if ( ! keywords ) {
  937. keywords = [];
  938. }
  939. newKeywords.forEach( function ( keyword ) {
  940. keywords.push( keyword.trim() );
  941. } );
  942. }
  943. break;
  944. case 'FILE':
  945. if ( lineIndex > 0 ) {
  946. // Start embedded text files parsing
  947. parsingEmbeddedFiles = true;
  948. currentEmbeddedFileName = lp.getRemainingString();
  949. currentEmbeddedText = '';
  950. bfcCertified = false;
  951. bfcCCW = true;
  952. }
  953. break;
  954. case 'BFC':
  955. // Changes to the backface culling state
  956. while ( ! lp.isAtTheEnd() ) {
  957. const token = lp.getToken();
  958. switch ( token ) {
  959. case 'CERTIFY':
  960. case 'NOCERTIFY':
  961. bfcCertified = token === 'CERTIFY';
  962. bfcCCW = true;
  963. break;
  964. case 'CW':
  965. case 'CCW':
  966. bfcCCW = token === 'CCW';
  967. break;
  968. case 'INVERTNEXT':
  969. bfcInverted = true;
  970. break;
  971. case 'CLIP':
  972. case 'NOCLIP':
  973. bfcCull = token === 'CLIP';
  974. break;
  975. default:
  976. console.warn( 'THREE.LDrawLoader: BFC directive "' + token + '" is unknown.' );
  977. break;
  978. }
  979. }
  980. break;
  981. case 'STEP':
  982. startingConstructionStep = true;
  983. break;
  984. default:
  985. // Other meta directives are not implemented
  986. break;
  987. }
  988. }
  989. break;
  990. // Line type 1: Sub-object file
  991. case '1':
  992. material = parseColourCode( lp );
  993. const posX = parseFloat( lp.getToken() );
  994. const posY = parseFloat( lp.getToken() );
  995. const posZ = parseFloat( lp.getToken() );
  996. const m0 = parseFloat( lp.getToken() );
  997. const m1 = parseFloat( lp.getToken() );
  998. const m2 = parseFloat( lp.getToken() );
  999. const m3 = parseFloat( lp.getToken() );
  1000. const m4 = parseFloat( lp.getToken() );
  1001. const m5 = parseFloat( lp.getToken() );
  1002. const m6 = parseFloat( lp.getToken() );
  1003. const m7 = parseFloat( lp.getToken() );
  1004. const m8 = parseFloat( lp.getToken() );
  1005. const matrix = new THREE.Matrix4().set( m0, m1, m2, posX, m3, m4, m5, posY, m6, m7, m8, posZ, 0, 0, 0, 1 );
  1006. let fileName = lp.getRemainingString().trim().replace( /\\/g, '/' );
  1007. if ( this.fileMap[ fileName ] ) {
  1008. // Found the subobject path in the preloaded file path map
  1009. fileName = this.fileMap[ fileName ];
  1010. } else {
  1011. // Standardized subfolders
  1012. if ( fileName.startsWith( 's/' ) ) {
  1013. fileName = 'parts/' + fileName;
  1014. } else if ( fileName.startsWith( '48/' ) ) {
  1015. fileName = 'p/' + fileName;
  1016. }
  1017. }
  1018. subobjects.push( {
  1019. material: material,
  1020. matrix: matrix,
  1021. fileName: fileName,
  1022. inverted: bfcInverted !== currentParseScope.inverted,
  1023. startingConstructionStep: startingConstructionStep
  1024. } );
  1025. bfcInverted = false;
  1026. break;
  1027. // Line type 2: Line segment
  1028. case '2':
  1029. material = parseColourCode( lp, true );
  1030. v0 = parseVector( lp );
  1031. v1 = parseVector( lp );
  1032. segment = {
  1033. material: material.userData.edgeMaterial,
  1034. colourCode: material.userData.code,
  1035. v0: v0,
  1036. v1: v1,
  1037. vertices: [ v0, v1 ]
  1038. };
  1039. lineSegments.push( segment );
  1040. break;
  1041. // Line type 5: Conditional Line segment
  1042. case '5':
  1043. material = parseColourCode( lp, true );
  1044. v0 = parseVector( lp );
  1045. v1 = parseVector( lp );
  1046. c0 = parseVector( lp );
  1047. c1 = parseVector( lp );
  1048. segment = {
  1049. material: material.userData.edgeMaterial.userData.conditionalEdgeMaterial,
  1050. colourCode: material.userData.code,
  1051. vertices: [ v0, v1 ],
  1052. controlPoints: [ c0, c1 ]
  1053. };
  1054. conditionalSegments.push( segment );
  1055. break;
  1056. // Line type 3: Triangle
  1057. case '3':
  1058. material = parseColourCode( lp );
  1059. inverted = currentParseScope.inverted;
  1060. ccw = bfcCCW !== inverted;
  1061. doubleSided = ! bfcCertified || ! bfcCull;
  1062. if ( ccw === true ) {
  1063. v0 = parseVector( lp );
  1064. v1 = parseVector( lp );
  1065. v2 = parseVector( lp );
  1066. } else {
  1067. v2 = parseVector( lp );
  1068. v1 = parseVector( lp );
  1069. v0 = parseVector( lp );
  1070. }
  1071. faces.push( {
  1072. material: material,
  1073. colourCode: material.userData.code,
  1074. faceNormal: null,
  1075. vertices: [ v0, v1, v2 ],
  1076. normals: [ null, null, null ]
  1077. } );
  1078. currentParseScope.totalFaces ++;
  1079. if ( doubleSided === true ) {
  1080. faces.push( {
  1081. material: material,
  1082. colourCode: material.userData.code,
  1083. faceNormal: null,
  1084. vertices: [ v2, v1, v0 ],
  1085. normals: [ null, null, null ]
  1086. } );
  1087. currentParseScope.totalFaces ++;
  1088. }
  1089. break;
  1090. // Line type 4: Quadrilateral
  1091. case '4':
  1092. material = parseColourCode( lp );
  1093. inverted = currentParseScope.inverted;
  1094. ccw = bfcCCW !== inverted;
  1095. doubleSided = ! bfcCertified || ! bfcCull;
  1096. if ( ccw === true ) {
  1097. v0 = parseVector( lp );
  1098. v1 = parseVector( lp );
  1099. v2 = parseVector( lp );
  1100. v3 = parseVector( lp );
  1101. } else {
  1102. v3 = parseVector( lp );
  1103. v2 = parseVector( lp );
  1104. v1 = parseVector( lp );
  1105. v0 = parseVector( lp );
  1106. } // specifically place the triangle diagonal in the v0 and v1 slots so we can
  1107. // account for the doubling of vertices later when smoothing normals.
  1108. faces.push( {
  1109. material: material,
  1110. colourCode: material.userData.code,
  1111. faceNormal: null,
  1112. vertices: [ v0, v1, v2, v3 ],
  1113. normals: [ null, null, null, null ]
  1114. } );
  1115. currentParseScope.totalFaces += 2;
  1116. if ( doubleSided === true ) {
  1117. faces.push( {
  1118. material: material,
  1119. colourCode: material.userData.code,
  1120. faceNormal: null,
  1121. vertices: [ v3, v2, v1, v0 ],
  1122. normals: [ null, null, null, null ]
  1123. } );
  1124. currentParseScope.totalFaces += 2;
  1125. }
  1126. break;
  1127. default:
  1128. throw new Error( 'LDrawLoader: Unknown line type "' + lineType + '"' + lp.getLineNumberString() + '.' );
  1129. }
  1130. }
  1131. if ( parsingEmbeddedFiles ) {
  1132. this.cache.setData( currentEmbeddedFileName.toLowerCase(), currentEmbeddedText );
  1133. }
  1134. currentParseScope.category = category;
  1135. currentParseScope.keywords = keywords;
  1136. currentParseScope.subobjects = subobjects;
  1137. currentParseScope.numSubobjects = subobjects.length;
  1138. currentParseScope.subobjectIndex = 0;
  1139. const isRoot = ! parentParseScope.isFromParse;
  1140. if ( isRoot || this.separateObjects && ! isPrimitiveType( type ) ) {
  1141. currentParseScope.groupObject = new THREE.Group();
  1142. currentParseScope.groupObject.userData.startingConstructionStep = currentParseScope.startingConstructionStep;
  1143. }
  1144. }
  1145. computeConstructionSteps( model ) {
  1146. // Sets userdata.constructionStep number in THREE.Group objects and userData.numConstructionSteps number in the root THREE.Group object.
  1147. let stepNumber = 0;
  1148. model.traverse( c => {
  1149. if ( c.isGroup ) {
  1150. if ( c.userData.startingConstructionStep ) {
  1151. stepNumber ++;
  1152. }
  1153. c.userData.constructionStep = stepNumber;
  1154. }
  1155. } );
  1156. model.userData.numConstructionSteps = stepNumber + 1;
  1157. }
  1158. finalizeObject( subobjectParseScope ) {
  1159. // fail gracefully if an object could not be loaded
  1160. if ( subobjectParseScope === null ) {
  1161. return;
  1162. }
  1163. const parentParseScope = subobjectParseScope.parentScope; // Smooth the normals if this is a part or if this is a case where the subpart
  1164. // is added directly into the parent model (meaning it will never get smoothed by
  1165. // being added to a part)
  1166. const doSmooth = isPartType( subobjectParseScope.type ) || isPrimitiveType( subobjectParseScope.type ) && isModelType( subobjectParseScope.parentScope.type );
  1167. if ( this.smoothNormals && doSmooth ) {
  1168. generateFaceNormals( subobjectParseScope.faces );
  1169. smoothNormals( subobjectParseScope.faces, subobjectParseScope.lineSegments );
  1170. }
  1171. const isRoot = ! parentParseScope.isFromParse;
  1172. if ( this.separateObjects && ! isPrimitiveType( subobjectParseScope.type ) || isRoot ) {
  1173. const objGroup = subobjectParseScope.groupObject;
  1174. if ( subobjectParseScope.faces.length > 0 ) {
  1175. objGroup.add( createObject( subobjectParseScope.faces, 3, false, subobjectParseScope.totalFaces ) );
  1176. }
  1177. if ( subobjectParseScope.lineSegments.length > 0 ) {
  1178. objGroup.add( createObject( subobjectParseScope.lineSegments, 2 ) );
  1179. }
  1180. if ( subobjectParseScope.conditionalSegments.length > 0 ) {
  1181. objGroup.add( createObject( subobjectParseScope.conditionalSegments, 2, true ) );
  1182. }
  1183. if ( parentParseScope.groupObject ) {
  1184. objGroup.name = subobjectParseScope.fileName;
  1185. objGroup.userData.category = subobjectParseScope.category;
  1186. objGroup.userData.keywords = subobjectParseScope.keywords;
  1187. subobjectParseScope.matrix.decompose( objGroup.position, objGroup.quaternion, objGroup.scale );
  1188. parentParseScope.groupObject.add( objGroup );
  1189. }
  1190. } else {
  1191. const separateObjects = this.separateObjects;
  1192. const parentLineSegments = parentParseScope.lineSegments;
  1193. const parentConditionalSegments = parentParseScope.conditionalSegments;
  1194. const parentFaces = parentParseScope.faces;
  1195. const lineSegments = subobjectParseScope.lineSegments;
  1196. const conditionalSegments = subobjectParseScope.conditionalSegments;
  1197. const faces = subobjectParseScope.faces;
  1198. for ( let i = 0, l = lineSegments.length; i < l; i ++ ) {
  1199. const ls = lineSegments[ i ];
  1200. if ( separateObjects ) {
  1201. const vertices = ls.vertices;
  1202. vertices[ 0 ].applyMatrix4( subobjectParseScope.matrix );
  1203. vertices[ 1 ].applyMatrix4( subobjectParseScope.matrix );
  1204. }
  1205. parentLineSegments.push( ls );
  1206. }
  1207. for ( let i = 0, l = conditionalSegments.length; i < l; i ++ ) {
  1208. const os = conditionalSegments[ i ];
  1209. if ( separateObjects ) {
  1210. const vertices = os.vertices;
  1211. const controlPoints = os.controlPoints;
  1212. vertices[ 0 ].applyMatrix4( subobjectParseScope.matrix );
  1213. vertices[ 1 ].applyMatrix4( subobjectParseScope.matrix );
  1214. controlPoints[ 0 ].applyMatrix4( subobjectParseScope.matrix );
  1215. controlPoints[ 1 ].applyMatrix4( subobjectParseScope.matrix );
  1216. }
  1217. parentConditionalSegments.push( os );
  1218. }
  1219. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  1220. const tri = faces[ i ];
  1221. if ( separateObjects ) {
  1222. const vertices = tri.vertices;
  1223. for ( let i = 0, l = vertices.length; i < l; i ++ ) {
  1224. vertices[ i ].applyMatrix4( subobjectParseScope.matrix );
  1225. }
  1226. }
  1227. parentFaces.push( tri );
  1228. }
  1229. parentParseScope.totalFaces += subobjectParseScope.totalFaces;
  1230. }
  1231. }
  1232. async processObject( text, subobject, url, parentScope ) {
  1233. const scope = this;
  1234. const parseScope = this.newParseScopeLevel( null, parentScope );
  1235. parseScope.url = url;
  1236. const parentParseScope = parseScope.parentScope; // Set current matrix
  1237. if ( subobject ) {
  1238. parseScope.currentMatrix.multiplyMatrices( parentParseScope.currentMatrix, subobject.matrix );
  1239. parseScope.matrix.copy( subobject.matrix );
  1240. parseScope.inverted = subobject.inverted;
  1241. parseScope.startingConstructionStep = subobject.startingConstructionStep;
  1242. parseScope.mainColourCode = subobject.material.userData.code;
  1243. parseScope.mainEdgeColourCode = subobject.material.userData.edgeMaterial.userData.code;
  1244. parseScope.fileName = subobject.fileName;
  1245. } // Parse the object
  1246. this.objectParse( text, parseScope );
  1247. const subobjects = parseScope.subobjects;
  1248. const promises = [];
  1249. for ( let i = 0, l = subobjects.length; i < l; i ++ ) {
  1250. promises.push( loadSubobject( parseScope.subobjects[ i ] ) );
  1251. } // Kick off of the downloads in parallel but process all the subobjects
  1252. // in order so all the assembly instructions are correct
  1253. const subobjectScopes = await Promise.all( promises );
  1254. for ( let i = 0, l = subobjectScopes.length; i < l; i ++ ) {
  1255. this.finalizeObject( subobjectScopes[ i ] );
  1256. } // If it is root object then finalize this object and compute construction steps
  1257. if ( ! parentParseScope.isFromParse ) {
  1258. this.finalizeObject( parseScope );
  1259. this.computeConstructionSteps( parseScope.groupObject );
  1260. }
  1261. return parseScope;
  1262. function loadSubobject( subobject ) {
  1263. return scope.cache.loadData( subobject.fileName ).then( function ( text ) {
  1264. return scope.processObject( text, subobject, url, parseScope );
  1265. } ).catch( function ( err ) {
  1266. console.warn( 'LDrawLoader: Subobject "' + subobject.fileName + '" could not be loaded.' );
  1267. console.warn( err );
  1268. return null;
  1269. } );
  1270. }
  1271. }
  1272. }
  1273. THREE.LDrawLoader = LDrawLoader;
  1274. } )();