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. groupObject: null,
  648. // If false, it is a root material scope previous to parse
  649. isFromParse: true,
  650. faces: [],
  651. lineSegments: [],
  652. conditionalSegments: [],
  653. totalFaces: 0,
  654. // If true, this object is the start of a construction step
  655. startingConstructionStep: false
  656. };
  657. return newParseScope;
  658. }
  659. addMaterial( material, parseScope ) {
  660. // Adds a material to the material library which is on top of the parse scopes stack. And also to the materials array
  661. const matLib = parseScope.lib;
  662. if ( ! matLib[ material.userData.code ] ) {
  663. this.materials.push( material );
  664. }
  665. matLib[ material.userData.code ] = material;
  666. return this;
  667. }
  668. getMaterial( colourCode, parseScope = this.rootParseScope ) {
  669. // Given a colour code search its material in the parse scopes stack
  670. if ( colourCode.startsWith( '0x2' ) ) {
  671. // Special 'direct' material value (RGB colour)
  672. const colour = colourCode.substring( 3 );
  673. return this.parseColourMetaDirective( new LineParser( 'Direct_Color_' + colour + ' CODE -1 VALUE #' + colour + ' EDGE #' + colour + '' ) );
  674. }
  675. while ( parseScope ) {
  676. const material = parseScope.lib[ colourCode ];
  677. if ( material ) {
  678. return material;
  679. } else {
  680. parseScope = parseScope.parentScope;
  681. }
  682. }
  683. // Material was not found
  684. return null;
  685. }
  686. parseColourMetaDirective( lineParser ) {
  687. // Parses a colour definition and returns a THREE.Material
  688. let code = null;
  689. // Triangle and line colours
  690. let colour = 0xFF00FF;
  691. let edgeColour = 0xFF00FF;
  692. // Transparency
  693. let alpha = 1;
  694. let isTransparent = false;
  695. // Self-illumination:
  696. let luminance = 0;
  697. let finishType = FINISH_TYPE_DEFAULT;
  698. let edgeMaterial = null;
  699. const name = lineParser.getToken();
  700. if ( ! name ) {
  701. throw 'LDrawLoader: Material name was expected after "!COLOUR tag' + lineParser.getLineNumberString() + '.';
  702. }
  703. // Parse tag tokens and their parameters
  704. let token = null;
  705. while ( true ) {
  706. token = lineParser.getToken();
  707. if ( ! token ) {
  708. break;
  709. }
  710. switch ( token.toUpperCase() ) {
  711. case 'CODE':
  712. code = lineParser.getToken();
  713. break;
  714. case 'VALUE':
  715. colour = lineParser.getToken();
  716. if ( colour.startsWith( '0x' ) ) {
  717. colour = '#' + colour.substring( 2 );
  718. } else if ( ! colour.startsWith( '#' ) ) {
  719. throw 'LDrawLoader: Invalid colour while parsing material' + lineParser.getLineNumberString() + '.';
  720. }
  721. break;
  722. case 'EDGE':
  723. edgeColour = lineParser.getToken();
  724. if ( edgeColour.startsWith( '0x' ) ) {
  725. edgeColour = '#' + edgeColour.substring( 2 );
  726. } else if ( ! edgeColour.startsWith( '#' ) ) {
  727. // Try to see if edge colour is a colour code
  728. edgeMaterial = this.getMaterial( edgeColour );
  729. if ( ! edgeMaterial ) {
  730. throw 'LDrawLoader: Invalid edge colour while parsing material' + lineParser.getLineNumberString() + '.';
  731. }
  732. // Get the edge material for this triangle material
  733. edgeMaterial = edgeMaterial.userData.edgeMaterial;
  734. }
  735. break;
  736. case 'ALPHA':
  737. alpha = parseInt( lineParser.getToken() );
  738. if ( isNaN( alpha ) ) {
  739. throw 'LDrawLoader: Invalid alpha value in material definition' + lineParser.getLineNumberString() + '.';
  740. }
  741. alpha = Math.max( 0, Math.min( 1, alpha / 255 ) );
  742. if ( alpha < 1 ) {
  743. isTransparent = true;
  744. }
  745. break;
  746. case 'LUMINANCE':
  747. luminance = parseInt( lineParser.getToken() );
  748. if ( isNaN( luminance ) ) {
  749. throw 'LDrawLoader: Invalid luminance value in material definition' + LineParser.getLineNumberString() + '.';
  750. }
  751. luminance = Math.max( 0, Math.min( 1, luminance / 255 ) );
  752. break;
  753. case 'CHROME':
  754. finishType = FINISH_TYPE_CHROME;
  755. break;
  756. case 'PEARLESCENT':
  757. finishType = FINISH_TYPE_PEARLESCENT;
  758. break;
  759. case 'RUBBER':
  760. finishType = FINISH_TYPE_RUBBER;
  761. break;
  762. case 'MATTE_METALLIC':
  763. finishType = FINISH_TYPE_MATTE_METALLIC;
  764. break;
  765. case 'METAL':
  766. finishType = FINISH_TYPE_METAL;
  767. break;
  768. case 'MATERIAL':
  769. // Not implemented
  770. lineParser.setToEnd();
  771. break;
  772. default:
  773. throw 'LDrawLoader: Unknown token "' + token + '" while parsing material' + lineParser.getLineNumberString() + '.';
  774. break;
  775. }
  776. }
  777. let material = null;
  778. switch ( finishType ) {
  779. case FINISH_TYPE_DEFAULT:
  780. material = new MeshStandardMaterial( { color: colour, roughness: 0.3, metalness: 0 } );
  781. break;
  782. case FINISH_TYPE_PEARLESCENT:
  783. // Try to imitate pearlescency by making the surface glossy
  784. material = new MeshStandardMaterial( { color: colour, roughness: 0.3, metalness: 0.25 } );
  785. break;
  786. case FINISH_TYPE_CHROME:
  787. // Mirror finish surface
  788. material = new MeshStandardMaterial( { color: colour, roughness: 0, metalness: 1 } );
  789. break;
  790. case FINISH_TYPE_RUBBER:
  791. // Rubber finish
  792. material = new MeshStandardMaterial( { color: colour, roughness: 0.9, metalness: 0 } );
  793. break;
  794. case FINISH_TYPE_MATTE_METALLIC:
  795. // Brushed metal finish
  796. material = new MeshStandardMaterial( { color: colour, roughness: 0.8, metalness: 0.4 } );
  797. break;
  798. case FINISH_TYPE_METAL:
  799. // Average metal finish
  800. material = new MeshStandardMaterial( { color: colour, roughness: 0.2, metalness: 0.85 } );
  801. break;
  802. default:
  803. // Should not happen
  804. break;
  805. }
  806. material.transparent = isTransparent;
  807. material.premultipliedAlpha = true;
  808. material.opacity = alpha;
  809. material.depthWrite = ! isTransparent;
  810. material.polygonOffset = true;
  811. material.polygonOffsetFactor = 1;
  812. if ( luminance !== 0 ) {
  813. material.emissive.set( material.color ).multiplyScalar( luminance );
  814. }
  815. if ( ! edgeMaterial ) {
  816. // This is the material used for edges
  817. edgeMaterial = new LineBasicMaterial( {
  818. color: edgeColour,
  819. transparent: isTransparent,
  820. opacity: alpha,
  821. depthWrite: ! isTransparent
  822. } );
  823. edgeMaterial.userData.code = code;
  824. edgeMaterial.name = name + ' - Edge';
  825. // This is the material used for conditional edges
  826. edgeMaterial.userData.conditionalEdgeMaterial = new LDrawConditionalLineMaterial( {
  827. fog: true,
  828. transparent: isTransparent,
  829. depthWrite: ! isTransparent,
  830. color: edgeColour,
  831. opacity: alpha,
  832. } );
  833. }
  834. material.userData.code = code;
  835. material.name = name;
  836. material.userData.edgeMaterial = edgeMaterial;
  837. return material;
  838. }
  839. //
  840. objectParse( text, parseScope ) {
  841. // Retrieve data from the parent parse scope
  842. const currentParseScope = parseScope;
  843. const parentParseScope = currentParseScope.parentScope;
  844. // Main colour codes passed to this subobject (or default codes 16 and 24 if it is the root object)
  845. const mainColourCode = currentParseScope.mainColourCode;
  846. const mainEdgeColourCode = currentParseScope.mainEdgeColourCode;
  847. // Parse result variables
  848. let faces;
  849. let lineSegments;
  850. let conditionalSegments;
  851. const subobjects = [];
  852. let category = null;
  853. let keywords = null;
  854. if ( text.indexOf( '\r\n' ) !== - 1 ) {
  855. // This is faster than String.split with regex that splits on both
  856. text = text.replace( /\r\n/g, '\n' );
  857. }
  858. const lines = text.split( '\n' );
  859. const numLines = lines.length;
  860. let parsingEmbeddedFiles = false;
  861. let currentEmbeddedFileName = null;
  862. let currentEmbeddedText = null;
  863. let bfcCertified = false;
  864. let bfcCCW = true;
  865. let bfcInverted = false;
  866. let bfcCull = true;
  867. let type = '';
  868. let startingConstructionStep = false;
  869. const scope = this;
  870. function parseColourCode( lineParser, forEdge ) {
  871. // Parses next colour code and returns a THREE.Material
  872. let colourCode = lineParser.getToken();
  873. if ( ! forEdge && colourCode === '16' ) {
  874. colourCode = mainColourCode;
  875. }
  876. if ( forEdge && colourCode === '24' ) {
  877. colourCode = mainEdgeColourCode;
  878. }
  879. const material = scope.getMaterial( colourCode, currentParseScope );
  880. if ( ! material ) {
  881. throw 'LDrawLoader: Unknown colour code "' + colourCode + '" is used' + lineParser.getLineNumberString() + ' but it was not defined previously.';
  882. }
  883. return material;
  884. }
  885. function parseVector( lp ) {
  886. const v = new Vector3( parseFloat( lp.getToken() ), parseFloat( lp.getToken() ), parseFloat( lp.getToken() ) );
  887. if ( ! scope.separateObjects ) {
  888. v.applyMatrix4( currentParseScope.currentMatrix );
  889. }
  890. return v;
  891. }
  892. // Parse all line commands
  893. for ( let lineIndex = 0; lineIndex < numLines; lineIndex ++ ) {
  894. const line = lines[ lineIndex ];
  895. if ( line.length === 0 ) continue;
  896. if ( parsingEmbeddedFiles ) {
  897. if ( line.startsWith( '0 FILE ' ) ) {
  898. // Save previous embedded file in the cache
  899. this.cache.setData( currentEmbeddedFileName.toLowerCase(), currentEmbeddedText );
  900. // New embedded text file
  901. currentEmbeddedFileName = line.substring( 7 );
  902. currentEmbeddedText = '';
  903. } else {
  904. currentEmbeddedText += line + '\n';
  905. }
  906. continue;
  907. }
  908. const lp = new LineParser( line, lineIndex + 1 );
  909. lp.seekNonSpace();
  910. if ( lp.isAtTheEnd() ) {
  911. // Empty line
  912. continue;
  913. }
  914. // Parse the line type
  915. const lineType = lp.getToken();
  916. let material;
  917. let segment;
  918. let inverted;
  919. let ccw;
  920. let doubleSided;
  921. let v0, v1, v2, v3, c0, c1, faceNormal;
  922. switch ( lineType ) {
  923. // Line type 0: Comment or META
  924. case '0':
  925. // Parse meta directive
  926. const meta = lp.getToken();
  927. if ( meta ) {
  928. switch ( meta ) {
  929. case '!LDRAW_ORG':
  930. type = lp.getToken();
  931. currentParseScope.type = type;
  932. // If the scale of the object is negated then the triangle winding order
  933. // needs to be flipped.
  934. if (
  935. currentParseScope.matrix.determinant() < 0 && (
  936. scope.separateObjects && isPrimitiveType( type ) ||
  937. ! scope.separateObjects
  938. ) ) {
  939. currentParseScope.inverted = ! currentParseScope.inverted;
  940. }
  941. faces = currentParseScope.faces;
  942. lineSegments = currentParseScope.lineSegments;
  943. conditionalSegments = currentParseScope.conditionalSegments;
  944. break;
  945. case '!COLOUR':
  946. material = this.parseColourMetaDirective( lp );
  947. if ( material ) {
  948. this.addMaterial( material, parseScope );
  949. } else {
  950. console.warn( 'LDrawLoader: Error parsing material' + lp.getLineNumberString() );
  951. }
  952. break;
  953. case '!CATEGORY':
  954. category = lp.getToken();
  955. break;
  956. case '!KEYWORDS':
  957. const newKeywords = lp.getRemainingString().split( ',' );
  958. if ( newKeywords.length > 0 ) {
  959. if ( ! keywords ) {
  960. keywords = [];
  961. }
  962. newKeywords.forEach( function ( keyword ) {
  963. keywords.push( keyword.trim() );
  964. } );
  965. }
  966. break;
  967. case 'FILE':
  968. if ( lineIndex > 0 ) {
  969. // Start embedded text files parsing
  970. parsingEmbeddedFiles = true;
  971. currentEmbeddedFileName = lp.getRemainingString();
  972. currentEmbeddedText = '';
  973. bfcCertified = false;
  974. bfcCCW = true;
  975. }
  976. break;
  977. case 'BFC':
  978. // Changes to the backface culling state
  979. while ( ! lp.isAtTheEnd() ) {
  980. const token = lp.getToken();
  981. switch ( token ) {
  982. case 'CERTIFY':
  983. case 'NOCERTIFY':
  984. bfcCertified = token === 'CERTIFY';
  985. bfcCCW = true;
  986. break;
  987. case 'CW':
  988. case 'CCW':
  989. bfcCCW = token === 'CCW';
  990. break;
  991. case 'INVERTNEXT':
  992. bfcInverted = true;
  993. break;
  994. case 'CLIP':
  995. case 'NOCLIP':
  996. bfcCull = token === 'CLIP';
  997. break;
  998. default:
  999. console.warn( 'THREE.LDrawLoader: BFC directive "' + token + '" is unknown.' );
  1000. break;
  1001. }
  1002. }
  1003. break;
  1004. case 'STEP':
  1005. startingConstructionStep = true;
  1006. break;
  1007. default:
  1008. // Other meta directives are not implemented
  1009. break;
  1010. }
  1011. }
  1012. break;
  1013. // Line type 1: Sub-object file
  1014. case '1':
  1015. material = parseColourCode( lp );
  1016. const posX = parseFloat( lp.getToken() );
  1017. const posY = parseFloat( lp.getToken() );
  1018. const posZ = parseFloat( lp.getToken() );
  1019. const m0 = parseFloat( lp.getToken() );
  1020. const m1 = parseFloat( lp.getToken() );
  1021. const m2 = parseFloat( lp.getToken() );
  1022. const m3 = parseFloat( lp.getToken() );
  1023. const m4 = parseFloat( lp.getToken() );
  1024. const m5 = parseFloat( lp.getToken() );
  1025. const m6 = parseFloat( lp.getToken() );
  1026. const m7 = parseFloat( lp.getToken() );
  1027. const m8 = parseFloat( lp.getToken() );
  1028. const matrix = new Matrix4().set(
  1029. m0, m1, m2, posX,
  1030. m3, m4, m5, posY,
  1031. m6, m7, m8, posZ,
  1032. 0, 0, 0, 1
  1033. );
  1034. let fileName = lp.getRemainingString().trim().replace( /\\/g, '/' );
  1035. if ( scope.fileMap[ fileName ] ) {
  1036. // Found the subobject path in the preloaded file path map
  1037. fileName = scope.fileMap[ fileName ];
  1038. } else {
  1039. // Standardized subfolders
  1040. if ( fileName.startsWith( 's/' ) ) {
  1041. fileName = 'parts/' + fileName;
  1042. } else if ( fileName.startsWith( '48/' ) ) {
  1043. fileName = 'p/' + fileName;
  1044. }
  1045. }
  1046. subobjects.push( {
  1047. material: material,
  1048. matrix: matrix,
  1049. fileName: fileName,
  1050. inverted: bfcInverted !== currentParseScope.inverted,
  1051. startingConstructionStep: startingConstructionStep
  1052. } );
  1053. bfcInverted = false;
  1054. break;
  1055. // Line type 2: Line segment
  1056. case '2':
  1057. material = parseColourCode( lp, true );
  1058. v0 = parseVector( lp );
  1059. v1 = parseVector( lp );
  1060. segment = {
  1061. material: material.userData.edgeMaterial,
  1062. colourCode: material.userData.code,
  1063. v0: v0,
  1064. v1: v1,
  1065. vertices: [ v0, v1 ],
  1066. };
  1067. lineSegments.push( segment );
  1068. break;
  1069. // Line type 5: Conditional Line segment
  1070. case '5':
  1071. material = parseColourCode( lp, true );
  1072. v0 = parseVector( lp );
  1073. v1 = parseVector( lp );
  1074. c0 = parseVector( lp );
  1075. c1 = parseVector( lp );
  1076. segment = {
  1077. material: material.userData.edgeMaterial.userData.conditionalEdgeMaterial,
  1078. colourCode: material.userData.code,
  1079. vertices: [ v0, v1 ],
  1080. controlPoints: [ c0, c1 ],
  1081. };
  1082. conditionalSegments.push( segment );
  1083. break;
  1084. // Line type 3: Triangle
  1085. case '3':
  1086. material = parseColourCode( lp );
  1087. inverted = currentParseScope.inverted;
  1088. ccw = bfcCCW !== inverted;
  1089. doubleSided = ! bfcCertified || ! bfcCull;
  1090. if ( ccw === true ) {
  1091. v0 = parseVector( lp );
  1092. v1 = parseVector( lp );
  1093. v2 = parseVector( lp );
  1094. } else {
  1095. v2 = parseVector( lp );
  1096. v1 = parseVector( lp );
  1097. v0 = parseVector( lp );
  1098. }
  1099. _tempVec0.subVectors( v1, v0 );
  1100. _tempVec1.subVectors( v2, v1 );
  1101. faceNormal = new Vector3()
  1102. .crossVectors( _tempVec0, _tempVec1 )
  1103. .normalize();
  1104. faces.push( {
  1105. material: material,
  1106. colourCode: material.userData.code,
  1107. faceNormal: faceNormal,
  1108. vertices: [ v0, v1, v2 ],
  1109. normals: [ null, null, null ],
  1110. } );
  1111. currentParseScope.totalFaces ++;
  1112. if ( doubleSided === true ) {
  1113. faces.push( {
  1114. material: material,
  1115. colourCode: material.userData.code,
  1116. faceNormal: faceNormal,
  1117. vertices: [ v2, v1, v0 ],
  1118. normals: [ null, null, null ],
  1119. } );
  1120. currentParseScope.totalFaces ++;
  1121. }
  1122. break;
  1123. // Line type 4: Quadrilateral
  1124. case '4':
  1125. material = parseColourCode( lp );
  1126. inverted = currentParseScope.inverted;
  1127. ccw = bfcCCW !== inverted;
  1128. doubleSided = ! bfcCertified || ! bfcCull;
  1129. if ( ccw === true ) {
  1130. v0 = parseVector( lp );
  1131. v1 = parseVector( lp );
  1132. v2 = parseVector( lp );
  1133. v3 = parseVector( lp );
  1134. } else {
  1135. v3 = parseVector( lp );
  1136. v2 = parseVector( lp );
  1137. v1 = parseVector( lp );
  1138. v0 = parseVector( lp );
  1139. }
  1140. _tempVec0.subVectors( v1, v0 );
  1141. _tempVec1.subVectors( v2, v1 );
  1142. faceNormal = new Vector3()
  1143. .crossVectors( _tempVec0, _tempVec1 )
  1144. .normalize();
  1145. // specifically place the triangle diagonal in the v0 and v1 slots so we can
  1146. // account for the doubling of vertices later when smoothing normals.
  1147. faces.push( {
  1148. material: material,
  1149. colourCode: material.userData.code,
  1150. faceNormal: faceNormal,
  1151. vertices: [ v0, v1, v2, v3 ],
  1152. normals: [ null, null, null, null ],
  1153. } );
  1154. currentParseScope.totalFaces += 2;
  1155. if ( doubleSided === true ) {
  1156. faces.push( {
  1157. material: material,
  1158. colourCode: material.userData.code,
  1159. faceNormal: faceNormal,
  1160. vertices: [ v3, v2, v1, v0 ],
  1161. normals: [ null, null, null, null ],
  1162. } );
  1163. currentParseScope.totalFaces += 2;
  1164. }
  1165. break;
  1166. default:
  1167. throw 'LDrawLoader: Unknown line type "' + lineType + '"' + lp.getLineNumberString() + '.';
  1168. break;
  1169. }
  1170. }
  1171. if ( parsingEmbeddedFiles ) {
  1172. this.cache.setData( currentEmbeddedFileName.toLowerCase(), currentEmbeddedText );
  1173. }
  1174. currentParseScope.category = category;
  1175. currentParseScope.keywords = keywords;
  1176. currentParseScope.subobjects = subobjects;
  1177. currentParseScope.numSubobjects = subobjects.length;
  1178. currentParseScope.subobjectIndex = 0;
  1179. const isRoot = ! parentParseScope.isFromParse;
  1180. if ( isRoot || scope.separateObjects && ! isPrimitiveType( type ) ) {
  1181. currentParseScope.groupObject = new Group();
  1182. currentParseScope.groupObject.userData.startingConstructionStep = currentParseScope.startingConstructionStep;
  1183. }
  1184. }
  1185. computeConstructionSteps( model ) {
  1186. // Sets userdata.constructionStep number in Group objects and userData.numConstructionSteps number in the root Group object.
  1187. let stepNumber = 0;
  1188. model.traverse( c => {
  1189. if ( c.isGroup ) {
  1190. if ( c.userData.startingConstructionStep ) {
  1191. stepNumber ++;
  1192. }
  1193. c.userData.constructionStep = stepNumber;
  1194. }
  1195. } );
  1196. model.userData.numConstructionSteps = stepNumber + 1;
  1197. }
  1198. finalizeObject( subobjectParseScope ) {
  1199. // fail gracefully if an object could not be loaded
  1200. if ( subobjectParseScope === null ) {
  1201. return;
  1202. }
  1203. const parentParseScope = subobjectParseScope.parentScope;
  1204. // Smooth the normals if this is a part or if this is a case where the subpart
  1205. // is added directly into the parent model (meaning it will never get smoothed by
  1206. // being added to a part)
  1207. const doSmooth =
  1208. isPartType( subobjectParseScope.type ) ||
  1209. (
  1210. ! isPartType( subobjectParseScope.type ) &&
  1211. ! isModelType( subobjectParseScope.type ) &&
  1212. isModelType( subobjectParseScope.parentScope.type )
  1213. );
  1214. if ( this.smoothNormals && doSmooth ) {
  1215. smoothNormals( subobjectParseScope.faces, subobjectParseScope.lineSegments );
  1216. }
  1217. const isRoot = ! parentParseScope.isFromParse;
  1218. if ( this.separateObjects && ! isPrimitiveType( subobjectParseScope.type ) || isRoot ) {
  1219. const objGroup = subobjectParseScope.groupObject;
  1220. if ( subobjectParseScope.faces.length > 0 ) {
  1221. objGroup.add( createObject( subobjectParseScope.faces, 3, false, subobjectParseScope.totalFaces ) );
  1222. }
  1223. if ( subobjectParseScope.lineSegments.length > 0 ) {
  1224. objGroup.add( createObject( subobjectParseScope.lineSegments, 2 ) );
  1225. }
  1226. if ( subobjectParseScope.conditionalSegments.length > 0 ) {
  1227. objGroup.add( createObject( subobjectParseScope.conditionalSegments, 2, true ) );
  1228. }
  1229. if ( parentParseScope.groupObject ) {
  1230. objGroup.name = subobjectParseScope.fileName;
  1231. objGroup.userData.category = subobjectParseScope.category;
  1232. objGroup.userData.keywords = subobjectParseScope.keywords;
  1233. subobjectParseScope.matrix.decompose( objGroup.position, objGroup.quaternion, objGroup.scale );
  1234. parentParseScope.groupObject.add( objGroup );
  1235. }
  1236. } else {
  1237. const separateObjects = this.separateObjects;
  1238. const parentLineSegments = parentParseScope.lineSegments;
  1239. const parentConditionalSegments = parentParseScope.conditionalSegments;
  1240. const parentFaces = parentParseScope.faces;
  1241. const lineSegments = subobjectParseScope.lineSegments;
  1242. const conditionalSegments = subobjectParseScope.conditionalSegments;
  1243. const faces = subobjectParseScope.faces;
  1244. for ( let i = 0, l = lineSegments.length; i < l; i ++ ) {
  1245. const ls = lineSegments[ i ];
  1246. if ( separateObjects ) {
  1247. const vertices = ls.vertices;
  1248. vertices[ 0 ].applyMatrix4( subobjectParseScope.matrix );
  1249. vertices[ 1 ].applyMatrix4( subobjectParseScope.matrix );
  1250. }
  1251. parentLineSegments.push( ls );
  1252. }
  1253. for ( let i = 0, l = conditionalSegments.length; i < l; i ++ ) {
  1254. const os = conditionalSegments[ i ];
  1255. if ( separateObjects ) {
  1256. const vertices = os.vertices;
  1257. const controlPoints = os.controlPoints;
  1258. vertices[ 0 ].applyMatrix4( subobjectParseScope.matrix );
  1259. vertices[ 1 ].applyMatrix4( subobjectParseScope.matrix );
  1260. controlPoints[ 0 ].applyMatrix4( subobjectParseScope.matrix );
  1261. controlPoints[ 1 ].applyMatrix4( subobjectParseScope.matrix );
  1262. }
  1263. parentConditionalSegments.push( os );
  1264. }
  1265. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  1266. const tri = faces[ i ];
  1267. if ( separateObjects ) {
  1268. const vertices = tri.vertices;
  1269. for ( let i = 0, l = vertices.length; i < l; i ++ ) {
  1270. vertices[ i ] = vertices[ i ].clone().applyMatrix4( subobjectParseScope.matrix );
  1271. }
  1272. _tempVec0.subVectors( vertices[ 1 ], vertices[ 0 ] );
  1273. _tempVec1.subVectors( vertices[ 2 ], vertices[ 1 ] );
  1274. tri.faceNormal.crossVectors( _tempVec0, _tempVec1 ).normalize();
  1275. }
  1276. parentFaces.push( tri );
  1277. }
  1278. parentParseScope.totalFaces += subobjectParseScope.totalFaces;
  1279. }
  1280. }
  1281. async processObject( text, subobject, url, parentScope ) {
  1282. const scope = this;
  1283. const parseScope = this.newParseScopeLevel( null, parentScope );
  1284. parseScope.url = url;
  1285. const parentParseScope = parseScope.parentScope;
  1286. // Set current matrix
  1287. if ( subobject ) {
  1288. parseScope.currentMatrix.multiplyMatrices( parentParseScope.currentMatrix, subobject.matrix );
  1289. parseScope.matrix.copy( subobject.matrix );
  1290. parseScope.inverted = subobject.inverted;
  1291. parseScope.startingConstructionStep = subobject.startingConstructionStep;
  1292. parseScope.mainColourCode = subobject.material.userData.code;
  1293. parseScope.mainEdgeColourCode = subobject.material.userData.edgeMaterial.userData.code;
  1294. parseScope.fileName = subobject.fileName;
  1295. }
  1296. // Parse the object
  1297. this.objectParse( text, parseScope );
  1298. const subobjects = parseScope.subobjects;
  1299. const promises = [];
  1300. for ( let i = 0, l = subobjects.length; i < l; i ++ ) {
  1301. promises.push( loadSubobject( parseScope.subobjects[ i ] ) );
  1302. }
  1303. // Kick off of the downloads in parallel but process all the subobjects
  1304. // in order so all the assembly instructions are correct
  1305. const subobjectScopes = await Promise.all( promises );
  1306. for ( let i = 0, l = subobjectScopes.length; i < l; i ++ ) {
  1307. this.finalizeObject( subobjectScopes[ i ] );
  1308. }
  1309. // If it is root object then finalize this object and compute construction steps
  1310. if ( ! parentParseScope.isFromParse ) {
  1311. this.finalizeObject( parseScope );
  1312. this.computeConstructionSteps( parseScope.groupObject );
  1313. }
  1314. return parseScope;
  1315. function loadSubobject( subobject ) {
  1316. return scope.cache.loadData( subobject.fileName ).then( function ( text ) {
  1317. return scope.processObject( text, subobject, url, parseScope );
  1318. } ).catch( function () {
  1319. console.warn( 'LDrawLoader: Subobject "' + subobject.fileName + '" could not be found.' );
  1320. return null;
  1321. } );
  1322. }
  1323. }
  1324. }
  1325. export { LDrawLoader };