LDrawLoader.js 33 KB

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