OBJLoader.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  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. addNormal : function( a, b, c ) {
  106. var src = this.normals;
  107. this.object.geometry.normals.push(src[ a ]);
  108. this.object.geometry.normals.push(src[ a + 1 ]);
  109. this.object.geometry.normals.push(src[ a + 2 ]);
  110. this.object.geometry.normals.push(src[ b ]);
  111. this.object.geometry.normals.push(src[ b + 1 ]);
  112. this.object.geometry.normals.push(src[ b + 2 ]);
  113. this.object.geometry.normals.push(src[ c ]);
  114. this.object.geometry.normals.push(src[ c + 1 ]);
  115. this.object.geometry.normals.push(src[ c + 2 ]);
  116. },
  117. addUV : function( a, b, c ) {
  118. var src = this.uvs;
  119. this.object.geometry.uvs.push(src[ a ]);
  120. this.object.geometry.uvs.push(src[ a + 1 ]);
  121. this.object.geometry.uvs.push(src[ b ]);
  122. this.object.geometry.uvs.push(src[ b + 1 ]);
  123. this.object.geometry.uvs.push(src[ c ]);
  124. this.object.geometry.uvs.push(src[ c + 1 ]);
  125. },
  126. addFace : function( a, b, c, d, ua, ub, uc, ud, na, nb, nc, nd ) {
  127. var vLen = this.vertices.length;
  128. var ia = this.parseVertexIndex( a, vLen );
  129. var ib = this.parseVertexIndex( b, vLen );
  130. var ic = this.parseVertexIndex( c, vLen );
  131. var id;
  132. if ( d === undefined ) {
  133. this.addVertex( ia, ib, ic );
  134. } else {
  135. id = this.parseVertexIndex( d, vLen );
  136. this.addVertex( ia, ib, id );
  137. this.addVertex( ib, ic, id );
  138. }
  139. if ( ua !== undefined ) {
  140. var uvLen = this.uvs.length;
  141. ia = this.parseUVIndex( ua, uvLen );
  142. ib = this.parseUVIndex( ub, uvLen );
  143. ic = this.parseUVIndex( uc, uvLen );
  144. if ( d === undefined ) {
  145. this.addUV( ia, ib, ic );
  146. } else {
  147. id = this.parseUVIndex( ud, uvLen );
  148. this.addUV( ia, ib, id );
  149. this.addUV( ib, ic, id );
  150. }
  151. }
  152. if ( na !== undefined ) {
  153. // Normals are many times the same. If so, skip function call and parseInt.
  154. var nLen = this.normals.length;
  155. ia = this.parseNormalIndex( na, nLen );
  156. if (na === nb)
  157. ib = ia;
  158. else
  159. ib = this.parseNormalIndex( nb, nLen );
  160. if (na === nc)
  161. ic = ia;
  162. else
  163. ic = this.parseNormalIndex( nc, nLen );
  164. if ( d === undefined ) {
  165. this.addNormal( ia, ib, ic );
  166. } else {
  167. id = this.parseNormalIndex( nd, nLen );
  168. this.addNormal( ia, ib, id );
  169. this.addNormal( ib, ic, id );
  170. }
  171. }
  172. }
  173. };
  174. state.startObject('', false);
  175. return state;
  176. },
  177. parse: function ( text ) {
  178. console.time( 'OBJLoader' );
  179. var state = this._createParserState();
  180. if ( text.indexOf('\r\n') !== -1 ) {
  181. // This is faster than String.split with regex that splits on both
  182. text = text.replace('\r\n', '\n');
  183. }
  184. var lines = text.split( '\n' );
  185. var line = '', lineFirstChar = '', lineSecondChar = '';
  186. var lineLength = 0;
  187. var result = [];
  188. // Faster to just trim left side of the line. Use if available.
  189. var trimLeft = (typeof ''.trimLeft === 'function');
  190. for ( var i = 0, l = lines.length; i < l; i ++ ) {
  191. line = lines[ i ];
  192. if (trimLeft)
  193. line = line.trimLeft();
  194. else
  195. line = line.trim();
  196. lineLength = line.length;
  197. if ( lineLength === 0 ) {
  198. continue;
  199. }
  200. lineFirstChar = line.charAt( 0 );
  201. if ( lineFirstChar === '#' ) {
  202. // @todo invoke passed in handler if any
  203. continue;
  204. }
  205. if ( lineFirstChar === 'v' ) {
  206. lineSecondChar = line.charAt( 1 );
  207. if ( lineSecondChar === ' ' && ( result = this.regexp.vertex_pattern.exec( line ) ) !== null ) {
  208. // 0 1 2 3
  209. // ["v 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  210. state.vertices.push(
  211. parseFloat( result[ 1 ] ),
  212. parseFloat( result[ 2 ] ),
  213. parseFloat( result[ 3 ] )
  214. );
  215. } else if ( lineSecondChar === 'n' && ( result = this.regexp.normal_pattern.exec( line ) ) !== null ) {
  216. // 0 1 2 3
  217. // ["vn 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  218. state.normals.push(
  219. parseFloat( result[ 1 ] ),
  220. parseFloat( result[ 2 ] ),
  221. parseFloat( result[ 3 ] )
  222. );
  223. } else if ( lineSecondChar === 't' && ( result = this.regexp.uv_pattern.exec( line ) ) !== null ) {
  224. // 0 1 2
  225. // ["vt 0.1 0.2", "0.1", "0.2"]
  226. state.uvs.push(
  227. parseFloat( result[ 1 ] ),
  228. parseFloat( result[ 2 ] )
  229. );
  230. } else {
  231. throw new Error( "Unexpected vertex/normal/uv line: '" + line + "'");
  232. }
  233. } else if ( lineFirstChar === "f" ) {
  234. if ( ( result = this.regexp.face_vertex_uv_normal.exec( line ) ) !== null ) {
  235. // f vertex/uv/normal vertex/uv/normal vertex/uv/normal
  236. // 0 1 2 3 4 5 6 7 8 9 10 11 12
  237. // ["f 1/1/1 2/2/2 3/3/3", "1", "1", "1", "2", "2", "2", "3", "3", "3", undefined, undefined, undefined]
  238. state.addFace(
  239. result[ 1 ], result[ 4 ], result[ 7 ], result[ 10 ],
  240. result[ 2 ], result[ 5 ], result[ 8 ], result[ 11 ],
  241. result[ 3 ], result[ 6 ], result[ 9 ], result[ 12 ]
  242. );
  243. } else if ( ( result = this.regexp.face_vertex_uv.exec( line ) ) !== null ) {
  244. // f vertex/uv vertex/uv vertex/uv
  245. // 0 1 2 3 4 5 6 7 8
  246. // ["f 1/1 2/2 3/3", "1", "1", "2", "2", "3", "3", undefined, undefined]
  247. state.addFace(
  248. result[ 1 ], result[ 3 ], result[ 5 ], result[ 7 ],
  249. result[ 2 ], result[ 4 ], result[ 6 ], result[ 8 ]
  250. );
  251. } else if ( ( result = this.regexp.face_vertex_normal.exec( line ) ) !== null ) {
  252. // f vertex//normal vertex//normal vertex//normal
  253. // 0 1 2 3 4 5 6 7 8
  254. // ["f 1//1 2//2 3//3", "1", "1", "2", "2", "3", "3", undefined, undefined]
  255. state.addFace(
  256. result[ 1 ], result[ 3 ], result[ 5 ], result[ 7 ],
  257. undefined, undefined, undefined, undefined,
  258. result[ 2 ], result[ 4 ], result[ 6 ], result[ 8 ]
  259. );
  260. } else if ( ( result = this.regexp.face_vertex.exec( line ) ) !== null ) {
  261. // f vertex vertex vertex
  262. // 0 1 2 3 4
  263. // ["f 1 2 3", "1", "2", "3", undefined]
  264. state.addFace(
  265. result[ 1 ], result[ 2 ], result[ 3 ], result[ 4 ]
  266. );
  267. } else {
  268. throw new Error( "Unexpected face line: '" + line + "'");
  269. }
  270. } else if ( ( result = this.regexp.object_pattern.exec( line ) ) !== null ) {
  271. // o object_name
  272. // or
  273. // g group_name
  274. var name = result[ 0 ].substr( 1 ).trim();
  275. state.startObject(name);
  276. } else if ( this.regexp.material_use_pattern.test( line ) ) {
  277. // material
  278. state.object.material.name = line.substring( 7 ).trim();
  279. } else if ( this.regexp.material_library_pattern.test( line ) ) {
  280. // mtl file
  281. state.materialLibraries.push( line.substring( 7 ).trim() );
  282. } else if ( ( result = this.regexp.smoothing_pattern.exec( line ) ) !== null ) {
  283. // smooth shading
  284. var value = result[ 1 ].trim().toLowerCase();
  285. state.object.material.smooth = ( value === '1' || value === 'on' );
  286. } else {
  287. // Handle null terminated files without exception
  288. if (line === "\0")
  289. continue;
  290. throw new Error( "Unexpected line: '" + line + "'");
  291. }
  292. }
  293. var container = new THREE.Group();
  294. container.materialLibraries = [].concat(state.materialLibraries);
  295. for ( var i = 0, l = state.objects.length; i < l; i ++ ) {
  296. var object = state.objects[ i ];
  297. var geometry = object.geometry;
  298. var buffergeometry = new THREE.BufferGeometry();
  299. buffergeometry.addAttribute( 'position', new THREE.BufferAttribute( new Float32Array( geometry.vertices ), 3 ) );
  300. if ( geometry.normals.length > 0 ) {
  301. buffergeometry.addAttribute( 'normal', new THREE.BufferAttribute( new Float32Array( geometry.normals ), 3 ) );
  302. } else {
  303. buffergeometry.computeVertexNormals();
  304. }
  305. if ( geometry.uvs.length > 0 ) {
  306. buffergeometry.addAttribute( 'uv', new THREE.BufferAttribute( new Float32Array( geometry.uvs ), 2 ) );
  307. }
  308. var material;
  309. if ( this.materials !== null ) {
  310. material = this.materials.create( object.material.name );
  311. }
  312. if ( !material ) {
  313. material = new THREE.MeshPhongMaterial();
  314. material.name = object.material.name;
  315. }
  316. material.shading = object.material.smooth ? THREE.SmoothShading : THREE.FlatShading;
  317. var mesh = new THREE.Mesh( buffergeometry, material );
  318. mesh.name = object.name;
  319. container.add( mesh );
  320. }
  321. console.timeEnd( 'OBJLoader' );
  322. return container;
  323. }
  324. };