LDrawLoader.js 44 KB

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