LDrawLoader.js 46 KB

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