LDrawLoader.js 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520
  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. SRGBColorSpace,
  14. Vector3,
  15. Ray
  16. } from 'three';
  17. // Special surface finish tag types.
  18. // Note: "MATERIAL" tag (e.g. GLITTER, SPECKLE) is not implemented
  19. const FINISH_TYPE_DEFAULT = 0;
  20. const FINISH_TYPE_CHROME = 1;
  21. const FINISH_TYPE_PEARLESCENT = 2;
  22. const FINISH_TYPE_RUBBER = 3;
  23. const FINISH_TYPE_MATTE_METALLIC = 4;
  24. const FINISH_TYPE_METAL = 5;
  25. // State machine to search a subobject path.
  26. // The LDraw standard establishes these various possible subfolders.
  27. const FILE_LOCATION_TRY_PARTS = 0;
  28. const FILE_LOCATION_TRY_P = 1;
  29. const FILE_LOCATION_TRY_MODELS = 2;
  30. const FILE_LOCATION_AS_IS = 3;
  31. const FILE_LOCATION_TRY_RELATIVE = 4;
  32. const FILE_LOCATION_TRY_ABSOLUTE = 5;
  33. const FILE_LOCATION_NOT_FOUND = 6;
  34. const MAIN_COLOUR_CODE = '16';
  35. const MAIN_EDGE_COLOUR_CODE = '24';
  36. const COLOR_SPACE_LDRAW = SRGBColorSpace;
  37. const _tempVec0 = new Vector3();
  38. const _tempVec1 = new Vector3();
  39. class ConditionalLineSegments extends LineSegments {
  40. constructor( geometry, material ) {
  41. super( geometry, material );
  42. this.isConditionalLine = true;
  43. }
  44. }
  45. function generateFaceNormals( faces ) {
  46. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  47. const face = faces[ i ];
  48. const vertices = face.vertices;
  49. const v0 = vertices[ 0 ];
  50. const v1 = vertices[ 1 ];
  51. const v2 = vertices[ 2 ];
  52. _tempVec0.subVectors( v1, v0 );
  53. _tempVec1.subVectors( v2, v1 );
  54. face.faceNormal = new Vector3()
  55. .crossVectors( _tempVec0, _tempVec1 )
  56. .normalize();
  57. }
  58. }
  59. const _ray = new Ray();
  60. function smoothNormals( faces, lineSegments, checkSubSegments = false ) {
  61. // NOTE: 1e2 is pretty coarse but was chosen to quantize the resulting value because
  62. // it allows edges to be smoothed as expected (see minifig arms).
  63. // --
  64. // And the vector values are initialize multiplied by 1 + 1e-10 to account for floating
  65. // point errors on vertices along quantization boundaries. Ie after matrix multiplication
  66. // vertices that should be merged might be set to "1.7" and "1.6999..." meaning they won't
  67. // get merged. This added epsilon attempts to push these error values to the same quantized
  68. // value for the sake of hashing. See "AT-ST mini" dishes. See mrdoob/three#23169.
  69. const hashMultiplier = ( 1 + 1e-10 ) * 1e2;
  70. function hashVertex( v ) {
  71. const x = ~ ~ ( v.x * hashMultiplier );
  72. const y = ~ ~ ( v.y * hashMultiplier );
  73. const z = ~ ~ ( v.z * hashMultiplier );
  74. return `${ x },${ y },${ z }`;
  75. }
  76. function hashEdge( v0, v1 ) {
  77. return `${ hashVertex( v0 ) }_${ hashVertex( v1 ) }`;
  78. }
  79. // converts the two vertices to a ray with a normalized direction and origin of 0, 0, 0 projected
  80. // onto the original line.
  81. function toNormalizedRay( v0, v1, targetRay ) {
  82. targetRay.direction.subVectors( v1, v0 ).normalize();
  83. const scalar = v0.dot( targetRay.direction );
  84. targetRay.origin.copy( v0 ).addScaledVector( targetRay.direction, - scalar );
  85. return targetRay;
  86. }
  87. function hashRay( ray ) {
  88. return hashEdge( ray.origin, ray.direction );
  89. }
  90. const hardEdges = new Set();
  91. const hardEdgeRays = new Map();
  92. const halfEdgeList = {};
  93. const normals = [];
  94. // Save the list of hard edges by hash
  95. for ( let i = 0, l = lineSegments.length; i < l; i ++ ) {
  96. const ls = lineSegments[ i ];
  97. const vertices = ls.vertices;
  98. const v0 = vertices[ 0 ];
  99. const v1 = vertices[ 1 ];
  100. hardEdges.add( hashEdge( v0, v1 ) );
  101. hardEdges.add( hashEdge( v1, v0 ) );
  102. // only generate the hard edge ray map if we're checking subsegments because it's more expensive to check
  103. // and requires more memory.
  104. if ( checkSubSegments ) {
  105. // add both ray directions to the map
  106. const ray = toNormalizedRay( v0, v1, new Ray() );
  107. const rh1 = hashRay( ray );
  108. if ( ! hardEdgeRays.has( rh1 ) ) {
  109. toNormalizedRay( v1, v0, ray );
  110. const rh2 = hashRay( ray );
  111. const info = {
  112. ray,
  113. distances: [],
  114. };
  115. hardEdgeRays.set( rh1, info );
  116. hardEdgeRays.set( rh2, info );
  117. }
  118. // store both segments ends in min, max order in the distances array to check if a face edge is a
  119. // subsegment later.
  120. const info = hardEdgeRays.get( rh1 );
  121. let d0 = info.ray.direction.dot( v0 );
  122. let d1 = info.ray.direction.dot( v1 );
  123. if ( d0 > d1 ) {
  124. [ d0, d1 ] = [ d1, d0 ];
  125. }
  126. info.distances.push( d0, d1 );
  127. }
  128. }
  129. // track the half edges associated with each triangle
  130. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  131. const tri = faces[ i ];
  132. const vertices = tri.vertices;
  133. const vertCount = vertices.length;
  134. for ( let i2 = 0; i2 < vertCount; i2 ++ ) {
  135. const index = i2;
  136. const next = ( i2 + 1 ) % vertCount;
  137. const v0 = vertices[ index ];
  138. const v1 = vertices[ next ];
  139. const hash = hashEdge( v0, v1 );
  140. // don't add the triangle if the edge is supposed to be hard
  141. if ( hardEdges.has( hash ) ) {
  142. continue;
  143. }
  144. // if checking subsegments then check to see if this edge lies on a hard edge ray and whether its within any ray bounds
  145. if ( checkSubSegments ) {
  146. toNormalizedRay( v0, v1, _ray );
  147. const rayHash = hashRay( _ray );
  148. if ( hardEdgeRays.has( rayHash ) ) {
  149. const info = hardEdgeRays.get( rayHash );
  150. const { ray, distances } = info;
  151. let d0 = ray.direction.dot( v0 );
  152. let d1 = ray.direction.dot( v1 );
  153. if ( d0 > d1 ) {
  154. [ d0, d1 ] = [ d1, d0 ];
  155. }
  156. // return early if the face edge is found to be a subsegment of a line edge meaning the edge will have "hard" normals
  157. let found = false;
  158. for ( let i = 0, l = distances.length; i < l; i += 2 ) {
  159. if ( d0 >= distances[ i ] && d1 <= distances[ i + 1 ] ) {
  160. found = true;
  161. break;
  162. }
  163. }
  164. if ( found ) {
  165. continue;
  166. }
  167. }
  168. }
  169. const info = {
  170. index: index,
  171. tri: tri
  172. };
  173. halfEdgeList[ hash ] = info;
  174. }
  175. }
  176. // Iterate until we've tried to connect all faces to share normals
  177. while ( true ) {
  178. // Stop if there are no more faces left
  179. let halfEdge = null;
  180. for ( const key in halfEdgeList ) {
  181. halfEdge = halfEdgeList[ key ];
  182. break;
  183. }
  184. if ( halfEdge === null ) {
  185. break;
  186. }
  187. // Exhaustively find all connected faces
  188. const queue = [ halfEdge ];
  189. while ( queue.length > 0 ) {
  190. // initialize all vertex normals in this triangle
  191. const tri = queue.pop().tri;
  192. const vertices = tri.vertices;
  193. const vertNormals = tri.normals;
  194. const faceNormal = tri.faceNormal;
  195. // Check if any edge is connected to another triangle edge
  196. const vertCount = vertices.length;
  197. for ( let i2 = 0; i2 < vertCount; i2 ++ ) {
  198. const index = i2;
  199. const next = ( i2 + 1 ) % vertCount;
  200. const v0 = vertices[ index ];
  201. const v1 = vertices[ next ];
  202. // delete this triangle from the list so it won't be found again
  203. const hash = hashEdge( v0, v1 );
  204. delete halfEdgeList[ hash ];
  205. const reverseHash = hashEdge( v1, v0 );
  206. const otherInfo = halfEdgeList[ reverseHash ];
  207. if ( otherInfo ) {
  208. const otherTri = otherInfo.tri;
  209. const otherIndex = otherInfo.index;
  210. const otherNormals = otherTri.normals;
  211. const otherVertCount = otherNormals.length;
  212. const otherFaceNormal = otherTri.faceNormal;
  213. // NOTE: If the angle between faces is > 67.5 degrees then assume it's
  214. // hard edge. There are some cases where the line segments do not line up exactly
  215. // with or span multiple triangle edges (see Lunar Vehicle wheels).
  216. if ( Math.abs( otherTri.faceNormal.dot( tri.faceNormal ) ) < 0.25 ) {
  217. continue;
  218. }
  219. // if this triangle has already been traversed then it won't be in
  220. // the halfEdgeList. If it has not then add it to the queue and delete
  221. // it so it won't be found again.
  222. if ( reverseHash in halfEdgeList ) {
  223. queue.push( otherInfo );
  224. delete halfEdgeList[ reverseHash ];
  225. }
  226. // share the first normal
  227. const otherNext = ( otherIndex + 1 ) % otherVertCount;
  228. if (
  229. vertNormals[ index ] && otherNormals[ otherNext ] &&
  230. vertNormals[ index ] !== otherNormals[ otherNext ]
  231. ) {
  232. otherNormals[ otherNext ].norm.add( vertNormals[ index ].norm );
  233. vertNormals[ index ].norm = otherNormals[ otherNext ].norm;
  234. }
  235. let sharedNormal1 = vertNormals[ index ] || otherNormals[ otherNext ];
  236. if ( sharedNormal1 === null ) {
  237. // it's possible to encounter an edge of a triangle that has already been traversed meaning
  238. // both edges already have different normals defined and shared. To work around this we create
  239. // a wrapper object so when those edges are merged the normals can be updated everywhere.
  240. sharedNormal1 = { norm: new Vector3() };
  241. normals.push( sharedNormal1.norm );
  242. }
  243. if ( vertNormals[ index ] === null ) {
  244. vertNormals[ index ] = sharedNormal1;
  245. sharedNormal1.norm.add( faceNormal );
  246. }
  247. if ( otherNormals[ otherNext ] === null ) {
  248. otherNormals[ otherNext ] = sharedNormal1;
  249. sharedNormal1.norm.add( otherFaceNormal );
  250. }
  251. // share the second normal
  252. if (
  253. vertNormals[ next ] && otherNormals[ otherIndex ] &&
  254. vertNormals[ next ] !== otherNormals[ otherIndex ]
  255. ) {
  256. otherNormals[ otherIndex ].norm.add( vertNormals[ next ].norm );
  257. vertNormals[ next ].norm = otherNormals[ otherIndex ].norm;
  258. }
  259. let sharedNormal2 = vertNormals[ next ] || otherNormals[ otherIndex ];
  260. if ( sharedNormal2 === null ) {
  261. sharedNormal2 = { norm: new Vector3() };
  262. normals.push( sharedNormal2.norm );
  263. }
  264. if ( vertNormals[ next ] === null ) {
  265. vertNormals[ next ] = sharedNormal2;
  266. sharedNormal2.norm.add( faceNormal );
  267. }
  268. if ( otherNormals[ otherIndex ] === null ) {
  269. otherNormals[ otherIndex ] = sharedNormal2;
  270. sharedNormal2.norm.add( otherFaceNormal );
  271. }
  272. }
  273. }
  274. }
  275. }
  276. // The normals of each face have been added up so now we average them by normalizing the vector.
  277. for ( let i = 0, l = normals.length; i < l; i ++ ) {
  278. normals[ i ].normalize();
  279. }
  280. }
  281. function isPartType( type ) {
  282. return type === 'Part' || type === 'Unofficial_Part';
  283. }
  284. function isPrimitiveType( type ) {
  285. return /primitive/i.test( type ) || type === 'Subpart';
  286. }
  287. class LineParser {
  288. constructor( line, lineNumber ) {
  289. this.line = line;
  290. this.lineLength = line.length;
  291. this.currentCharIndex = 0;
  292. this.currentChar = ' ';
  293. this.lineNumber = lineNumber;
  294. }
  295. seekNonSpace() {
  296. while ( this.currentCharIndex < this.lineLength ) {
  297. this.currentChar = this.line.charAt( this.currentCharIndex );
  298. if ( this.currentChar !== ' ' && this.currentChar !== '\t' ) {
  299. return;
  300. }
  301. this.currentCharIndex ++;
  302. }
  303. }
  304. getToken() {
  305. const pos0 = this.currentCharIndex ++;
  306. // Seek space
  307. while ( this.currentCharIndex < this.lineLength ) {
  308. this.currentChar = this.line.charAt( this.currentCharIndex );
  309. if ( this.currentChar === ' ' || this.currentChar === '\t' ) {
  310. break;
  311. }
  312. this.currentCharIndex ++;
  313. }
  314. const pos1 = this.currentCharIndex;
  315. this.seekNonSpace();
  316. return this.line.substring( pos0, pos1 );
  317. }
  318. getVector() {
  319. return new Vector3( parseFloat( this.getToken() ), parseFloat( this.getToken() ), parseFloat( this.getToken() ) );
  320. }
  321. getRemainingString() {
  322. return this.line.substring( this.currentCharIndex, this.lineLength );
  323. }
  324. isAtTheEnd() {
  325. return this.currentCharIndex >= this.lineLength;
  326. }
  327. setToEnd() {
  328. this.currentCharIndex = this.lineLength;
  329. }
  330. getLineNumberString() {
  331. return this.lineNumber >= 0 ? ' at line ' + this.lineNumber : '';
  332. }
  333. }
  334. // Fetches and parses an intermediate representation of LDraw parts files.
  335. class LDrawParsedCache {
  336. constructor( loader ) {
  337. this.loader = loader;
  338. this._cache = {};
  339. }
  340. cloneResult( original ) {
  341. const result = {};
  342. // vertices are transformed and normals computed before being converted to geometry
  343. // so these pieces must be cloned.
  344. result.faces = original.faces.map( face => {
  345. return {
  346. colorCode: face.colorCode,
  347. material: face.material,
  348. vertices: face.vertices.map( v => v.clone() ),
  349. normals: face.normals.map( () => null ),
  350. faceNormal: null
  351. };
  352. } );
  353. result.conditionalSegments = original.conditionalSegments.map( face => {
  354. return {
  355. colorCode: face.colorCode,
  356. material: face.material,
  357. vertices: face.vertices.map( v => v.clone() ),
  358. controlPoints: face.controlPoints.map( v => v.clone() )
  359. };
  360. } );
  361. result.lineSegments = original.lineSegments.map( face => {
  362. return {
  363. colorCode: face.colorCode,
  364. material: face.material,
  365. vertices: face.vertices.map( v => v.clone() )
  366. };
  367. } );
  368. // none if this is subsequently modified
  369. result.type = original.type;
  370. result.category = original.category;
  371. result.keywords = original.keywords;
  372. result.author = original.author;
  373. result.subobjects = original.subobjects;
  374. result.fileName = original.fileName;
  375. result.totalFaces = original.totalFaces;
  376. result.startingBuildingStep = original.startingBuildingStep;
  377. result.materials = original.materials;
  378. result.group = null;
  379. return result;
  380. }
  381. async fetchData( fileName ) {
  382. let triedLowerCase = false;
  383. let locationState = FILE_LOCATION_TRY_PARTS;
  384. while ( locationState !== FILE_LOCATION_NOT_FOUND ) {
  385. let subobjectURL = fileName;
  386. switch ( locationState ) {
  387. case FILE_LOCATION_AS_IS:
  388. locationState = locationState + 1;
  389. break;
  390. case FILE_LOCATION_TRY_PARTS:
  391. subobjectURL = 'parts/' + subobjectURL;
  392. locationState = locationState + 1;
  393. break;
  394. case FILE_LOCATION_TRY_P:
  395. subobjectURL = 'p/' + subobjectURL;
  396. locationState = locationState + 1;
  397. break;
  398. case FILE_LOCATION_TRY_MODELS:
  399. subobjectURL = 'models/' + subobjectURL;
  400. locationState = locationState + 1;
  401. break;
  402. case FILE_LOCATION_TRY_RELATIVE:
  403. subobjectURL = fileName.substring( 0, fileName.lastIndexOf( '/' ) + 1 ) + subobjectURL;
  404. locationState = locationState + 1;
  405. break;
  406. case FILE_LOCATION_TRY_ABSOLUTE:
  407. if ( triedLowerCase ) {
  408. // Try absolute path
  409. locationState = FILE_LOCATION_NOT_FOUND;
  410. } else {
  411. // Next attempt is lower case
  412. fileName = fileName.toLowerCase();
  413. subobjectURL = fileName;
  414. triedLowerCase = true;
  415. locationState = FILE_LOCATION_TRY_PARTS;
  416. }
  417. break;
  418. }
  419. const loader = this.loader;
  420. const fileLoader = new FileLoader( loader.manager );
  421. fileLoader.setPath( loader.partsLibraryPath );
  422. fileLoader.setRequestHeader( loader.requestHeader );
  423. fileLoader.setWithCredentials( loader.withCredentials );
  424. try {
  425. const text = await fileLoader.loadAsync( subobjectURL );
  426. return text;
  427. } catch ( _ ) {
  428. continue;
  429. }
  430. }
  431. throw new Error( 'LDrawLoader: Subobject "' + fileName + '" could not be loaded.' );
  432. }
  433. parse( text, fileName = null ) {
  434. const loader = this.loader;
  435. // final results
  436. const faces = [];
  437. const lineSegments = [];
  438. const conditionalSegments = [];
  439. const subobjects = [];
  440. const materials = {};
  441. const getLocalMaterial = colorCode => {
  442. return materials[ colorCode ] || null;
  443. };
  444. let type = 'Model';
  445. let category = null;
  446. let keywords = null;
  447. let author = null;
  448. let totalFaces = 0;
  449. // split into lines
  450. if ( text.indexOf( '\r\n' ) !== - 1 ) {
  451. // This is faster than String.split with regex that splits on both
  452. text = text.replace( /\r\n/g, '\n' );
  453. }
  454. const lines = text.split( '\n' );
  455. const numLines = lines.length;
  456. let parsingEmbeddedFiles = false;
  457. let currentEmbeddedFileName = null;
  458. let currentEmbeddedText = null;
  459. let bfcCertified = false;
  460. let bfcCCW = true;
  461. let bfcInverted = false;
  462. let bfcCull = true;
  463. let startingBuildingStep = false;
  464. // Parse all line commands
  465. for ( let lineIndex = 0; lineIndex < numLines; lineIndex ++ ) {
  466. const line = lines[ lineIndex ];
  467. if ( line.length === 0 ) continue;
  468. if ( parsingEmbeddedFiles ) {
  469. if ( line.startsWith( '0 FILE ' ) ) {
  470. // Save previous embedded file in the cache
  471. this.setData( currentEmbeddedFileName, currentEmbeddedText );
  472. // New embedded text file
  473. currentEmbeddedFileName = line.substring( 7 );
  474. currentEmbeddedText = '';
  475. } else {
  476. currentEmbeddedText += line + '\n';
  477. }
  478. continue;
  479. }
  480. const lp = new LineParser( line, lineIndex + 1 );
  481. lp.seekNonSpace();
  482. if ( lp.isAtTheEnd() ) {
  483. // Empty line
  484. continue;
  485. }
  486. // Parse the line type
  487. const lineType = lp.getToken();
  488. let material;
  489. let colorCode;
  490. let segment;
  491. let ccw;
  492. let doubleSided;
  493. let v0, v1, v2, v3, c0, c1;
  494. switch ( lineType ) {
  495. // Line type 0: Comment or META
  496. case '0':
  497. // Parse meta directive
  498. const meta = lp.getToken();
  499. if ( meta ) {
  500. switch ( meta ) {
  501. case '!LDRAW_ORG':
  502. type = lp.getToken();
  503. break;
  504. case '!COLOUR':
  505. material = loader.parseColorMetaDirective( lp );
  506. if ( material ) {
  507. materials[ material.userData.code ] = material;
  508. } else {
  509. console.warn( 'LDrawLoader: Error parsing material' + lp.getLineNumberString() );
  510. }
  511. break;
  512. case '!CATEGORY':
  513. category = lp.getToken();
  514. break;
  515. case '!KEYWORDS':
  516. const newKeywords = lp.getRemainingString().split( ',' );
  517. if ( newKeywords.length > 0 ) {
  518. if ( ! keywords ) {
  519. keywords = [];
  520. }
  521. newKeywords.forEach( function ( keyword ) {
  522. keywords.push( keyword.trim() );
  523. } );
  524. }
  525. break;
  526. case 'FILE':
  527. if ( lineIndex > 0 ) {
  528. // Start embedded text files parsing
  529. parsingEmbeddedFiles = true;
  530. currentEmbeddedFileName = lp.getRemainingString();
  531. currentEmbeddedText = '';
  532. bfcCertified = false;
  533. bfcCCW = true;
  534. }
  535. break;
  536. case 'BFC':
  537. // Changes to the backface culling state
  538. while ( ! lp.isAtTheEnd() ) {
  539. const token = lp.getToken();
  540. switch ( token ) {
  541. case 'CERTIFY':
  542. case 'NOCERTIFY':
  543. bfcCertified = token === 'CERTIFY';
  544. bfcCCW = true;
  545. break;
  546. case 'CW':
  547. case 'CCW':
  548. bfcCCW = token === 'CCW';
  549. break;
  550. case 'INVERTNEXT':
  551. bfcInverted = true;
  552. break;
  553. case 'CLIP':
  554. case 'NOCLIP':
  555. bfcCull = token === 'CLIP';
  556. break;
  557. default:
  558. console.warn( 'THREE.LDrawLoader: BFC directive "' + token + '" is unknown.' );
  559. break;
  560. }
  561. }
  562. break;
  563. case 'STEP':
  564. startingBuildingStep = true;
  565. break;
  566. case 'Author:':
  567. author = lp.getToken();
  568. break;
  569. default:
  570. // Other meta directives are not implemented
  571. break;
  572. }
  573. }
  574. break;
  575. // Line type 1: Sub-object file
  576. case '1':
  577. colorCode = lp.getToken();
  578. material = getLocalMaterial( colorCode );
  579. const posX = parseFloat( lp.getToken() );
  580. const posY = parseFloat( lp.getToken() );
  581. const posZ = parseFloat( lp.getToken() );
  582. const m0 = parseFloat( lp.getToken() );
  583. const m1 = parseFloat( lp.getToken() );
  584. const m2 = parseFloat( lp.getToken() );
  585. const m3 = parseFloat( lp.getToken() );
  586. const m4 = parseFloat( lp.getToken() );
  587. const m5 = parseFloat( lp.getToken() );
  588. const m6 = parseFloat( lp.getToken() );
  589. const m7 = parseFloat( lp.getToken() );
  590. const m8 = parseFloat( lp.getToken() );
  591. const matrix = new Matrix4().set(
  592. m0, m1, m2, posX,
  593. m3, m4, m5, posY,
  594. m6, m7, m8, posZ,
  595. 0, 0, 0, 1
  596. );
  597. let fileName = lp.getRemainingString().trim().replace( /\\/g, '/' );
  598. if ( loader.fileMap[ fileName ] ) {
  599. // Found the subobject path in the preloaded file path map
  600. fileName = loader.fileMap[ fileName ];
  601. } else {
  602. // Standardized subfolders
  603. if ( fileName.startsWith( 's/' ) ) {
  604. fileName = 'parts/' + fileName;
  605. } else if ( fileName.startsWith( '48/' ) ) {
  606. fileName = 'p/' + fileName;
  607. }
  608. }
  609. subobjects.push( {
  610. material: material,
  611. colorCode: colorCode,
  612. matrix: matrix,
  613. fileName: fileName,
  614. inverted: bfcInverted,
  615. startingBuildingStep: startingBuildingStep
  616. } );
  617. startingBuildingStep = false;
  618. bfcInverted = false;
  619. break;
  620. // Line type 2: Line segment
  621. case '2':
  622. colorCode = lp.getToken();
  623. material = getLocalMaterial( colorCode );
  624. v0 = lp.getVector();
  625. v1 = lp.getVector();
  626. segment = {
  627. material: material,
  628. colorCode: colorCode,
  629. vertices: [ v0, v1 ],
  630. };
  631. lineSegments.push( segment );
  632. break;
  633. // Line type 5: Conditional Line segment
  634. case '5':
  635. colorCode = lp.getToken();
  636. material = getLocalMaterial( colorCode );
  637. v0 = lp.getVector();
  638. v1 = lp.getVector();
  639. c0 = lp.getVector();
  640. c1 = lp.getVector();
  641. segment = {
  642. material: material,
  643. colorCode: colorCode,
  644. vertices: [ v0, v1 ],
  645. controlPoints: [ c0, c1 ],
  646. };
  647. conditionalSegments.push( segment );
  648. break;
  649. // Line type 3: Triangle
  650. case '3':
  651. colorCode = lp.getToken();
  652. material = getLocalMaterial( colorCode );
  653. ccw = bfcCCW;
  654. doubleSided = ! bfcCertified || ! bfcCull;
  655. if ( ccw === true ) {
  656. v0 = lp.getVector();
  657. v1 = lp.getVector();
  658. v2 = lp.getVector();
  659. } else {
  660. v2 = lp.getVector();
  661. v1 = lp.getVector();
  662. v0 = lp.getVector();
  663. }
  664. faces.push( {
  665. material: material,
  666. colorCode: colorCode,
  667. faceNormal: null,
  668. vertices: [ v0, v1, v2 ],
  669. normals: [ null, null, null ],
  670. } );
  671. totalFaces ++;
  672. if ( doubleSided === true ) {
  673. faces.push( {
  674. material: material,
  675. colorCode: colorCode,
  676. faceNormal: null,
  677. vertices: [ v2, v1, v0 ],
  678. normals: [ null, null, null ],
  679. } );
  680. totalFaces ++;
  681. }
  682. break;
  683. // Line type 4: Quadrilateral
  684. case '4':
  685. colorCode = lp.getToken();
  686. material = getLocalMaterial( colorCode );
  687. ccw = bfcCCW;
  688. doubleSided = ! bfcCertified || ! bfcCull;
  689. if ( ccw === true ) {
  690. v0 = lp.getVector();
  691. v1 = lp.getVector();
  692. v2 = lp.getVector();
  693. v3 = lp.getVector();
  694. } else {
  695. v3 = lp.getVector();
  696. v2 = lp.getVector();
  697. v1 = lp.getVector();
  698. v0 = lp.getVector();
  699. }
  700. // specifically place the triangle diagonal in the v0 and v1 slots so we can
  701. // account for the doubling of vertices later when smoothing normals.
  702. faces.push( {
  703. material: material,
  704. colorCode: colorCode,
  705. faceNormal: null,
  706. vertices: [ v0, v1, v2, v3 ],
  707. normals: [ null, null, null, null ],
  708. } );
  709. totalFaces += 2;
  710. if ( doubleSided === true ) {
  711. faces.push( {
  712. material: material,
  713. colorCode: colorCode,
  714. faceNormal: null,
  715. vertices: [ v3, v2, v1, v0 ],
  716. normals: [ null, null, null, null ],
  717. } );
  718. totalFaces += 2;
  719. }
  720. break;
  721. default:
  722. throw new Error( 'LDrawLoader: Unknown line type "' + lineType + '"' + lp.getLineNumberString() + '.' );
  723. }
  724. }
  725. if ( parsingEmbeddedFiles ) {
  726. this.setData( currentEmbeddedFileName, currentEmbeddedText );
  727. }
  728. return {
  729. faces,
  730. conditionalSegments,
  731. lineSegments,
  732. type,
  733. category,
  734. keywords,
  735. author,
  736. subobjects,
  737. totalFaces,
  738. startingBuildingStep,
  739. materials,
  740. fileName,
  741. group: null
  742. };
  743. }
  744. // returns an (optionally cloned) instance of the data
  745. getData( fileName, clone = true ) {
  746. const key = fileName.toLowerCase();
  747. const result = this._cache[ key ];
  748. if ( result === null || result instanceof Promise ) {
  749. return null;
  750. }
  751. if ( clone ) {
  752. return this.cloneResult( result );
  753. } else {
  754. return result;
  755. }
  756. }
  757. // kicks off a fetch and parse of the requested data if it hasn't already been loaded. Returns when
  758. // the data is ready to use and can be retrieved synchronously with "getData".
  759. async ensureDataLoaded( fileName ) {
  760. const key = fileName.toLowerCase();
  761. if ( ! ( key in this._cache ) ) {
  762. // replace the promise with a copy of the parsed data for immediate processing
  763. this._cache[ key ] = this.fetchData( fileName ).then( text => {
  764. const info = this.parse( text, fileName );
  765. this._cache[ key ] = info;
  766. return info;
  767. } );
  768. }
  769. await this._cache[ key ];
  770. }
  771. // sets the data in the cache from parsed data
  772. setData( fileName, text ) {
  773. const key = fileName.toLowerCase();
  774. this._cache[ key ] = this.parse( text, fileName );
  775. }
  776. }
  777. // returns the material for an associated color code. If the color code is 16 for a face or 24 for
  778. // an edge then the passthroughColorCode is used.
  779. function getMaterialFromCode( colorCode, parentColorCode, materialHierarchy, forEdge ) {
  780. const isPassthrough = ! forEdge && colorCode === MAIN_COLOUR_CODE || forEdge && colorCode === MAIN_EDGE_COLOUR_CODE;
  781. if ( isPassthrough ) {
  782. colorCode = parentColorCode;
  783. }
  784. return materialHierarchy[ colorCode ] || null;
  785. }
  786. // Class used to parse and build LDraw parts as three.js objects and cache them if they're a "Part" type.
  787. class LDrawPartsGeometryCache {
  788. constructor( loader ) {
  789. this.loader = loader;
  790. this.parseCache = new LDrawParsedCache( loader );
  791. this._cache = {};
  792. }
  793. // Convert the given file information into a mesh by processing subobjects.
  794. async processIntoMesh( info ) {
  795. const loader = this.loader;
  796. const parseCache = this.parseCache;
  797. const faceMaterials = new Set();
  798. // Processes the part subobject information to load child parts and merge geometry onto part
  799. // piece object.
  800. const processInfoSubobjects = async ( info, subobject = null ) => {
  801. const subobjects = info.subobjects;
  802. const promises = [];
  803. // Trigger load of all subobjects. If a subobject isn't a primitive then load it as a separate
  804. // group which lets instruction steps apply correctly.
  805. for ( let i = 0, l = subobjects.length; i < l; i ++ ) {
  806. const subobject = subobjects[ i ];
  807. const promise = parseCache.ensureDataLoaded( subobject.fileName ).then( () => {
  808. const subobjectInfo = parseCache.getData( subobject.fileName, false );
  809. if ( ! isPrimitiveType( subobjectInfo.type ) ) {
  810. return this.loadModel( subobject.fileName ).catch( error => {
  811. console.warn( error );
  812. return null;
  813. } );
  814. }
  815. return processInfoSubobjects( parseCache.getData( subobject.fileName ), subobject );
  816. } );
  817. promises.push( promise );
  818. }
  819. const group = new Group();
  820. group.userData.category = info.category;
  821. group.userData.keywords = info.keywords;
  822. group.userData.author = info.author;
  823. group.userData.type = info.type;
  824. group.userData.fileName = info.fileName;
  825. info.group = group;
  826. const subobjectInfos = await Promise.all( promises );
  827. for ( let i = 0, l = subobjectInfos.length; i < l; i ++ ) {
  828. const subobject = info.subobjects[ i ];
  829. const subobjectInfo = subobjectInfos[ i ];
  830. if ( subobjectInfo === null ) {
  831. // the subobject failed to load
  832. continue;
  833. }
  834. // if the subobject was loaded as a separate group then apply the parent scopes materials
  835. if ( subobjectInfo.isGroup ) {
  836. const subobjectGroup = subobjectInfo;
  837. subobject.matrix.decompose( subobjectGroup.position, subobjectGroup.quaternion, subobjectGroup.scale );
  838. subobjectGroup.userData.startingBuildingStep = subobject.startingBuildingStep;
  839. subobjectGroup.name = subobject.fileName;
  840. loader.applyMaterialsToMesh( subobjectGroup, subobject.colorCode, info.materials );
  841. subobjectGroup.userData.colorCode = subobject.colorCode;
  842. group.add( subobjectGroup );
  843. continue;
  844. }
  845. // add the subobject group if it has children in case it has both children and primitives
  846. if ( subobjectInfo.group.children.length ) {
  847. group.add( subobjectInfo.group );
  848. }
  849. // transform the primitives into the local space of the parent piece and append them to
  850. // to the parent primitives list.
  851. const parentLineSegments = info.lineSegments;
  852. const parentConditionalSegments = info.conditionalSegments;
  853. const parentFaces = info.faces;
  854. const lineSegments = subobjectInfo.lineSegments;
  855. const conditionalSegments = subobjectInfo.conditionalSegments;
  856. const faces = subobjectInfo.faces;
  857. const matrix = subobject.matrix;
  858. const inverted = subobject.inverted;
  859. const matrixScaleInverted = matrix.determinant() < 0;
  860. const colorCode = subobject.colorCode;
  861. const lineColorCode = colorCode === MAIN_COLOUR_CODE ? MAIN_EDGE_COLOUR_CODE : colorCode;
  862. for ( let i = 0, l = lineSegments.length; i < l; i ++ ) {
  863. const ls = lineSegments[ i ];
  864. const vertices = ls.vertices;
  865. vertices[ 0 ].applyMatrix4( matrix );
  866. vertices[ 1 ].applyMatrix4( matrix );
  867. ls.colorCode = ls.colorCode === MAIN_EDGE_COLOUR_CODE ? lineColorCode : ls.colorCode;
  868. ls.material = ls.material || getMaterialFromCode( ls.colorCode, ls.colorCode, info.materials, true );
  869. parentLineSegments.push( ls );
  870. }
  871. for ( let i = 0, l = conditionalSegments.length; i < l; i ++ ) {
  872. const os = conditionalSegments[ i ];
  873. const vertices = os.vertices;
  874. const controlPoints = os.controlPoints;
  875. vertices[ 0 ].applyMatrix4( matrix );
  876. vertices[ 1 ].applyMatrix4( matrix );
  877. controlPoints[ 0 ].applyMatrix4( matrix );
  878. controlPoints[ 1 ].applyMatrix4( matrix );
  879. os.colorCode = os.colorCode === MAIN_EDGE_COLOUR_CODE ? lineColorCode : os.colorCode;
  880. os.material = os.material || getMaterialFromCode( os.colorCode, os.colorCode, info.materials, true );
  881. parentConditionalSegments.push( os );
  882. }
  883. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  884. const tri = faces[ i ];
  885. const vertices = tri.vertices;
  886. for ( let i = 0, l = vertices.length; i < l; i ++ ) {
  887. vertices[ i ].applyMatrix4( matrix );
  888. }
  889. tri.colorCode = tri.colorCode === MAIN_COLOUR_CODE ? colorCode : tri.colorCode;
  890. tri.material = tri.material || getMaterialFromCode( tri.colorCode, colorCode, info.materials, false );
  891. faceMaterials.add( tri.colorCode );
  892. // If the scale of the object is negated then the triangle winding order
  893. // needs to be flipped.
  894. if ( matrixScaleInverted !== inverted ) {
  895. vertices.reverse();
  896. }
  897. parentFaces.push( tri );
  898. }
  899. info.totalFaces += subobjectInfo.totalFaces;
  900. }
  901. // Apply the parent subobjects pass through material code to this object. This is done several times due
  902. // to material scoping.
  903. if ( subobject ) {
  904. loader.applyMaterialsToMesh( group, subobject.colorCode, info.materials );
  905. group.userData.colorCode = subobject.colorCode;
  906. }
  907. return info;
  908. };
  909. // Track material use to see if we need to use the normal smooth slow path for hard edges.
  910. for ( let i = 0, l = info.faces; i < l; i ++ ) {
  911. faceMaterials.add( info.faces[ i ].colorCode );
  912. }
  913. await processInfoSubobjects( info );
  914. if ( loader.smoothNormals ) {
  915. const checkSubSegments = faceMaterials.size > 1;
  916. generateFaceNormals( info.faces );
  917. smoothNormals( info.faces, info.lineSegments, checkSubSegments );
  918. }
  919. // Add the primitive objects and metadata.
  920. const group = info.group;
  921. if ( info.faces.length > 0 ) {
  922. group.add( createObject( this.loader, info.faces, 3, false, info.totalFaces ) );
  923. }
  924. if ( info.lineSegments.length > 0 ) {
  925. group.add( createObject( this.loader, info.lineSegments, 2 ) );
  926. }
  927. if ( info.conditionalSegments.length > 0 ) {
  928. group.add( createObject( this.loader, info.conditionalSegments, 2, true ) );
  929. }
  930. return group;
  931. }
  932. hasCachedModel( fileName ) {
  933. return fileName !== null && fileName.toLowerCase() in this._cache;
  934. }
  935. async getCachedModel( fileName ) {
  936. if ( fileName !== null && this.hasCachedModel( fileName ) ) {
  937. const key = fileName.toLowerCase();
  938. const group = await this._cache[ key ];
  939. return group.clone();
  940. } else {
  941. return null;
  942. }
  943. }
  944. // Loads and parses the model with the given file name. Returns a cached copy if available.
  945. async loadModel( fileName ) {
  946. const parseCache = this.parseCache;
  947. const key = fileName.toLowerCase();
  948. if ( this.hasCachedModel( fileName ) ) {
  949. // Return cached model if available.
  950. return this.getCachedModel( fileName );
  951. } else {
  952. // Otherwise parse a new model.
  953. // Ensure the file data is loaded and pre parsed.
  954. await parseCache.ensureDataLoaded( fileName );
  955. const info = parseCache.getData( fileName );
  956. const promise = this.processIntoMesh( info );
  957. // Now that the file has loaded it's possible that another part parse has been waiting in parallel
  958. // so check the cache again to see if it's been added since the last async operation so we don't
  959. // do unnecessary work.
  960. if ( this.hasCachedModel( fileName ) ) {
  961. return this.getCachedModel( fileName );
  962. }
  963. // Cache object if it's a part so it can be reused later.
  964. if ( isPartType( info.type ) ) {
  965. this._cache[ key ] = promise;
  966. }
  967. // return a copy
  968. const group = await promise;
  969. return group.clone();
  970. }
  971. }
  972. // parses the given model text into a renderable object. Returns cached copy if available.
  973. async parseModel( text ) {
  974. const parseCache = this.parseCache;
  975. const info = parseCache.parse( text );
  976. if ( isPartType( info.type ) && this.hasCachedModel( info.fileName ) ) {
  977. return this.getCachedModel( info.fileName );
  978. }
  979. return this.processIntoMesh( info );
  980. }
  981. }
  982. function sortByMaterial( a, b ) {
  983. if ( a.colorCode === b.colorCode ) {
  984. return 0;
  985. }
  986. if ( a.colorCode < b.colorCode ) {
  987. return - 1;
  988. }
  989. return 1;
  990. }
  991. function createObject( loader, elements, elementSize, isConditionalSegments = false, totalElements = null ) {
  992. // Creates a LineSegments (elementSize = 2) or a Mesh (elementSize = 3 )
  993. // With per face / segment material, implemented with mesh groups and materials array
  994. // Sort the faces or line segments by color code to make later the mesh groups
  995. elements.sort( sortByMaterial );
  996. if ( totalElements === null ) {
  997. totalElements = elements.length;
  998. }
  999. const positions = new Float32Array( elementSize * totalElements * 3 );
  1000. const normals = elementSize === 3 ? new Float32Array( elementSize * totalElements * 3 ) : null;
  1001. const materials = [];
  1002. const quadArray = new Array( 6 );
  1003. const bufferGeometry = new BufferGeometry();
  1004. let prevMaterial = null;
  1005. let index0 = 0;
  1006. let numGroupVerts = 0;
  1007. let offset = 0;
  1008. for ( let iElem = 0, nElem = elements.length; iElem < nElem; iElem ++ ) {
  1009. const elem = elements[ iElem ];
  1010. let vertices = elem.vertices;
  1011. if ( vertices.length === 4 ) {
  1012. quadArray[ 0 ] = vertices[ 0 ];
  1013. quadArray[ 1 ] = vertices[ 1 ];
  1014. quadArray[ 2 ] = vertices[ 2 ];
  1015. quadArray[ 3 ] = vertices[ 0 ];
  1016. quadArray[ 4 ] = vertices[ 2 ];
  1017. quadArray[ 5 ] = vertices[ 3 ];
  1018. vertices = quadArray;
  1019. }
  1020. for ( let j = 0, l = vertices.length; j < l; j ++ ) {
  1021. const v = vertices[ j ];
  1022. const index = offset + j * 3;
  1023. positions[ index + 0 ] = v.x;
  1024. positions[ index + 1 ] = v.y;
  1025. positions[ index + 2 ] = v.z;
  1026. }
  1027. // create the normals array if this is a set of faces
  1028. if ( elementSize === 3 ) {
  1029. if ( ! elem.faceNormal ) {
  1030. const v0 = vertices[ 0 ];
  1031. const v1 = vertices[ 1 ];
  1032. const v2 = vertices[ 2 ];
  1033. _tempVec0.subVectors( v1, v0 );
  1034. _tempVec1.subVectors( v2, v1 );
  1035. elem.faceNormal = new Vector3()
  1036. .crossVectors( _tempVec0, _tempVec1 )
  1037. .normalize();
  1038. }
  1039. let elemNormals = elem.normals;
  1040. if ( elemNormals.length === 4 ) {
  1041. quadArray[ 0 ] = elemNormals[ 0 ];
  1042. quadArray[ 1 ] = elemNormals[ 1 ];
  1043. quadArray[ 2 ] = elemNormals[ 2 ];
  1044. quadArray[ 3 ] = elemNormals[ 0 ];
  1045. quadArray[ 4 ] = elemNormals[ 2 ];
  1046. quadArray[ 5 ] = elemNormals[ 3 ];
  1047. elemNormals = quadArray;
  1048. }
  1049. for ( let j = 0, l = elemNormals.length; j < l; j ++ ) {
  1050. // use face normal if a vertex normal is not provided
  1051. let n = elem.faceNormal;
  1052. if ( elemNormals[ j ] ) {
  1053. n = elemNormals[ j ].norm;
  1054. }
  1055. const index = offset + j * 3;
  1056. normals[ index + 0 ] = n.x;
  1057. normals[ index + 1 ] = n.y;
  1058. normals[ index + 2 ] = n.z;
  1059. }
  1060. }
  1061. if ( prevMaterial !== elem.colorCode ) {
  1062. if ( prevMaterial !== null ) {
  1063. bufferGeometry.addGroup( index0, numGroupVerts, materials.length - 1 );
  1064. }
  1065. const material = elem.material;
  1066. if ( material !== null ) {
  1067. if ( elementSize === 3 ) {
  1068. materials.push( material );
  1069. } else if ( elementSize === 2 ) {
  1070. if ( isConditionalSegments ) {
  1071. const edgeMaterial = loader.edgeMaterialCache.get( material );
  1072. materials.push( loader.conditionalEdgeMaterialCache.get( edgeMaterial ) );
  1073. } else {
  1074. materials.push( loader.edgeMaterialCache.get( material ) );
  1075. }
  1076. }
  1077. } else {
  1078. // If a material has not been made available yet then keep the color code string in the material array
  1079. // to save the spot for the material once a parent scopes materials are being applied to the object.
  1080. materials.push( elem.colorCode );
  1081. }
  1082. prevMaterial = elem.colorCode;
  1083. index0 = offset / 3;
  1084. numGroupVerts = vertices.length;
  1085. } else {
  1086. numGroupVerts += vertices.length;
  1087. }
  1088. offset += 3 * vertices.length;
  1089. }
  1090. if ( numGroupVerts > 0 ) {
  1091. bufferGeometry.addGroup( index0, Infinity, materials.length - 1 );
  1092. }
  1093. bufferGeometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  1094. if ( normals !== null ) {
  1095. bufferGeometry.setAttribute( 'normal', new BufferAttribute( normals, 3 ) );
  1096. }
  1097. let object3d = null;
  1098. if ( elementSize === 2 ) {
  1099. if ( isConditionalSegments ) {
  1100. object3d = new ConditionalLineSegments( bufferGeometry, materials.length === 1 ? materials[ 0 ] : materials );
  1101. } else {
  1102. object3d = new LineSegments( bufferGeometry, materials.length === 1 ? materials[ 0 ] : materials );
  1103. }
  1104. } else if ( elementSize === 3 ) {
  1105. object3d = new Mesh( bufferGeometry, materials.length === 1 ? materials[ 0 ] : materials );
  1106. }
  1107. if ( isConditionalSegments ) {
  1108. object3d.isConditionalLine = true;
  1109. const controlArray0 = new Float32Array( elements.length * 3 * 2 );
  1110. const controlArray1 = new Float32Array( elements.length * 3 * 2 );
  1111. const directionArray = new Float32Array( elements.length * 3 * 2 );
  1112. for ( let i = 0, l = elements.length; i < l; i ++ ) {
  1113. const os = elements[ i ];
  1114. const vertices = os.vertices;
  1115. const controlPoints = os.controlPoints;
  1116. const c0 = controlPoints[ 0 ];
  1117. const c1 = controlPoints[ 1 ];
  1118. const v0 = vertices[ 0 ];
  1119. const v1 = vertices[ 1 ];
  1120. const index = i * 3 * 2;
  1121. controlArray0[ index + 0 ] = c0.x;
  1122. controlArray0[ index + 1 ] = c0.y;
  1123. controlArray0[ index + 2 ] = c0.z;
  1124. controlArray0[ index + 3 ] = c0.x;
  1125. controlArray0[ index + 4 ] = c0.y;
  1126. controlArray0[ index + 5 ] = c0.z;
  1127. controlArray1[ index + 0 ] = c1.x;
  1128. controlArray1[ index + 1 ] = c1.y;
  1129. controlArray1[ index + 2 ] = c1.z;
  1130. controlArray1[ index + 3 ] = c1.x;
  1131. controlArray1[ index + 4 ] = c1.y;
  1132. controlArray1[ index + 5 ] = c1.z;
  1133. directionArray[ index + 0 ] = v1.x - v0.x;
  1134. directionArray[ index + 1 ] = v1.y - v0.y;
  1135. directionArray[ index + 2 ] = v1.z - v0.z;
  1136. directionArray[ index + 3 ] = v1.x - v0.x;
  1137. directionArray[ index + 4 ] = v1.y - v0.y;
  1138. directionArray[ index + 5 ] = v1.z - v0.z;
  1139. }
  1140. bufferGeometry.setAttribute( 'control0', new BufferAttribute( controlArray0, 3, false ) );
  1141. bufferGeometry.setAttribute( 'control1', new BufferAttribute( controlArray1, 3, false ) );
  1142. bufferGeometry.setAttribute( 'direction', new BufferAttribute( directionArray, 3, false ) );
  1143. }
  1144. return object3d;
  1145. }
  1146. /**
  1147. * A loader for the LDraw format.
  1148. *
  1149. * [LDraw]{@link https://ldraw.org/} (LEGO Draw) is an [open format specification]{@link https://ldraw.org/article/218.html}
  1150. * for describing LEGO and other construction set 3D models.
  1151. *
  1152. * An LDraw asset (a text file usually with extension .ldr, .dat or .txt) can describe just a single construction
  1153. * piece, or an entire model. In the case of a model the LDraw file can reference other LDraw files, which are
  1154. * loaded from a library path set with `setPartsLibraryPath`. You usually download the LDraw official parts library,
  1155. * extract to a folder and point setPartsLibraryPath to it.
  1156. *
  1157. * Library parts will be loaded by trial and error in subfolders 'parts', 'p' and 'models'. These file accesses
  1158. * are not optimal for web environment, so a script tool has been made to pack an LDraw file with all its dependencies
  1159. * into a single file, which loads much faster. See section 'Packing LDraw models'. The LDrawLoader example loads
  1160. * several packed files. The official parts library is not included due to its large size.
  1161. *
  1162. * `LDrawLoader` supports the following extensions:
  1163. * - !COLOUR: Color and surface finish declarations.
  1164. * - BFC: Back Face Culling specification.
  1165. * - !CATEGORY: Model/part category declarations.
  1166. * - !KEYWORDS: Model/part keywords declarations.
  1167. *
  1168. * ```js
  1169. * const loader = new LDrawLoader();
  1170. * loader.setConditionalLineMaterial( LDrawConditionalLineMaterial ); // the type of line material depends on the used renderer
  1171. * const object = await loader.loadAsync( 'models/ldraw/officialLibrary/models/car.ldr_Packed.mpd' );
  1172. * scene.add( object );
  1173. * ```
  1174. *
  1175. * @augments Loader
  1176. * @three_import import { LDrawLoader } from 'three/addons/loaders/LDrawLoader.js';
  1177. */
  1178. class LDrawLoader extends Loader {
  1179. /**
  1180. * Constructs a new LDraw loader.
  1181. *
  1182. * @param {LoadingManager} [manager] - The loading manager.
  1183. */
  1184. constructor( manager ) {
  1185. super( manager );
  1186. // Array of THREE.Material
  1187. this.materials = [];
  1188. this.materialLibrary = {};
  1189. this.edgeMaterialCache = new WeakMap();
  1190. this.conditionalEdgeMaterialCache = new WeakMap();
  1191. // This also allows to handle the embedded text files ("0 FILE" lines)
  1192. this.partsCache = new LDrawPartsGeometryCache( this );
  1193. // 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.
  1194. this.fileMap = {};
  1195. // If this flag is set to true the vertex normals will be smoothed.
  1196. this.smoothNormals = true;
  1197. // The path to load parts from the LDraw parts library from.
  1198. this.partsLibraryPath = '';
  1199. // this material type must be injected via setConditionalLineMaterial()
  1200. this.ConditionalLineMaterial = null;
  1201. // Material assigned to not available colors for meshes and edges
  1202. this.missingColorMaterial = new MeshStandardMaterial( { name: Loader.DEFAULT_MATERIAL_NAME, color: 0xFF00FF, roughness: 0.3, metalness: 0 } );
  1203. this.missingEdgeColorMaterial = new LineBasicMaterial( { name: Loader.DEFAULT_MATERIAL_NAME, color: 0xFF00FF } );
  1204. this.missingConditionalEdgeColorMaterial = null;
  1205. this.edgeMaterialCache.set( this.missingColorMaterial, this.missingEdgeColorMaterial );
  1206. this.conditionalEdgeMaterialCache.set( this.missingEdgeColorMaterial, this.missingConditionalEdgeColorMaterial );
  1207. }
  1208. /**
  1209. * This method must be called prior to `load()` unless the model to load does not reference
  1210. * library parts (usually it will be a model with all its parts packed in a single file).
  1211. *
  1212. * @param {string} path - Path to library parts files to load referenced parts from.
  1213. * This is different from Loader.setPath, which indicates the path to load the main asset from.
  1214. * @return {LDrawLoader} A reference to this loader.
  1215. */
  1216. setPartsLibraryPath( path ) {
  1217. this.partsLibraryPath = path;
  1218. return this;
  1219. }
  1220. /**
  1221. * Sets the conditional line material type which depends on the used renderer.
  1222. * Use {@link LDrawConditionalLineMaterial} when using `WebGLRenderer` and
  1223. * {@link LDrawConditionalLineNodeMaterial} when using `WebGPURenderer`.
  1224. *
  1225. * @param {(LDrawConditionalLineMaterial.constructor|LDrawConditionalLineNodeMaterial.constructor)} type - The conditional line material type.
  1226. * @return {LDrawLoader} A reference to this loader.
  1227. */
  1228. setConditionalLineMaterial( type ) {
  1229. this.ConditionalLineMaterial = type;
  1230. this.missingConditionalEdgeColorMaterial = new this.ConditionalLineMaterial( { name: Loader.DEFAULT_MATERIAL_NAME, fog: true, color: 0xFF00FF } );
  1231. return this;
  1232. }
  1233. /**
  1234. * This async method preloads materials from a single LDraw file. In the official
  1235. * parts library there is a special file which is loaded always the first (LDConfig.ldr)
  1236. * and contains all the standard color codes. This method is intended to be used with
  1237. * not packed files, for example in an editor where materials are preloaded and parts
  1238. * are loaded on demand.
  1239. *
  1240. * @async
  1241. * @param {string} url - Path of the LDraw materials asset.
  1242. * @return {Promise} A Promise that resolves when the preload has finished.
  1243. */
  1244. async preloadMaterials( url ) {
  1245. const fileLoader = new FileLoader( this.manager );
  1246. fileLoader.setPath( this.path );
  1247. fileLoader.setRequestHeader( this.requestHeader );
  1248. fileLoader.setWithCredentials( this.withCredentials );
  1249. const text = await fileLoader.loadAsync( url );
  1250. const colorLineRegex = /^0 !COLOUR/;
  1251. const lines = text.split( /[\n\r]/g );
  1252. const materials = [];
  1253. for ( let i = 0, l = lines.length; i < l; i ++ ) {
  1254. const line = lines[ i ];
  1255. if ( colorLineRegex.test( line ) ) {
  1256. const directive = line.replace( colorLineRegex, '' );
  1257. const material = this.parseColorMetaDirective( new LineParser( directive ) );
  1258. materials.push( material );
  1259. }
  1260. }
  1261. this.addMaterials( materials );
  1262. }
  1263. /**
  1264. * Starts loading from the given URL and passes the loaded LDraw asset
  1265. * to the `onLoad()` callback.
  1266. *
  1267. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  1268. * @param {function(Group)} onLoad - Executed when the loading process has been finished.
  1269. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  1270. * @param {onErrorCallback} onError - Executed when errors occur.
  1271. */
  1272. load( url, onLoad, onProgress, onError ) {
  1273. const fileLoader = new FileLoader( this.manager );
  1274. fileLoader.setPath( this.path );
  1275. fileLoader.setRequestHeader( this.requestHeader );
  1276. fileLoader.setWithCredentials( this.withCredentials );
  1277. fileLoader.load( url, text => {
  1278. // Initializes the materials library with default materials
  1279. this.addDefaultMaterials();
  1280. this.partsCache
  1281. .parseModel( text )
  1282. .then( group => {
  1283. this.applyMaterialsToMesh( group, MAIN_COLOUR_CODE, this.materialLibrary, true );
  1284. this.computeBuildingSteps( group );
  1285. group.userData.fileName = url;
  1286. onLoad( group );
  1287. } )
  1288. .catch( onError );
  1289. }, onProgress, onError );
  1290. }
  1291. /**
  1292. * Parses the given LDraw data and returns the resulting group.
  1293. *
  1294. * @param {string} text - The raw VRML data as a string.
  1295. * @param {function(Group)} onLoad - Executed when the loading/parsing process has been finished.
  1296. * @param {onErrorCallback} onError - Executed when errors occur.
  1297. */
  1298. parse( text, onLoad, onError ) {
  1299. this.partsCache
  1300. .parseModel( text )
  1301. .then( group => {
  1302. this.applyMaterialsToMesh( group, MAIN_COLOUR_CODE, this.materialLibrary, true );
  1303. this.computeBuildingSteps( group );
  1304. group.userData.fileName = '';
  1305. onLoad( group );
  1306. } )
  1307. .catch( onError );
  1308. }
  1309. /**
  1310. * Sets the loader's material library. This method clears existing
  1311. * material definitions.
  1312. *
  1313. * @param {Array<Material>} materials - The materials to set.
  1314. * @return {LDrawLoader} A reference to this loader.
  1315. */
  1316. setMaterials( materials ) {
  1317. this.clearMaterials();
  1318. this.addMaterials( materials );
  1319. return this;
  1320. }
  1321. /**
  1322. * Clears the loader's material library.
  1323. *
  1324. * @return {LDrawLoader} A reference to this loader.
  1325. */
  1326. clearMaterials() {
  1327. this.materialLibrary = {};
  1328. this.materials = [];
  1329. return this;
  1330. }
  1331. /**
  1332. * Adds a list of materials to the loader's material library.
  1333. *
  1334. * @param {Array<Material>} materials - The materials to add.
  1335. * @return {LDrawLoader} A reference to this loader.
  1336. */
  1337. addMaterials( materials ) {
  1338. for ( let i = 0, l = materials.length; i < l; i ++ ) {
  1339. this.addMaterial( materials[ i ] );
  1340. }
  1341. return this;
  1342. }
  1343. /**
  1344. * Initializes the loader with default materials.
  1345. *
  1346. * @return {LDrawLoader} A reference to this loader.
  1347. */
  1348. addDefaultMaterials() {
  1349. // Add default main triangle and line edge materials (used in pieces that can be colored with a main color)
  1350. this.addMaterial( this.parseColorMetaDirective( new LineParser( 'Main_Colour CODE 16 VALUE #FF8080 EDGE #333333' ) ) );
  1351. this.addMaterial( this.parseColorMetaDirective( new LineParser( 'Edge_Colour CODE 24 VALUE #A0A0A0 EDGE #333333' ) ) );
  1352. return this;
  1353. }
  1354. /**
  1355. * Sets a map which maps referenced library filenames to new filenames.
  1356. * If a fileMap is not specified (the default), library parts will be accessed by trial and
  1357. * error in subfolders 'parts', 'p' and 'models'.
  1358. *
  1359. * @param {Object<string,string>} fileMap - The file map to set.
  1360. * @return {LDrawLoader} A reference to this loader.
  1361. */
  1362. setFileMap( fileMap ) {
  1363. this.fileMap = fileMap;
  1364. return this;
  1365. }
  1366. /**
  1367. * Adds a single material to the loader's material library.
  1368. *
  1369. * @param {Material} material - The material to add.
  1370. * @return {LDrawLoader} A reference to this loader.
  1371. */
  1372. addMaterial( material ) {
  1373. // Adds a material to the material library which is on top of the parse scopes stack. And also to the materials array
  1374. const matLib = this.materialLibrary;
  1375. if ( ! matLib[ material.userData.code ] ) {
  1376. this.materials.push( material );
  1377. matLib[ material.userData.code ] = material;
  1378. }
  1379. return this;
  1380. }
  1381. /**
  1382. * Returns a material for the given color code.
  1383. *
  1384. * @param {string} colorCode - The color code.
  1385. * @return {?Material} The material. Returns `null` if no material has been found.
  1386. */
  1387. getMaterial( colorCode ) {
  1388. if ( colorCode.startsWith( '0x2' ) ) {
  1389. // Special 'direct' material value (RGB color)
  1390. const color = colorCode.substring( 3 );
  1391. return this.parseColorMetaDirective( new LineParser( 'Direct_Color_' + color + ' CODE -1 VALUE #' + color + ' EDGE #' + color + '' ) );
  1392. }
  1393. return this.materialLibrary[ colorCode ] || null;
  1394. }
  1395. // Applies the appropriate materials to a prebuilt hierarchy of geometry. Assumes that color codes are present
  1396. // in the material array if they need to be filled in.
  1397. applyMaterialsToMesh( group, parentColorCode, materialHierarchy, finalMaterialPass = false ) {
  1398. // find any missing materials as indicated by a color code string and replace it with a material from the current material lib
  1399. const loader = this;
  1400. const parentIsPassthrough = parentColorCode === MAIN_COLOUR_CODE;
  1401. group.traverse( c => {
  1402. if ( c.isMesh || c.isLineSegments ) {
  1403. if ( Array.isArray( c.material ) ) {
  1404. for ( let i = 0, l = c.material.length; i < l; i ++ ) {
  1405. if ( ! c.material[ i ].isMaterial ) {
  1406. c.material[ i ] = getMaterial( c, c.material[ i ] );
  1407. }
  1408. }
  1409. } else if ( ! c.material.isMaterial ) {
  1410. c.material = getMaterial( c, c.material );
  1411. }
  1412. }
  1413. } );
  1414. // Returns the appropriate material for the object (line or face) given color code. If the code is "pass through"
  1415. // (24 for lines, 16 for edges) then the pass through color code is used. If that is also pass through then it's
  1416. // simply returned for the subsequent material application.
  1417. function getMaterial( c, colorCode ) {
  1418. // if our parent is a passthrough color code and we don't have the current material color available then
  1419. // return early.
  1420. if ( parentIsPassthrough && ! ( colorCode in materialHierarchy ) && ! finalMaterialPass ) {
  1421. return colorCode;
  1422. }
  1423. const forEdge = c.isLineSegments || c.isConditionalLine;
  1424. const isPassthrough = ! forEdge && colorCode === MAIN_COLOUR_CODE || forEdge && colorCode === MAIN_EDGE_COLOUR_CODE;
  1425. if ( isPassthrough ) {
  1426. colorCode = parentColorCode;
  1427. }
  1428. let material = null;
  1429. if ( colorCode in materialHierarchy ) {
  1430. material = materialHierarchy[ colorCode ];
  1431. } else if ( finalMaterialPass ) {
  1432. // see if we can get the final material from the "getMaterial" function which will attempt to
  1433. // parse the "direct" colors
  1434. material = loader.getMaterial( colorCode );
  1435. if ( material === null ) {
  1436. // otherwise throw a warning if this is final opportunity to set the material
  1437. console.warn( `LDrawLoader: Material properties for code ${ colorCode } not available.` );
  1438. // And return the 'missing color' material
  1439. material = loader.missingColorMaterial;
  1440. }
  1441. } else {
  1442. return colorCode;
  1443. }
  1444. if ( c.isLineSegments ) {
  1445. material = loader.edgeMaterialCache.get( material );
  1446. if ( c.isConditionalLine ) {
  1447. material = loader.conditionalEdgeMaterialCache.get( material );
  1448. }
  1449. }
  1450. return material;
  1451. }
  1452. }
  1453. /**
  1454. * Returns the Material for the main LDraw color.
  1455. *
  1456. * For an already loaded LDraw asset, returns the Material associated with the main color code.
  1457. * This method can be useful to modify the main material of a model or part that exposes it.
  1458. *
  1459. * The main color code is the standard way to color an LDraw part. It is '16' for triangles and
  1460. * '24' for edges. Usually a complete model will not expose the main color (that is, no part
  1461. * uses the code '16' at the top level, because they are assigned other specific colors) An LDraw
  1462. * part file on the other hand will expose the code '16' to be colored, and can have additional
  1463. * fixed colors.
  1464. *
  1465. * @return {?Material} The material. Returns `null` if no material has been found.
  1466. */
  1467. getMainMaterial() {
  1468. return this.getMaterial( MAIN_COLOUR_CODE );
  1469. }
  1470. /**
  1471. * Returns the material for the edges main LDraw color.
  1472. *
  1473. * @return {?Material} The material. Returns `null` if no material has been found.
  1474. */
  1475. getMainEdgeMaterial() {
  1476. const mat = this.getMaterial( MAIN_EDGE_COLOUR_CODE );
  1477. return mat ? this.edgeMaterialCache.get( mat ) : null;
  1478. }
  1479. parseColorMetaDirective( lineParser ) {
  1480. // Parses a color definition and returns a THREE.Material
  1481. let code = null;
  1482. // Triangle and line colors
  1483. let fillColor = '#FF00FF';
  1484. let edgeColor = '#FF00FF';
  1485. // Transparency
  1486. let alpha = 1;
  1487. let isTransparent = false;
  1488. // Self-illumination:
  1489. let luminance = 0;
  1490. let finishType = FINISH_TYPE_DEFAULT;
  1491. let edgeMaterial = null;
  1492. const name = lineParser.getToken();
  1493. if ( ! name ) {
  1494. throw new Error( 'LDrawLoader: Material name was expected after "!COLOUR tag' + lineParser.getLineNumberString() + '.' );
  1495. }
  1496. // Parse tag tokens and their parameters
  1497. let token = null;
  1498. while ( true ) {
  1499. token = lineParser.getToken();
  1500. if ( ! token ) {
  1501. break;
  1502. }
  1503. if ( ! parseLuminance( token ) ) {
  1504. switch ( token.toUpperCase() ) {
  1505. case 'CODE':
  1506. code = lineParser.getToken();
  1507. break;
  1508. case 'VALUE':
  1509. fillColor = lineParser.getToken();
  1510. if ( fillColor.startsWith( '0x' ) ) {
  1511. fillColor = '#' + fillColor.substring( 2 );
  1512. } else if ( ! fillColor.startsWith( '#' ) ) {
  1513. throw new Error( 'LDrawLoader: Invalid color while parsing material' + lineParser.getLineNumberString() + '.' );
  1514. }
  1515. break;
  1516. case 'EDGE':
  1517. edgeColor = lineParser.getToken();
  1518. if ( edgeColor.startsWith( '0x' ) ) {
  1519. edgeColor = '#' + edgeColor.substring( 2 );
  1520. } else if ( ! edgeColor.startsWith( '#' ) ) {
  1521. // Try to see if edge color is a color code
  1522. edgeMaterial = this.getMaterial( edgeColor );
  1523. if ( ! edgeMaterial ) {
  1524. throw new Error( 'LDrawLoader: Invalid edge color while parsing material' + lineParser.getLineNumberString() + '.' );
  1525. }
  1526. // Get the edge material for this triangle material
  1527. edgeMaterial = this.edgeMaterialCache.get( edgeMaterial );
  1528. }
  1529. break;
  1530. case 'ALPHA':
  1531. alpha = parseInt( lineParser.getToken() );
  1532. if ( isNaN( alpha ) ) {
  1533. throw new Error( 'LDrawLoader: Invalid alpha value in material definition' + lineParser.getLineNumberString() + '.' );
  1534. }
  1535. alpha = Math.max( 0, Math.min( 1, alpha / 255 ) );
  1536. if ( alpha < 1 ) {
  1537. isTransparent = true;
  1538. }
  1539. break;
  1540. case 'LUMINANCE':
  1541. if ( ! parseLuminance( lineParser.getToken() ) ) {
  1542. throw new Error( 'LDrawLoader: Invalid luminance value in material definition' + lineParser.getLineNumberString() + '.' );
  1543. }
  1544. break;
  1545. case 'CHROME':
  1546. finishType = FINISH_TYPE_CHROME;
  1547. break;
  1548. case 'PEARLESCENT':
  1549. finishType = FINISH_TYPE_PEARLESCENT;
  1550. break;
  1551. case 'RUBBER':
  1552. finishType = FINISH_TYPE_RUBBER;
  1553. break;
  1554. case 'MATTE_METALLIC':
  1555. finishType = FINISH_TYPE_MATTE_METALLIC;
  1556. break;
  1557. case 'METAL':
  1558. finishType = FINISH_TYPE_METAL;
  1559. break;
  1560. case 'MATERIAL':
  1561. // Not implemented
  1562. lineParser.setToEnd();
  1563. break;
  1564. default:
  1565. throw new Error( 'LDrawLoader: Unknown token "' + token + '" while parsing material' + lineParser.getLineNumberString() + '.' );
  1566. }
  1567. }
  1568. }
  1569. let material = null;
  1570. switch ( finishType ) {
  1571. case FINISH_TYPE_DEFAULT:
  1572. material = new MeshStandardMaterial( { roughness: 0.3, metalness: 0 } );
  1573. break;
  1574. case FINISH_TYPE_PEARLESCENT:
  1575. // Try to imitate pearlescency by making the surface glossy
  1576. material = new MeshStandardMaterial( { roughness: 0.3, metalness: 0.25 } );
  1577. break;
  1578. case FINISH_TYPE_CHROME:
  1579. // Mirror finish surface
  1580. material = new MeshStandardMaterial( { roughness: 0, metalness: 1 } );
  1581. break;
  1582. case FINISH_TYPE_RUBBER:
  1583. // Rubber finish
  1584. material = new MeshStandardMaterial( { roughness: 0.9, metalness: 0 } );
  1585. break;
  1586. case FINISH_TYPE_MATTE_METALLIC:
  1587. // Brushed metal finish
  1588. material = new MeshStandardMaterial( { roughness: 0.8, metalness: 0.4 } );
  1589. break;
  1590. case FINISH_TYPE_METAL:
  1591. // Average metal finish
  1592. material = new MeshStandardMaterial( { roughness: 0.2, metalness: 0.85 } );
  1593. break;
  1594. default:
  1595. // Should not happen
  1596. break;
  1597. }
  1598. material.color.setStyle( fillColor, COLOR_SPACE_LDRAW );
  1599. material.transparent = isTransparent;
  1600. material.premultipliedAlpha = true;
  1601. material.opacity = alpha;
  1602. material.depthWrite = ! isTransparent;
  1603. material.polygonOffset = true;
  1604. material.polygonOffsetFactor = 1;
  1605. if ( luminance !== 0 ) {
  1606. material.emissive.setStyle( fillColor, COLOR_SPACE_LDRAW ).multiplyScalar( luminance );
  1607. }
  1608. if ( ! edgeMaterial ) {
  1609. // This is the material used for edges
  1610. edgeMaterial = new LineBasicMaterial( {
  1611. color: new Color().setStyle( edgeColor, COLOR_SPACE_LDRAW ),
  1612. transparent: isTransparent,
  1613. opacity: alpha,
  1614. depthWrite: ! isTransparent
  1615. } );
  1616. edgeMaterial.color;
  1617. edgeMaterial.userData.code = code;
  1618. edgeMaterial.name = name + ' - Edge';
  1619. if ( this.ConditionalLineMaterial === null ) {
  1620. throw new Error( 'THREE.LDrawLoader: ConditionalLineMaterial type must be specified via .setConditionalLineMaterial().' );
  1621. }
  1622. // This is the material used for conditional edges
  1623. const conditionalEdgeMaterial = new this.ConditionalLineMaterial( {
  1624. fog: true,
  1625. transparent: isTransparent,
  1626. depthWrite: ! isTransparent,
  1627. color: new Color().setStyle( edgeColor, COLOR_SPACE_LDRAW ),
  1628. opacity: alpha,
  1629. } );
  1630. conditionalEdgeMaterial.userData.code = code;
  1631. conditionalEdgeMaterial.name = name + ' - Conditional Edge';
  1632. this.conditionalEdgeMaterialCache.set( edgeMaterial, conditionalEdgeMaterial );
  1633. }
  1634. material.userData.code = code;
  1635. material.name = name;
  1636. this.edgeMaterialCache.set( material, edgeMaterial );
  1637. this.addMaterial( material );
  1638. return material;
  1639. function parseLuminance( token ) {
  1640. // Returns success
  1641. let lum;
  1642. if ( token.startsWith( 'LUMINANCE' ) ) {
  1643. lum = parseInt( token.substring( 9 ) );
  1644. } else {
  1645. lum = parseInt( token );
  1646. }
  1647. if ( isNaN( lum ) ) {
  1648. return false;
  1649. }
  1650. luminance = Math.max( 0, Math.min( 1, lum / 255 ) );
  1651. return true;
  1652. }
  1653. }
  1654. computeBuildingSteps( model ) {
  1655. // Sets userdata.buildingStep number in Group objects and userData.numBuildingSteps number in the root Group object.
  1656. let stepNumber = 0;
  1657. model.traverse( c => {
  1658. if ( c.isGroup ) {
  1659. if ( c.userData.startingBuildingStep ) {
  1660. stepNumber ++;
  1661. }
  1662. c.userData.buildingStep = stepNumber;
  1663. }
  1664. } );
  1665. model.userData.numBuildingSteps = stepNumber + 1;
  1666. }
  1667. }
  1668. export { LDrawLoader };