LDrawLoader.js 31 KB

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