LDrawLoader.js 46 KB

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