LDrawLoader.js 52 KB

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