LDrawLoader.js 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443
  1. /**
  2. * @author mrdoob / http://mrdoob.com/
  3. * @author yomboprime / https://github.com/yomboprime/
  4. *
  5. *
  6. */
  7. THREE.LDrawLoader = ( function () {
  8. function LineParser( line, lineNumber ) {
  9. this.line = line;
  10. this.lineLength = line.length;
  11. this.currentCharIndex = 0;
  12. this.currentChar = ' ';
  13. this.lineNumber = lineNumber;
  14. }
  15. LineParser.prototype = {
  16. constructor: LineParser,
  17. seekNonSpace: function () {
  18. while ( this.currentCharIndex < this.lineLength ) {
  19. this.currentChar = this.line.charAt( this.currentCharIndex );
  20. if ( this.currentChar !== ' ' && this.currentChar !== '\t' ) {
  21. return;
  22. }
  23. this.currentCharIndex ++;
  24. }
  25. },
  26. getToken: function () {
  27. var pos0 = this.currentCharIndex ++;
  28. // Seek space
  29. while ( this.currentCharIndex < this.lineLength ) {
  30. this.currentChar = this.line.charAt( this.currentCharIndex );
  31. if ( this.currentChar === ' ' || this.currentChar === '\t' ) {
  32. break;
  33. }
  34. this.currentCharIndex ++;
  35. }
  36. var pos1 = this.currentCharIndex;
  37. this.seekNonSpace();
  38. return this.line.substring( pos0, pos1 );
  39. },
  40. getRemainingString: function () {
  41. return this.line.substring( this.currentCharIndex, this.lineLength );
  42. },
  43. isAtTheEnd: function () {
  44. return this.currentCharIndex >= this.lineLength;
  45. },
  46. setToEnd: function () {
  47. this.currentCharIndex = this.lineLength;
  48. },
  49. getLineNumberString: function () {
  50. return this.lineNumber >= 0 ? " at line " + this.lineNumber : "";
  51. }
  52. };
  53. function sortByMaterial( a, b ) {
  54. if ( a.colourCode === b.colourCode ) {
  55. return 0;
  56. }
  57. if ( a.colourCode < b.colourCode ) {
  58. return - 1;
  59. }
  60. return 1;
  61. }
  62. function createObject( elements, elementSize ) {
  63. // Creates a THREE.LineSegments (elementSize = 2) or a THREE.Mesh (elementSize = 3 )
  64. // With per face / segment material, implemented with mesh groups and materials array
  65. // Sort the triangles or line segments by colour code to make later the mesh groups
  66. elements.sort( sortByMaterial );
  67. var vertices = [];
  68. var materials = [];
  69. var bufferGeometry = new THREE.BufferGeometry();
  70. bufferGeometry.clearGroups();
  71. var prevMaterial = null;
  72. var index0 = 0;
  73. var numGroupVerts = 0;
  74. for ( var iElem = 0, nElem = elements.length; iElem < nElem; iElem ++ ) {
  75. var elem = elements[ iElem ];
  76. var v0 = elem.v0;
  77. var v1 = elem.v1;
  78. // Note that LDraw coordinate system is rotated 180 deg. in the X axis w.r.t. Three.js's one
  79. vertices.push( v0.x, v0.y, v0.z, v1.x, v1.y, v1.z );
  80. if ( elementSize === 3 ) {
  81. vertices.push( elem.v2.x, elem.v2.y, elem.v2.z );
  82. }
  83. if ( prevMaterial !== elem.material ) {
  84. if ( prevMaterial !== null ) {
  85. bufferGeometry.addGroup( index0, numGroupVerts, materials.length - 1 );
  86. }
  87. materials.push( elem.material );
  88. prevMaterial = elem.material;
  89. index0 = iElem * elementSize;
  90. numGroupVerts = elementSize;
  91. } else {
  92. numGroupVerts += elementSize;
  93. }
  94. }
  95. if ( numGroupVerts > 0 ) {
  96. bufferGeometry.addGroup( index0, Infinity, materials.length - 1 );
  97. }
  98. bufferGeometry.addAttribute( 'position', new THREE.Float32BufferAttribute( vertices, 3 ) );
  99. var object3d = null;
  100. if ( elementSize === 2 ) {
  101. object3d = new THREE.LineSegments( bufferGeometry, materials );
  102. } else if ( elementSize === 3 ) {
  103. bufferGeometry.computeVertexNormals();
  104. object3d = new THREE.Mesh( bufferGeometry, materials );
  105. }
  106. return object3d;
  107. }
  108. //
  109. function LDrawLoader( manager ) {
  110. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  111. // This is a stack of 'parse scopes' with one level per subobject loaded file.
  112. // Each level contains a material lib and also other runtime variables passed between parent and child subobjects
  113. // When searching for a material code, the stack is read from top of the stack to bottom
  114. // Each material library is an object map keyed by colour codes.
  115. this.parseScopesStack = null;
  116. this.path = '';
  117. // Array of THREE.Material
  118. this.materials = [];
  119. // Not using THREE.Cache here because it returns the previous HTML error response instead of calling onError()
  120. // This also allows to handle the embedded text files ("0 FILE" lines)
  121. this.subobjectCache = {};
  122. // 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.
  123. this.fileMap = null;
  124. // Add default main triangle and line edge materials (used in piecess that can be coloured with a main color)
  125. this.setMaterials( [
  126. this.parseColourMetaDirective( new LineParser( "Main_Colour CODE 16 VALUE #FF8080 EDGE #333333" ) ),
  127. this.parseColourMetaDirective( new LineParser( "Edge_Colour CODE 24 VALUE #A0A0A0 EDGE #333333" ) )
  128. ] );
  129. // If this flag is set to true, each subobject will be a THREE.Object.
  130. // If not (the default), only one object which contains all the merged primitives will be created.
  131. this.separateObjects = false;
  132. }
  133. // Special surface finish tag types.
  134. // Note: "MATERIAL" tag (e.g. GLITTER, SPECKLE) is not implemented
  135. LDrawLoader.FINISH_TYPE_DEFAULT = 0;
  136. LDrawLoader.FINISH_TYPE_CHROME = 1;
  137. LDrawLoader.FINISH_TYPE_PEARLESCENT = 2;
  138. LDrawLoader.FINISH_TYPE_RUBBER = 3;
  139. LDrawLoader.FINISH_TYPE_MATTE_METALLIC = 4;
  140. LDrawLoader.FINISH_TYPE_METAL = 5;
  141. // State machine to search a subobject path.
  142. // The LDraw standard establishes these various possible subfolders.
  143. LDrawLoader.FILE_LOCATION_AS_IS = 0;
  144. LDrawLoader.FILE_LOCATION_TRY_PARTS = 1;
  145. LDrawLoader.FILE_LOCATION_TRY_P = 2;
  146. LDrawLoader.FILE_LOCATION_TRY_MODELS = 3;
  147. LDrawLoader.FILE_LOCATION_TRY_RELATIVE = 4;
  148. LDrawLoader.FILE_LOCATION_TRY_ABSOLUTE = 5;
  149. LDrawLoader.FILE_LOCATION_NOT_FOUND = 6;
  150. LDrawLoader.prototype = {
  151. constructor: LDrawLoader,
  152. load: function ( url, onLoad, onProgress, onError ) {
  153. if ( ! this.fileMap ) {
  154. this.fileMap = {};
  155. }
  156. var scope = this;
  157. var fileLoader = new THREE.FileLoader( this.manager );
  158. fileLoader.setPath( this.path );
  159. fileLoader.load( url, function ( text ) {
  160. processObject( text, onLoad );
  161. }, onProgress, onError );
  162. function processObject( text, onProcessed, subobject ) {
  163. var parseScope = scope.newParseScopeLevel();
  164. parseScope.url = url;
  165. var parentParseScope = scope.getParentParseScope();
  166. // Add to cache
  167. var currentFileName = parentParseScope.currentFileName;
  168. if ( currentFileName !== null ) {
  169. currentFileName = parentParseScope.currentFileName.toLowerCase();
  170. }
  171. if ( scope.subobjectCache[ currentFileName ] === undefined ) {
  172. scope.subobjectCache[ currentFileName ] = text;
  173. }
  174. parseScope.inverted = subobject !== undefined ? subobject.inverted : false;
  175. // Parse the object (returns a THREE.Group)
  176. var objGroup = scope.parse( text );
  177. // Load subobjects
  178. parseScope.subobjects = objGroup.userData.subobjects;
  179. parseScope.numSubobjects = parseScope.subobjects.length;
  180. parseScope.subobjectIndex = 0;
  181. var finishedCount = 0;
  182. onSubobjectFinish();
  183. return objGroup;
  184. function onSubobjectFinish() {
  185. finishedCount ++;
  186. if ( finishedCount === parseScope.subobjects.length + 1 ) {
  187. finalizeObject();
  188. } else {
  189. // Once the previous subobject has finished we can start processing the next one in the list.
  190. // The subobject processing shares scope in processing so it's important that they be loaded serially
  191. // to avoid race conditions.
  192. // Promise.resolve is used as an approach to asynchronously schedule a task _before_ this frame ends to
  193. // avoid stack overflow exceptions when loading many subobjects from the cache. RequestAnimationFrame
  194. // will work but causes the load to happen after the next frame which causes the load to take significantly longer.
  195. var subobject = parseScope.subobjects[ parseScope.subobjectIndex ];
  196. Promise.resolve().then( function () {
  197. loadSubobject( subobject );
  198. } );
  199. parseScope.subobjectIndex ++;
  200. }
  201. }
  202. function finalizeObject() {
  203. // TODO: Handle smoothing
  204. if ( scope.separateObjects && parseScope.type === 'Part' || ! parentParseScope.isFromParse ) {
  205. const objGroup = parseScope.groupObject;
  206. if ( parseScope.lineSegments.length > 0 ) {
  207. objGroup.add( createObject( parseScope.lineSegments, 2 ) );
  208. }
  209. if ( parseScope.optionalSegments.length > 0 ) {
  210. objGroup.add( createObject( parseScope.optionalSegments, 2 ) );
  211. }
  212. if ( parseScope.triangles.length > 0 ) {
  213. objGroup.add( createObject( parseScope.triangles, 3 ) );
  214. }
  215. if ( parentParseScope.groupObject ) {
  216. parentParseScope.groupObject.add( objGroup );
  217. }
  218. } else {
  219. // TODO: we need to multiple matrices here
  220. // TODO: First, instead of tracking matrices anywhere else we
  221. // should just multiple everything here.
  222. parentParseScope.lineSegments.push( ...parseScope.lineSegments );
  223. parentParseScope.optionalSegments.push( ...parseScope.optionalSegments );
  224. parentParseScope.triangles.push( ...parseScope.triangles );
  225. }
  226. scope.removeScopeLevel();
  227. if ( onProcessed ) {
  228. onProcessed( objGroup );
  229. }
  230. }
  231. function loadSubobject( subobject ) {
  232. parseScope.mainColourCode = subobject.material.userData.code;
  233. parseScope.mainEdgeColourCode = subobject.material.userData.edgeMaterial.userData.code;
  234. parseScope.currentFileName = subobject.originalFileName;
  235. if ( ! scope.separateObjects ) {
  236. // Set current matrix
  237. parseScope.currentMatrix.multiplyMatrices( parentParseScope.currentMatrix, subobject.matrix );
  238. }
  239. // If subobject was cached previously, use the cached one
  240. var cached = scope.subobjectCache[ subobject.originalFileName.toLowerCase() ];
  241. if ( cached ) {
  242. processObject( cached, function ( subobjectGroup ) {
  243. onSubobjectLoaded( subobjectGroup, subobject );
  244. onSubobjectFinish();
  245. }, subobject );
  246. return;
  247. }
  248. // Adjust file name to locate the subobject file path in standard locations (always under directory scope.path)
  249. // Update also subobject.locationState for the next try if this load fails.
  250. var subobjectURL = subobject.fileName;
  251. var newLocationState = LDrawLoader.FILE_LOCATION_NOT_FOUND;
  252. switch ( subobject.locationState ) {
  253. case LDrawLoader.FILE_LOCATION_AS_IS:
  254. newLocationState = subobject.locationState + 1;
  255. break;
  256. case LDrawLoader.FILE_LOCATION_TRY_PARTS:
  257. subobjectURL = 'parts/' + subobjectURL;
  258. newLocationState = subobject.locationState + 1;
  259. break;
  260. case LDrawLoader.FILE_LOCATION_TRY_P:
  261. subobjectURL = 'p/' + subobjectURL;
  262. newLocationState = subobject.locationState + 1;
  263. break;
  264. case LDrawLoader.FILE_LOCATION_TRY_MODELS:
  265. subobjectURL = 'models/' + subobjectURL;
  266. newLocationState = subobject.locationState + 1;
  267. break;
  268. case LDrawLoader.FILE_LOCATION_TRY_RELATIVE:
  269. subobjectURL = url.substring( 0, url.lastIndexOf( "/" ) + 1 ) + subobjectURL;
  270. newLocationState = subobject.locationState + 1;
  271. break;
  272. case LDrawLoader.FILE_LOCATION_TRY_ABSOLUTE:
  273. if ( subobject.triedLowerCase ) {
  274. // Try absolute path
  275. newLocationState = LDrawLoader.FILE_LOCATION_NOT_FOUND;
  276. } else {
  277. // Next attempt is lower case
  278. subobject.fileName = subobject.fileName.toLowerCase();
  279. subobjectURL = subobject.fileName;
  280. subobject.triedLowerCase = true;
  281. newLocationState = LDrawLoader.FILE_LOCATION_AS_IS;
  282. }
  283. break;
  284. case LDrawLoader.FILE_LOCATION_NOT_FOUND:
  285. // All location possibilities have been tried, give up loading this object
  286. console.warn( 'LDrawLoader: Subobject "' + subobject.originalFileName + '" could not be found.' );
  287. return;
  288. }
  289. subobject.locationState = newLocationState;
  290. subobject.url = subobjectURL;
  291. // Load the subobject
  292. // Use another file loader here so we can keep track of the subobject information
  293. // and use it when processing the next model.
  294. var fileLoader = new THREE.FileLoader( scope.manager );
  295. fileLoader.setPath( scope.path );
  296. fileLoader.load( subobjectURL, function ( text ) {
  297. processObject( text, function ( subobjectGroup ) {
  298. onSubobjectLoaded( subobjectGroup, subobject );
  299. onSubobjectFinish();
  300. }, subobject );
  301. }, undefined, function ( err ) {
  302. onSubobjectError( err, subobject );
  303. }, subobject );
  304. }
  305. function onSubobjectLoaded( subobjectGroup, subobject ) {
  306. if ( subobjectGroup === null ) {
  307. // Try to reload
  308. loadSubobject( subobject );
  309. return;
  310. }
  311. // Add the subobject just loaded
  312. addSubobject( subobject, subobjectGroup );
  313. }
  314. function addSubobject( subobject, subobjectGroup ) {
  315. if ( scope.separateObjects ) {
  316. subobjectGroup.name = subobject.fileName;
  317. objGroup.add( subobjectGroup );
  318. subobjectGroup.matrix.copy( subobject.matrix );
  319. subobjectGroup.matrixAutoUpdate = false;
  320. }
  321. scope.fileMap[ subobject.originalFileName ] = subobject.url;
  322. }
  323. function onSubobjectError( err, subobject ) {
  324. // Retry download from a different default possible location
  325. loadSubobject( subobject );
  326. }
  327. }
  328. },
  329. setPath: function ( value ) {
  330. this.path = value;
  331. return this;
  332. },
  333. setMaterials: function ( materials ) {
  334. // Clears parse scopes stack, adds new scope with material library
  335. this.parseScopesStack = [];
  336. this.newParseScopeLevel( materials );
  337. this.getCurrentParseScope().isFromParse = false;
  338. this.materials = materials;
  339. return this;
  340. },
  341. setFileMap: function ( fileMap ) {
  342. this.fileMap = fileMap;
  343. return this;
  344. },
  345. newParseScopeLevel: function ( materials ) {
  346. // Adds a new scope level, assign materials to it and returns it
  347. var matLib = {};
  348. if ( materials ) {
  349. for ( var i = 0, n = materials.length; i < n; i ++ ) {
  350. var material = materials[ i ];
  351. matLib[ material.userData.code ] = material;
  352. }
  353. }
  354. var topParseScope = this.getCurrentParseScope();
  355. var parentParseScope = this.getParentParseScope();
  356. var newParseScope = {
  357. lib: matLib,
  358. url: null,
  359. // Subobjects
  360. subobjects: null,
  361. numSubobjects: 0,
  362. subobjectIndex: 0,
  363. inverted: false,
  364. // Current subobject
  365. currentFileName: null,
  366. mainColourCode: topParseScope ? topParseScope.mainColourCode : '16',
  367. mainEdgeColourCode: topParseScope ? topParseScope.mainEdgeColourCode : '24',
  368. currentMatrix: new THREE.Matrix4(),
  369. // If false, it is a root material scope previous to parse
  370. isFromParse: true,
  371. triangles: null,
  372. lineSegments: null,
  373. optionalSegments: null,
  374. };
  375. this.parseScopesStack.push( newParseScope );
  376. return newParseScope;
  377. },
  378. removeScopeLevel: function () {
  379. this.parseScopesStack.pop();
  380. return this;
  381. },
  382. addMaterial: function ( material ) {
  383. // Adds a material to the material library which is on top of the parse scopes stack. And also to the materials array
  384. var matLib = this.getCurrentParseScope().lib;
  385. if ( ! matLib[ material.userData.code ] ) {
  386. this.materials.push( material );
  387. }
  388. matLib[ material.userData.code ] = material;
  389. return this;
  390. },
  391. getMaterial: function ( colourCode ) {
  392. // Given a colour code search its material in the parse scopes stack
  393. if ( colourCode.startsWith( "0x2" ) ) {
  394. // Special 'direct' material value (RGB colour)
  395. var colour = colourCode.substring( 3 );
  396. return this.parseColourMetaDirective( new LineParser( "Direct_Color_" + colour + " CODE -1 VALUE #" + colour + " EDGE #" + colour + "" ) );
  397. }
  398. for ( var i = this.parseScopesStack.length - 1; i >= 0; i -- ) {
  399. var material = this.parseScopesStack[ i ].lib[ colourCode ];
  400. if ( material ) {
  401. return material;
  402. }
  403. }
  404. // Material was not found
  405. return null;
  406. },
  407. getParentParseScope: function () {
  408. if ( this.parseScopesStack.length > 1 ) {
  409. return this.parseScopesStack[ this.parseScopesStack.length - 2 ];
  410. }
  411. return null;
  412. },
  413. getCurrentParseScope: function () {
  414. if ( this.parseScopesStack.length > 0 ) {
  415. return this.parseScopesStack[ this.parseScopesStack.length - 1 ];
  416. }
  417. return null;
  418. },
  419. parseColourMetaDirective: function ( lineParser ) {
  420. // Parses a colour definition and returns a THREE.Material or null if error
  421. var code = null;
  422. // Triangle and line colours
  423. var colour = 0xFF00FF;
  424. var edgeColour = 0xFF00FF;
  425. // Transparency
  426. var alpha = 1;
  427. var isTransparent = false;
  428. // Self-illumination:
  429. var luminance = 0;
  430. var finishType = LDrawLoader.FINISH_TYPE_DEFAULT;
  431. var canHaveEnvMap = true;
  432. var edgeMaterial = null;
  433. var name = lineParser.getToken();
  434. if ( ! name ) {
  435. throw 'LDrawLoader: Material name was expected after "!COLOUR tag' + lineParser.getLineNumberString() + ".";
  436. }
  437. // Parse tag tokens and their parameters
  438. var token = null;
  439. while ( true ) {
  440. token = lineParser.getToken();
  441. if ( ! token ) {
  442. break;
  443. }
  444. switch ( token.toUpperCase() ) {
  445. case "CODE":
  446. code = lineParser.getToken();
  447. break;
  448. case "VALUE":
  449. colour = lineParser.getToken();
  450. if ( colour.startsWith( '0x' ) ) {
  451. colour = '#' + colour.substring( 2 );
  452. } else if ( ! colour.startsWith( '#' ) ) {
  453. throw 'LDrawLoader: Invalid colour while parsing material' + lineParser.getLineNumberString() + ".";
  454. }
  455. break;
  456. case "EDGE":
  457. edgeColour = lineParser.getToken();
  458. if ( edgeColour.startsWith( '0x' ) ) {
  459. edgeColour = '#' + edgeColour.substring( 2 );
  460. } else if ( ! edgeColour.startsWith( '#' ) ) {
  461. // Try to see if edge colour is a colour code
  462. edgeMaterial = this.getMaterial( edgeColour );
  463. if ( ! edgeMaterial ) {
  464. throw 'LDrawLoader: Invalid edge colour while parsing material' + lineParser.getLineNumberString() + ".";
  465. }
  466. // Get the edge material for this triangle material
  467. edgeMaterial = edgeMaterial.userData.edgeMaterial;
  468. }
  469. break;
  470. case 'ALPHA':
  471. alpha = parseInt( lineParser.getToken() );
  472. if ( isNaN( alpha ) ) {
  473. throw 'LDrawLoader: Invalid alpha value in material definition' + lineParser.getLineNumberString() + ".";
  474. }
  475. alpha = Math.max( 0, Math.min( 1, alpha / 255 ) );
  476. if ( alpha < 1 ) {
  477. isTransparent = true;
  478. }
  479. break;
  480. case 'LUMINANCE':
  481. luminance = parseInt( lineParser.getToken() );
  482. if ( isNaN( luminance ) ) {
  483. throw 'LDrawLoader: Invalid luminance value in material definition' + LineParser.getLineNumberString() + ".";
  484. }
  485. luminance = Math.max( 0, Math.min( 1, luminance / 255 ) );
  486. break;
  487. case 'CHROME':
  488. finishType = LDrawLoader.FINISH_TYPE_CHROME;
  489. break;
  490. case 'PEARLESCENT':
  491. finishType = LDrawLoader.FINISH_TYPE_PEARLESCENT;
  492. break;
  493. case 'RUBBER':
  494. finishType = LDrawLoader.FINISH_TYPE_RUBBER;
  495. break;
  496. case 'MATTE_METALLIC':
  497. finishType = LDrawLoader.FINISH_TYPE_MATTE_METALLIC;
  498. break;
  499. case 'METAL':
  500. finishType = LDrawLoader.FINISH_TYPE_METAL;
  501. break;
  502. case 'MATERIAL':
  503. // Not implemented
  504. lineParser.setToEnd();
  505. break;
  506. default:
  507. throw 'LDrawLoader: Unknown token "' + token + '" while parsing material' + lineParser.getLineNumberString() + ".";
  508. break;
  509. }
  510. }
  511. var material = null;
  512. switch ( finishType ) {
  513. case LDrawLoader.FINISH_TYPE_DEFAULT:
  514. material = new THREE.MeshStandardMaterial( { color: colour, roughness: 0.3, envMapIntensity: 0.3, metalness: 0 } );
  515. break;
  516. case LDrawLoader.FINISH_TYPE_PEARLESCENT:
  517. // Try to imitate pearlescency by setting the specular to the complementary of the color, and low shininess
  518. var specular = new THREE.Color( colour );
  519. var hsl = specular.getHSL( { h: 0, s: 0, l: 0 } );
  520. hsl.h = ( hsl.h + 0.5 ) % 1;
  521. hsl.l = Math.min( 1, hsl.l + ( 1 - hsl.l ) * 0.7 );
  522. specular.setHSL( hsl.h, hsl.s, hsl.l );
  523. material = new THREE.MeshPhongMaterial( { color: colour, specular: specular, shininess: 10, reflectivity: 0.3 } );
  524. break;
  525. case LDrawLoader.FINISH_TYPE_CHROME:
  526. // Mirror finish surface
  527. material = new THREE.MeshStandardMaterial( { color: colour, roughness: 0, metalness: 1 } );
  528. break;
  529. case LDrawLoader.FINISH_TYPE_RUBBER:
  530. // Rubber is best simulated with Lambert
  531. material = new THREE.MeshStandardMaterial( { color: colour, roughness: 0.9, metalness: 0 } );
  532. canHaveEnvMap = false;
  533. break;
  534. case LDrawLoader.FINISH_TYPE_MATTE_METALLIC:
  535. // Brushed metal finish
  536. material = new THREE.MeshStandardMaterial( { color: colour, roughness: 0.8, metalness: 0.4 } );
  537. break;
  538. case LDrawLoader.FINISH_TYPE_METAL:
  539. // Average metal finish
  540. material = new THREE.MeshStandardMaterial( { color: colour, roughness: 0.2, metalness: 0.85 } );
  541. break;
  542. default:
  543. // Should not happen
  544. break;
  545. }
  546. material.transparent = isTransparent;
  547. material.opacity = alpha;
  548. material.userData.canHaveEnvMap = canHaveEnvMap;
  549. if ( luminance !== 0 ) {
  550. material.emissive.set( material.color ).multiplyScalar( luminance );
  551. }
  552. if ( ! edgeMaterial ) {
  553. // This is the material used for edges
  554. edgeMaterial = new THREE.LineBasicMaterial( { color: edgeColour } );
  555. edgeMaterial.userData.code = code;
  556. edgeMaterial.name = name + " - Edge";
  557. edgeMaterial.userData.canHaveEnvMap = false;
  558. }
  559. material.userData.code = code;
  560. material.name = name;
  561. material.userData.edgeMaterial = edgeMaterial;
  562. return material;
  563. },
  564. //
  565. parse: function ( text ) {
  566. //console.time( 'LDrawLoader' );
  567. // Retrieve data from the parent parse scope
  568. var parentParseScope = this.getParentParseScope();
  569. // Main colour codes passed to this subobject (or default codes 16 and 24 if it is the root object)
  570. var mainColourCode = parentParseScope.mainColourCode;
  571. var mainEdgeColourCode = parentParseScope.mainEdgeColourCode;
  572. var url = parentParseScope.url;
  573. var currentParseScope = this.getCurrentParseScope();
  574. // Parse result variables
  575. var triangles;
  576. var lineSegments;
  577. var optionalSegments;
  578. var subobjects = [];
  579. var category = null;
  580. var keywords = null;
  581. if ( text.indexOf( '\r\n' ) !== - 1 ) {
  582. // This is faster than String.split with regex that splits on both
  583. text = text.replace( /\r\n/g, '\n' );
  584. }
  585. var lines = text.split( '\n' );
  586. var numLines = lines.length;
  587. var lineIndex = 0;
  588. var parsingEmbeddedFiles = false;
  589. var currentEmbeddedFileName = null;
  590. var currentEmbeddedText = null;
  591. var bfcCertified = false;
  592. var bfcCCW = true;
  593. var bfcInverted = false;
  594. var bfcCull = true;
  595. var type = '';
  596. var scope = this;
  597. function parseColourCode( lineParser, forEdge ) {
  598. // Parses next colour code and returns a THREE.Material
  599. var colourCode = lineParser.getToken();
  600. if ( ! forEdge && colourCode === '16' ) {
  601. colourCode = mainColourCode;
  602. }
  603. if ( forEdge && colourCode === '24' ) {
  604. colourCode = mainEdgeColourCode;
  605. }
  606. var material = scope.getMaterial( colourCode );
  607. if ( ! material ) {
  608. throw 'LDrawLoader: Unknown colour code "' + colourCode + '" is used' + lineParser.getLineNumberString() + ' but it was not defined previously.';
  609. }
  610. return material;
  611. }
  612. function parseVector( lp ) {
  613. var v = new THREE.Vector3( parseFloat( lp.getToken() ), parseFloat( lp.getToken() ), parseFloat( lp.getToken() ) );
  614. if ( ! scope.separateObjects ) {
  615. v.applyMatrix4( parentParseScope.currentMatrix );
  616. }
  617. return v;
  618. }
  619. // Parse all line commands
  620. for ( lineIndex = 0; lineIndex < numLines; lineIndex ++ ) {
  621. var line = lines[ lineIndex ];
  622. if ( line.length === 0 ) continue;
  623. if ( parsingEmbeddedFiles ) {
  624. if ( line.startsWith( '0 FILE ' ) ) {
  625. // Save previous embedded file in the cache
  626. this.subobjectCache[ currentEmbeddedFileName.toLowerCase() ] = currentEmbeddedText;
  627. // New embedded text file
  628. currentEmbeddedFileName = line.substring( 7 );
  629. currentEmbeddedText = '';
  630. } else {
  631. currentEmbeddedText += line + '\n';
  632. }
  633. continue;
  634. }
  635. var lp = new LineParser( line, lineIndex + 1 );
  636. lp.seekNonSpace();
  637. if ( lp.isAtTheEnd() ) {
  638. // Empty line
  639. continue;
  640. }
  641. // Parse the line type
  642. var lineType = lp.getToken();
  643. switch ( lineType ) {
  644. // Line type 0: Comment or META
  645. case '0':
  646. // Parse meta directive
  647. var meta = lp.getToken();
  648. if ( meta ) {
  649. switch ( meta ) {
  650. case '!LDRAW_ORG':
  651. type = lp.getToken();
  652. if ( ! parsingEmbeddedFiles ) {
  653. currentParseScope.triangles = [];
  654. currentParseScope.lineSegments = [];
  655. currentParseScope.optionalSegments = [];
  656. currentParseScope.groupObject = new THREE.Group();
  657. triangles = currentParseScope.triangles;
  658. lineSegments = currentParseScope.lineSegments;
  659. optionalSegments = currentParseScope.optionalSegments;
  660. currentParseScope.type = type;
  661. }
  662. break;
  663. case '!COLOUR':
  664. var material = this.parseColourMetaDirective( lp );
  665. if ( material ) {
  666. this.addMaterial( material );
  667. } else {
  668. console.warn( 'LDrawLoader: Error parsing material' + lp.getLineNumberString() );
  669. }
  670. break;
  671. case '!CATEGORY':
  672. category = lp.getToken();
  673. break;
  674. case '!KEYWORDS':
  675. var newKeywords = lp.getRemainingString().split( ',' );
  676. if ( newKeywords.length > 0 ) {
  677. if ( ! keywords ) {
  678. keywords = [];
  679. }
  680. newKeywords.forEach( function ( keyword ) {
  681. keywords.push( keyword.trim() );
  682. } );
  683. }
  684. break;
  685. case 'FILE':
  686. if ( lineIndex > 0 ) {
  687. // Start embedded text files parsing
  688. parsingEmbeddedFiles = true;
  689. currentEmbeddedFileName = lp.getRemainingString();
  690. currentEmbeddedText = '';
  691. bfcCertified = false;
  692. bfcCCW = true;
  693. }
  694. break;
  695. case 'BFC':
  696. // Changes to the backface culling state
  697. while ( ! lp.isAtTheEnd() ) {
  698. var token = lp.getToken();
  699. switch ( token ) {
  700. case 'CERTIFY':
  701. case 'NOCERTIFY':
  702. bfcCertified = token === 'CERTIFY';
  703. bfcCCW = true;
  704. break;
  705. case 'CW':
  706. case 'CCW':
  707. bfcCCW = token === 'CCW';
  708. break;
  709. case 'INVERTNEXT':
  710. bfcInverted = true;
  711. break;
  712. case 'CLIP':
  713. case 'NOCLIP':
  714. bfcCull = token === 'CLIP';
  715. break;
  716. default:
  717. console.warn( 'THREE.LDrawLoader: BFC directive "' + token + '" is unknown.' );
  718. break;
  719. }
  720. }
  721. break;
  722. default:
  723. // Other meta directives are not implemented
  724. break;
  725. }
  726. }
  727. break;
  728. // Line type 1: Sub-object file
  729. case '1':
  730. var material = parseColourCode( lp );
  731. var posX = parseFloat( lp.getToken() );
  732. var posY = parseFloat( lp.getToken() );
  733. var posZ = parseFloat( lp.getToken() );
  734. var m0 = parseFloat( lp.getToken() );
  735. var m1 = parseFloat( lp.getToken() );
  736. var m2 = parseFloat( lp.getToken() );
  737. var m3 = parseFloat( lp.getToken() );
  738. var m4 = parseFloat( lp.getToken() );
  739. var m5 = parseFloat( lp.getToken() );
  740. var m6 = parseFloat( lp.getToken() );
  741. var m7 = parseFloat( lp.getToken() );
  742. var m8 = parseFloat( lp.getToken() );
  743. var matrix = new THREE.Matrix4().set(
  744. m0, m1, m2, posX,
  745. m3, m4, m5, posY,
  746. m6, m7, m8, posZ,
  747. 0, 0, 0, 1
  748. );
  749. var fileName = lp.getRemainingString().trim().replace( "\\", "/" );
  750. if ( scope.fileMap[ fileName ] ) {
  751. // Found the subobject path in the preloaded file path map
  752. fileName = scope.fileMap[ fileName ];
  753. } else {
  754. // Standardized subfolders
  755. if ( fileName.startsWith( 's/' ) ) {
  756. fileName = 'parts/' + fileName;
  757. } else if ( fileName.startsWith( '48/' ) ) {
  758. fileName = 'p/' + fileName;
  759. }
  760. }
  761. // If the scale of the object is negated then the triangle winding order
  762. // needs to be flipped.
  763. if ( scope.separateObjects === false && matrix.determinant() < 0 ) {
  764. bfcInverted = ! bfcInverted;
  765. }
  766. subobjects.push( {
  767. material: material,
  768. matrix: matrix,
  769. fileName: fileName,
  770. originalFileName: fileName,
  771. locationState: LDrawLoader.FILE_LOCATION_AS_IS,
  772. url: null,
  773. triedLowerCase: false,
  774. inverted: bfcInverted !== currentParseScope.inverted
  775. } );
  776. bfcInverted = false;
  777. break;
  778. // Line type 2: Line segment
  779. case '5':
  780. case '2':
  781. var material = parseColourCode( lp, true );
  782. var arr = lineType === '2' ? lineSegments : optionalSegments;
  783. arr.push( {
  784. material: material.userData.edgeMaterial,
  785. colourCode: material.userData.code,
  786. v0: parseVector( lp ),
  787. v1: parseVector( lp )
  788. } );
  789. break;
  790. // Line type 3: Triangle
  791. case '3':
  792. var material = parseColourCode( lp );
  793. var inverted = currentParseScope.inverted;
  794. var ccw = bfcCCW !== inverted;
  795. var doubleSided = ! bfcCertified || ! bfcCull;
  796. var v0, v1, v2;
  797. if ( ccw === true ) {
  798. v0 = parseVector( lp );
  799. v1 = parseVector( lp );
  800. v2 = parseVector( lp );
  801. } else {
  802. v2 = parseVector( lp );
  803. v1 = parseVector( lp );
  804. v0 = parseVector( lp );
  805. }
  806. triangles.push( {
  807. material: material,
  808. colourCode: material.userData.code,
  809. v0: v0,
  810. v1: v1,
  811. v2: v2
  812. } );
  813. if ( doubleSided === true ) {
  814. triangles.push( {
  815. material: material,
  816. colourCode: material.userData.code,
  817. v0: v0,
  818. v1: v2,
  819. v2: v1
  820. } );
  821. }
  822. break;
  823. // Line type 4: Quadrilateral
  824. case '4':
  825. var material = parseColourCode( lp );
  826. var inverted = currentParseScope.inverted;
  827. var ccw = bfcCCW !== inverted;
  828. var doubleSided = ! bfcCertified || ! bfcCull;
  829. var v0, v1, v2, v3;
  830. if ( ccw === true ) {
  831. v0 = parseVector( lp );
  832. v1 = parseVector( lp );
  833. v2 = parseVector( lp );
  834. v3 = parseVector( lp );
  835. } else {
  836. v3 = parseVector( lp );
  837. v2 = parseVector( lp );
  838. v1 = parseVector( lp );
  839. v0 = parseVector( lp );
  840. }
  841. triangles.push( {
  842. material: material,
  843. colourCode: material.userData.code,
  844. v0: v0,
  845. v1: v1,
  846. v2: v2
  847. } );
  848. triangles.push( {
  849. material: material,
  850. colourCode: material.userData.code,
  851. v0: v0,
  852. v1: v2,
  853. v2: v3
  854. } );
  855. if ( doubleSided === true ) {
  856. triangles.push( {
  857. material: material,
  858. colourCode: material.userData.code,
  859. v0: v0,
  860. v1: v2,
  861. v2: v1
  862. } );
  863. triangles.push( {
  864. material: material,
  865. colourCode: material.userData.code,
  866. v0: v0,
  867. v1: v3,
  868. v2: v2
  869. } );
  870. }
  871. break;
  872. // Line type 5: Optional line
  873. case '5':
  874. // Line type 5 is not implemented
  875. break;
  876. default:
  877. throw 'LDrawLoader: Unknown line type "' + lineType + '"' + lp.getLineNumberString() + '.';
  878. break;
  879. }
  880. }
  881. if ( parsingEmbeddedFiles ) {
  882. this.subobjectCache[ currentEmbeddedFileName.toLowerCase() ] = currentEmbeddedText;
  883. }
  884. const groupObject = currentParseScope.groupObject;
  885. groupObject.userData.category = category;
  886. groupObject.userData.keywords = keywords;
  887. groupObject.userData.subobjects = subobjects;
  888. return currentParseScope.groupObject;
  889. }
  890. };
  891. return LDrawLoader;
  892. } )();