LDrawLoader.js 51 KB

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