LDrawLoader.js 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431
  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. // Current merged object and primitives
  133. this.currentGroupObject = null;
  134. this.currentTriangles = null;
  135. this.currentLineSegments = null;
  136. }
  137. // Special surface finish tag types.
  138. // Note: "MATERIAL" tag (e.g. GLITTER, SPECKLE) is not implemented
  139. LDrawLoader.FINISH_TYPE_DEFAULT = 0;
  140. LDrawLoader.FINISH_TYPE_CHROME = 1;
  141. LDrawLoader.FINISH_TYPE_PEARLESCENT = 2;
  142. LDrawLoader.FINISH_TYPE_RUBBER = 3;
  143. LDrawLoader.FINISH_TYPE_MATTE_METALLIC = 4;
  144. LDrawLoader.FINISH_TYPE_METAL = 5;
  145. // State machine to search a subobject path.
  146. // The LDraw standard establishes these various possible subfolders.
  147. LDrawLoader.FILE_LOCATION_AS_IS = 0;
  148. LDrawLoader.FILE_LOCATION_TRY_PARTS = 1;
  149. LDrawLoader.FILE_LOCATION_TRY_P = 2;
  150. LDrawLoader.FILE_LOCATION_TRY_MODELS = 3;
  151. LDrawLoader.FILE_LOCATION_TRY_RELATIVE = 4;
  152. LDrawLoader.FILE_LOCATION_TRY_ABSOLUTE = 5;
  153. LDrawLoader.FILE_LOCATION_NOT_FOUND = 6;
  154. LDrawLoader.prototype = {
  155. constructor: LDrawLoader,
  156. load: function ( url, onLoad, onProgress, onError ) {
  157. if ( ! this.fileMap ) {
  158. this.fileMap = {};
  159. }
  160. var scope = this;
  161. var fileLoader = new THREE.FileLoader( this.manager );
  162. fileLoader.setPath( this.path );
  163. fileLoader.load( url, function ( text ) {
  164. processObject( text, onLoad );
  165. }, onProgress, onError );
  166. function subobjectLoad( url, onLoad, onProgress, onError, subobject ) {
  167. var fileLoader = new THREE.FileLoader( scope.manager );
  168. fileLoader.setPath( scope.path );
  169. fileLoader.load( url, function ( text ) {
  170. processObject( text, onLoad, subobject );
  171. }, onProgress, onError );
  172. }
  173. function processObject( text, onProcessed, subobject ) {
  174. var parseScope = scope.newParseScopeLevel();
  175. parseScope.url = url;
  176. var parentParseScope = scope.getParentParseScope();
  177. // Add to cache
  178. var currentFileName = parentParseScope.currentFileName;
  179. if ( scope.subobjectCache[ currentFileName ] === undefined ) {
  180. scope.subobjectCache[ currentFileName ] = text;
  181. }
  182. parseScope.inverted = subobject !== undefined ? subobject.inverted : false;
  183. // Parse the object (returns a THREE.Group)
  184. var objGroup = scope.parse( text );
  185. // Load subobjects
  186. parseScope.subobjects = objGroup.userData.subobjects;
  187. parseScope.numSubobjects = parseScope.subobjects.length;
  188. parseScope.subobjectIndex = 0;
  189. if ( parseScope.numSubobjects > 0 ) {
  190. // Load the first subobject
  191. var subobjectGroup = loadSubobject( parseScope.subobjects[ 0 ], true );
  192. // Optimization for loading pack: If subobjects are obtained from cache, keep loading them iteratively rather than recursively
  193. if ( subobjectGroup ) {
  194. while ( subobjectGroup && parseScope.subobjectIndex < parseScope.numSubobjects - 1 ) {
  195. subobjectGroup = loadSubobject( parseScope.subobjects[ ++ parseScope.subobjectIndex ], true );
  196. }
  197. if ( subobjectGroup ) {
  198. finalizeObject();
  199. }
  200. }
  201. } else {
  202. // No subobjects, finish object
  203. finalizeObject();
  204. }
  205. return objGroup;
  206. function finalizeObject() {
  207. if ( ! scope.separateObjects && ! parentParseScope.isFromParse ) {
  208. // We are finalizing the root object and merging primitives is activated, so create the entire Mesh and LineSegments objects now
  209. if ( scope.currentLineSegments.length > 0 ) {
  210. objGroup.add( createObject( scope.currentLineSegments, 2 ) );
  211. }
  212. if ( scope.currentTriangles.length > 0 ) {
  213. objGroup.add( createObject( scope.currentTriangles, 3 ) );
  214. }
  215. }
  216. scope.removeScopeLevel();
  217. if ( onProcessed ) {
  218. onProcessed( objGroup );
  219. }
  220. }
  221. function loadSubobject( subobject, sync ) {
  222. parseScope.mainColourCode = subobject.material.userData.code;
  223. parseScope.mainEdgeColourCode = subobject.material.userData.edgeMaterial.userData.code;
  224. parseScope.currentFileName = subobject.originalFileName;
  225. if ( ! scope.separateObjects ) {
  226. // Set current matrix
  227. parseScope.currentMatrix.multiplyMatrices( parentParseScope.currentMatrix, subobject.matrix );
  228. }
  229. // If subobject was cached previously, use the cached one
  230. var cached = scope.subobjectCache[ subobject.originalFileName ];
  231. if ( cached ) {
  232. var subobjectGroup = processObject( cached, sync ? undefined : onSubobjectLoaded, subobject );
  233. if ( sync ) {
  234. addSubobject( subobject, subobjectGroup );
  235. return subobjectGroup;
  236. }
  237. return;
  238. }
  239. // Adjust file name to locate the subobject file path in standard locations (always under directory scope.path)
  240. // Update also subobject.locationState for the next try if this load fails.
  241. var subobjectURL = subobject.fileName;
  242. var newLocationState = LDrawLoader.FILE_LOCATION_NOT_FOUND;
  243. switch ( subobject.locationState ) {
  244. case LDrawLoader.FILE_LOCATION_AS_IS:
  245. newLocationState = subobject.locationState + 1;
  246. break;
  247. case LDrawLoader.FILE_LOCATION_TRY_PARTS:
  248. subobjectURL = 'parts/' + subobjectURL;
  249. newLocationState = subobject.locationState + 1;
  250. break;
  251. case LDrawLoader.FILE_LOCATION_TRY_P:
  252. subobjectURL = 'p/' + subobjectURL;
  253. newLocationState = subobject.locationState + 1;
  254. break;
  255. case LDrawLoader.FILE_LOCATION_TRY_MODELS:
  256. subobjectURL = 'models/' + subobjectURL;
  257. newLocationState = subobject.locationState + 1;
  258. break;
  259. case LDrawLoader.FILE_LOCATION_TRY_RELATIVE:
  260. subobjectURL = url.substring( 0, url.lastIndexOf( "/" ) + 1 ) + subobjectURL;
  261. newLocationState = subobject.locationState + 1;
  262. break;
  263. case LDrawLoader.FILE_LOCATION_TRY_ABSOLUTE:
  264. if ( subobject.triedLowerCase ) {
  265. // Try absolute path
  266. newLocationState = LDrawLoader.FILE_LOCATION_NOT_FOUND;
  267. } else {
  268. // Next attempt is lower case
  269. subobject.fileName = subobject.fileName.toLowerCase();
  270. subobjectURL = subobject.fileName;
  271. subobject.triedLowerCase = true;
  272. newLocationState = LDrawLoader.FILE_LOCATION_AS_IS;
  273. }
  274. break;
  275. case LDrawLoader.FILE_LOCATION_NOT_FOUND:
  276. // All location possibilities have been tried, give up loading this object
  277. console.warn( 'LDrawLoader: Subobject "' + subobject.originalFileName + '" could not be found.' );
  278. // Try to read the next subobject
  279. parseScope.subobjectIndex ++;
  280. if ( parseScope.subobjectIndex >= parseScope.numSubobjects ) {
  281. // All subojects have been loaded. Finish parent object
  282. scope.removeScopeLevel();
  283. onProcessed( objGroup );
  284. } else {
  285. // Load next subobject
  286. loadSubobject( parseScope.subobjects[ parseScope.subobjectIndex ] );
  287. }
  288. return;
  289. }
  290. subobject.locationState = newLocationState;
  291. subobject.url = subobjectURL;
  292. // Load the subobject
  293. subobjectLoad( subobjectURL, onSubobjectLoaded, undefined, onSubobjectError, subobject );
  294. }
  295. function onSubobjectLoaded( subobjectGroup ) {
  296. var subobject = parseScope.subobjects[ parseScope.subobjectIndex ];
  297. if ( subobjectGroup === null ) {
  298. // Try to reload
  299. loadSubobject( subobject );
  300. return;
  301. }
  302. // Add the subobject just loaded
  303. addSubobject( subobject, subobjectGroup );
  304. // Proceed to load the next subobject, or finish the parent object
  305. parseScope.subobjectIndex ++;
  306. if ( parseScope.subobjectIndex < parseScope.numSubobjects ) {
  307. loadSubobject( parseScope.subobjects[ parseScope.subobjectIndex ] );
  308. } else {
  309. finalizeObject();
  310. }
  311. }
  312. function addSubobject( subobject, subobjectGroup ) {
  313. if ( scope.separateObjects ) {
  314. subobjectGroup.name = subobject.fileName;
  315. objGroup.add( subobjectGroup );
  316. subobjectGroup.matrix.copy( subobject.matrix );
  317. subobjectGroup.matrixAutoUpdate = false;
  318. }
  319. scope.fileMap[ subobject.originalFileName ] = subobject.url;
  320. }
  321. function onSubobjectError( err ) {
  322. // Retry download from a different default possible location
  323. loadSubobject( parseScope.subobjects[ parseScope.subobjectIndex ] );
  324. }
  325. }
  326. },
  327. setPath: function ( value ) {
  328. this.path = value;
  329. return this;
  330. },
  331. setMaterials: function ( materials ) {
  332. // Clears parse scopes stack, adds new scope with material library
  333. this.parseScopesStack = [];
  334. this.newParseScopeLevel( materials );
  335. this.getCurrentParseScope().isFromParse = false;
  336. this.materials = materials;
  337. this.currentGroupObject = null;
  338. return this;
  339. },
  340. setFileMap: function ( fileMap ) {
  341. this.fileMap = fileMap;
  342. return this;
  343. },
  344. newParseScopeLevel: function ( materials ) {
  345. // Adds a new scope level, assign materials to it and returns it
  346. var matLib = {};
  347. if ( materials ) {
  348. for ( var i = 0, n = materials.length; i < n; i ++ ) {
  349. var material = materials[ i ];
  350. matLib[ material.userData.code ] = material;
  351. }
  352. }
  353. var topParseScope = this.getCurrentParseScope();
  354. var parentParseScope = this.getParentParseScope();
  355. var newParseScope = {
  356. lib: matLib,
  357. url: null,
  358. // Subobjects
  359. subobjects: null,
  360. numSubobjects: 0,
  361. subobjectIndex: 0,
  362. inverted: false,
  363. // Current subobject
  364. currentFileName: null,
  365. mainColourCode: topParseScope ? topParseScope.mainColourCode : '16',
  366. mainEdgeColourCode: topParseScope ? topParseScope.mainEdgeColourCode : '24',
  367. currentMatrix: new THREE.Matrix4(),
  368. // If false, it is a root material scope previous to parse
  369. isFromParse: true
  370. };
  371. this.parseScopesStack.push( newParseScope );
  372. return newParseScope;
  373. },
  374. removeScopeLevel: function () {
  375. this.parseScopesStack.pop();
  376. return this;
  377. },
  378. addMaterial: function ( material ) {
  379. // Adds a material to the material library which is on top of the parse scopes stack. And also to the materials array
  380. var matLib = this.getCurrentParseScope().lib;
  381. if ( ! matLib[ material.userData.code ] ) {
  382. this.materials.push( material );
  383. }
  384. matLib[ material.userData.code ] = material;
  385. return this;
  386. },
  387. getMaterial: function ( colourCode ) {
  388. // Given a colour code search its material in the parse scopes stack
  389. if ( colourCode.startsWith( "0x2" ) ) {
  390. // Special 'direct' material value (RGB colour)
  391. var colour = colourCode.substring( 3 );
  392. return this.parseColourMetaDirective( new LineParser( "Direct_Color_" + colour + " CODE -1 VALUE #" + colour + " EDGE #" + colour + "" ) );
  393. }
  394. for ( var i = this.parseScopesStack.length - 1; i >= 0; i -- ) {
  395. var material = this.parseScopesStack[ i ].lib[ colourCode ];
  396. if ( material ) {
  397. return material;
  398. }
  399. }
  400. // Material was not found
  401. return null;
  402. },
  403. getParentParseScope: function () {
  404. if ( this.parseScopesStack.length > 1 ) {
  405. return this.parseScopesStack[ this.parseScopesStack.length - 2 ];
  406. }
  407. return null;
  408. },
  409. getCurrentParseScope: function () {
  410. if ( this.parseScopesStack.length > 0 ) {
  411. return this.parseScopesStack[ this.parseScopesStack.length - 1 ];
  412. }
  413. return null;
  414. },
  415. parseColourMetaDirective: function ( lineParser ) {
  416. // Parses a colour definition and returns a THREE.Material or null if error
  417. var code = null;
  418. // Triangle and line colours
  419. var colour = 0xFF00FF;
  420. var edgeColour = 0xFF00FF;
  421. // Transparency
  422. var alpha = 1;
  423. var isTransparent = false;
  424. // Self-illumination:
  425. var luminance = 0;
  426. var finishType = LDrawLoader.FINISH_TYPE_DEFAULT;
  427. var canHaveEnvMap = true;
  428. var edgeMaterial = null;
  429. var name = lineParser.getToken();
  430. if ( ! name ) {
  431. throw 'LDrawLoader: Material name was expected after "!COLOUR tag' + lineParser.getLineNumberString() + ".";
  432. }
  433. // Parse tag tokens and their parameters
  434. var token = null;
  435. while ( true ) {
  436. token = lineParser.getToken();
  437. if ( ! token ) {
  438. break;
  439. }
  440. switch ( token.toUpperCase() ) {
  441. case "CODE":
  442. code = lineParser.getToken();
  443. break;
  444. case "VALUE":
  445. colour = lineParser.getToken();
  446. if ( colour.startsWith( '0x' ) ) {
  447. colour = '#' + colour.substring( 2 );
  448. } else if ( ! colour.startsWith( '#' ) ) {
  449. throw 'LDrawLoader: Invalid colour while parsing material' + lineParser.getLineNumberString() + ".";
  450. }
  451. break;
  452. case "EDGE":
  453. edgeColour = lineParser.getToken();
  454. if ( edgeColour.startsWith( '0x' ) ) {
  455. edgeColour = '#' + edgeColour.substring( 2 );
  456. } else if ( ! edgeColour.startsWith( '#' ) ) {
  457. // Try to see if edge colour is a colour code
  458. edgeMaterial = this.getMaterial( edgeColour );
  459. if ( ! edgeMaterial ) {
  460. throw 'LDrawLoader: Invalid edge colour while parsing material' + lineParser.getLineNumberString() + ".";
  461. }
  462. // Get the edge material for this triangle material
  463. edgeMaterial = edgeMaterial.userData.edgeMaterial;
  464. }
  465. break;
  466. case 'ALPHA':
  467. alpha = parseInt( lineParser.getToken() );
  468. if ( isNaN( alpha ) ) {
  469. throw 'LDrawLoader: Invalid alpha value in material definition' + lineParser.getLineNumberString() + ".";
  470. }
  471. alpha = Math.max( 0, Math.min( 1, alpha / 255 ) );
  472. if ( alpha < 1 ) {
  473. isTransparent = true;
  474. }
  475. break;
  476. case 'LUMINANCE':
  477. luminance = parseInt( lineParser.getToken() );
  478. if ( isNaN( luminance ) ) {
  479. throw 'LDrawLoader: Invalid luminance value in material definition' + LineParser.getLineNumberString() + ".";
  480. }
  481. luminance = Math.max( 0, Math.min( 1, luminance / 255 ) );
  482. break;
  483. case 'CHROME':
  484. finishType = LDrawLoader.FINISH_TYPE_CHROME;
  485. break;
  486. case 'PEARLESCENT':
  487. finishType = LDrawLoader.FINISH_TYPE_PEARLESCENT;
  488. break;
  489. case 'RUBBER':
  490. finishType = LDrawLoader.FINISH_TYPE_RUBBER;
  491. break;
  492. case 'MATTE_METALLIC':
  493. finishType = LDrawLoader.FINISH_TYPE_MATTE_METALLIC;
  494. break;
  495. case 'METAL':
  496. finishType = LDrawLoader.FINISH_TYPE_METAL;
  497. break;
  498. case 'MATERIAL':
  499. // Not implemented
  500. lineParser.setToEnd();
  501. break;
  502. default:
  503. throw 'LDrawLoader: Unknown token "' + token + '" while parsing material' + lineParser.getLineNumberString() + ".";
  504. break;
  505. }
  506. }
  507. var material = null;
  508. switch ( finishType ) {
  509. case LDrawLoader.FINISH_TYPE_DEFAULT:
  510. case LDrawLoader.FINISH_TYPE_PEARLESCENT:
  511. var specular = new THREE.Color( colour );
  512. var shininess = 35;
  513. var hsl = specular.getHSL( { h: 0, s: 0, l: 0 } );
  514. if ( finishType === LDrawLoader.FINISH_TYPE_DEFAULT ) {
  515. // Default plastic material with shiny specular
  516. hsl.l = Math.min( 1, hsl.l + ( 1 - hsl.l ) * 0.12 );
  517. } else {
  518. // Try to imitate pearlescency by setting the specular to the complementary of the color, and low shininess
  519. hsl.h = ( hsl.h + 0.5 ) % 1;
  520. hsl.l = Math.min( 1, hsl.l + ( 1 - hsl.l ) * 0.7 );
  521. shininess = 10;
  522. }
  523. specular.setHSL( hsl.h, hsl.s, hsl.l );
  524. material = new THREE.MeshPhongMaterial( { color: colour, specular: specular, shininess: shininess, reflectivity: 0.3 } );
  525. break;
  526. case LDrawLoader.FINISH_TYPE_CHROME:
  527. // Mirror finish surface
  528. material = new THREE.MeshStandardMaterial( { color: colour, roughness: 0, metalness: 1 } );
  529. break;
  530. case LDrawLoader.FINISH_TYPE_RUBBER:
  531. // Rubber is best simulated with Lambert
  532. material = new THREE.MeshLambertMaterial( { color: colour } );
  533. canHaveEnvMap = false;
  534. break;
  535. case LDrawLoader.FINISH_TYPE_MATTE_METALLIC:
  536. // Brushed metal finish
  537. material = new THREE.MeshStandardMaterial( { color: colour, roughness: 0.8, metalness: 0.4 } );
  538. break;
  539. case LDrawLoader.FINISH_TYPE_METAL:
  540. // Average metal finish
  541. material = new THREE.MeshStandardMaterial( { color: colour, roughness: 0.2, metalness: 0.85 } );
  542. break;
  543. default:
  544. // Should not happen
  545. break;
  546. }
  547. material.transparent = isTransparent;
  548. material.opacity = alpha;
  549. material.userData.canHaveEnvMap = canHaveEnvMap;
  550. if ( luminance !== 0 ) {
  551. material.emissive.set( material.color ).multiplyScalar( luminance );
  552. }
  553. if ( ! edgeMaterial ) {
  554. // This is the material used for edges
  555. edgeMaterial = new THREE.LineBasicMaterial( { color: edgeColour } );
  556. edgeMaterial.userData.code = code;
  557. edgeMaterial.name = name + " - Edge";
  558. edgeMaterial.userData.canHaveEnvMap = false;
  559. }
  560. material.userData.code = code;
  561. material.name = name;
  562. material.userData.edgeMaterial = edgeMaterial;
  563. return material;
  564. },
  565. //
  566. parse: function ( text ) {
  567. //console.time( 'LDrawLoader' );
  568. // Retrieve data from the parent parse scope
  569. var parentParseScope = this.getParentParseScope();
  570. // Main colour codes passed to this subobject (or default codes 16 and 24 if it is the root object)
  571. var mainColourCode = parentParseScope.mainColourCode;
  572. var mainEdgeColourCode = parentParseScope.mainEdgeColourCode;
  573. var url = parentParseScope.url;
  574. var currentParseScope = this.getCurrentParseScope();
  575. // Parse result variables
  576. var triangles;
  577. var lineSegments;
  578. if ( this.separateObjects ) {
  579. triangles = [];
  580. lineSegments = [];
  581. } else {
  582. if ( this.currentGroupObject === null ) {
  583. this.currentGroupObject = new THREE.Group();
  584. this.currentTriangles = [];
  585. this.currentLineSegments = [];
  586. }
  587. triangles = this.currentTriangles;
  588. lineSegments = this.currentLineSegments;
  589. }
  590. var subobjects = [];
  591. var category = null;
  592. var keywords = null;
  593. if ( text.indexOf( '\r\n' ) !== - 1 ) {
  594. // This is faster than String.split with regex that splits on both
  595. text = text.replace( /\r\n/g, '\n' );
  596. }
  597. var lines = text.split( '\n' );
  598. var numLines = lines.length;
  599. var lineIndex = 0;
  600. var parsingEmbeddedFiles = false;
  601. var currentEmbeddedFileName = null;
  602. var currentEmbeddedText = null;
  603. var scope = this;
  604. function parseColourCode( lineParser, forEdge ) {
  605. // Parses next colour code and returns a THREE.Material
  606. var colourCode = lineParser.getToken();
  607. if ( ! forEdge && colourCode === '16' ) {
  608. colourCode = mainColourCode;
  609. }
  610. if ( forEdge && colourCode === '24' ) {
  611. colourCode = mainEdgeColourCode;
  612. }
  613. var material = scope.getMaterial( colourCode );
  614. if ( ! material ) {
  615. throw 'LDrawLoader: Unknown colour code "' + colourCode + '" is used' + lineParser.getLineNumberString() + ' but it was not defined previously.';
  616. }
  617. return material;
  618. }
  619. function parseVector( lp ) {
  620. var v = new THREE.Vector3( parseFloat( lp.getToken() ), parseFloat( lp.getToken() ), parseFloat( lp.getToken() ) );
  621. if ( ! scope.separateObjects ) {
  622. v.applyMatrix4( parentParseScope.currentMatrix );
  623. }
  624. return v;
  625. }
  626. var bfcEnabled = false;
  627. var bfcCCW = true;
  628. var bfcInverted = false;
  629. // Parse all line commands
  630. for ( lineIndex = 0; lineIndex < numLines; lineIndex ++ ) {
  631. var line = lines[ lineIndex ];
  632. if ( line.length === 0 ) continue;
  633. if ( parsingEmbeddedFiles ) {
  634. if ( line.startsWith( '0 FILE ' ) ) {
  635. // Save previous embedded file in the cache
  636. this.subobjectCache[ currentEmbeddedFileName ] = currentEmbeddedText;
  637. // New embedded text file
  638. currentEmbeddedFileName = line.substring( 7 );
  639. currentEmbeddedText = '';
  640. } else {
  641. currentEmbeddedText += line + '\n';
  642. }
  643. continue;
  644. }
  645. var lp = new LineParser( line, lineIndex + 1 );
  646. lp.seekNonSpace();
  647. if ( lp.isAtTheEnd() ) {
  648. // Empty line
  649. continue;
  650. }
  651. // Parse the line type
  652. var lineType = lp.getToken();
  653. switch ( lineType ) {
  654. // Line type 0: Comment or META
  655. case '0':
  656. // Parse meta directive
  657. var meta = lp.getToken();
  658. if ( meta ) {
  659. switch ( meta ) {
  660. case '!COLOUR':
  661. var material = this.parseColourMetaDirective( lp );
  662. if ( material ) {
  663. this.addMaterial( material );
  664. } else {
  665. console.warn( 'LDrawLoader: Error parsing material' + lp.getLineNumberString() );
  666. }
  667. break;
  668. case '!CATEGORY':
  669. category = lp.getToken();
  670. break;
  671. case '!KEYWORDS':
  672. var newKeywords = lp.getRemainingString().split( ',' );
  673. if ( newKeywords.length > 0 ) {
  674. if ( ! keywords ) {
  675. keywords = [];
  676. }
  677. newKeywords.forEach( function ( keyword ) {
  678. keywords.push( keyword.trim() );
  679. } );
  680. }
  681. break;
  682. case 'FILE':
  683. if ( lineIndex > 0 ) {
  684. // Start embedded text files parsing
  685. parsingEmbeddedFiles = true;
  686. currentEmbeddedFileName = lp.getRemainingString();
  687. currentEmbeddedText = '';
  688. bfcEnabled = false;
  689. bfcCCW = true;
  690. }
  691. break;
  692. case 'BFC':
  693. while ( ! lp.isAtTheEnd() ) {
  694. var token = lp.getToken();
  695. bfcCCW = true;
  696. switch ( token ) {
  697. case 'CERTIFY':
  698. case 'NOCERTIFY':
  699. bfcEnabled = token === 'CERTIFY';
  700. break;
  701. case 'CW':
  702. case 'CCW':
  703. bfcCCW = token === 'CCW';
  704. break;
  705. case 'INVERTNEXT':
  706. bfcInverted = true;
  707. break;
  708. case 'CLIP':
  709. case 'NOCLIP':
  710. console.warn( 'THREE.LDrawLoader: BFC CLIP and NOCLIP directives ignored.' );
  711. break;
  712. default:
  713. console.warn( 'THREE.LDrawLoader: BFC directive "' + token + '" is unknown.' );
  714. break;
  715. }
  716. }
  717. break;
  718. default:
  719. // Other meta directives are not implemented
  720. break;
  721. }
  722. }
  723. break;
  724. // Line type 1: Sub-object file
  725. case '1':
  726. var material = parseColourCode( lp );
  727. var posX = parseFloat( lp.getToken() );
  728. var posY = parseFloat( lp.getToken() );
  729. var posZ = parseFloat( lp.getToken() );
  730. var m0 = parseFloat( lp.getToken() );
  731. var m1 = parseFloat( lp.getToken() );
  732. var m2 = parseFloat( lp.getToken() );
  733. var m3 = parseFloat( lp.getToken() );
  734. var m4 = parseFloat( lp.getToken() );
  735. var m5 = parseFloat( lp.getToken() );
  736. var m6 = parseFloat( lp.getToken() );
  737. var m7 = parseFloat( lp.getToken() );
  738. var m8 = parseFloat( lp.getToken() );
  739. var matrix = new THREE.Matrix4().set(
  740. m0, m1, m2, posX,
  741. m3, m4, m5, posY,
  742. m6, m7, m8, posZ,
  743. 0, 0, 0, 1
  744. );
  745. var fileName = lp.getRemainingString().trim().replace( "\\", "/" );
  746. if ( scope.fileMap[ fileName ] ) {
  747. // Found the subobject path in the preloaded file path map
  748. fileName = scope.fileMap[ fileName ];
  749. } else {
  750. // Standardized subfolders
  751. if ( fileName.startsWith( 's/' ) ) {
  752. fileName = 'parts/' + fileName;
  753. } else if ( fileName.startsWith( '48/' ) ) {
  754. fileName = 'p/' + fileName;
  755. }
  756. }
  757. subobjects.push( {
  758. material: material,
  759. matrix: matrix,
  760. fileName: fileName,
  761. originalFileName: fileName,
  762. locationState: LDrawLoader.FILE_LOCATION_AS_IS,
  763. url: null,
  764. triedLowerCase: false,
  765. inverted: bfcInverted !== currentParseScope.inverted
  766. } );
  767. bfcInverted = false;
  768. break;
  769. // Line type 2: Line segment
  770. case '2':
  771. var material = parseColourCode( lp, true );
  772. lineSegments.push( {
  773. material: material.userData.edgeMaterial,
  774. colourCode: material.userData.code,
  775. v0: parseVector( lp ),
  776. v1: parseVector( lp )
  777. } );
  778. break;
  779. // Line type 3: Triangle
  780. case '3':
  781. var material = parseColourCode( lp );
  782. var inverted = currentParseScope.inverted;
  783. var ccw = ! bfcEnabled || bfcEnabled && bfcCCW && ! inverted;
  784. var v0, v1, v2;
  785. if ( ccw === true ) {
  786. v0 = parseVector( lp );
  787. v1 = parseVector( lp );
  788. v2 = parseVector( lp );
  789. } else {
  790. v2 = parseVector( lp );
  791. v1 = parseVector( lp );
  792. v0 = parseVector( lp );
  793. }
  794. triangles.push( {
  795. material: material,
  796. colourCode: material.userData.code,
  797. v0: v0,
  798. v1: v1,
  799. v2: v2
  800. } );
  801. break;
  802. // Line type 4: Quadrilateral
  803. case '4':
  804. var material = parseColourCode( lp );
  805. var inverted = currentParseScope.inverted;
  806. var ccw = ! bfcEnabled || bfcEnabled && bfcCCW && ! inverted;
  807. var v0, v1, v2, v3;
  808. if ( ccw === true ) {
  809. v0 = parseVector( lp );
  810. v1 = parseVector( lp );
  811. v2 = parseVector( lp );
  812. v3 = parseVector( lp );
  813. } else {
  814. v3 = parseVector( lp );
  815. v2 = parseVector( lp );
  816. v1 = parseVector( lp );
  817. v0 = parseVector( lp );
  818. }
  819. triangles.push( {
  820. material: material,
  821. colourCode: material.userData.code,
  822. v0: v0,
  823. v1: v1,
  824. v2: v2
  825. } );
  826. triangles.push( {
  827. material: material,
  828. colourCode: material.userData.code,
  829. v0: v0,
  830. v1: v2,
  831. v2: v3
  832. } );
  833. break;
  834. // Line type 5: Optional line
  835. case '5':
  836. // Line type 5 is not implemented
  837. break;
  838. default:
  839. throw 'LDrawLoader: Unknown line type "' + lineType + '"' + lp.getLineNumberString() + '.';
  840. break;
  841. }
  842. }
  843. if ( parsingEmbeddedFiles ) {
  844. this.subobjectCache[ currentEmbeddedFileName ] = currentEmbeddedText;
  845. }
  846. //
  847. var groupObject = null;
  848. if ( this.separateObjects ) {
  849. groupObject = new THREE.Group();
  850. if ( lineSegments.length > 0 ) {
  851. groupObject.add( createObject( lineSegments, 2 ) );
  852. }
  853. if ( triangles.length > 0 ) {
  854. groupObject.add( createObject( triangles, 3 ) );
  855. }
  856. } else {
  857. groupObject = this.currentGroupObject;
  858. }
  859. groupObject.userData.category = category;
  860. groupObject.userData.keywords = keywords;
  861. groupObject.userData.subobjects = subobjects;
  862. //console.timeEnd( 'LDrawLoader' );
  863. return groupObject;
  864. }
  865. };
  866. return LDrawLoader;
  867. } )();