CTMLoader.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672
  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. xhr.setRequestHeader( "Content-Type", "text/plain" );
  44. xhr.send( null );
  45. };
  46. // Load CTMLoader compressed models
  47. // - parameters
  48. // - url (required)
  49. // - callback (required)
  50. THREE.CTMLoader.prototype.load = function( url, callback, parameters ) {
  51. var scope = this;
  52. var offsets = parameters.offsets !== undefined ? parameters.offsets : [ 0 ];
  53. var useBuffers = parameters.useBuffers !== undefined ? parameters.useBuffers : true;
  54. var xhr = new XMLHttpRequest(),
  55. callbackProgress = null;
  56. var length = 0;
  57. xhr.onreadystatechange = function() {
  58. if ( xhr.readyState === 4 ) {
  59. if ( xhr.status === 200 || xhr.status === 0 ) {
  60. var binaryData = new Uint8Array(xhr.response);
  61. var s = Date.now();
  62. if ( parameters.useWorker ) {
  63. var worker = new Worker( "js/loaders/ctm/CTMWorker.js" );
  64. worker.onmessage = function( event ) {
  65. var files = event.data;
  66. for ( var i = 0; i < files.length; i ++ ) {
  67. var ctmFile = files[ i ];
  68. var e1 = Date.now();
  69. // console.log( "CTM data parse time [worker]: " + (e1-s) + " ms" );
  70. if ( useBuffers ) {
  71. scope.createModelBuffers( ctmFile, callback );
  72. } else {
  73. scope.createModelClassic( ctmFile, callback );
  74. }
  75. var e = Date.now();
  76. console.log( "model load time [worker]: " + (e-e1) + " ms, total: " + (e-s));
  77. }
  78. };
  79. worker.postMessage( { "data": binaryData, "offsets": offsets } );
  80. } else {
  81. for ( var i = 0; i < offsets.length; i ++ ) {
  82. var stream = new CTM.Stream( binaryData );
  83. stream.offset = offsets[ i ];
  84. var ctmFile = new CTM.File( stream );
  85. if ( useBuffers ) {
  86. scope.createModelBuffers( ctmFile, callback );
  87. } else {
  88. scope.createModelClassic( ctmFile, callback );
  89. }
  90. }
  91. //var e = Date.now();
  92. //console.log( "CTM data parse time [inline]: " + (e-s) + " ms" );
  93. }
  94. } else {
  95. console.error( "Couldn't load [" + url + "] [" + xhr.status + "]" );
  96. }
  97. } else if ( xhr.readyState === 3 ) {
  98. if ( callbackProgress ) {
  99. if ( length === 0 ) {
  100. length = xhr.getResponseHeader( "Content-Length" );
  101. }
  102. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  103. }
  104. } else if ( xhr.readyState === 2 ) {
  105. length = xhr.getResponseHeader( "Content-Length" );
  106. }
  107. }
  108. xhr.open( "GET", url, true );
  109. xhr.responseType = "arraybuffer";
  110. xhr.send( null );
  111. };
  112. THREE.CTMLoader.prototype.createModelBuffers = function ( file, callback ) {
  113. var Model = function ( ) {
  114. var scope = this;
  115. var reorderVertices = true;
  116. scope.materials = [];
  117. THREE.BufferGeometry.call( this );
  118. var s = Date.now();
  119. // init GL buffers
  120. var vertexIndexArray = file.body.indices,
  121. vertexPositionArray = file.body.vertices,
  122. vertexNormalArray = file.body.normals;
  123. var vertexUvArray, vertexColorArray;
  124. if ( file.body.uvMaps !== undefined && file.body.uvMaps.length > 0 ) {
  125. vertexUvArray = file.body.uvMaps[ 0 ].uv;
  126. }
  127. if ( file.body.attrMaps !== undefined && file.body.attrMaps.length > 0 && file.body.attrMaps[ 0 ].name === "Color" ) {
  128. vertexColorArray = file.body.attrMaps[ 0 ].attr;
  129. }
  130. // reorder vertices
  131. // (needed for buffer splitting, to keep together face vertices)
  132. if ( reorderVertices ) {
  133. function copyVertexInfo(v, vt) {
  134. var sx = v * 3,
  135. sy = v * 3 + 1,
  136. sz = v * 3 + 2,
  137. dx = vt * 3,
  138. dy = vt * 3 + 1,
  139. dz = vt * 3 + 2;
  140. newVertices[ dx ] = vertexPositionArray[ sx ];
  141. newVertices[ dy ] = vertexPositionArray[ sy ];
  142. newVertices[ dz ] = vertexPositionArray[ sz ];
  143. if ( vertexNormalArray ) {
  144. newNormals[ dx ] = vertexNormalArray[ sx ];
  145. newNormals[ dy ] = vertexNormalArray[ sy ];
  146. newNormals[ dz ] = vertexNormalArray[ sz ];
  147. }
  148. if ( vertexUvArray ) {
  149. newUvs[ vt * 2 ] = vertexUvArray[ v * 2 ];
  150. newUvs[ vt * 2 + 1 ] = vertexUvArray[ v * 2 + 1 ];
  151. }
  152. if ( vertexColorArray ) {
  153. newColors[ vt * 4 ] = vertexColorArray[ v * 4 ];
  154. newColors[ vt * 4 + 1 ] = vertexColorArray[ v * 4 + 1 ];
  155. newColors[ vt * 4 + 2 ] = vertexColorArray[ v * 4 + 2 ];
  156. newColors[ vt * 4 + 3 ] = vertexColorArray[ v * 4 + 3 ];
  157. }
  158. }
  159. function handleVertex( v, iMap ) {
  160. if ( iMap[ v ] === undefined ) {
  161. iMap[ v ] = vertexCounter;
  162. reverseIndexMap[vertexCounter] = v;
  163. vertexCounter += 1;
  164. }
  165. return iMap[ v ];
  166. }
  167. var newFaces = new Uint32Array( vertexIndexArray.length );
  168. var indexMap = {}, reverseIndexMap = {}, vertexCounter = 0;
  169. var spawledFaceCount = 0,
  170. spawledFaceLimit = Math.ceil(vertexIndexArray.length/3000);
  171. var sprawledFaces = new Uint32Array( spawledFaceLimit ); // to store sprawled triangle indices
  172. for ( var i = 0; i < vertexIndexArray.length; i += 3 ) {
  173. var a = vertexIndexArray[ i ];
  174. var b = vertexIndexArray[ i + 1 ];
  175. var c = vertexIndexArray[ i + 2 ];
  176. handleVertex( a, indexMap );
  177. handleVertex( b, indexMap );
  178. handleVertex( c, indexMap );
  179. // check for sprawled triangles and put them aside to recreate later
  180. if ( Math.abs( indexMap[a] - indexMap[b] ) > 65535 ||
  181. Math.abs( indexMap[b] - indexMap[c] ) > 65535 ||
  182. Math.abs( indexMap[c] - indexMap[a] ) > 65535 ){
  183. // expand storage when neccessary
  184. if (spawledFaceCount >= spawledFaceLimit) {
  185. console.warn("reached sprawled faces limit: " + spawledFaceCount);
  186. spawledFaceLimit *= 2;
  187. var tArr = new Uint32Array( spawledFaceLimit );
  188. tArr.set(sprawledFaces);
  189. sprawledFaces = tArr;
  190. }
  191. sprawledFaces[ spawledFaceCount ] = i; // starting index in newFaces
  192. spawledFaceCount += 1;
  193. }
  194. else {
  195. newFaces[ i ] = indexMap[ a ];
  196. newFaces[ i + 1 ] = indexMap[ b ];
  197. newFaces[ i + 2 ] = indexMap[ c ];
  198. }
  199. }
  200. // console.log("Number of sprawled faces: " + spawledFaceCount + " current limit: " + spawledFaceLimit +
  201. // " total: " + vertexIndexArray.length/3 + " vertices: " + vertexCounter);
  202. // create dublicate vertices and update sprawled faces
  203. var indexMap2 = {},
  204. noov = vertexCounter; // # of original vertices
  205. for (var isf = 0; isf < spawledFaceCount; isf++ ) {
  206. var i = sprawledFaces[isf];
  207. for (var j = 0; j < 3; j++) {
  208. var v = vertexIndexArray[ i + j ];
  209. newFaces[ i + j] = handleVertex(v, indexMap2); // new vertex
  210. }
  211. }
  212. // console.log("Created duplicated vertices: " + (vertexCounter - noov));
  213. // copy xyz, uv, normals and colors into new arrays
  214. var newVertices = new Float32Array( 3*vertexCounter );
  215. var newNormals, newUvs, newColors;
  216. if ( vertexNormalArray ) newNormals = new Float32Array( 3*vertexCounter );
  217. if ( vertexUvArray ) newUvs = new Float32Array( 2*vertexCounter );
  218. if ( vertexColorArray ) newColors = new Float32Array( 4*vertexCounter );
  219. for (var iv = 0; iv < vertexCounter; iv++) {
  220. copyVertexInfo(reverseIndexMap[iv], iv);
  221. }
  222. vertexIndexArray = newFaces;
  223. vertexPositionArray = newVertices;
  224. if ( vertexNormalArray ) vertexNormalArray = newNormals;
  225. if ( vertexUvArray ) vertexUvArray = newUvs;
  226. if ( vertexColorArray ) vertexColorArray = newColors;
  227. }
  228. // compute offsets
  229. scope.offsets = [];
  230. var indices = vertexIndexArray;
  231. var start = 0,
  232. min = vertexPositionArray.length,
  233. max = 0,
  234. minPrev = min;
  235. for ( var i = 0; i < indices.length; ) {
  236. for ( var j = 0; j < 3; ++ j ) {
  237. var idx = indices[ i ++ ];
  238. if ( idx < min ) min = idx;
  239. if ( idx > max ) max = idx;
  240. }
  241. if ( max - min > 65535 ) {
  242. i -= 3;
  243. if ( minPrev > 0 ) {
  244. for ( var k = start; k < i; ++ k )
  245. indices[ k ] -= minPrev;
  246. }
  247. scope.offsets.push( { start: start, count: i - start, index: minPrev } );
  248. start = i;
  249. min = vertexPositionArray.length;
  250. max = 0;
  251. }
  252. minPrev = min;
  253. }
  254. if ( minPrev > 0 ) {
  255. for ( var k = start; k < i; ++ k )
  256. indices[ k ] -= minPrev;
  257. }
  258. scope.offsets.push( { start: start, count: i - start, index: minPrev } );
  259. // var e = Date.now();
  260. // console.log( "Vetex reordering time: " + (e-s) + " ms" );
  261. // recast CTM 32-bit indices as 16-bit WebGL indices
  262. var vertexIndexArray16 = new Uint16Array( vertexIndexArray );
  263. // attributes
  264. var attributes = scope.attributes;
  265. attributes[ "index" ] = { itemSize: 1, array: vertexIndexArray16, numItems: vertexIndexArray16.length };
  266. attributes[ "position" ] = { itemSize: 3, array: vertexPositionArray, numItems: vertexPositionArray.length };
  267. if ( vertexNormalArray !== undefined ) {
  268. attributes[ "normal" ] = { itemSize: 3, array: vertexNormalArray, numItems: vertexNormalArray.length };
  269. }
  270. if ( vertexUvArray !== undefined ) {
  271. attributes[ "uv" ] = { itemSize: 2, array: vertexUvArray, numItems: vertexUvArray.length };
  272. }
  273. if ( vertexColorArray !== undefined ) {
  274. attributes[ "color" ] = { itemSize: 4, array: vertexColorArray, numItems: vertexColorArray.length };
  275. }
  276. }
  277. Model.prototype = Object.create( THREE.BufferGeometry.prototype );
  278. var geometry = new Model();
  279. // compute vertex normals if not present in the CTM model
  280. if ( geometry.attributes[ "normal" ] === undefined ) {
  281. geometry.computeVertexNormals();
  282. }
  283. callback( geometry );
  284. };
  285. THREE.CTMLoader.prototype.createModelClassic = function ( file, callback ) {
  286. var Model = function ( ) {
  287. var scope = this;
  288. scope.materials = [];
  289. THREE.Geometry.call( this );
  290. var normals = [],
  291. uvs = [],
  292. colors = [];
  293. init_vertices( file.body.vertices );
  294. if ( file.body.normals !== undefined )
  295. init_normals( file.body.normals );
  296. if ( file.body.uvMaps !== undefined && file.body.uvMaps.length > 0 )
  297. init_uvs( file.body.uvMaps[ 0 ].uv );
  298. if ( file.body.attrMaps !== undefined && file.body.attrMaps.length > 0 && file.body.attrMaps[ 0 ].name === "Color" )
  299. init_colors( file.body.attrMaps[ 0 ].attr );
  300. var hasNormals = normals.length > 0 ? true : false,
  301. hasUvs = uvs.length > 0 ? true : false,
  302. hasColors = colors.length > 0 ? true : false;
  303. init_faces( file.body.indices );
  304. this.computeCentroids();
  305. this.computeFaceNormals();
  306. //this.computeTangents();
  307. function init_vertices( buffer ) {
  308. var x, y, z, i, il = buffer.length;
  309. for( i = 0; i < il; i += 3 ) {
  310. x = buffer[ i ];
  311. y = buffer[ i + 1 ];
  312. z = buffer[ i + 2 ];
  313. vertex( scope, x, y, z );
  314. }
  315. };
  316. function init_normals( buffer ) {
  317. var x, y, z, i, il = buffer.length;
  318. for( i = 0; i < il; i += 3 ) {
  319. x = buffer[ i ];
  320. y = buffer[ i + 1 ];
  321. z = buffer[ i + 2 ];
  322. normals.push( x, y, z );
  323. }
  324. };
  325. function init_colors( buffer ) {
  326. var r, g, b, a, i, il = buffer.length;
  327. for( i = 0; i < il; i += 4 ) {
  328. r = buffer[ i ];
  329. g = buffer[ i + 1 ];
  330. b = buffer[ i + 2 ];
  331. a = buffer[ i + 3 ];
  332. var color = new THREE.Color();
  333. color.setRGB( r, g, b );
  334. colors.push( color );
  335. }
  336. };
  337. function init_uvs( buffer ) {
  338. var u, v, i, il = buffer.length;
  339. for( i = 0; i < il; i += 2 ) {
  340. u = buffer[ i ];
  341. v = buffer[ i + 1 ];
  342. uvs.push( u, v );
  343. }
  344. };
  345. function init_faces( buffer ) {
  346. var a, b, c,
  347. u1, v1, u2, v2, u3, v3,
  348. m, face,
  349. i, il = buffer.length;
  350. m = 0; // all faces defaulting to material 0
  351. for( i = 0; i < il; i += 3 ) {
  352. a = buffer[ i ];
  353. b = buffer[ i + 1 ];
  354. c = buffer[ i + 2 ];
  355. if ( hasNormals ){
  356. face = f3n( scope, normals, a, b, c, m, a, b, c );
  357. } else {
  358. face = f3( scope, a, b, c, m );
  359. }
  360. if ( hasColors ) {
  361. face.vertexColors[ 0 ] = colors[ a ];
  362. face.vertexColors[ 1 ] = colors[ b ];
  363. face.vertexColors[ 2 ] = colors[ c ];
  364. }
  365. if ( hasUvs ) {
  366. u1 = uvs[ a * 2 ];
  367. v1 = uvs[ a * 2 + 1 ];
  368. u2 = uvs[ b * 2 ];
  369. v2 = uvs[ b * 2 + 1 ];
  370. u3 = uvs[ c * 2 ];
  371. v3 = uvs[ c * 2 + 1 ];
  372. uv3( scope.faceVertexUvs[ 0 ], u1, v1, u2, v2, u3, v3 );
  373. }
  374. }
  375. }
  376. };
  377. function vertex ( scope, x, y, z ) {
  378. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  379. };
  380. function f3 ( scope, a, b, c, mi ) {
  381. var face = new THREE.Face3( a, b, c, null, null, mi );
  382. scope.faces.push( face );
  383. return face;
  384. };
  385. function f3n ( scope, normals, a, b, c, mi, nai, nbi, nci ) {
  386. var nax = normals[ nai * 3 ],
  387. nay = normals[ nai * 3 + 1 ],
  388. naz = normals[ nai * 3 + 2 ],
  389. nbx = normals[ nbi * 3 ],
  390. nby = normals[ nbi * 3 + 1 ],
  391. nbz = normals[ nbi * 3 + 2 ],
  392. ncx = normals[ nci * 3 ],
  393. ncy = normals[ nci * 3 + 1 ],
  394. ncz = normals[ nci * 3 + 2 ];
  395. var na = new THREE.Vector3( nax, nay, naz ),
  396. nb = new THREE.Vector3( nbx, nby, nbz ),
  397. nc = new THREE.Vector3( ncx, ncy, ncz );
  398. var face = new THREE.Face3( a, b, c, [ na, nb, nc ], null, mi );
  399. scope.faces.push( face );
  400. return face;
  401. };
  402. function uv3 ( where, u1, v1, u2, v2, u3, v3 ) {
  403. var uv = [];
  404. uv.push( new THREE.Vector2( u1, v1 ) );
  405. uv.push( new THREE.Vector2( u2, v2 ) );
  406. uv.push( new THREE.Vector2( u3, v3 ) );
  407. where.push( uv );
  408. };
  409. Model.prototype = Object.create( THREE.Geometry.prototype );
  410. callback( new Model() );
  411. };