LDrawLoader.js 45 KB

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