LDrawLoader.js 45 KB

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