OBJLoader.js 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307
  1. var getObjLoader = function(){
  2. var BufferAttribute = THREE.BufferAttribute
  3. function Int8BufferAttribute( array, itemSize, normalized ) {
  4. BufferAttribute.call( this, new Int8Array( array ), itemSize, normalized );
  5. }
  6. Int8BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  7. Int8BufferAttribute.prototype.constructor = Int8BufferAttribute;
  8. function Uint8BufferAttribute( array, itemSize, normalized ) {
  9. BufferAttribute.call( this, new Uint8Array( array ), itemSize, normalized );
  10. }
  11. Uint8BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  12. Uint8BufferAttribute.prototype.constructor = Uint8BufferAttribute;
  13. function Uint8ClampedBufferAttribute( array, itemSize, normalized ) {
  14. BufferAttribute.call( this, new Uint8ClampedArray( array ), itemSize, normalized );
  15. }
  16. Uint8ClampedBufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  17. Uint8ClampedBufferAttribute.prototype.constructor = Uint8ClampedBufferAttribute;
  18. function Int16BufferAttribute( array, itemSize, normalized ) {
  19. BufferAttribute.call( this, new Int16Array( array ), itemSize, normalized );
  20. }
  21. Int16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  22. Int16BufferAttribute.prototype.constructor = Int16BufferAttribute;
  23. function Uint16BufferAttribute( array, itemSize, normalized ) {
  24. BufferAttribute.call( this, new Uint16Array( array ), itemSize, normalized );
  25. }
  26. Uint16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  27. Uint16BufferAttribute.prototype.constructor = Uint16BufferAttribute;
  28. function Int32BufferAttribute( array, itemSize, normalized ) {
  29. BufferAttribute.call( this, new Int32Array( array ), itemSize, normalized );
  30. }
  31. Int32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  32. Int32BufferAttribute.prototype.constructor = Int32BufferAttribute;
  33. function Uint32BufferAttribute( array, itemSize, normalized ) {
  34. BufferAttribute.call( this, new Uint32Array( array ), itemSize, normalized );
  35. }
  36. Uint32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  37. Uint32BufferAttribute.prototype.constructor = Uint32BufferAttribute;
  38. function Float32BufferAttribute( array, itemSize, normalized ) {
  39. BufferAttribute.call( this, new Float32Array( array ), itemSize, normalized );
  40. }
  41. Float32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  42. Float32BufferAttribute.prototype.constructor = Float32BufferAttribute;
  43. function Float64BufferAttribute( array, itemSize, normalized ) {
  44. BufferAttribute.call( this, new Float64Array( array ), itemSize, normalized );
  45. }
  46. Float64BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  47. Float64BufferAttribute.prototype.constructor = Float64BufferAttribute;
  48. function LoadingManager( onLoad, onProgress, onError ) {
  49. var scope = this;
  50. var isLoading = false;
  51. var itemsLoaded = 0;
  52. var itemsTotal = 0;
  53. var urlModifier = undefined;
  54. this.onStart = undefined;
  55. this.onLoad = onLoad;
  56. this.onProgress = onProgress;
  57. this.onError = onError;
  58. this.itemStart = function ( url ) {
  59. itemsTotal ++;
  60. if ( isLoading === false ) {
  61. if ( scope.onStart !== undefined ) {
  62. scope.onStart( url, itemsLoaded, itemsTotal );
  63. }
  64. }
  65. isLoading = true;
  66. };
  67. this.itemEnd = function ( url ) {
  68. itemsLoaded ++;
  69. if ( scope.onProgress !== undefined ) {
  70. scope.onProgress( url, itemsLoaded, itemsTotal );
  71. }
  72. if ( itemsLoaded === itemsTotal ) {
  73. isLoading = false;
  74. if ( scope.onLoad !== undefined ) {
  75. scope.onLoad();
  76. }
  77. }
  78. };
  79. this.itemError = function ( url ) {
  80. if ( scope.onError !== undefined ) {
  81. scope.onError( url );
  82. }
  83. };
  84. this.resolveURL = function ( url ) {
  85. if ( urlModifier ) {
  86. return urlModifier( url );
  87. }
  88. return url;
  89. };
  90. this.setURLModifier = function ( transform ) {
  91. urlModifier = transform;
  92. return this;
  93. };
  94. }
  95. var DefaultLoadingManager1 = new LoadingManager();
  96. /**
  97. * @author mrdoob / http://mrdoob.com/
  98. */
  99. var loading = {};
  100. function FileLoader( manager ) {
  101. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager1;
  102. }
  103. Object.assign( FileLoader.prototype, {
  104. load: function ( url, onLoad, onProgress, onError ) {
  105. if ( url === undefined ) url = '';
  106. if ( this.path !== undefined ) url = this.path + url;
  107. url = this.manager.resolveURL( url );
  108. var scope = this;
  109. var cached = THREE.Cache.get( url );
  110. if ( cached !== undefined ) {
  111. scope.manager.itemStart( url );
  112. setTimeout( function () {
  113. if ( onLoad ) onLoad( cached );
  114. scope.manager.itemEnd( url );
  115. }, 0 );
  116. return cached;
  117. }
  118. // Check if request is duplicate
  119. if ( loading[ url ] !== undefined ) {
  120. loading[ url ].push( {
  121. onLoad: onLoad,
  122. onProgress: onProgress,
  123. onError: onError
  124. } );
  125. return;
  126. }
  127. // Check for data: URI
  128. var dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  129. var dataUriRegexResult = url.match( dataUriRegex );
  130. // Safari can not handle Data URIs through XMLHttpRequest so process manually
  131. if ( dataUriRegexResult ) {
  132. var mimeType = dataUriRegexResult[ 1 ];
  133. var isBase64 = !! dataUriRegexResult[ 2 ];
  134. var data = dataUriRegexResult[ 3 ];
  135. data = window.decodeURIComponent( data );
  136. if ( isBase64 ) data = window.atob( data );
  137. try {
  138. var response;
  139. var responseType = ( this.responseType || '' ).toLowerCase();
  140. switch ( responseType ) {
  141. case 'arraybuffer':
  142. case 'blob':
  143. var view = new Uint8Array( data.length );
  144. for ( var i = 0; i < data.length; i ++ ) {
  145. view[ i ] = data.charCodeAt( i );
  146. }
  147. if ( responseType === 'blob' ) {
  148. response = new Blob( [ view.buffer ], { type: mimeType } );
  149. } else {
  150. response = view.buffer;
  151. }
  152. break;
  153. case 'document':
  154. var parser = new DOMParser();
  155. response = parser.parseFromString( data, mimeType );
  156. break;
  157. case 'json':
  158. response = JSON.parse( data );
  159. break;
  160. default: // 'text' or other
  161. response = data;
  162. break;
  163. }
  164. // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  165. window.setTimeout( function () {
  166. if ( onLoad ) onLoad( response );
  167. scope.manager.itemEnd( url );
  168. }, 0 );
  169. } catch ( error ) {
  170. // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  171. window.setTimeout( function () {
  172. if ( onError ) onError( error );
  173. scope.manager.itemEnd( url );
  174. scope.manager.itemError( url );
  175. }, 0 );
  176. }
  177. } else {
  178. // Initialise array for duplicate requests
  179. loading[ url ] = [];
  180. loading[ url ].push( {
  181. onLoad: onLoad,
  182. onProgress: onProgress,
  183. onError: onError
  184. } );
  185. var request = new XMLHttpRequest();
  186. request.open( 'GET', url, true );
  187. request.addEventListener( 'load', function ( event ) {
  188. var response = this.response;
  189. THREE.Cache.add( url, response );
  190. var callbacks = loading[ url ];
  191. delete loading[ url ];
  192. if ( this.status === 200 || this.status === 0 ) {
  193. // Some browsers return HTTP Status 0 when using non-http protocol
  194. // e.g. 'file://' or 'data://'. Handle as success.
  195. if ( this.status === 0 ) console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  196. for ( var i = 0, il = callbacks.length; i < il; i ++ ) {
  197. var callback = callbacks[ i ];
  198. if ( callback.onLoad ) callback.onLoad( response );
  199. }
  200. scope.manager.itemEnd( url );
  201. } else {
  202. for ( var i = 0, il = callbacks.length; i < il; i ++ ) {
  203. var callback = callbacks[ i ];
  204. if ( callback.onError ) callback.onError( event );
  205. }
  206. scope.manager.itemEnd( url );
  207. scope.manager.itemError( url );
  208. }
  209. }, false );
  210. request.addEventListener( 'progress', function ( event ) {
  211. var callbacks = loading[ url ];
  212. for ( var i = 0, il = callbacks.length; i < il; i ++ ) {
  213. var callback = callbacks[ i ];
  214. if ( callback.onProgress ) callback.onProgress( event );
  215. }
  216. }, false );
  217. request.addEventListener( 'error', function ( event ) {
  218. var callbacks = loading[ url ];
  219. delete loading[ url ];
  220. for ( var i = 0, il = callbacks.length; i < il; i ++ ) {
  221. var callback = callbacks[ i ];
  222. if ( callback.onError ) callback.onError( event );
  223. }
  224. scope.manager.itemEnd( url );
  225. scope.manager.itemError( url );
  226. }, false );
  227. if ( this.responseType !== undefined ) request.responseType = this.responseType;
  228. if ( this.withCredentials !== undefined ) request.withCredentials = this.withCredentials;
  229. if ( request.overrideMimeType ) request.overrideMimeType( this.mimeType !== undefined ? this.mimeType : 'text/plain' );
  230. for ( var header in this.requestHeader ) {
  231. request.setRequestHeader( header, this.requestHeader[ header ] );
  232. }
  233. request.send( null );
  234. }
  235. scope.manager.itemStart( url );
  236. return request;
  237. },
  238. setPath: function ( value ) {
  239. this.path = value;
  240. return this;
  241. },
  242. setResponseType: function ( value ) {
  243. this.responseType = value;
  244. return this;
  245. },
  246. setWithCredentials: function ( value ) {
  247. this.withCredentials = value;
  248. return this;
  249. },
  250. setMimeType: function ( value ) {
  251. this.mimeType = value;
  252. return this;
  253. },
  254. setRequestHeader: function ( value ) {
  255. this.requestHeader = value;
  256. return this;
  257. }
  258. } );
  259. THREE.FileLoader = FileLoader
  260. THREE.OBJLoader = ( function () {
  261. var BufferGeometry = THREE.BufferGeometry;
  262. var DefaultLoadingManager = DefaultLoadingManager1//THREE.DefaultLoadingManager;
  263. var FileLoader = THREE.FileLoader;
  264. //var Float32BufferAttribute = THREE.Float32BufferAttribute;
  265. var Group = THREE.Group;
  266. var LineBasicMaterial = THREE.LineBasicMaterial;
  267. var LineSegments = THREE.LineSegments;
  268. var Material = THREE.Material;
  269. var Mesh = THREE.Mesh;
  270. var MeshPhongMaterial = THREE.MeshPhongMaterial;
  271. var NoColors = THREE.NoColors;
  272. var PointsMaterial = THREE.PointsMaterial;
  273. var VertexColors = THREE.VertexColors;
  274. // o object_name | g group_name
  275. var object_pattern = /^[og]\s*(.+)?/;
  276. // mtllib file_reference
  277. var material_library_pattern = /^mtllib /;
  278. // usemtl material_name
  279. var material_use_pattern = /^usemtl /;
  280. function ParserState() {
  281. var state = {
  282. objects: [],
  283. object: {},
  284. vertices: [],
  285. normals: [],
  286. colors: [],
  287. uvs: [],
  288. materialLibraries: [],
  289. startObject: function ( name, fromDeclaration ) {
  290. // If the current object (initial from reset) is not from a g/o declaration in the parsed
  291. // file. We need to use it for the first parsed g/o to keep things in sync.
  292. if ( this.object && this.object.fromDeclaration === false ) {
  293. this.object.name = name;
  294. this.object.fromDeclaration = ( fromDeclaration !== false );
  295. return;
  296. }
  297. var previousMaterial = ( this.object && typeof this.object.currentMaterial === 'function' ? this.object.currentMaterial() : undefined );
  298. if ( this.object && typeof this.object._finalize === 'function' ) {
  299. this.object._finalize( true );
  300. }
  301. this.object = {
  302. name: name || '',
  303. fromDeclaration: ( fromDeclaration !== false ),
  304. geometry: {
  305. vertices: [],
  306. normals: [],
  307. colors: [],
  308. uvs: []
  309. },
  310. materials: [],
  311. smooth: true,
  312. startMaterial: function ( name, libraries ) {
  313. var previous = this._finalize( false );
  314. // New usemtl declaration overwrites an inherited material, except if faces were declared
  315. // after the material, then it must be preserved for proper MultiMaterial continuation.
  316. if ( previous && ( previous.inherited || previous.groupCount <= 0 ) ) {
  317. this.materials.splice( previous.index, 1 );
  318. }
  319. var material = {
  320. index: this.materials.length,
  321. name: name || '',
  322. mtllib: ( Array.isArray( libraries ) && libraries.length > 0 ? libraries[ libraries.length - 1 ] : '' ),
  323. smooth: ( previous !== undefined ? previous.smooth : this.smooth ),
  324. groupStart: ( previous !== undefined ? previous.groupEnd : 0 ),
  325. groupEnd: - 1,
  326. groupCount: - 1,
  327. inherited: false,
  328. clone: function ( index ) {
  329. var cloned = {
  330. index: ( typeof index === 'number' ? index : this.index ),
  331. name: this.name,
  332. mtllib: this.mtllib,
  333. smooth: this.smooth,
  334. groupStart: 0,
  335. groupEnd: - 1,
  336. groupCount: - 1,
  337. inherited: false
  338. };
  339. cloned.clone = this.clone.bind( cloned );
  340. return cloned;
  341. }
  342. };
  343. this.materials.push( material );
  344. return material;
  345. },
  346. currentMaterial: function () {
  347. if ( this.materials.length > 0 ) {
  348. return this.materials[ this.materials.length - 1 ];
  349. }
  350. return undefined;
  351. },
  352. _finalize: function ( end ) {
  353. var lastMultiMaterial = this.currentMaterial();
  354. if ( lastMultiMaterial && lastMultiMaterial.groupEnd === - 1 ) {
  355. lastMultiMaterial.groupEnd = this.geometry.vertices.length / 3;
  356. lastMultiMaterial.groupCount = lastMultiMaterial.groupEnd - lastMultiMaterial.groupStart;
  357. lastMultiMaterial.inherited = false;
  358. }
  359. // Ignore objects tail materials if no face declarations followed them before a new o/g started.
  360. if ( end && this.materials.length > 1 ) {
  361. for ( var mi = this.materials.length - 1; mi >= 0; mi -- ) {
  362. if ( this.materials[ mi ].groupCount <= 0 ) {
  363. this.materials.splice( mi, 1 );
  364. }
  365. }
  366. }
  367. // Guarantee at least one empty material, this makes the creation later more straight forward.
  368. if ( end && this.materials.length === 0 ) {
  369. this.materials.push( {
  370. name: '',
  371. smooth: this.smooth
  372. } );
  373. }
  374. return lastMultiMaterial;
  375. }
  376. };
  377. // Inherit previous objects material.
  378. // Spec tells us that a declared material must be set to all objects until a new material is declared.
  379. // If a usemtl declaration is encountered while this new object is being parsed, it will
  380. // overwrite the inherited material. Exception being that there was already face declarations
  381. // to the inherited material, then it will be preserved for proper MultiMaterial continuation.
  382. if ( previousMaterial && previousMaterial.name && typeof previousMaterial.clone === 'function' ) {
  383. var declared = previousMaterial.clone( 0 );
  384. declared.inherited = true;
  385. this.object.materials.push( declared );
  386. }
  387. this.objects.push( this.object );
  388. },
  389. finalize: function () {
  390. if ( this.object && typeof this.object._finalize === 'function' ) {
  391. this.object._finalize( true );
  392. }
  393. },
  394. parseVertexIndex: function ( value, len ) {
  395. var index = parseInt( value, 10 );
  396. return ( index >= 0 ? index - 1 : index + len / 3 ) * 3;
  397. },
  398. parseNormalIndex: function ( value, len ) {
  399. var index = parseInt( value, 10 );
  400. return ( index >= 0 ? index - 1 : index + len / 3 ) * 3;
  401. },
  402. parseUVIndex: function ( value, len ) {
  403. var index = parseInt( value, 10 );
  404. return ( index >= 0 ? index - 1 : index + len / 2 ) * 2;
  405. },
  406. addVertex: function ( a, b, c ) {
  407. var src = this.vertices;
  408. var dst = this.object.geometry.vertices;
  409. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  410. dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] );
  411. dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] );
  412. },
  413. addVertexPoint: function ( a ) {
  414. var src = this.vertices;
  415. var dst = this.object.geometry.vertices;
  416. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  417. },
  418. addVertexLine: function ( a ) {
  419. var src = this.vertices;
  420. var dst = this.object.geometry.vertices;
  421. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  422. },
  423. addNormal: function ( a, b, c ) {
  424. var src = this.normals;
  425. var dst = this.object.geometry.normals;
  426. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  427. dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] );
  428. dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] );
  429. },
  430. addColor: function ( a, b, c ) {
  431. var src = this.colors;
  432. var dst = this.object.geometry.colors;
  433. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  434. dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] );
  435. dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] );
  436. },
  437. addUV: function ( a, b, c ) {
  438. var src = this.uvs;
  439. var dst = this.object.geometry.uvs;
  440. dst.push( src[ a + 0 ], src[ a + 1 ] );
  441. dst.push( src[ b + 0 ], src[ b + 1 ] );
  442. dst.push( src[ c + 0 ], src[ c + 1 ] );
  443. },
  444. addUVLine: function ( a ) {
  445. var src = this.uvs;
  446. var dst = this.object.geometry.uvs;
  447. dst.push( src[ a + 0 ], src[ a + 1 ] );
  448. },
  449. addFace: function ( a, b, c, ua, ub, uc, na, nb, nc ) {
  450. var vLen = this.vertices.length;
  451. var ia = this.parseVertexIndex( a, vLen );
  452. var ib = this.parseVertexIndex( b, vLen );
  453. var ic = this.parseVertexIndex( c, vLen );
  454. this.addVertex( ia, ib, ic );
  455. if ( ua !== undefined && ua !== '' ) {
  456. var uvLen = this.uvs.length;
  457. ia = this.parseUVIndex( ua, uvLen );
  458. ib = this.parseUVIndex( ub, uvLen );
  459. ic = this.parseUVIndex( uc, uvLen );
  460. this.addUV( ia, ib, ic );
  461. }
  462. if ( na !== undefined && na !== '' ) {
  463. // Normals are many times the same. If so, skip function call and parseInt.
  464. var nLen = this.normals.length;
  465. ia = this.parseNormalIndex( na, nLen );
  466. ib = na === nb ? ia : this.parseNormalIndex( nb, nLen );
  467. ic = na === nc ? ia : this.parseNormalIndex( nc, nLen );
  468. this.addNormal( ia, ib, ic );
  469. }
  470. if ( this.colors.length > 0 ) {
  471. this.addColor( ia, ib, ic );
  472. }
  473. },
  474. addPointGeometry: function ( vertices ) {
  475. this.object.geometry.type = 'Points';
  476. var vLen = this.vertices.length;
  477. for ( var vi = 0, l = vertices.length; vi < l; vi ++ ) {
  478. this.addVertexPoint( this.parseVertexIndex( vertices[ vi ], vLen ) );
  479. }
  480. },
  481. addLineGeometry: function ( vertices, uvs ) {
  482. this.object.geometry.type = 'Line';
  483. var vLen = this.vertices.length;
  484. var uvLen = this.uvs.length;
  485. for ( var vi = 0, l = vertices.length; vi < l; vi ++ ) {
  486. this.addVertexLine( this.parseVertexIndex( vertices[ vi ], vLen ) );
  487. }
  488. for ( var uvi = 0, l = uvs.length; uvi < l; uvi ++ ) {
  489. this.addUVLine( this.parseUVIndex( uvs[ uvi ], uvLen ) );
  490. }
  491. }
  492. };
  493. state.startObject( '', false );
  494. return state;
  495. }
  496. //
  497. function OBJLoader( manager ) {
  498. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager1;
  499. this.materials = null;
  500. }
  501. OBJLoader.prototype = {
  502. constructor: OBJLoader,
  503. load: function ( url, onLoad, onProgress, onError ) {
  504. var scope = this;
  505. var loader = new FileLoader( scope.manager );
  506. loader.setPath( this.path );
  507. loader.load( url, function ( text ) {
  508. onLoad( scope.parse( text ) );
  509. }, onProgress, onError );
  510. },
  511. setPath: function ( value ) {
  512. this.path = value;
  513. return this;
  514. },
  515. setMaterials: function ( materials ) {
  516. this.materials = materials;
  517. return this;
  518. },
  519. parse: function ( text ) {
  520. console.time( 'OBJLoader' );
  521. var state = new ParserState();
  522. if ( text.indexOf( '\r\n' ) !== - 1 ) {
  523. // This is faster than String.split with regex that splits on both
  524. text = text.replace( /\r\n/g, '\n' );
  525. }
  526. if ( text.indexOf( '\\\n' ) !== - 1 ) {
  527. // join lines separated by a line continuation character (\)
  528. text = text.replace( /\\\n/g, '' );
  529. }
  530. var lines = text.split( '\n' );
  531. var line = '', lineFirstChar = '';
  532. var lineLength = 0;
  533. var result = [];
  534. // Faster to just trim left side of the line. Use if available.
  535. var trimLeft = ( typeof ''.trimLeft === 'function' );
  536. for ( var i = 0, l = lines.length; i < l; i ++ ) {
  537. line = lines[ i ];
  538. line = trimLeft ? line.trimLeft() : line.trim();
  539. lineLength = line.length;
  540. if ( lineLength === 0 ) continue;
  541. lineFirstChar = line.charAt( 0 );
  542. // @todo invoke passed in handler if any
  543. if ( lineFirstChar === '#' ) continue;
  544. if ( lineFirstChar === 'v' ) {
  545. var data = line.split( /\s+/ );
  546. switch ( data[ 0 ] ) {
  547. case 'v':
  548. state.vertices.push(
  549. parseFloat( data[ 1 ] ),
  550. parseFloat( data[ 2 ] ),
  551. parseFloat( data[ 3 ] )
  552. );
  553. if ( data.length >= 7 ) {
  554. state.colors.push(
  555. parseFloat( data[ 4 ] ),
  556. parseFloat( data[ 5 ] ),
  557. parseFloat( data[ 6 ] )
  558. );
  559. }
  560. break;
  561. case 'vn':
  562. state.normals.push(
  563. parseFloat( data[ 1 ] ),
  564. parseFloat( data[ 2 ] ),
  565. parseFloat( data[ 3 ] )
  566. );
  567. break;
  568. case 'vt':
  569. state.uvs.push(
  570. parseFloat( data[ 1 ] ),
  571. parseFloat( data[ 2 ] )
  572. );
  573. break;
  574. }
  575. } else if ( lineFirstChar === 'f' ) {
  576. var lineData = line.substr( 1 ).trim();
  577. var vertexData = lineData.split( /\s+/ );
  578. var faceVertices = [];
  579. // Parse the face vertex data into an easy to work with format
  580. for ( var j = 0, jl = vertexData.length; j < jl; j ++ ) {
  581. var vertex = vertexData[ j ];
  582. if ( vertex.length > 0 ) {
  583. var vertexParts = vertex.split( '/' );
  584. faceVertices.push( vertexParts );
  585. }
  586. }
  587. // Draw an edge between the first vertex and all subsequent vertices to form an n-gon
  588. var v1 = faceVertices[ 0 ];
  589. for ( var j = 1, jl = faceVertices.length - 1; j < jl; j ++ ) {
  590. var v2 = faceVertices[ j ];
  591. var v3 = faceVertices[ j + 1 ];
  592. state.addFace(
  593. v1[ 0 ], v2[ 0 ], v3[ 0 ],
  594. v1[ 1 ], v2[ 1 ], v3[ 1 ],
  595. v1[ 2 ], v2[ 2 ], v3[ 2 ]
  596. );
  597. }
  598. } else if ( lineFirstChar === 'l' ) {
  599. var lineParts = line.substring( 1 ).trim().split( " " );
  600. var lineVertices = [], lineUVs = [];
  601. if ( line.indexOf( "/" ) === - 1 ) {
  602. lineVertices = lineParts;
  603. } else {
  604. for ( var li = 0, llen = lineParts.length; li < llen; li ++ ) {
  605. var parts = lineParts[ li ].split( "/" );
  606. if ( parts[ 0 ] !== "" ) lineVertices.push( parts[ 0 ] );
  607. if ( parts[ 1 ] !== "" ) lineUVs.push( parts[ 1 ] );
  608. }
  609. }
  610. state.addLineGeometry( lineVertices, lineUVs );
  611. } else if ( lineFirstChar === 'p' ) {
  612. var lineData = line.substr( 1 ).trim();
  613. var pointData = lineData.split( " " );
  614. state.addPointGeometry( pointData );
  615. } else if ( ( result = object_pattern.exec( line ) ) !== null ) {
  616. // o object_name
  617. // or
  618. // g group_name
  619. // WORKAROUND: https://bugs.chromium.org/p/v8/issues/detail?id=2869
  620. // var name = result[ 0 ].substr( 1 ).trim();
  621. var name = ( " " + result[ 0 ].substr( 1 ).trim() ).substr( 1 );
  622. state.startObject( name );
  623. } else if ( material_use_pattern.test( line ) ) {
  624. // material
  625. state.object.startMaterial( line.substring( 7 ).trim(), state.materialLibraries );
  626. } else if ( material_library_pattern.test( line ) ) {
  627. // mtl file
  628. state.materialLibraries.push( line.substring( 7 ).trim() );
  629. } else if ( lineFirstChar === 's' ) {
  630. result = line.split( ' ' );
  631. // smooth shading
  632. // @todo Handle files that have varying smooth values for a set of faces inside one geometry,
  633. // but does not define a usemtl for each face set.
  634. // This should be detected and a dummy material created (later MultiMaterial and geometry groups).
  635. // This requires some care to not create extra material on each smooth value for "normal" obj files.
  636. // where explicit usemtl defines geometry groups.
  637. // Example asset: examples/models/obj/cerberus/Cerberus.obj
  638. /*
  639. * http://paulbourke.net/dataformats/obj/
  640. * or
  641. * http://www.cs.utah.edu/~boulos/cs3505/obj_spec.pdf
  642. *
  643. * From chapter "Grouping" Syntax explanation "s group_number":
  644. * "group_number is the smoothing group number. To turn off smoothing groups, use a value of 0 or off.
  645. * Polygonal elements use group numbers to put elements in different smoothing groups. For free-form
  646. * surfaces, smoothing groups are either turned on or off; there is no difference between values greater
  647. * than 0."
  648. */
  649. if ( result.length > 1 ) {
  650. var value = result[ 1 ].trim().toLowerCase();
  651. state.object.smooth = ( value !== '0' && value !== 'off' );
  652. } else {
  653. // ZBrush can produce "s" lines #11707
  654. state.object.smooth = true;
  655. }
  656. var material = state.object.currentMaterial();
  657. if ( material ) material.smooth = state.object.smooth;
  658. } else {
  659. // Handle null terminated files without exception
  660. if ( line === '\0' ) continue;
  661. throw new Error( 'THREE.OBJLoader: Unexpected line: "' + line + '"' );
  662. }
  663. }
  664. state.finalize();
  665. var container = new Group();
  666. container.materialLibraries = [].concat( state.materialLibraries );
  667. for ( var i = 0, l = state.objects.length; i < l; i ++ ) {
  668. var object = state.objects[ i ];
  669. var geometry = object.geometry;
  670. var materials = object.materials;
  671. var isLine = ( geometry.type === 'Line' );
  672. var isPoints = ( geometry.type === 'Points' );
  673. var hasVertexColors = false;
  674. // Skip o/g line declarations that did not follow with any faces
  675. if ( geometry.vertices.length === 0 ) continue;
  676. var buffergeometry = new BufferGeometry();
  677. buffergeometry.addAttribute( 'position', new Float32BufferAttribute( geometry.vertices, 3 ) );
  678. if ( geometry.normals.length > 0 ) {
  679. buffergeometry.addAttribute( 'normal', new Float32BufferAttribute( geometry.normals, 3 ) );
  680. } else {
  681. buffergeometry.computeVertexNormals();
  682. }
  683. if ( geometry.colors.length > 0 ) {
  684. hasVertexColors = true;
  685. //buffergeometry.addAttribute( 'color', new Float32BufferAttribute( geometry.colors, 3 ) );
  686. buffergeometry.attributes[ 'color' ] = new Float32BufferAttribute( geometry.color, 3 )
  687. }
  688. if ( geometry.uvs.length > 0 ) {
  689. //buffergeometry.addAttribute( 'uv', new Float32BufferAttribute( geometry.uvs, 2 ) );
  690. buffergeometry.attributes[ 'uv' ] = new Float32BufferAttribute( geometry.uvs, 2 )
  691. }
  692. // Create materials
  693. var createdMaterials = [];
  694. for ( var mi = 0, miLen = materials.length; mi < miLen; mi ++ ) {
  695. var sourceMaterial = materials[ mi ];
  696. var material = undefined;
  697. if ( this.materials !== null ) {
  698. material = this.materials.create( sourceMaterial.name );
  699. // mtl etc. loaders probably can't create line materials correctly, copy properties to a line material.
  700. if ( isLine && material && ! ( material instanceof LineBasicMaterial ) ) {
  701. var materialLine = new LineBasicMaterial();
  702. Material.prototype.copy.call( materialLine, material );
  703. materialLine.color.copy( material.color );
  704. materialLine.lights = false;
  705. material = materialLine;
  706. } else if ( isPoints && material && ! ( material instanceof PointsMaterial ) ) {
  707. var materialPoints = new PointsMaterial( { size: 10, sizeAttenuation: false } );
  708. Material.prototype.copy.call( materialPoints, material );
  709. materialPoints.color.copy( material.color );
  710. materialPoints.map = material.map;
  711. materialPoints.lights = false;
  712. material = materialPoints;
  713. }
  714. }
  715. if ( ! material ) {
  716. if ( isLine ) {
  717. material = new LineBasicMaterial();
  718. } else if ( isPoints ) {
  719. material = new PointsMaterial( { size: 1, sizeAttenuation: false } );
  720. } else {
  721. material = new MeshPhongMaterial();
  722. }
  723. material.name = sourceMaterial.name;
  724. }
  725. material.flatShading = sourceMaterial.smooth ? false : true;
  726. material.vertexColors = hasVertexColors ? VertexColors : NoColors;
  727. createdMaterials.push( material );
  728. }
  729. // Create mesh
  730. var mesh;
  731. if ( createdMaterials.length > 1 ) {
  732. for ( var mi = 0, miLen = materials.length; mi < miLen; mi ++ ) {
  733. var sourceMaterial = materials[ mi ];
  734. buffergeometry.addGroup( sourceMaterial.groupStart, sourceMaterial.groupCount, mi );
  735. }
  736. if ( isLine ) {
  737. mesh = new LineSegments( buffergeometry, createdMaterials );
  738. } else if ( isPoints ) {
  739. mesh = new Points( buffergeometry, createdMaterials );
  740. } else {
  741. mesh = new Mesh( buffergeometry, createdMaterials );
  742. }
  743. } else {
  744. if ( isLine ) {
  745. mesh = new LineSegments( buffergeometry, createdMaterials[ 0 ] );
  746. } else if ( isPoints ) {
  747. mesh = new Points( buffergeometry, createdMaterials[ 0 ] );
  748. } else {
  749. mesh = new Mesh( buffergeometry, createdMaterials[ 0 ] );
  750. }
  751. }
  752. mesh.name = object.name;
  753. container.add( mesh );
  754. }
  755. console.timeEnd( 'OBJLoader' );
  756. return container;
  757. }
  758. };
  759. return OBJLoader;
  760. } )();
  761. }