LDrawLoader.js 46 KB

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