OBJLoader.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  1. /**
  2. * @author mrdoob / http://mrdoob.com/
  3. */
  4. THREE.OBJLoader = function ( manager ) {
  5. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6. this.materials = null;
  7. this.regexp = {
  8. // v float float float
  9. vertex_pattern : /^v\s+([\d|\.|\+|\-|e|E]+)\s+([\d|\.|\+|\-|e|E]+)\s+([\d|\.|\+|\-|e|E]+)/,
  10. // vn float float float
  11. normal_pattern : /^vn\s+([\d|\.|\+|\-|e|E]+)\s+([\d|\.|\+|\-|e|E]+)\s+([\d|\.|\+|\-|e|E]+)/,
  12. // vt float float
  13. uv_pattern : /^vt\s+([\d|\.|\+|\-|e|E]+)\s+([\d|\.|\+|\-|e|E]+)/,
  14. // f vertex vertex vertex
  15. face_vertex : /^f\s+(-?\d+)\s+(-?\d+)\s+(-?\d+)(?:\s+(-?\d+))?/,
  16. // f vertex/uv vertex/uv vertex/uv
  17. face_vertex_uv : /^f\s+(-?\d+)\/(-?\d+)\s+(-?\d+)\/(-?\d+)\s+(-?\d+)\/(-?\d+)(?:\s+(-?\d+)\/(-?\d+))?/,
  18. // f vertex/uv/normal vertex/uv/normal vertex/uv/normal
  19. face_vertex_uv_normal : /^f\s+(-?\d+)\/(-?\d+)\/(-?\d+)\s+(-?\d+)\/(-?\d+)\/(-?\d+)\s+(-?\d+)\/(-?\d+)\/(-?\d+)(?:\s+(-?\d+)\/(-?\d+)\/(-?\d+))?/,
  20. // f vertex//normal vertex//normal vertex//normal
  21. face_vertex_normal : /^f\s+(-?\d+)\/\/(-?\d+)\s+(-?\d+)\/\/(-?\d+)\s+(-?\d+)\/\/(-?\d+)(?:\s+(-?\d+)\/\/(-?\d+))?/,
  22. // o object_name | g group_name
  23. object_pattern : /^[og]\s*(.+)?/,
  24. // s boolean
  25. smoothing_pattern : /^s\s+(\d+|on|off)/,
  26. // mtllib file_reference
  27. material_library_pattern : /^mtllib /,
  28. // usemtl material_name
  29. material_use_pattern : /^usemtl /
  30. };
  31. };
  32. THREE.OBJLoader.prototype = {
  33. constructor: THREE.OBJLoader,
  34. load: function ( url, onLoad, onProgress, onError ) {
  35. var scope = this;
  36. var loader = new THREE.XHRLoader( scope.manager );
  37. loader.setPath( this.path );
  38. loader.load( url, function ( text ) {
  39. onLoad( scope.parse( text ) );
  40. }, onProgress, onError );
  41. },
  42. setPath: function ( value ) {
  43. this.path = value;
  44. },
  45. setMaterials: function ( materials ) {
  46. this.materials = materials;
  47. },
  48. _createParserState : function()
  49. {
  50. var state = {
  51. objects : [],
  52. object : {},
  53. vertices : [],
  54. normals : [],
  55. uvs : [],
  56. materialLibraries : [],
  57. startObject : function(name, fromDeclaration)
  58. {
  59. // If the current object (initial from reset) is not from a g/o declaration in the parsed
  60. // file. We need to use it for the first parsed g/o to keep things in sync.
  61. if ( this.object && this.object.fromDeclaration === false ) {
  62. this.object.name = name;
  63. this.object.fromDeclaration = (fromDeclaration !== false);
  64. return;
  65. }
  66. this.object = {
  67. name : name || '',
  68. geometry : {
  69. vertices : [],
  70. normals : [],
  71. uvs : []
  72. },
  73. material : {
  74. name : '',
  75. smooth : true
  76. },
  77. fromDeclaration : (fromDeclaration !== false)
  78. };
  79. this.objects.push(this.object);
  80. },
  81. parseVertexIndex : function( value, len ) {
  82. var index = parseInt( value, 10 );
  83. return ( index >= 0 ? index - 1 : index + len / 3 ) * 3;
  84. },
  85. parseNormalIndex : function( value, len ) {
  86. var index = parseInt( value, 10 );
  87. return ( index >= 0 ? index - 1 : index + len / 3 ) * 3;
  88. },
  89. parseUVIndex : function( value, len ) {
  90. var index = parseInt( value, 10 );
  91. return ( index >= 0 ? index - 1 : index + len / 2 ) * 2;
  92. },
  93. addVertex : function( a, b, c ) {
  94. var src = this.vertices;
  95. this.object.geometry.vertices.push(src[ a ]);
  96. this.object.geometry.vertices.push(src[ a + 1 ]);
  97. this.object.geometry.vertices.push(src[ a + 2 ]);
  98. this.object.geometry.vertices.push(src[ b ]);
  99. this.object.geometry.vertices.push(src[ b + 1 ]);
  100. this.object.geometry.vertices.push(src[ b + 2 ]);
  101. this.object.geometry.vertices.push(src[ c ]);
  102. this.object.geometry.vertices.push(src[ c + 1 ]);
  103. this.object.geometry.vertices.push(src[ c + 2 ]);
  104. },
  105. addVertexLine : function( a )
  106. {
  107. var src = this.vertices;
  108. this.object.geometry.vertices.push(src[ a ]);
  109. this.object.geometry.vertices.push(src[ a + 1 ]);
  110. this.object.geometry.vertices.push(src[ a + 2 ]);
  111. },
  112. addNormal : function( a, b, c ) {
  113. var src = this.normals;
  114. this.object.geometry.normals.push(src[ a ]);
  115. this.object.geometry.normals.push(src[ a + 1 ]);
  116. this.object.geometry.normals.push(src[ a + 2 ]);
  117. this.object.geometry.normals.push(src[ b ]);
  118. this.object.geometry.normals.push(src[ b + 1 ]);
  119. this.object.geometry.normals.push(src[ b + 2 ]);
  120. this.object.geometry.normals.push(src[ c ]);
  121. this.object.geometry.normals.push(src[ c + 1 ]);
  122. this.object.geometry.normals.push(src[ c + 2 ]);
  123. },
  124. addUV : function( a, b, c ) {
  125. var src = this.uvs;
  126. this.object.geometry.uvs.push(src[ a ]);
  127. this.object.geometry.uvs.push(src[ a + 1 ]);
  128. this.object.geometry.uvs.push(src[ b ]);
  129. this.object.geometry.uvs.push(src[ b + 1 ]);
  130. this.object.geometry.uvs.push(src[ c ]);
  131. this.object.geometry.uvs.push(src[ c + 1 ]);
  132. },
  133. addUVLine : function( a ) {
  134. var src = this.uvs;
  135. this.object.geometry.uvs.push(src[ a ]);
  136. this.object.geometry.uvs.push(src[ a + 1 ]);
  137. },
  138. addFace : function( a, b, c, d, ua, ub, uc, ud, na, nb, nc, nd ) {
  139. var vLen = this.vertices.length;
  140. var ia = this.parseVertexIndex( a, vLen );
  141. var ib = this.parseVertexIndex( b, vLen );
  142. var ic = this.parseVertexIndex( c, vLen );
  143. var id;
  144. if ( d === undefined ) {
  145. this.addVertex( ia, ib, ic );
  146. } else {
  147. id = this.parseVertexIndex( d, vLen );
  148. this.addVertex( ia, ib, id );
  149. this.addVertex( ib, ic, id );
  150. }
  151. if ( ua !== undefined ) {
  152. var uvLen = this.uvs.length;
  153. ia = this.parseUVIndex( ua, uvLen );
  154. ib = this.parseUVIndex( ub, uvLen );
  155. ic = this.parseUVIndex( uc, uvLen );
  156. if ( d === undefined ) {
  157. this.addUV( ia, ib, ic );
  158. } else {
  159. id = this.parseUVIndex( ud, uvLen );
  160. this.addUV( ia, ib, id );
  161. this.addUV( ib, ic, id );
  162. }
  163. }
  164. if ( na !== undefined ) {
  165. // Normals are many times the same. If so, skip function call and parseInt.
  166. var nLen = this.normals.length;
  167. ia = this.parseNormalIndex( na, nLen );
  168. if (na === nb)
  169. ib = ia;
  170. else
  171. ib = this.parseNormalIndex( nb, nLen );
  172. if (na === nc)
  173. ic = ia;
  174. else
  175. ic = this.parseNormalIndex( nc, nLen );
  176. if ( d === undefined ) {
  177. this.addNormal( ia, ib, ic );
  178. } else {
  179. id = this.parseNormalIndex( nd, nLen );
  180. this.addNormal( ia, ib, id );
  181. this.addNormal( ib, ic, id );
  182. }
  183. }
  184. },
  185. addLineGeometry : function(vertexes, uvs)
  186. {
  187. this.object.geometry.type = 'Line';
  188. var vLen = this.vertices.length;
  189. var uvLen = this.uvs.length;
  190. for (var vi = 0, l = vertexes.length; vi < l; vi++) {
  191. this.addVertexLine( this.parseVertexIndex( vertexes[vi], vLen ) );
  192. }
  193. for (var uvi = 0, l = uvs.length; uvi < l; uvi++) {
  194. this.addUVLine( this.parseUVIndex( uvs[uvi], uvLen ) );
  195. }
  196. }
  197. };
  198. state.startObject('', false);
  199. return state;
  200. },
  201. parse: function ( text ) {
  202. console.time( 'OBJLoader' );
  203. var state = this._createParserState();
  204. if ( text.indexOf('\r\n') !== -1 ) {
  205. // This is faster than String.split with regex that splits on both
  206. text = text.replace('\r\n', '\n');
  207. }
  208. var lines = text.split( '\n' );
  209. var line = '', lineFirstChar = '', lineSecondChar = '';
  210. var lineLength = 0;
  211. var result = [];
  212. // Faster to just trim left side of the line. Use if available.
  213. var trimLeft = (typeof ''.trimLeft === 'function');
  214. for ( var i = 0, l = lines.length; i < l; i ++ ) {
  215. line = lines[ i ];
  216. if (trimLeft)
  217. line = line.trimLeft();
  218. else
  219. line = line.trim();
  220. lineLength = line.length;
  221. if ( lineLength === 0 ) {
  222. continue;
  223. }
  224. lineFirstChar = line.charAt( 0 );
  225. if ( lineFirstChar === '#' ) {
  226. // @todo invoke passed in handler if any
  227. continue;
  228. }
  229. if ( lineFirstChar === 'v' ) {
  230. lineSecondChar = line.charAt( 1 );
  231. if ( lineSecondChar === ' ' && ( result = this.regexp.vertex_pattern.exec( line ) ) !== null ) {
  232. // 0 1 2 3
  233. // ["v 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  234. state.vertices.push(
  235. parseFloat( result[ 1 ] ),
  236. parseFloat( result[ 2 ] ),
  237. parseFloat( result[ 3 ] )
  238. );
  239. } else if ( lineSecondChar === 'n' && ( result = this.regexp.normal_pattern.exec( line ) ) !== null ) {
  240. // 0 1 2 3
  241. // ["vn 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  242. state.normals.push(
  243. parseFloat( result[ 1 ] ),
  244. parseFloat( result[ 2 ] ),
  245. parseFloat( result[ 3 ] )
  246. );
  247. } else if ( lineSecondChar === 't' && ( result = this.regexp.uv_pattern.exec( line ) ) !== null ) {
  248. // 0 1 2
  249. // ["vt 0.1 0.2", "0.1", "0.2"]
  250. state.uvs.push(
  251. parseFloat( result[ 1 ] ),
  252. parseFloat( result[ 2 ] )
  253. );
  254. } else {
  255. throw new Error( "Unexpected vertex/normal/uv line: '" + line + "'");
  256. }
  257. } else if ( lineFirstChar === "f" ) {
  258. if ( ( result = this.regexp.face_vertex_uv_normal.exec( line ) ) !== null ) {
  259. // f vertex/uv/normal vertex/uv/normal vertex/uv/normal
  260. // 0 1 2 3 4 5 6 7 8 9 10 11 12
  261. // ["f 1/1/1 2/2/2 3/3/3", "1", "1", "1", "2", "2", "2", "3", "3", "3", undefined, undefined, undefined]
  262. state.addFace(
  263. result[ 1 ], result[ 4 ], result[ 7 ], result[ 10 ],
  264. result[ 2 ], result[ 5 ], result[ 8 ], result[ 11 ],
  265. result[ 3 ], result[ 6 ], result[ 9 ], result[ 12 ]
  266. );
  267. } else if ( ( result = this.regexp.face_vertex_uv.exec( line ) ) !== null ) {
  268. // f vertex/uv vertex/uv vertex/uv
  269. // 0 1 2 3 4 5 6 7 8
  270. // ["f 1/1 2/2 3/3", "1", "1", "2", "2", "3", "3", undefined, undefined]
  271. state.addFace(
  272. result[ 1 ], result[ 3 ], result[ 5 ], result[ 7 ],
  273. result[ 2 ], result[ 4 ], result[ 6 ], result[ 8 ]
  274. );
  275. } else if ( ( result = this.regexp.face_vertex_normal.exec( line ) ) !== null ) {
  276. // f vertex//normal vertex//normal vertex//normal
  277. // 0 1 2 3 4 5 6 7 8
  278. // ["f 1//1 2//2 3//3", "1", "1", "2", "2", "3", "3", undefined, undefined]
  279. state.addFace(
  280. result[ 1 ], result[ 3 ], result[ 5 ], result[ 7 ],
  281. undefined, undefined, undefined, undefined,
  282. result[ 2 ], result[ 4 ], result[ 6 ], result[ 8 ]
  283. );
  284. } else if ( ( result = this.regexp.face_vertex.exec( line ) ) !== null ) {
  285. // f vertex vertex vertex
  286. // 0 1 2 3 4
  287. // ["f 1 2 3", "1", "2", "3", undefined]
  288. state.addFace(
  289. result[ 1 ], result[ 2 ], result[ 3 ], result[ 4 ]
  290. );
  291. } else {
  292. throw new Error( "Unexpected face line: '" + line + "'");
  293. }
  294. } else if ( lineFirstChar === "l" ) {
  295. var lineParts = line.substring(1).trim().split(" ");
  296. var lineVertexes = [], lineUVs = [];
  297. if (line.indexOf("/") === -1) {
  298. lineVertexes = lineParts;
  299. } else {
  300. for (var li = 0, llen = lineParts.length; li < llen; li++) {
  301. var parts = lineParts[li].split("/");
  302. if (parts[0] !== "")
  303. lineVertexes.push(parts[0]);
  304. if (parts[1] !== "")
  305. lineUVs.push(parts[1])
  306. }
  307. }
  308. state.addLineGeometry(lineVertexes, lineUVs);
  309. } else if ( ( result = this.regexp.object_pattern.exec( line ) ) !== null ) {
  310. // o object_name
  311. // or
  312. // g group_name
  313. var name = result[ 0 ].substr( 1 ).trim();
  314. state.startObject(name);
  315. } else if ( this.regexp.material_use_pattern.test( line ) ) {
  316. // material
  317. state.object.material.name = line.substring( 7 ).trim();
  318. } else if ( this.regexp.material_library_pattern.test( line ) ) {
  319. // mtl file
  320. state.materialLibraries.push( line.substring( 7 ).trim() );
  321. } else if ( ( result = this.regexp.smoothing_pattern.exec( line ) ) !== null ) {
  322. // smooth shading
  323. var value = result[ 1 ].trim().toLowerCase();
  324. state.object.material.smooth = ( value === '1' || value === 'on' );
  325. } else {
  326. // Handle null terminated files without exception
  327. if (line === '\0')
  328. continue;
  329. throw new Error( "Unexpected line: '" + line + "'");
  330. }
  331. }
  332. var container = new THREE.Group();
  333. container.materialLibraries = [].concat(state.materialLibraries);
  334. for ( var i = 0, l = state.objects.length; i < l; i ++ ) {
  335. var object = state.objects[ i ];
  336. var geometry = object.geometry;
  337. var isLine = (geometry.type === 'Line');
  338. var buffergeometry = new THREE.BufferGeometry();
  339. buffergeometry.addAttribute( 'position', new THREE.BufferAttribute( new Float32Array( geometry.vertices ), 3 ) );
  340. if ( geometry.normals.length > 0 ) {
  341. buffergeometry.addAttribute( 'normal', new THREE.BufferAttribute( new Float32Array( geometry.normals ), 3 ) );
  342. } else {
  343. buffergeometry.computeVertexNormals();
  344. }
  345. if ( geometry.uvs.length > 0 ) {
  346. buffergeometry.addAttribute( 'uv', new THREE.BufferAttribute( new Float32Array( geometry.uvs ), 2 ) );
  347. }
  348. var material;
  349. if ( this.materials !== null ) {
  350. material = this.materials.create( object.material.name );
  351. // mtl etc. loaders probably can't create line materials correctly, copy properties to a line material.
  352. if (isLine && material && !(material instanceof THREE.LineBasicMaterial)) {
  353. var materialLine = new THREE.LineBasicMaterial();
  354. materialLine.copy(material);
  355. material = materialLine;
  356. }
  357. }
  358. if ( !material ) {
  359. material = ( !isLine ? new THREE.MeshPhongMaterial() : new THREE.LineBasicMaterial() );
  360. material.name = object.material.name;
  361. }
  362. material.shading = object.material.smooth ? THREE.SmoothShading : THREE.FlatShading;
  363. var mesh = ( !isLine ? new THREE.Mesh( buffergeometry, material ) : new THREE.Line( buffergeometry, material ) );
  364. mesh.name = object.name;
  365. container.add( mesh );
  366. }
  367. console.timeEnd( 'OBJLoader' );
  368. return container;
  369. }
  370. };