LDrawLoader.js 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864
  1. /**
  2. * @author mrdoob / http://mrdoob.com/
  3. * @author yomboprime / https://github.com/yomboprime/
  4. *
  5. *
  6. */
  7. THREE.LDrawLoader = ( function () {
  8. var optionalLineVertShader = /* glsl */`
  9. attribute vec3 control0;
  10. attribute vec3 control1;
  11. attribute vec3 direction;
  12. varying float discardFlag;
  13. #include <common>
  14. #include <color_pars_vertex>
  15. #include <fog_pars_vertex>
  16. #include <logdepthbuf_pars_vertex>
  17. #include <clipping_planes_pars_vertex>
  18. void main() {
  19. #include <color_vertex>
  20. vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );
  21. gl_Position = projectionMatrix * mvPosition;
  22. // Transform the line segment ends and control points into camera clip space
  23. vec4 c0 = projectionMatrix * modelViewMatrix * vec4( control0, 1.0 );
  24. vec4 c1 = projectionMatrix * modelViewMatrix * vec4( control1, 1.0 );
  25. vec4 p0 = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  26. vec4 p1 = projectionMatrix * modelViewMatrix * vec4( position + direction, 1.0 );
  27. c0.xy /= c0.w;
  28. c1.xy /= c1.w;
  29. p0.xy /= p0.w;
  30. p1.xy /= p1.w;
  31. // Get the direction of the segment and an orthogonal vector
  32. vec2 dir = p1.xy - p0.xy;
  33. vec2 norm = vec2( -dir.y, dir.x );
  34. // Get control point directions from the line
  35. vec2 c0dir = c0.xy - p1.xy;
  36. vec2 c1dir = c1.xy - p1.xy;
  37. // If the vectors to the controls points are pointed in different directions away
  38. // from the line segment then the line should not be drawn.
  39. float d0 = dot( normalize( norm ), normalize( c0dir ) );
  40. float d1 = dot( normalize( norm ), normalize( c1dir ) );
  41. discardFlag = float( sign( d0 ) != sign( d1 ) );
  42. #include <logdepthbuf_vertex>
  43. #include <clipping_planes_vertex>
  44. #include <fog_vertex>
  45. }
  46. `;
  47. var optionalLineFragShader = /* glsl */`
  48. uniform vec3 diffuse;
  49. uniform float opacity;
  50. varying float discardFlag;
  51. #include <common>
  52. #include <color_pars_fragment>
  53. #include <fog_pars_fragment>
  54. #include <logdepthbuf_pars_fragment>
  55. #include <clipping_planes_pars_fragment>
  56. void main() {
  57. if ( discardFlag > 0.5 ) discard;
  58. #include <clipping_planes_fragment>
  59. vec3 outgoingLight = vec3( 0.0 );
  60. vec4 diffuseColor = vec4( diffuse, opacity );
  61. #include <logdepthbuf_fragment>
  62. #include <color_fragment>
  63. outgoingLight = diffuseColor.rgb; // simple shader
  64. gl_FragColor = vec4( outgoingLight, diffuseColor.a );
  65. #include <premultiplied_alpha_fragment>
  66. #include <tonemapping_fragment>
  67. #include <encodings_fragment>
  68. #include <fog_fragment>
  69. }
  70. `;
  71. var tempVec0 = new THREE.Vector3();
  72. var tempVec1 = new THREE.Vector3();
  73. function smoothNormals( triangles, lineSegments ) {
  74. function hashVertex( v ) {
  75. // NOTE: 1e2 is pretty coarse but was chosen because it allows edges
  76. // to be smoothed as expected (see minifig arms). The errors between edges
  77. // could be due to matrix multiplication.
  78. var x = ~ ~ ( v.x * 1e2 );
  79. var y = ~ ~ ( v.y * 1e2 );
  80. var z = ~ ~ ( v.z * 1e2 );
  81. return `${ x },${ y },${ z }`;
  82. }
  83. function hashEdge( v0, v1 ) {
  84. return `${ hashVertex( v0 ) }_${ hashVertex( v1 ) }`;
  85. }
  86. var hardEdges = new Set();
  87. var halfEdgeList = {};
  88. var fullHalfEdgeList = {};
  89. var normals = [];
  90. // Save the list of hard edges by hash
  91. for ( var i = 0, l = lineSegments.length; i < l; i ++ ) {
  92. var ls = lineSegments[ i ];
  93. var v0 = ls.v0;
  94. var v1 = ls.v1;
  95. hardEdges.add( hashEdge( v0, v1 ) );
  96. hardEdges.add( hashEdge( v1, v0 ) );
  97. }
  98. // track the half edges associated with each triangle
  99. for ( var i = 0, l = triangles.length; i < l; i ++ ) {
  100. var tri = triangles[ i ];
  101. for ( var i2 = 0, l2 = 3; i2 < l2; i2 ++ ) {
  102. var index = i2;
  103. var next = ( i2 + 1 ) % 3;
  104. var v0 = tri[ `v${ index }` ];
  105. var v1 = tri[ `v${ next }` ];
  106. var hash = hashEdge( v0, v1 );
  107. // don't add the triangle if the edge is supposed to be hard
  108. if ( hardEdges.has( hash ) ) continue;
  109. halfEdgeList[ hash ] = tri;
  110. fullHalfEdgeList[ hash ] = tri;
  111. }
  112. }
  113. // Iterate until we've tried to connect all triangles to share normals
  114. while ( true ) {
  115. // Stop if there are no more triangles left
  116. var halfEdges = Object.keys( halfEdgeList );
  117. if ( halfEdges.length === 0 ) break;
  118. // Exhaustively find all connected triangles
  119. var i = 0;
  120. var queue = [ fullHalfEdgeList[ halfEdges[ 0 ] ] ];
  121. while ( i < queue.length ) {
  122. // initialize all vertex normals in this triangle
  123. var tri = queue[ i ];
  124. i ++;
  125. var faceNormal = tri.faceNormal;
  126. if ( tri.n0 === null ) {
  127. tri.n0 = faceNormal.clone();
  128. normals.push( tri.n0 );
  129. }
  130. if ( tri.n1 === null ) {
  131. tri.n1 = faceNormal.clone();
  132. normals.push( tri.n1 );
  133. }
  134. if ( tri.n2 === null ) {
  135. tri.n2 = faceNormal.clone();
  136. normals.push( tri.n2 );
  137. }
  138. // Check if any edge is connected to another triangle edge
  139. for ( var i2 = 0, l2 = 3; i2 < l2; i2 ++ ) {
  140. var index = i2;
  141. var next = ( i2 + 1 ) % 3;
  142. var v0 = tri[ `v${ index }` ];
  143. var v1 = tri[ `v${ next }` ];
  144. // delete this triangle from the list so it won't be found again
  145. var hash = hashEdge( v0, v1 );
  146. delete halfEdgeList[ hash ];
  147. var reverseHash = hashEdge( v1, v0 );
  148. var otherTri = fullHalfEdgeList[ reverseHash ];
  149. if ( otherTri ) {
  150. // NOTE: If the angle between triangles is > 67.5 degrees then assume it's
  151. // hard edge. There are some cases where the line segments do not line up exactly
  152. // with or span multiple triangle edges (see Lunar Vehicle wheels).
  153. if ( Math.abs( otherTri.faceNormal.dot( tri.faceNormal ) ) < 0.25 ) {
  154. continue;
  155. }
  156. // if this triangle has already been traversed then it won't be in
  157. // the halfEdgeList. If it has not then add it to the queue and delete
  158. // it so it won't be found again.
  159. if ( reverseHash in halfEdgeList ) {
  160. queue.push( otherTri );
  161. delete halfEdgeList[ reverseHash ];
  162. }
  163. // Find the matching edge in this triangle and copy the normal vector over
  164. for ( var i3 = 0, l3 = 3; i3 < l3; i3 ++ ) {
  165. var otherIndex = i3;
  166. var otherNext = ( i3 + 1 ) % 3;
  167. var otherV0 = otherTri[ `v${ otherIndex }` ];
  168. var otherV1 = otherTri[ `v${ otherNext }` ];
  169. var otherHash = hashEdge( otherV0, otherV1 );
  170. if ( otherHash === reverseHash ) {
  171. otherTri[ `n${ otherIndex }` ] = tri[ `n${ next }` ];
  172. otherTri[ `n${ otherNext }` ] = tri[ `n${ index }` ];
  173. tri[ `n${ next }` ].add( otherTri.faceNormal );
  174. tri[ `n${ index }` ].add( otherTri.faceNormal );
  175. break;
  176. }
  177. }
  178. }
  179. }
  180. }
  181. }
  182. // The normals of each face have been added up so now we average them by normalizing the vector.
  183. for ( var i = 0, l = normals.length; i < l; i ++ ) {
  184. normals[ i ].normalize();
  185. }
  186. }
  187. function isPrimitiveType( type ) {
  188. return /primitive/i.test( type ) || type === 'Subpart';
  189. }
  190. function LineParser( line, lineNumber ) {
  191. this.line = line;
  192. this.lineLength = line.length;
  193. this.currentCharIndex = 0;
  194. this.currentChar = ' ';
  195. this.lineNumber = lineNumber;
  196. }
  197. LineParser.prototype = {
  198. constructor: LineParser,
  199. seekNonSpace: function () {
  200. while ( this.currentCharIndex < this.lineLength ) {
  201. this.currentChar = this.line.charAt( this.currentCharIndex );
  202. if ( this.currentChar !== ' ' && this.currentChar !== '\t' ) {
  203. return;
  204. }
  205. this.currentCharIndex ++;
  206. }
  207. },
  208. getToken: function () {
  209. var pos0 = this.currentCharIndex ++;
  210. // Seek space
  211. while ( this.currentCharIndex < this.lineLength ) {
  212. this.currentChar = this.line.charAt( this.currentCharIndex );
  213. if ( this.currentChar === ' ' || this.currentChar === '\t' ) {
  214. break;
  215. }
  216. this.currentCharIndex ++;
  217. }
  218. var pos1 = this.currentCharIndex;
  219. this.seekNonSpace();
  220. return this.line.substring( pos0, pos1 );
  221. },
  222. getRemainingString: function () {
  223. return this.line.substring( this.currentCharIndex, this.lineLength );
  224. },
  225. isAtTheEnd: function () {
  226. return this.currentCharIndex >= this.lineLength;
  227. },
  228. setToEnd: function () {
  229. this.currentCharIndex = this.lineLength;
  230. },
  231. getLineNumberString: function () {
  232. return this.lineNumber >= 0 ? " at line " + this.lineNumber : "";
  233. }
  234. };
  235. function sortByMaterial( a, b ) {
  236. if ( a.colourCode === b.colourCode ) {
  237. return 0;
  238. }
  239. if ( a.colourCode < b.colourCode ) {
  240. return - 1;
  241. }
  242. return 1;
  243. }
  244. function createObject( elements, elementSize ) {
  245. // Creates a THREE.LineSegments (elementSize = 2) or a THREE.Mesh (elementSize = 3 )
  246. // With per face / segment material, implemented with mesh groups and materials array
  247. // Sort the triangles or line segments by colour code to make later the mesh groups
  248. elements.sort( sortByMaterial );
  249. var positions = [];
  250. var normals = [];
  251. var materials = [];
  252. var bufferGeometry = new THREE.BufferGeometry();
  253. var prevMaterial = null;
  254. var index0 = 0;
  255. var numGroupVerts = 0;
  256. for ( var iElem = 0, nElem = elements.length; iElem < nElem; iElem ++ ) {
  257. var elem = elements[ iElem ];
  258. var v0 = elem.v0;
  259. var v1 = elem.v1;
  260. // Note that LDraw coordinate system is rotated 180 deg. in the X axis w.r.t. Three.js's one
  261. positions.push( v0.x, v0.y, v0.z, v1.x, v1.y, v1.z );
  262. if ( elementSize === 3 ) {
  263. positions.push( elem.v2.x, elem.v2.y, elem.v2.z );
  264. var n0 = elem.n0 || elem.faceNormal;
  265. var n1 = elem.n1 || elem.faceNormal;
  266. var n2 = elem.n2 || elem.faceNormal;
  267. normals.push( n0.x, n0.y, n0.z );
  268. normals.push( n1.x, n1.y, n1.z );
  269. normals.push( n2.x, n2.y, n2.z );
  270. }
  271. if ( prevMaterial !== elem.material ) {
  272. if ( prevMaterial !== null ) {
  273. bufferGeometry.addGroup( index0, numGroupVerts, materials.length - 1 );
  274. }
  275. materials.push( elem.material );
  276. prevMaterial = elem.material;
  277. index0 = iElem * elementSize;
  278. numGroupVerts = elementSize;
  279. } else {
  280. numGroupVerts += elementSize;
  281. }
  282. }
  283. if ( numGroupVerts > 0 ) {
  284. bufferGeometry.addGroup( index0, Infinity, materials.length - 1 );
  285. }
  286. bufferGeometry.addAttribute( 'position', new THREE.Float32BufferAttribute( positions, 3 ) );
  287. if ( elementSize === 3 ) {
  288. bufferGeometry.addAttribute( 'normal', new THREE.Float32BufferAttribute( normals, 3 ) );
  289. }
  290. var object3d = null;
  291. if ( elementSize === 2 ) {
  292. object3d = new THREE.LineSegments( bufferGeometry, materials );
  293. } else if ( elementSize === 3 ) {
  294. object3d = new THREE.Mesh( bufferGeometry, materials );
  295. }
  296. return object3d;
  297. }
  298. //
  299. function LDrawLoader( manager ) {
  300. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  301. // This is a stack of 'parse scopes' with one level per subobject loaded file.
  302. // Each level contains a material lib and also other runtime variables passed between parent and child subobjects
  303. // When searching for a material code, the stack is read from top of the stack to bottom
  304. // Each material library is an object map keyed by colour codes.
  305. this.parseScopesStack = null;
  306. this.path = '';
  307. // Array of THREE.Material
  308. this.materials = [];
  309. // Not using THREE.Cache here because it returns the previous HTML error response instead of calling onError()
  310. // This also allows to handle the embedded text files ("0 FILE" lines)
  311. this.subobjectCache = {};
  312. // 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.
  313. this.fileMap = null;
  314. // Add default main triangle and line edge materials (used in piecess that can be coloured with a main color)
  315. this.setMaterials( [
  316. this.parseColourMetaDirective( new LineParser( "Main_Colour CODE 16 VALUE #FF8080 EDGE #333333" ) ),
  317. this.parseColourMetaDirective( new LineParser( "Edge_Colour CODE 24 VALUE #A0A0A0 EDGE #333333" ) )
  318. ] );
  319. // If this flag is set to true, each subobject will be a THREE.Object.
  320. // If not (the default), only one object which contains all the merged primitives will be created.
  321. this.separateObjects = false;
  322. // If this flag is set to true the vertex normals will be smoothed.
  323. this.smoothNormals = true;
  324. }
  325. // Special surface finish tag types.
  326. // Note: "MATERIAL" tag (e.g. GLITTER, SPECKLE) is not implemented
  327. LDrawLoader.FINISH_TYPE_DEFAULT = 0;
  328. LDrawLoader.FINISH_TYPE_CHROME = 1;
  329. LDrawLoader.FINISH_TYPE_PEARLESCENT = 2;
  330. LDrawLoader.FINISH_TYPE_RUBBER = 3;
  331. LDrawLoader.FINISH_TYPE_MATTE_METALLIC = 4;
  332. LDrawLoader.FINISH_TYPE_METAL = 5;
  333. // State machine to search a subobject path.
  334. // The LDraw standard establishes these various possible subfolders.
  335. LDrawLoader.FILE_LOCATION_AS_IS = 0;
  336. LDrawLoader.FILE_LOCATION_TRY_PARTS = 1;
  337. LDrawLoader.FILE_LOCATION_TRY_P = 2;
  338. LDrawLoader.FILE_LOCATION_TRY_MODELS = 3;
  339. LDrawLoader.FILE_LOCATION_TRY_RELATIVE = 4;
  340. LDrawLoader.FILE_LOCATION_TRY_ABSOLUTE = 5;
  341. LDrawLoader.FILE_LOCATION_NOT_FOUND = 6;
  342. LDrawLoader.prototype = {
  343. constructor: LDrawLoader,
  344. load: function ( url, onLoad, onProgress, onError ) {
  345. if ( ! this.fileMap ) {
  346. this.fileMap = {};
  347. }
  348. var scope = this;
  349. var fileLoader = new THREE.FileLoader( this.manager );
  350. fileLoader.setPath( this.path );
  351. fileLoader.load( url, function ( text ) {
  352. processObject( text, onLoad );
  353. }, onProgress, onError );
  354. function processObject( text, onProcessed, subobject ) {
  355. var parseScope = scope.newParseScopeLevel();
  356. parseScope.url = url;
  357. var parentParseScope = scope.getParentParseScope();
  358. // Set current matrix
  359. if ( subobject ) {
  360. parseScope.currentMatrix.multiplyMatrices( parentParseScope.currentMatrix, subobject.matrix );
  361. parseScope.matrix.copy( subobject.matrix );
  362. parseScope.inverted = subobject.inverted;
  363. }
  364. // Add to cache
  365. var currentFileName = parentParseScope.currentFileName;
  366. if ( currentFileName !== null ) {
  367. currentFileName = parentParseScope.currentFileName.toLowerCase();
  368. }
  369. if ( scope.subobjectCache[ currentFileName ] === undefined ) {
  370. scope.subobjectCache[ currentFileName ] = text;
  371. }
  372. // Parse the object (returns a THREE.Group)
  373. scope.parse( text );
  374. var finishedCount = 0;
  375. onSubobjectFinish();
  376. function onSubobjectFinish() {
  377. finishedCount ++;
  378. if ( finishedCount === parseScope.subobjects.length + 1 ) {
  379. finalizeObject();
  380. } else {
  381. // Once the previous subobject has finished we can start processing the next one in the list.
  382. // The subobject processing shares scope in processing so it's important that they be loaded serially
  383. // to avoid race conditions.
  384. // Promise.resolve is used as an approach to asynchronously schedule a task _before_ this frame ends to
  385. // avoid stack overflow exceptions when loading many subobjects from the cache. RequestAnimationFrame
  386. // will work but causes the load to happen after the next frame which causes the load to take significantly longer.
  387. var subobject = parseScope.subobjects[ parseScope.subobjectIndex ];
  388. Promise.resolve().then( function () {
  389. loadSubobject( subobject );
  390. } );
  391. parseScope.subobjectIndex ++;
  392. }
  393. }
  394. function finalizeObject() {
  395. if ( scope.smoothNormals && parseScope.type === 'Part' ) {
  396. smoothNormals( parseScope.triangles, parseScope.lineSegments );
  397. }
  398. var isRoot = ! parentParseScope.isFromParse;
  399. if ( scope.separateObjects && ! isPrimitiveType( parseScope.type ) || isRoot ) {
  400. const objGroup = parseScope.groupObject;
  401. if ( parseScope.triangles.length > 0 ) {
  402. objGroup.add( createObject( parseScope.triangles, 3 ) );
  403. }
  404. if ( parseScope.lineSegments.length > 0 ) {
  405. objGroup.add( createObject( parseScope.lineSegments, 2 ) );
  406. }
  407. if ( parseScope.conditionalSegments.length > 0 ) {
  408. var conditionalSegments = parseScope.conditionalSegments;
  409. var lines = createObject( conditionalSegments, 2 );
  410. lines.isConditionalLine = true;
  411. var controlArray0 = new Float32Array( conditionalSegments.length * 3 * 2 );
  412. var controlArray1 = new Float32Array( conditionalSegments.length * 3 * 2 );
  413. var directionArray = new Float32Array( conditionalSegments.length * 3 * 2 );
  414. for ( var i = 0, l = conditionalSegments.length; i < l; i ++ ) {
  415. var os = conditionalSegments[ i ];
  416. var c0 = os.c0;
  417. var c1 = os.c1;
  418. var v0 = os.v0;
  419. var v1 = os.v1;
  420. var index = i * 3 * 2;
  421. controlArray0[ index + 0 ] = c0.x;
  422. controlArray0[ index + 1 ] = c0.y;
  423. controlArray0[ index + 2 ] = c0.z;
  424. controlArray0[ index + 3 ] = c0.x;
  425. controlArray0[ index + 4 ] = c0.y;
  426. controlArray0[ index + 5 ] = c0.z;
  427. controlArray1[ index + 0 ] = c1.x;
  428. controlArray1[ index + 1 ] = c1.y;
  429. controlArray1[ index + 2 ] = c1.z;
  430. controlArray1[ index + 3 ] = c1.x;
  431. controlArray1[ index + 4 ] = c1.y;
  432. controlArray1[ index + 5 ] = c1.z;
  433. directionArray[ index + 0 ] = v1.x - v0.x;
  434. directionArray[ index + 1 ] = v1.y - v0.y;
  435. directionArray[ index + 2 ] = v1.z - v0.z;
  436. directionArray[ index + 3 ] = v1.x - v0.x;
  437. directionArray[ index + 4 ] = v1.y - v0.y;
  438. directionArray[ index + 5 ] = v1.z - v0.z;
  439. }
  440. lines.geometry.addAttribute( 'control0', new THREE.BufferAttribute( controlArray0, 3, false ) );
  441. lines.geometry.addAttribute( 'control1', new THREE.BufferAttribute( controlArray1, 3, false ) );
  442. lines.geometry.addAttribute( 'direction', new THREE.BufferAttribute( directionArray, 3, false ) );
  443. lines.material = lines.material.map( mat => {
  444. return new THREE.ShaderMaterial( {
  445. vertexShader: optionalLineVertShader,
  446. fragmentShader: optionalLineFragShader,
  447. uniforms: {
  448. diffuse: {
  449. value: mat.color
  450. },
  451. opacity: {
  452. value: mat.opacity
  453. }
  454. }
  455. } );
  456. } );
  457. objGroup.add( lines );
  458. }
  459. if ( parentParseScope.groupObject ) {
  460. objGroup.name = parseScope.fileName;
  461. objGroup.userData.category = parseScope.category;
  462. objGroup.userData.keywords = parseScope.keywords;
  463. parseScope.matrix.decompose( objGroup.position, objGroup.quaternion, objGroup.scale );
  464. parentParseScope.groupObject.add( objGroup );
  465. }
  466. } else {
  467. var separateObjects = scope.separateObjects;
  468. var parentLineSegments = parentParseScope.lineSegments;
  469. var parentConditionalSegments = parentParseScope.conditionalSegments;
  470. var parentTriangles = parentParseScope.triangles;
  471. var lineSegments = parseScope.lineSegments;
  472. var conditionalSegments = parseScope.conditionalSegments;
  473. var triangles = parseScope.triangles;
  474. for ( var i = 0, l = lineSegments.length; i < l; i ++ ) {
  475. var ls = lineSegments[ i ];
  476. if ( separateObjects ) {
  477. ls.v0.applyMatrix4( parseScope.matrix );
  478. ls.v1.applyMatrix4( parseScope.matrix );
  479. }
  480. parentLineSegments.push( ls );
  481. }
  482. for ( var i = 0, l = conditionalSegments.length; i < l; i ++ ) {
  483. var os = conditionalSegments[ i ];
  484. if ( separateObjects ) {
  485. os.v0.applyMatrix4( parseScope.matrix );
  486. os.v1.applyMatrix4( parseScope.matrix );
  487. os.c0.applyMatrix4( parseScope.matrix );
  488. os.c1.applyMatrix4( parseScope.matrix );
  489. }
  490. parentConditionalSegments.push( os );
  491. }
  492. for ( var i = 0, l = triangles.length; i < l; i ++ ) {
  493. var tri = triangles[ i ];
  494. if ( separateObjects ) {
  495. tri.v0 = tri.v0.clone().applyMatrix4( parseScope.matrix );
  496. tri.v1 = tri.v1.clone().applyMatrix4( parseScope.matrix );
  497. tri.v2 = tri.v2.clone().applyMatrix4( parseScope.matrix );
  498. tempVec0.subVectors( tri.v1, tri.v0 );
  499. tempVec1.subVectors( tri.v2, tri.v1 );
  500. tri.faceNormal.crossVectors( tempVec0, tempVec1 ).normalize();
  501. }
  502. parentTriangles.push( tri );
  503. }
  504. }
  505. scope.removeScopeLevel();
  506. if ( onProcessed ) {
  507. onProcessed( parseScope.groupObject );
  508. }
  509. }
  510. function loadSubobject( subobject ) {
  511. parseScope.mainColourCode = subobject.material.userData.code;
  512. parseScope.mainEdgeColourCode = subobject.material.userData.edgeMaterial.userData.code;
  513. parseScope.currentFileName = subobject.originalFileName;
  514. // If subobject was cached previously, use the cached one
  515. var cached = scope.subobjectCache[ subobject.originalFileName.toLowerCase() ];
  516. if ( cached ) {
  517. processObject( cached, function ( subobjectGroup ) {
  518. onSubobjectLoaded( subobjectGroup, subobject );
  519. onSubobjectFinish();
  520. }, subobject );
  521. return;
  522. }
  523. // Adjust file name to locate the subobject file path in standard locations (always under directory scope.path)
  524. // Update also subobject.locationState for the next try if this load fails.
  525. var subobjectURL = subobject.fileName;
  526. var newLocationState = LDrawLoader.FILE_LOCATION_NOT_FOUND;
  527. switch ( subobject.locationState ) {
  528. case LDrawLoader.FILE_LOCATION_AS_IS:
  529. newLocationState = subobject.locationState + 1;
  530. break;
  531. case LDrawLoader.FILE_LOCATION_TRY_PARTS:
  532. subobjectURL = 'parts/' + subobjectURL;
  533. newLocationState = subobject.locationState + 1;
  534. break;
  535. case LDrawLoader.FILE_LOCATION_TRY_P:
  536. subobjectURL = 'p/' + subobjectURL;
  537. newLocationState = subobject.locationState + 1;
  538. break;
  539. case LDrawLoader.FILE_LOCATION_TRY_MODELS:
  540. subobjectURL = 'models/' + subobjectURL;
  541. newLocationState = subobject.locationState + 1;
  542. break;
  543. case LDrawLoader.FILE_LOCATION_TRY_RELATIVE:
  544. subobjectURL = url.substring( 0, url.lastIndexOf( "/" ) + 1 ) + subobjectURL;
  545. newLocationState = subobject.locationState + 1;
  546. break;
  547. case LDrawLoader.FILE_LOCATION_TRY_ABSOLUTE:
  548. if ( subobject.triedLowerCase ) {
  549. // Try absolute path
  550. newLocationState = LDrawLoader.FILE_LOCATION_NOT_FOUND;
  551. } else {
  552. // Next attempt is lower case
  553. subobject.fileName = subobject.fileName.toLowerCase();
  554. subobjectURL = subobject.fileName;
  555. subobject.triedLowerCase = true;
  556. newLocationState = LDrawLoader.FILE_LOCATION_AS_IS;
  557. }
  558. break;
  559. case LDrawLoader.FILE_LOCATION_NOT_FOUND:
  560. // All location possibilities have been tried, give up loading this object
  561. console.warn( 'LDrawLoader: Subobject "' + subobject.originalFileName + '" could not be found.' );
  562. return;
  563. }
  564. subobject.locationState = newLocationState;
  565. subobject.url = subobjectURL;
  566. // Load the subobject
  567. // Use another file loader here so we can keep track of the subobject information
  568. // and use it when processing the next model.
  569. var fileLoader = new THREE.FileLoader( scope.manager );
  570. fileLoader.setPath( scope.path );
  571. fileLoader.load( subobjectURL, function ( text ) {
  572. processObject( text, function ( subobjectGroup ) {
  573. onSubobjectLoaded( subobjectGroup, subobject );
  574. onSubobjectFinish();
  575. }, subobject );
  576. }, undefined, function ( err ) {
  577. onSubobjectError( err, subobject );
  578. }, subobject );
  579. }
  580. function onSubobjectLoaded( subobjectGroup, subobject ) {
  581. if ( subobjectGroup === null ) {
  582. // Try to reload
  583. loadSubobject( subobject );
  584. return;
  585. }
  586. scope.fileMap[ subobject.originalFileName ] = subobject.url;
  587. }
  588. function onSubobjectError( err, subobject ) {
  589. // Retry download from a different default possible location
  590. loadSubobject( subobject );
  591. }
  592. }
  593. },
  594. setPath: function ( value ) {
  595. this.path = value;
  596. return this;
  597. },
  598. setMaterials: function ( materials ) {
  599. // Clears parse scopes stack, adds new scope with material library
  600. this.parseScopesStack = [];
  601. this.newParseScopeLevel( materials );
  602. this.getCurrentParseScope().isFromParse = false;
  603. this.materials = materials;
  604. return this;
  605. },
  606. setFileMap: function ( fileMap ) {
  607. this.fileMap = fileMap;
  608. return this;
  609. },
  610. newParseScopeLevel: function ( materials ) {
  611. // Adds a new scope level, assign materials to it and returns it
  612. var matLib = {};
  613. if ( materials ) {
  614. for ( var i = 0, n = materials.length; i < n; i ++ ) {
  615. var material = materials[ i ];
  616. matLib[ material.userData.code ] = material;
  617. }
  618. }
  619. var topParseScope = this.getCurrentParseScope();
  620. var newParseScope = {
  621. lib: matLib,
  622. url: null,
  623. // Subobjects
  624. subobjects: null,
  625. numSubobjects: 0,
  626. subobjectIndex: 0,
  627. inverted: false,
  628. category: null,
  629. keywords: null,
  630. // Current subobject
  631. currentFileName: null,
  632. mainColourCode: topParseScope ? topParseScope.mainColourCode : '16',
  633. mainEdgeColourCode: topParseScope ? topParseScope.mainEdgeColourCode : '24',
  634. currentMatrix: new THREE.Matrix4(),
  635. matrix: new THREE.Matrix4(),
  636. // If false, it is a root material scope previous to parse
  637. isFromParse: true,
  638. triangles: null,
  639. lineSegments: null,
  640. conditionalSegments: null,
  641. };
  642. this.parseScopesStack.push( newParseScope );
  643. return newParseScope;
  644. },
  645. removeScopeLevel: function () {
  646. this.parseScopesStack.pop();
  647. return this;
  648. },
  649. addMaterial: function ( material ) {
  650. // Adds a material to the material library which is on top of the parse scopes stack. And also to the materials array
  651. var matLib = this.getCurrentParseScope().lib;
  652. if ( ! matLib[ material.userData.code ] ) {
  653. this.materials.push( material );
  654. }
  655. matLib[ material.userData.code ] = material;
  656. return this;
  657. },
  658. getMaterial: function ( colourCode ) {
  659. // Given a colour code search its material in the parse scopes stack
  660. if ( colourCode.startsWith( "0x2" ) ) {
  661. // Special 'direct' material value (RGB colour)
  662. var colour = colourCode.substring( 3 );
  663. return this.parseColourMetaDirective( new LineParser( "Direct_Color_" + colour + " CODE -1 VALUE #" + colour + " EDGE #" + colour + "" ) );
  664. }
  665. for ( var i = this.parseScopesStack.length - 1; i >= 0; i -- ) {
  666. var material = this.parseScopesStack[ i ].lib[ colourCode ];
  667. if ( material ) {
  668. return material;
  669. }
  670. }
  671. // Material was not found
  672. return null;
  673. },
  674. getParentParseScope: function () {
  675. if ( this.parseScopesStack.length > 1 ) {
  676. return this.parseScopesStack[ this.parseScopesStack.length - 2 ];
  677. }
  678. return null;
  679. },
  680. getCurrentParseScope: function () {
  681. if ( this.parseScopesStack.length > 0 ) {
  682. return this.parseScopesStack[ this.parseScopesStack.length - 1 ];
  683. }
  684. return null;
  685. },
  686. parseColourMetaDirective: function ( lineParser ) {
  687. // Parses a colour definition and returns a THREE.Material or null if error
  688. var code = null;
  689. // Triangle and line colours
  690. var colour = 0xFF00FF;
  691. var edgeColour = 0xFF00FF;
  692. // Transparency
  693. var alpha = 1;
  694. var isTransparent = false;
  695. // Self-illumination:
  696. var luminance = 0;
  697. var finishType = LDrawLoader.FINISH_TYPE_DEFAULT;
  698. var canHaveEnvMap = true;
  699. var edgeMaterial = null;
  700. var name = lineParser.getToken();
  701. if ( ! name ) {
  702. throw 'LDrawLoader: Material name was expected after "!COLOUR tag' + lineParser.getLineNumberString() + ".";
  703. }
  704. // Parse tag tokens and their parameters
  705. var token = null;
  706. while ( true ) {
  707. token = lineParser.getToken();
  708. if ( ! token ) {
  709. break;
  710. }
  711. switch ( token.toUpperCase() ) {
  712. case "CODE":
  713. code = lineParser.getToken();
  714. break;
  715. case "VALUE":
  716. colour = lineParser.getToken();
  717. if ( colour.startsWith( '0x' ) ) {
  718. colour = '#' + colour.substring( 2 );
  719. } else if ( ! colour.startsWith( '#' ) ) {
  720. throw 'LDrawLoader: Invalid colour while parsing material' + lineParser.getLineNumberString() + ".";
  721. }
  722. break;
  723. case "EDGE":
  724. edgeColour = lineParser.getToken();
  725. if ( edgeColour.startsWith( '0x' ) ) {
  726. edgeColour = '#' + edgeColour.substring( 2 );
  727. } else if ( ! edgeColour.startsWith( '#' ) ) {
  728. // Try to see if edge colour is a colour code
  729. edgeMaterial = this.getMaterial( edgeColour );
  730. if ( ! edgeMaterial ) {
  731. throw 'LDrawLoader: Invalid edge colour while parsing material' + lineParser.getLineNumberString() + ".";
  732. }
  733. // Get the edge material for this triangle material
  734. edgeMaterial = edgeMaterial.userData.edgeMaterial;
  735. }
  736. break;
  737. case 'ALPHA':
  738. alpha = parseInt( lineParser.getToken() );
  739. if ( isNaN( alpha ) ) {
  740. throw 'LDrawLoader: Invalid alpha value in material definition' + lineParser.getLineNumberString() + ".";
  741. }
  742. alpha = Math.max( 0, Math.min( 1, alpha / 255 ) );
  743. if ( alpha < 1 ) {
  744. isTransparent = true;
  745. }
  746. break;
  747. case 'LUMINANCE':
  748. luminance = parseInt( lineParser.getToken() );
  749. if ( isNaN( luminance ) ) {
  750. throw 'LDrawLoader: Invalid luminance value in material definition' + LineParser.getLineNumberString() + ".";
  751. }
  752. luminance = Math.max( 0, Math.min( 1, luminance / 255 ) );
  753. break;
  754. case 'CHROME':
  755. finishType = LDrawLoader.FINISH_TYPE_CHROME;
  756. break;
  757. case 'PEARLESCENT':
  758. finishType = LDrawLoader.FINISH_TYPE_PEARLESCENT;
  759. break;
  760. case 'RUBBER':
  761. finishType = LDrawLoader.FINISH_TYPE_RUBBER;
  762. break;
  763. case 'MATTE_METALLIC':
  764. finishType = LDrawLoader.FINISH_TYPE_MATTE_METALLIC;
  765. break;
  766. case 'METAL':
  767. finishType = LDrawLoader.FINISH_TYPE_METAL;
  768. break;
  769. case 'MATERIAL':
  770. // Not implemented
  771. lineParser.setToEnd();
  772. break;
  773. default:
  774. throw 'LDrawLoader: Unknown token "' + token + '" while parsing material' + lineParser.getLineNumberString() + ".";
  775. break;
  776. }
  777. }
  778. var material = null;
  779. switch ( finishType ) {
  780. case LDrawLoader.FINISH_TYPE_DEFAULT:
  781. material = new THREE.MeshStandardMaterial( { color: colour, roughness: 0.3, envMapIntensity: 0.3, metalness: 0 } );
  782. break;
  783. case LDrawLoader.FINISH_TYPE_PEARLESCENT:
  784. // Try to imitate pearlescency by setting the specular to the complementary of the color, and low shininess
  785. var specular = new THREE.Color( colour );
  786. var hsl = specular.getHSL( { h: 0, s: 0, l: 0 } );
  787. hsl.h = ( hsl.h + 0.5 ) % 1;
  788. hsl.l = Math.min( 1, hsl.l + ( 1 - hsl.l ) * 0.7 );
  789. specular.setHSL( hsl.h, hsl.s, hsl.l );
  790. material = new THREE.MeshPhongMaterial( { color: colour, specular: specular, shininess: 10, reflectivity: 0.3 } );
  791. break;
  792. case LDrawLoader.FINISH_TYPE_CHROME:
  793. // Mirror finish surface
  794. material = new THREE.MeshStandardMaterial( { color: colour, roughness: 0, metalness: 1 } );
  795. break;
  796. case LDrawLoader.FINISH_TYPE_RUBBER:
  797. // Rubber is best simulated with Lambert
  798. material = new THREE.MeshStandardMaterial( { color: colour, roughness: 0.9, metalness: 0 } );
  799. canHaveEnvMap = false;
  800. break;
  801. case LDrawLoader.FINISH_TYPE_MATTE_METALLIC:
  802. // Brushed metal finish
  803. material = new THREE.MeshStandardMaterial( { color: colour, roughness: 0.8, metalness: 0.4 } );
  804. break;
  805. case LDrawLoader.FINISH_TYPE_METAL:
  806. // Average metal finish
  807. material = new THREE.MeshStandardMaterial( { color: colour, roughness: 0.2, metalness: 0.85 } );
  808. break;
  809. default:
  810. // Should not happen
  811. break;
  812. }
  813. material.transparent = isTransparent;
  814. material.premultipliedAlpha = true;
  815. material.opacity = alpha;
  816. material.polygonOffset = true;
  817. material.polygonOffsetFactor = 1;
  818. material.userData.canHaveEnvMap = canHaveEnvMap;
  819. if ( luminance !== 0 ) {
  820. material.emissive.set( material.color ).multiplyScalar( luminance );
  821. }
  822. if ( ! edgeMaterial ) {
  823. // This is the material used for edges
  824. edgeMaterial = new THREE.LineBasicMaterial( { color: edgeColour } );
  825. edgeMaterial.userData.code = code;
  826. edgeMaterial.name = name + " - Edge";
  827. edgeMaterial.userData.canHaveEnvMap = false;
  828. }
  829. material.userData.code = code;
  830. material.name = name;
  831. material.userData.edgeMaterial = edgeMaterial;
  832. return material;
  833. },
  834. //
  835. parse: function ( text ) {
  836. //console.time( 'LDrawLoader' );
  837. // Retrieve data from the parent parse scope
  838. var parentParseScope = this.getParentParseScope();
  839. // Main colour codes passed to this subobject (or default codes 16 and 24 if it is the root object)
  840. var mainColourCode = parentParseScope.mainColourCode;
  841. var mainEdgeColourCode = parentParseScope.mainEdgeColourCode;
  842. var url = parentParseScope.url;
  843. var currentParseScope = this.getCurrentParseScope();
  844. // Parse result variables
  845. var triangles;
  846. var lineSegments;
  847. var conditionalSegments;
  848. var subobjects = [];
  849. var category = null;
  850. var keywords = null;
  851. if ( text.indexOf( '\r\n' ) !== - 1 ) {
  852. // This is faster than String.split with regex that splits on both
  853. text = text.replace( /\r\n/g, '\n' );
  854. }
  855. var lines = text.split( '\n' );
  856. var numLines = lines.length;
  857. var lineIndex = 0;
  858. var parsingEmbeddedFiles = false;
  859. var currentEmbeddedFileName = null;
  860. var currentEmbeddedText = null;
  861. var bfcCertified = false;
  862. var bfcCCW = true;
  863. var bfcInverted = false;
  864. var bfcCull = true;
  865. var type = '';
  866. var scope = this;
  867. function parseColourCode( lineParser, forEdge ) {
  868. // Parses next colour code and returns a THREE.Material
  869. var colourCode = lineParser.getToken();
  870. if ( ! forEdge && colourCode === '16' ) {
  871. colourCode = mainColourCode;
  872. }
  873. if ( forEdge && colourCode === '24' ) {
  874. colourCode = mainEdgeColourCode;
  875. }
  876. var material = scope.getMaterial( colourCode );
  877. if ( ! material ) {
  878. throw 'LDrawLoader: Unknown colour code "' + colourCode + '" is used' + lineParser.getLineNumberString() + ' but it was not defined previously.';
  879. }
  880. return material;
  881. }
  882. function parseVector( lp ) {
  883. var v = new THREE.Vector3( parseFloat( lp.getToken() ), parseFloat( lp.getToken() ), parseFloat( lp.getToken() ) );
  884. if ( ! scope.separateObjects ) {
  885. v.applyMatrix4( currentParseScope.currentMatrix );
  886. }
  887. return v;
  888. }
  889. // Parse all line commands
  890. for ( lineIndex = 0; lineIndex < numLines; lineIndex ++ ) {
  891. var line = lines[ lineIndex ];
  892. if ( line.length === 0 ) continue;
  893. if ( parsingEmbeddedFiles ) {
  894. if ( line.startsWith( '0 FILE ' ) ) {
  895. // Save previous embedded file in the cache
  896. this.subobjectCache[ currentEmbeddedFileName.toLowerCase() ] = currentEmbeddedText;
  897. // New embedded text file
  898. currentEmbeddedFileName = line.substring( 7 );
  899. currentEmbeddedText = '';
  900. } else {
  901. currentEmbeddedText += line + '\n';
  902. }
  903. continue;
  904. }
  905. var lp = new LineParser( line, lineIndex + 1 );
  906. lp.seekNonSpace();
  907. if ( lp.isAtTheEnd() ) {
  908. // Empty line
  909. continue;
  910. }
  911. // Parse the line type
  912. var lineType = lp.getToken();
  913. switch ( lineType ) {
  914. // Line type 0: Comment or META
  915. case '0':
  916. // Parse meta directive
  917. var meta = lp.getToken();
  918. if ( meta ) {
  919. switch ( meta ) {
  920. case '!LDRAW_ORG':
  921. type = lp.getToken();
  922. if ( ! parsingEmbeddedFiles ) {
  923. currentParseScope.triangles = [];
  924. currentParseScope.lineSegments = [];
  925. currentParseScope.conditionalSegments = [];
  926. currentParseScope.type = type;
  927. var isRoot = ! parentParseScope.isFromParse;
  928. if ( isRoot || scope.separateObjects && ! isPrimitiveType( type ) ) {
  929. currentParseScope.groupObject = new THREE.Group();
  930. }
  931. // If the scale of the object is negated then the triangle winding order
  932. // needs to be flipped.
  933. var matrix = currentParseScope.matrix;
  934. if (
  935. matrix.determinant() < 0 && (
  936. scope.separateObjects && isPrimitiveType( type ) ||
  937. ! scope.separateObjects
  938. ) ) {
  939. currentParseScope.inverted = ! currentParseScope.inverted;
  940. }
  941. triangles = currentParseScope.triangles;
  942. lineSegments = currentParseScope.lineSegments;
  943. conditionalSegments = currentParseScope.conditionalSegments;
  944. }
  945. break;
  946. case '!COLOUR':
  947. var material = this.parseColourMetaDirective( lp );
  948. if ( material ) {
  949. this.addMaterial( material );
  950. } else {
  951. console.warn( 'LDrawLoader: Error parsing material' + lp.getLineNumberString() );
  952. }
  953. break;
  954. case '!CATEGORY':
  955. category = lp.getToken();
  956. break;
  957. case '!KEYWORDS':
  958. var newKeywords = lp.getRemainingString().split( ',' );
  959. if ( newKeywords.length > 0 ) {
  960. if ( ! keywords ) {
  961. keywords = [];
  962. }
  963. newKeywords.forEach( function ( keyword ) {
  964. keywords.push( keyword.trim() );
  965. } );
  966. }
  967. break;
  968. case 'FILE':
  969. if ( lineIndex > 0 ) {
  970. // Start embedded text files parsing
  971. parsingEmbeddedFiles = true;
  972. currentEmbeddedFileName = lp.getRemainingString();
  973. currentEmbeddedText = '';
  974. bfcCertified = false;
  975. bfcCCW = true;
  976. }
  977. break;
  978. case 'BFC':
  979. // Changes to the backface culling state
  980. while ( ! lp.isAtTheEnd() ) {
  981. var token = lp.getToken();
  982. switch ( token ) {
  983. case 'CERTIFY':
  984. case 'NOCERTIFY':
  985. bfcCertified = token === 'CERTIFY';
  986. bfcCCW = true;
  987. break;
  988. case 'CW':
  989. case 'CCW':
  990. bfcCCW = token === 'CCW';
  991. break;
  992. case 'INVERTNEXT':
  993. bfcInverted = true;
  994. break;
  995. case 'CLIP':
  996. case 'NOCLIP':
  997. bfcCull = token === 'CLIP';
  998. break;
  999. default:
  1000. console.warn( 'THREE.LDrawLoader: BFC directive "' + token + '" is unknown.' );
  1001. break;
  1002. }
  1003. }
  1004. break;
  1005. default:
  1006. // Other meta directives are not implemented
  1007. break;
  1008. }
  1009. }
  1010. break;
  1011. // Line type 1: Sub-object file
  1012. case '1':
  1013. var material = parseColourCode( lp );
  1014. var posX = parseFloat( lp.getToken() );
  1015. var posY = parseFloat( lp.getToken() );
  1016. var posZ = parseFloat( lp.getToken() );
  1017. var m0 = parseFloat( lp.getToken() );
  1018. var m1 = parseFloat( lp.getToken() );
  1019. var m2 = parseFloat( lp.getToken() );
  1020. var m3 = parseFloat( lp.getToken() );
  1021. var m4 = parseFloat( lp.getToken() );
  1022. var m5 = parseFloat( lp.getToken() );
  1023. var m6 = parseFloat( lp.getToken() );
  1024. var m7 = parseFloat( lp.getToken() );
  1025. var m8 = parseFloat( lp.getToken() );
  1026. var matrix = new THREE.Matrix4().set(
  1027. m0, m1, m2, posX,
  1028. m3, m4, m5, posY,
  1029. m6, m7, m8, posZ,
  1030. 0, 0, 0, 1
  1031. );
  1032. var fileName = lp.getRemainingString().trim().replace( "\\", "/" );
  1033. if ( scope.fileMap[ fileName ] ) {
  1034. // Found the subobject path in the preloaded file path map
  1035. fileName = scope.fileMap[ fileName ];
  1036. } else {
  1037. // Standardized subfolders
  1038. if ( fileName.startsWith( 's/' ) ) {
  1039. fileName = 'parts/' + fileName;
  1040. } else if ( fileName.startsWith( '48/' ) ) {
  1041. fileName = 'p/' + fileName;
  1042. }
  1043. }
  1044. subobjects.push( {
  1045. material: material,
  1046. matrix: matrix,
  1047. fileName: fileName,
  1048. originalFileName: fileName,
  1049. locationState: LDrawLoader.FILE_LOCATION_AS_IS,
  1050. url: null,
  1051. triedLowerCase: false,
  1052. inverted: bfcInverted !== currentParseScope.inverted
  1053. } );
  1054. bfcInverted = false;
  1055. break;
  1056. // Line type 2: Line segment
  1057. // Line type 5: Conditional Line segment
  1058. case '2':
  1059. case '5':
  1060. var material = parseColourCode( lp, true );
  1061. var arr = lineType === '2' ? lineSegments : conditionalSegments;
  1062. var segment = {
  1063. material: material.userData.edgeMaterial,
  1064. colourCode: material.userData.code,
  1065. v0: parseVector( lp ),
  1066. v1: parseVector( lp )
  1067. };
  1068. if ( lineType === '5' ) {
  1069. segment.c0 = parseVector( lp );
  1070. segment.c1 = parseVector( lp );
  1071. }
  1072. arr.push( segment );
  1073. break;
  1074. // Line type 3: Triangle
  1075. case '3':
  1076. var material = parseColourCode( lp );
  1077. var inverted = currentParseScope.inverted;
  1078. var ccw = bfcCCW !== inverted;
  1079. var doubleSided = ! bfcCertified || ! bfcCull;
  1080. var v0, v1, v2, faceNormal;
  1081. if ( ccw === true ) {
  1082. v0 = parseVector( lp );
  1083. v1 = parseVector( lp );
  1084. v2 = parseVector( lp );
  1085. } else {
  1086. v2 = parseVector( lp );
  1087. v1 = parseVector( lp );
  1088. v0 = parseVector( lp );
  1089. }
  1090. tempVec0.subVectors( v1, v0 );
  1091. tempVec1.subVectors( v2, v1 );
  1092. faceNormal = new THREE.Vector3()
  1093. .crossVectors( tempVec0, tempVec1 )
  1094. .normalize();
  1095. triangles.push( {
  1096. material: material,
  1097. colourCode: material.userData.code,
  1098. v0: v0,
  1099. v1: v1,
  1100. v2: v2,
  1101. faceNormal: faceNormal,
  1102. n0: null,
  1103. n1: null,
  1104. n2: null
  1105. } );
  1106. if ( doubleSided === true ) {
  1107. triangles.push( {
  1108. material: material,
  1109. colourCode: material.userData.code,
  1110. v0: v0,
  1111. v1: v2,
  1112. v2: v1,
  1113. faceNormal: faceNormal,
  1114. n0: null,
  1115. n1: null,
  1116. n2: null
  1117. } );
  1118. }
  1119. break;
  1120. // Line type 4: Quadrilateral
  1121. case '4':
  1122. var material = parseColourCode( lp );
  1123. var inverted = currentParseScope.inverted;
  1124. var ccw = bfcCCW !== inverted;
  1125. var doubleSided = ! bfcCertified || ! bfcCull;
  1126. var v0, v1, v2, v3, faceNormal;
  1127. if ( ccw === true ) {
  1128. v0 = parseVector( lp );
  1129. v1 = parseVector( lp );
  1130. v2 = parseVector( lp );
  1131. v3 = parseVector( lp );
  1132. } else {
  1133. v3 = parseVector( lp );
  1134. v2 = parseVector( lp );
  1135. v1 = parseVector( lp );
  1136. v0 = parseVector( lp );
  1137. }
  1138. tempVec0.subVectors( v1, v0 );
  1139. tempVec1.subVectors( v2, v1 );
  1140. faceNormal = new THREE.Vector3()
  1141. .crossVectors( tempVec0, tempVec1 )
  1142. .normalize();
  1143. triangles.push( {
  1144. material: material,
  1145. colourCode: material.userData.code,
  1146. v0: v0,
  1147. v1: v1,
  1148. v2: v2,
  1149. faceNormal: faceNormal,
  1150. n0: null,
  1151. n1: null,
  1152. n2: null
  1153. } );
  1154. triangles.push( {
  1155. material: material,
  1156. colourCode: material.userData.code,
  1157. v0: v0,
  1158. v1: v2,
  1159. v2: v3,
  1160. faceNormal: faceNormal,
  1161. n0: null,
  1162. n1: null,
  1163. n2: null
  1164. } );
  1165. if ( doubleSided === true ) {
  1166. triangles.push( {
  1167. material: material,
  1168. colourCode: material.userData.code,
  1169. v0: v0,
  1170. v1: v2,
  1171. v2: v1,
  1172. faceNormal: faceNormal,
  1173. n0: null,
  1174. n1: null,
  1175. n2: null
  1176. } );
  1177. triangles.push( {
  1178. material: material,
  1179. colourCode: material.userData.code,
  1180. v0: v0,
  1181. v1: v3,
  1182. v2: v2,
  1183. faceNormal: faceNormal,
  1184. n0: null,
  1185. n1: null,
  1186. n2: null
  1187. } );
  1188. }
  1189. break;
  1190. default:
  1191. throw 'LDrawLoader: Unknown line type "' + lineType + '"' + lp.getLineNumberString() + '.';
  1192. break;
  1193. }
  1194. }
  1195. if ( parsingEmbeddedFiles ) {
  1196. this.subobjectCache[ currentEmbeddedFileName.toLowerCase() ] = currentEmbeddedText;
  1197. }
  1198. currentParseScope.category = category;
  1199. currentParseScope.keywords = keywords;
  1200. currentParseScope.subobjects = subobjects;
  1201. currentParseScope.numSubobjects = subobjects.length;
  1202. currentParseScope.subobjectIndex = 0;
  1203. }
  1204. };
  1205. return LDrawLoader;
  1206. } )();