LDrawLoader.js 51 KB

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