LDrawLoader.js 31 KB

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