LDrawLoader.js 44 KB

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