LDrawLoader.js 45 KB

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