CTMLoader.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635
  1. /**
  2. * Loader for CTM encoded models generated by OpenCTM tools:
  3. * http://openctm.sourceforge.net/
  4. *
  5. * Uses js-openctm library by Juan Mellado
  6. * http://code.google.com/p/js-openctm/
  7. *
  8. * @author alteredq / http://alteredqualia.com/
  9. */
  10. THREE.CTMLoader = function ( showStatus ) {
  11. THREE.Loader.call( this, showStatus );
  12. };
  13. THREE.CTMLoader.prototype = Object.create( THREE.Loader.prototype );
  14. // Load multiple CTM parts defined in JSON
  15. THREE.CTMLoader.prototype.loadParts = function( url, callback, parameters ) {
  16. var scope = this;
  17. var xhr = new XMLHttpRequest();
  18. var basePath = parameters.basePath ? parameters.basePath : this.extractUrlBase( url );
  19. xhr.onreadystatechange = function() {
  20. if ( xhr.readyState === 4 ) {
  21. if ( xhr.status === 200 || xhr.status === 0 ) {
  22. var jsonObject = JSON.parse( xhr.responseText );
  23. var materials = [], geometries = [], counter = 0;
  24. function callbackFinal( geometry ) {
  25. counter += 1;
  26. geometries.push( geometry );
  27. if ( counter === jsonObject.offsets.length ) {
  28. callback( geometries, materials );
  29. }
  30. }
  31. // init materials
  32. for ( var i = 0; i < jsonObject.materials.length; i ++ ) {
  33. materials[ i ] = THREE.Loader.prototype.createMaterial( jsonObject.materials[ i ], basePath );
  34. }
  35. // load joined CTM file
  36. var partUrl = basePath + jsonObject.data;
  37. var parametersPart = { useWorker: parameters.useWorker, useBuffers: parameters.useBuffers, offsets: jsonObject.offsets };
  38. scope.load( partUrl, callbackFinal, parametersPart );
  39. }
  40. }
  41. }
  42. xhr.open( "GET", url, true );
  43. if ( xhr.overrideMimeType ) xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
  44. xhr.setRequestHeader( "Content-Type", "text/plain" );
  45. xhr.send( null );
  46. };
  47. // Load CTMLoader compressed models
  48. // - parameters
  49. // - url (required)
  50. // - callback (required)
  51. THREE.CTMLoader.prototype.load = function( url, callback, parameters ) {
  52. var scope = this;
  53. var offsets = parameters.offsets !== undefined ? parameters.offsets : [ 0 ];
  54. var useBuffers = parameters.useBuffers !== undefined ? parameters.useBuffers : true;
  55. var xhr = new XMLHttpRequest(),
  56. callbackProgress = null;
  57. var length = 0;
  58. xhr.onreadystatechange = function() {
  59. if ( xhr.readyState === 4 ) {
  60. if ( xhr.status === 200 || xhr.status === 0 ) {
  61. var binaryData = xhr.responseText;
  62. //var s = Date.now();
  63. if ( parameters.useWorker ) {
  64. var worker = new Worker( "js/loaders/ctm/CTMWorker.js" );
  65. worker.onmessage = function( event ) {
  66. var files = event.data;
  67. for ( var i = 0; i < files.length; i ++ ) {
  68. var ctmFile = files[ i ];
  69. if ( useBuffers ) {
  70. scope.createModelBuffers( ctmFile, callback );
  71. } else {
  72. scope.createModelClassic( ctmFile, callback );
  73. }
  74. }
  75. //var e = Date.now();
  76. //console.log( "CTM data parse time [worker]: " + (e-s) + " ms" );
  77. };
  78. worker.postMessage( { "data": binaryData, "offsets": offsets } );
  79. } else {
  80. for ( var i = 0; i < offsets.length; i ++ ) {
  81. var stream = new CTM.Stream( binaryData );
  82. stream.offset = offsets[ i ];
  83. var ctmFile = new CTM.File( stream );
  84. if ( useBuffers ) {
  85. scope.createModelBuffers( ctmFile, callback );
  86. } else {
  87. scope.createModelClassic( ctmFile, callback );
  88. }
  89. }
  90. //var e = Date.now();
  91. //console.log( "CTM data parse time [inline]: " + (e-s) + " ms" );
  92. }
  93. } else {
  94. console.error( "Couldn't load [" + url + "] [" + xhr.status + "]" );
  95. }
  96. } else if ( xhr.readyState === 3 ) {
  97. if ( callbackProgress ) {
  98. if ( length === 0 ) {
  99. length = xhr.getResponseHeader( "Content-Length" );
  100. }
  101. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  102. }
  103. } else if ( xhr.readyState === 2 ) {
  104. length = xhr.getResponseHeader( "Content-Length" );
  105. }
  106. }
  107. xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
  108. xhr.open( "GET", url, true );
  109. xhr.send( null );
  110. };
  111. THREE.CTMLoader.prototype.createModelBuffers = function ( file, callback ) {
  112. var Model = function ( ) {
  113. var scope = this;
  114. var reorderVertices = true;
  115. scope.materials = [];
  116. THREE.BufferGeometry.call( this );
  117. // init GL buffers
  118. var vertexIndexArray = file.body.indices,
  119. vertexPositionArray = file.body.vertices,
  120. vertexNormalArray = file.body.normals;
  121. var vertexUvArray, vertexColorArray;
  122. if ( file.body.uvMaps !== undefined && file.body.uvMaps.length > 0 ) {
  123. vertexUvArray = file.body.uvMaps[ 0 ].uv;
  124. }
  125. if ( file.body.attrMaps !== undefined && file.body.attrMaps.length > 0 && file.body.attrMaps[ 0 ].name === "Color" ) {
  126. vertexColorArray = file.body.attrMaps[ 0 ].attr;
  127. }
  128. // reorder vertices
  129. // (needed for buffer splitting, to keep together face vertices)
  130. if ( reorderVertices ) {
  131. var newFaces = new Uint32Array( vertexIndexArray.length ),
  132. newVertices = new Float32Array( vertexPositionArray.length );
  133. var newNormals, newUvs, newColors;
  134. if ( vertexNormalArray ) newNormals = new Float32Array( vertexNormalArray.length );
  135. if ( vertexUvArray ) newUvs = new Float32Array( vertexUvArray.length );
  136. if ( vertexColorArray ) newColors = new Float32Array( vertexColorArray.length );
  137. var indexMap = {}, vertexCounter = 0;
  138. function handleVertex( v ) {
  139. if ( indexMap[ v ] === undefined ) {
  140. indexMap[ v ] = vertexCounter;
  141. var sx = v * 3,
  142. sy = v * 3 + 1,
  143. sz = v * 3 + 2,
  144. dx = vertexCounter * 3,
  145. dy = vertexCounter * 3 + 1,
  146. dz = vertexCounter * 3 + 2;
  147. newVertices[ dx ] = vertexPositionArray[ sx ];
  148. newVertices[ dy ] = vertexPositionArray[ sy ];
  149. newVertices[ dz ] = vertexPositionArray[ sz ];
  150. if ( vertexNormalArray ) {
  151. newNormals[ dx ] = vertexNormalArray[ sx ];
  152. newNormals[ dy ] = vertexNormalArray[ sy ];
  153. newNormals[ dz ] = vertexNormalArray[ sz ];
  154. }
  155. if ( vertexUvArray ) {
  156. newUvs[ vertexCounter * 2 ] = vertexUvArray[ v * 2 ];
  157. newUvs[ vertexCounter * 2 + 1 ] = vertexUvArray[ v * 2 + 1 ];
  158. }
  159. if ( vertexColorArray ) {
  160. newColors[ vertexCounter * 4 ] = vertexColorArray[ v * 4 ];
  161. newColors[ vertexCounter * 4 + 1 ] = vertexColorArray[ v * 4 + 1 ];
  162. newColors[ vertexCounter * 4 + 2 ] = vertexColorArray[ v * 4 + 2 ];
  163. newColors[ vertexCounter * 4 + 3 ] = vertexColorArray[ v * 4 + 3 ];
  164. }
  165. vertexCounter += 1;
  166. }
  167. }
  168. var a, b, c;
  169. for ( var i = 0; i < vertexIndexArray.length; i += 3 ) {
  170. a = vertexIndexArray[ i ];
  171. b = vertexIndexArray[ i + 1 ];
  172. c = vertexIndexArray[ i + 2 ];
  173. handleVertex( a );
  174. handleVertex( b );
  175. handleVertex( c );
  176. newFaces[ i ] = indexMap[ a ];
  177. newFaces[ i + 1 ] = indexMap[ b ];
  178. newFaces[ i + 2 ] = indexMap[ c ];
  179. }
  180. vertexIndexArray = newFaces;
  181. vertexPositionArray = newVertices;
  182. if ( vertexNormalArray ) vertexNormalArray = newNormals;
  183. if ( vertexUvArray ) vertexUvArray = newUvs;
  184. if ( vertexColorArray ) vertexColorArray = newColors;
  185. }
  186. // compute offsets
  187. scope.offsets = [];
  188. var indices = vertexIndexArray;
  189. var start = 0,
  190. min = vertexPositionArray.length,
  191. max = 0,
  192. minPrev = min;
  193. for ( var i = 0; i < indices.length; ) {
  194. for ( var j = 0; j < 3; ++ j ) {
  195. var idx = indices[ i ++ ];
  196. if ( idx < min ) min = idx;
  197. if ( idx > max ) max = idx;
  198. }
  199. if ( max - min > 65535 ) {
  200. i -= 3;
  201. for ( var k = start; k < i; ++ k ) {
  202. indices[ k ] -= minPrev;
  203. }
  204. scope.offsets.push( { start: start, count: i - start, index: minPrev } );
  205. start = i;
  206. min = vertexPositionArray.length;
  207. max = 0;
  208. }
  209. minPrev = min;
  210. }
  211. for ( var k = start; k < i; ++ k ) {
  212. indices[ k ] -= minPrev;
  213. }
  214. scope.offsets.push( { start: start, count: i - start, index: minPrev } );
  215. // recast CTM 32-bit indices as 16-bit WebGL indices
  216. var vertexIndexArray16 = new Uint16Array( vertexIndexArray );
  217. // attributes
  218. var attributes = scope.attributes;
  219. attributes[ "index" ] = { itemSize: 1, array: vertexIndexArray16, numItems: vertexIndexArray16.length };
  220. attributes[ "position" ] = { itemSize: 3, array: vertexPositionArray, numItems: vertexPositionArray.length };
  221. if ( vertexNormalArray !== undefined ) {
  222. attributes[ "normal" ] = { itemSize: 3, array: vertexNormalArray, numItems: vertexNormalArray.length };
  223. }
  224. if ( vertexUvArray !== undefined ) {
  225. attributes[ "uv" ] = { itemSize: 2, array: vertexUvArray, numItems: vertexUvArray.length };
  226. }
  227. if ( vertexColorArray !== undefined ) {
  228. attributes[ "color" ] = { itemSize: 4, array: vertexColorArray, numItems: vertexColorArray.length };
  229. }
  230. }
  231. Model.prototype = Object.create( THREE.BufferGeometry.prototype );
  232. var geometry = new Model();
  233. // compute vertex normals if not present in the CTM model
  234. if ( geometry.attributes[ "normal" ] === undefined ) {
  235. geometry.computeVertexNormals();
  236. }
  237. callback( geometry );
  238. };
  239. THREE.CTMLoader.prototype.createModelClassic = function ( file, callback ) {
  240. var Model = function ( ) {
  241. var scope = this;
  242. scope.materials = [];
  243. THREE.Geometry.call( this );
  244. var normals = [],
  245. uvs = [],
  246. colors = [];
  247. init_vertices( file.body.vertices );
  248. if ( file.body.normals !== undefined )
  249. init_normals( file.body.normals );
  250. if ( file.body.uvMaps !== undefined && file.body.uvMaps.length > 0 )
  251. init_uvs( file.body.uvMaps[ 0 ].uv );
  252. if ( file.body.attrMaps !== undefined && file.body.attrMaps.length > 0 && file.body.attrMaps[ 0 ].name === "Color" )
  253. init_colors( file.body.attrMaps[ 0 ].attr );
  254. var hasNormals = normals.length > 0 ? true : false,
  255. hasUvs = uvs.length > 0 ? true : false,
  256. hasColors = colors.length > 0 ? true : false;
  257. init_faces( file.body.indices );
  258. this.computeCentroids();
  259. this.computeFaceNormals();
  260. //this.computeTangents();
  261. function init_vertices( buffer ) {
  262. var x, y, z, i, il = buffer.length;
  263. for( i = 0; i < il; i += 3 ) {
  264. x = buffer[ i ];
  265. y = buffer[ i + 1 ];
  266. z = buffer[ i + 2 ];
  267. vertex( scope, x, y, z );
  268. }
  269. };
  270. function init_normals( buffer ) {
  271. var x, y, z, i, il = buffer.length;
  272. for( i = 0; i < il; i += 3 ) {
  273. x = buffer[ i ];
  274. y = buffer[ i + 1 ];
  275. z = buffer[ i + 2 ];
  276. normals.push( x, y, z );
  277. }
  278. };
  279. function init_colors( buffer ) {
  280. var r, g, b, a, i, il = buffer.length;
  281. for( i = 0; i < il; i += 4 ) {
  282. r = buffer[ i ];
  283. g = buffer[ i + 1 ];
  284. b = buffer[ i + 2 ];
  285. a = buffer[ i + 3 ];
  286. var color = new THREE.Color();
  287. color.setRGB( r, g, b );
  288. colors.push( color );
  289. }
  290. };
  291. function init_uvs( buffer ) {
  292. var u, v, i, il = buffer.length;
  293. for( i = 0; i < il; i += 2 ) {
  294. u = buffer[ i ];
  295. v = buffer[ i + 1 ];
  296. uvs.push( u, v );
  297. }
  298. };
  299. function init_faces( buffer ) {
  300. var a, b, c,
  301. u1, v1, u2, v2, u3, v3,
  302. m, face,
  303. i, il = buffer.length;
  304. m = 0; // all faces defaulting to material 0
  305. for( i = 0; i < il; i += 3 ) {
  306. a = buffer[ i ];
  307. b = buffer[ i + 1 ];
  308. c = buffer[ i + 2 ];
  309. if ( hasNormals ){
  310. face = f3n( scope, normals, a, b, c, m, a, b, c );
  311. } else {
  312. face = f3( scope, a, b, c, m );
  313. }
  314. if ( hasColors ) {
  315. face.vertexColors[ 0 ] = colors[ a ];
  316. face.vertexColors[ 1 ] = colors[ b ];
  317. face.vertexColors[ 2 ] = colors[ c ];
  318. }
  319. if ( hasUvs ) {
  320. u1 = uvs[ a * 2 ];
  321. v1 = uvs[ a * 2 + 1 ];
  322. u2 = uvs[ b * 2 ];
  323. v2 = uvs[ b * 2 + 1 ];
  324. u3 = uvs[ c * 2 ];
  325. v3 = uvs[ c * 2 + 1 ];
  326. uv3( scope.faceVertexUvs[ 0 ], u1, v1, u2, v2, u3, v3 );
  327. }
  328. }
  329. }
  330. };
  331. function vertex ( scope, x, y, z ) {
  332. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  333. };
  334. function f3 ( scope, a, b, c, mi ) {
  335. var face = new THREE.Face3( a, b, c, null, null, mi );
  336. scope.faces.push( face );
  337. return face;
  338. };
  339. function f3n ( scope, normals, a, b, c, mi, nai, nbi, nci ) {
  340. var nax = normals[ nai * 3 ],
  341. nay = normals[ nai * 3 + 1 ],
  342. naz = normals[ nai * 3 + 2 ],
  343. nbx = normals[ nbi * 3 ],
  344. nby = normals[ nbi * 3 + 1 ],
  345. nbz = normals[ nbi * 3 + 2 ],
  346. ncx = normals[ nci * 3 ],
  347. ncy = normals[ nci * 3 + 1 ],
  348. ncz = normals[ nci * 3 + 2 ];
  349. var na = new THREE.Vector3( nax, nay, naz ),
  350. nb = new THREE.Vector3( nbx, nby, nbz ),
  351. nc = new THREE.Vector3( ncx, ncy, ncz );
  352. var face = new THREE.Face3( a, b, c, [ na, nb, nc ], null, mi );
  353. scope.faces.push( face );
  354. return face;
  355. };
  356. function uv3 ( where, u1, v1, u2, v2, u3, v3 ) {
  357. var uv = [];
  358. uv.push( new THREE.Vector2( u1, v1 ) );
  359. uv.push( new THREE.Vector2( u2, v2 ) );
  360. uv.push( new THREE.Vector2( u3, v3 ) );
  361. where.push( uv );
  362. };
  363. Model.prototype = Object.create( THREE.Geometry.prototype );
  364. callback( new Model() );
  365. };