GeometryCompressionUtils.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  1. ( function () {
  2. /**
  3. * Octahedron and Quantization encodings based on work by:
  4. *
  5. * @link https://github.com/tsherif/mesh-quantization-example
  6. *
  7. */
  8. /**
  9. * Make the input mesh.geometry's normal attribute encoded and compressed by 3 different methods.
  10. * Also will change the mesh.material to `PackedPhongMaterial` which let the vertex shader program decode the normal data.
  11. *
  12. * @param {THREE.Mesh} mesh
  13. * @param {String} encodeMethod "DEFAULT" || "OCT1Byte" || "OCT2Byte" || "ANGLES"
  14. *
  15. */
  16. function compressNormals( mesh, encodeMethod ) {
  17. if ( ! mesh.geometry ) {
  18. console.error( 'Mesh must contain geometry. ' );
  19. }
  20. const normal = mesh.geometry.attributes.normal;
  21. if ( ! normal ) {
  22. console.error( 'Geometry must contain normal attribute. ' );
  23. }
  24. if ( normal.isPacked ) return;
  25. if ( normal.itemSize != 3 ) {
  26. console.error( 'normal.itemSize is not 3, which cannot be encoded. ' );
  27. }
  28. const array = normal.array;
  29. const count = normal.count;
  30. let result;
  31. if ( encodeMethod == 'DEFAULT' ) {
  32. // TODO: Add 1 byte to the result, making the encoded length to be 4 bytes.
  33. result = new Uint8Array( count * 3 );
  34. for ( let idx = 0; idx < array.length; idx += 3 ) {
  35. const encoded = defaultEncode( array[ idx ], array[ idx + 1 ], array[ idx + 2 ], 1 );
  36. result[ idx + 0 ] = encoded[ 0 ];
  37. result[ idx + 1 ] = encoded[ 1 ];
  38. result[ idx + 2 ] = encoded[ 2 ];
  39. }
  40. mesh.geometry.setAttribute( 'normal', new THREE.BufferAttribute( result, 3, true ) );
  41. mesh.geometry.attributes.normal.bytes = result.length * 1;
  42. } else if ( encodeMethod == 'OCT1Byte' ) {
  43. /**
  44. * It is not recommended to use 1-byte octahedron normals encoding unless you want to extremely reduce the memory usage
  45. * As it makes vertex data not aligned to a 4 byte boundary which may harm some WebGL implementations and sometimes the normal distortion is visible
  46. * Please refer to @zeux 's comments in https://github.com/mrdoob/three.js/pull/18208
  47. */
  48. result = new Int8Array( count * 2 );
  49. for ( let idx = 0; idx < array.length; idx += 3 ) {
  50. const encoded = octEncodeBest( array[ idx ], array[ idx + 1 ], array[ idx + 2 ], 1 );
  51. result[ idx / 3 * 2 + 0 ] = encoded[ 0 ];
  52. result[ idx / 3 * 2 + 1 ] = encoded[ 1 ];
  53. }
  54. mesh.geometry.setAttribute( 'normal', new THREE.BufferAttribute( result, 2, true ) );
  55. mesh.geometry.attributes.normal.bytes = result.length * 1;
  56. } else if ( encodeMethod == 'OCT2Byte' ) {
  57. result = new Int16Array( count * 2 );
  58. for ( let idx = 0; idx < array.length; idx += 3 ) {
  59. const encoded = octEncodeBest( array[ idx ], array[ idx + 1 ], array[ idx + 2 ], 2 );
  60. result[ idx / 3 * 2 + 0 ] = encoded[ 0 ];
  61. result[ idx / 3 * 2 + 1 ] = encoded[ 1 ];
  62. }
  63. mesh.geometry.setAttribute( 'normal', new THREE.BufferAttribute( result, 2, true ) );
  64. mesh.geometry.attributes.normal.bytes = result.length * 2;
  65. } else if ( encodeMethod == 'ANGLES' ) {
  66. result = new Uint16Array( count * 2 );
  67. for ( let idx = 0; idx < array.length; idx += 3 ) {
  68. const encoded = anglesEncode( array[ idx ], array[ idx + 1 ], array[ idx + 2 ] );
  69. result[ idx / 3 * 2 + 0 ] = encoded[ 0 ];
  70. result[ idx / 3 * 2 + 1 ] = encoded[ 1 ];
  71. }
  72. mesh.geometry.setAttribute( 'normal', new THREE.BufferAttribute( result, 2, true ) );
  73. mesh.geometry.attributes.normal.bytes = result.length * 2;
  74. } else {
  75. console.error( 'Unrecognized encoding method, should be `DEFAULT` or `ANGLES` or `OCT`. ' );
  76. }
  77. mesh.geometry.attributes.normal.needsUpdate = true;
  78. mesh.geometry.attributes.normal.isPacked = true;
  79. mesh.geometry.attributes.normal.packingMethod = encodeMethod; // modify material
  80. if ( ! ( mesh.material instanceof THREE.PackedPhongMaterial ) ) {
  81. mesh.material = new THREE.PackedPhongMaterial().copy( mesh.material );
  82. }
  83. if ( encodeMethod == 'ANGLES' ) {
  84. mesh.material.defines.USE_PACKED_NORMAL = 0;
  85. }
  86. if ( encodeMethod == 'OCT1Byte' ) {
  87. mesh.material.defines.USE_PACKED_NORMAL = 1;
  88. }
  89. if ( encodeMethod == 'OCT2Byte' ) {
  90. mesh.material.defines.USE_PACKED_NORMAL = 1;
  91. }
  92. if ( encodeMethod == 'DEFAULT' ) {
  93. mesh.material.defines.USE_PACKED_NORMAL = 2;
  94. }
  95. }
  96. /**
  97. * Make the input mesh.geometry's position attribute encoded and compressed.
  98. * Also will change the mesh.material to `PackedPhongMaterial` which let the vertex shader program decode the position data.
  99. *
  100. * @param {THREE.Mesh} mesh
  101. *
  102. */
  103. function compressPositions( mesh ) {
  104. if ( ! mesh.geometry ) {
  105. console.error( 'Mesh must contain geometry. ' );
  106. }
  107. const position = mesh.geometry.attributes.position;
  108. if ( ! position ) {
  109. console.error( 'Geometry must contain position attribute. ' );
  110. }
  111. if ( position.isPacked ) return;
  112. if ( position.itemSize != 3 ) {
  113. console.error( 'position.itemSize is not 3, which cannot be packed. ' );
  114. }
  115. const array = position.array;
  116. const encodingBytes = 2;
  117. const result = quantizedEncode( array, encodingBytes );
  118. const quantized = result.quantized;
  119. const decodeMat = result.decodeMat; // IMPORTANT: calculate original geometry bounding info first, before updating packed positions
  120. if ( mesh.geometry.boundingBox == null ) mesh.geometry.computeBoundingBox();
  121. if ( mesh.geometry.boundingSphere == null ) mesh.geometry.computeBoundingSphere();
  122. mesh.geometry.setAttribute( 'position', new THREE.BufferAttribute( quantized, 3 ) );
  123. mesh.geometry.attributes.position.isPacked = true;
  124. mesh.geometry.attributes.position.needsUpdate = true;
  125. mesh.geometry.attributes.position.bytes = quantized.length * encodingBytes; // modify material
  126. if ( ! ( mesh.material instanceof THREE.PackedPhongMaterial ) ) {
  127. mesh.material = new THREE.PackedPhongMaterial().copy( mesh.material );
  128. }
  129. mesh.material.defines.USE_PACKED_POSITION = 0;
  130. mesh.material.uniforms.quantizeMatPos.value = decodeMat;
  131. mesh.material.uniforms.quantizeMatPos.needsUpdate = true;
  132. }
  133. /**
  134. * Make the input mesh.geometry's uv attribute encoded and compressed.
  135. * Also will change the mesh.material to `PackedPhongMaterial` which let the vertex shader program decode the uv data.
  136. *
  137. * @param {THREE.Mesh} mesh
  138. *
  139. */
  140. function compressUvs( mesh ) {
  141. if ( ! mesh.geometry ) {
  142. console.error( 'Mesh must contain geometry property. ' );
  143. }
  144. const uvs = mesh.geometry.attributes.uv;
  145. if ( ! uvs ) {
  146. console.error( 'Geometry must contain uv attribute. ' );
  147. }
  148. if ( uvs.isPacked ) return;
  149. const range = {
  150. min: Infinity,
  151. max: - Infinity
  152. };
  153. const array = uvs.array;
  154. for ( let i = 0; i < array.length; i ++ ) {
  155. range.min = Math.min( range.min, array[ i ] );
  156. range.max = Math.max( range.max, array[ i ] );
  157. }
  158. let result;
  159. if ( range.min >= - 1.0 && range.max <= 1.0 ) {
  160. // use default encoding method
  161. result = new Uint16Array( array.length );
  162. for ( let i = 0; i < array.length; i += 2 ) {
  163. const encoded = defaultEncode( array[ i ], array[ i + 1 ], 0, 2 );
  164. result[ i ] = encoded[ 0 ];
  165. result[ i + 1 ] = encoded[ 1 ];
  166. }
  167. mesh.geometry.setAttribute( 'uv', new THREE.BufferAttribute( result, 2, true ) );
  168. mesh.geometry.attributes.uv.isPacked = true;
  169. mesh.geometry.attributes.uv.needsUpdate = true;
  170. mesh.geometry.attributes.uv.bytes = result.length * 2;
  171. if ( ! ( mesh.material instanceof THREE.PackedPhongMaterial ) ) {
  172. mesh.material = new THREE.PackedPhongMaterial().copy( mesh.material );
  173. }
  174. mesh.material.defines.USE_PACKED_UV = 0;
  175. } else {
  176. // use quantized encoding method
  177. result = quantizedEncodeUV( array, 2 );
  178. mesh.geometry.setAttribute( 'uv', new THREE.BufferAttribute( result.quantized, 2 ) );
  179. mesh.geometry.attributes.uv.isPacked = true;
  180. mesh.geometry.attributes.uv.needsUpdate = true;
  181. mesh.geometry.attributes.uv.bytes = result.quantized.length * 2;
  182. if ( ! ( mesh.material instanceof THREE.PackedPhongMaterial ) ) {
  183. mesh.material = new THREE.PackedPhongMaterial().copy( mesh.material );
  184. }
  185. mesh.material.defines.USE_PACKED_UV = 1;
  186. mesh.material.uniforms.quantizeMatUV.value = result.decodeMat;
  187. mesh.material.uniforms.quantizeMatUV.needsUpdate = true;
  188. }
  189. } // Encoding functions
  190. function defaultEncode( x, y, z, bytes ) {
  191. if ( bytes == 1 ) {
  192. const tmpx = Math.round( ( x + 1 ) * 0.5 * 255 );
  193. const tmpy = Math.round( ( y + 1 ) * 0.5 * 255 );
  194. const tmpz = Math.round( ( z + 1 ) * 0.5 * 255 );
  195. return new Uint8Array( [ tmpx, tmpy, tmpz ] );
  196. } else if ( bytes == 2 ) {
  197. const tmpx = Math.round( ( x + 1 ) * 0.5 * 65535 );
  198. const tmpy = Math.round( ( y + 1 ) * 0.5 * 65535 );
  199. const tmpz = Math.round( ( z + 1 ) * 0.5 * 65535 );
  200. return new Uint16Array( [ tmpx, tmpy, tmpz ] );
  201. } else {
  202. console.error( 'number of bytes must be 1 or 2' );
  203. }
  204. } // for `Angles` encoding
  205. function anglesEncode( x, y, z ) {
  206. const normal0 = parseInt( 0.5 * ( 1.0 + Math.atan2( y, x ) / Math.PI ) * 65535 );
  207. const normal1 = parseInt( 0.5 * ( 1.0 + z ) * 65535 );
  208. return new Uint16Array( [ normal0, normal1 ] );
  209. } // for `Octahedron` encoding
  210. function octEncodeBest( x, y, z, bytes ) {
  211. let oct, dec, best, currentCos, bestCos; // Test various combinations of ceil and floor
  212. // to minimize rounding errors
  213. best = oct = octEncodeVec3( x, y, z, 'floor', 'floor' );
  214. dec = octDecodeVec2( oct );
  215. bestCos = dot( x, y, z, dec );
  216. oct = octEncodeVec3( x, y, z, 'ceil', 'floor' );
  217. dec = octDecodeVec2( oct );
  218. currentCos = dot( x, y, z, dec );
  219. if ( currentCos > bestCos ) {
  220. best = oct;
  221. bestCos = currentCos;
  222. }
  223. oct = octEncodeVec3( x, y, z, 'floor', 'ceil' );
  224. dec = octDecodeVec2( oct );
  225. currentCos = dot( x, y, z, dec );
  226. if ( currentCos > bestCos ) {
  227. best = oct;
  228. bestCos = currentCos;
  229. }
  230. oct = octEncodeVec3( x, y, z, 'ceil', 'ceil' );
  231. dec = octDecodeVec2( oct );
  232. currentCos = dot( x, y, z, dec );
  233. if ( currentCos > bestCos ) {
  234. best = oct;
  235. }
  236. return best;
  237. function octEncodeVec3( x0, y0, z0, xfunc, yfunc ) {
  238. let x = x0 / ( Math.abs( x0 ) + Math.abs( y0 ) + Math.abs( z0 ) );
  239. let y = y0 / ( Math.abs( x0 ) + Math.abs( y0 ) + Math.abs( z0 ) );
  240. if ( z < 0 ) {
  241. const tempx = ( 1 - Math.abs( y ) ) * ( x >= 0 ? 1 : - 1 );
  242. const tempy = ( 1 - Math.abs( x ) ) * ( y >= 0 ? 1 : - 1 );
  243. x = tempx;
  244. y = tempy;
  245. let diff = 1 - Math.abs( x ) - Math.abs( y );
  246. if ( diff > 0 ) {
  247. diff += 0.001;
  248. x += x > 0 ? diff / 2 : - diff / 2;
  249. y += y > 0 ? diff / 2 : - diff / 2;
  250. }
  251. }
  252. if ( bytes == 1 ) {
  253. return new Int8Array( [ Math[ xfunc ]( x * 127.5 + ( x < 0 ? 1 : 0 ) ), Math[ yfunc ]( y * 127.5 + ( y < 0 ? 1 : 0 ) ) ] );
  254. }
  255. if ( bytes == 2 ) {
  256. return new Int16Array( [ Math[ xfunc ]( x * 32767.5 + ( x < 0 ? 1 : 0 ) ), Math[ yfunc ]( y * 32767.5 + ( y < 0 ? 1 : 0 ) ) ] );
  257. }
  258. }
  259. function octDecodeVec2( oct ) {
  260. let x = oct[ 0 ];
  261. let y = oct[ 1 ];
  262. if ( bytes == 1 ) {
  263. x /= x < 0 ? 127 : 128;
  264. y /= y < 0 ? 127 : 128;
  265. } else if ( bytes == 2 ) {
  266. x /= x < 0 ? 32767 : 32768;
  267. y /= y < 0 ? 32767 : 32768;
  268. }
  269. const z = 1 - Math.abs( x ) - Math.abs( y );
  270. if ( z < 0 ) {
  271. const tmpx = x;
  272. x = ( 1 - Math.abs( y ) ) * ( x >= 0 ? 1 : - 1 );
  273. y = ( 1 - Math.abs( tmpx ) ) * ( y >= 0 ? 1 : - 1 );
  274. }
  275. const length = Math.sqrt( x * x + y * y + z * z );
  276. return [ x / length, y / length, z / length ];
  277. }
  278. function dot( x, y, z, vec3 ) {
  279. return x * vec3[ 0 ] + y * vec3[ 1 ] + z * vec3[ 2 ];
  280. }
  281. }
  282. function quantizedEncode( array, bytes ) {
  283. let quantized, segments;
  284. if ( bytes == 1 ) {
  285. quantized = new Uint8Array( array.length );
  286. segments = 255;
  287. } else if ( bytes == 2 ) {
  288. quantized = new Uint16Array( array.length );
  289. segments = 65535;
  290. } else {
  291. console.error( 'number of bytes error! ' );
  292. }
  293. const decodeMat = new THREE.Matrix4();
  294. const min = new Float32Array( 3 );
  295. const max = new Float32Array( 3 );
  296. min[ 0 ] = min[ 1 ] = min[ 2 ] = Number.MAX_VALUE;
  297. max[ 0 ] = max[ 1 ] = max[ 2 ] = - Number.MAX_VALUE;
  298. for ( let i = 0; i < array.length; i += 3 ) {
  299. min[ 0 ] = Math.min( min[ 0 ], array[ i + 0 ] );
  300. min[ 1 ] = Math.min( min[ 1 ], array[ i + 1 ] );
  301. min[ 2 ] = Math.min( min[ 2 ], array[ i + 2 ] );
  302. max[ 0 ] = Math.max( max[ 0 ], array[ i + 0 ] );
  303. max[ 1 ] = Math.max( max[ 1 ], array[ i + 1 ] );
  304. max[ 2 ] = Math.max( max[ 2 ], array[ i + 2 ] );
  305. }
  306. decodeMat.scale( new THREE.Vector3( ( max[ 0 ] - min[ 0 ] ) / segments, ( max[ 1 ] - min[ 1 ] ) / segments, ( max[ 2 ] - min[ 2 ] ) / segments ) );
  307. decodeMat.elements[ 12 ] = min[ 0 ];
  308. decodeMat.elements[ 13 ] = min[ 1 ];
  309. decodeMat.elements[ 14 ] = min[ 2 ];
  310. decodeMat.transpose();
  311. const multiplier = new Float32Array( [ max[ 0 ] !== min[ 0 ] ? segments / ( max[ 0 ] - min[ 0 ] ) : 0, max[ 1 ] !== min[ 1 ] ? segments / ( max[ 1 ] - min[ 1 ] ) : 0, max[ 2 ] !== min[ 2 ] ? segments / ( max[ 2 ] - min[ 2 ] ) : 0 ] );
  312. for ( let i = 0; i < array.length; i += 3 ) {
  313. quantized[ i + 0 ] = Math.floor( ( array[ i + 0 ] - min[ 0 ] ) * multiplier[ 0 ] );
  314. quantized[ i + 1 ] = Math.floor( ( array[ i + 1 ] - min[ 1 ] ) * multiplier[ 1 ] );
  315. quantized[ i + 2 ] = Math.floor( ( array[ i + 2 ] - min[ 2 ] ) * multiplier[ 2 ] );
  316. }
  317. return {
  318. quantized: quantized,
  319. decodeMat: decodeMat
  320. };
  321. }
  322. function quantizedEncodeUV( array, bytes ) {
  323. let quantized, segments;
  324. if ( bytes == 1 ) {
  325. quantized = new Uint8Array( array.length );
  326. segments = 255;
  327. } else if ( bytes == 2 ) {
  328. quantized = new Uint16Array( array.length );
  329. segments = 65535;
  330. } else {
  331. console.error( 'number of bytes error! ' );
  332. }
  333. const decodeMat = new THREE.Matrix3();
  334. const min = new Float32Array( 2 );
  335. const max = new Float32Array( 2 );
  336. min[ 0 ] = min[ 1 ] = Number.MAX_VALUE;
  337. max[ 0 ] = max[ 1 ] = - Number.MAX_VALUE;
  338. for ( let i = 0; i < array.length; i += 2 ) {
  339. min[ 0 ] = Math.min( min[ 0 ], array[ i + 0 ] );
  340. min[ 1 ] = Math.min( min[ 1 ], array[ i + 1 ] );
  341. max[ 0 ] = Math.max( max[ 0 ], array[ i + 0 ] );
  342. max[ 1 ] = Math.max( max[ 1 ], array[ i + 1 ] );
  343. }
  344. decodeMat.scale( ( max[ 0 ] - min[ 0 ] ) / segments, ( max[ 1 ] - min[ 1 ] ) / segments );
  345. decodeMat.elements[ 6 ] = min[ 0 ];
  346. decodeMat.elements[ 7 ] = min[ 1 ];
  347. decodeMat.transpose();
  348. const multiplier = new Float32Array( [ max[ 0 ] !== min[ 0 ] ? segments / ( max[ 0 ] - min[ 0 ] ) : 0, max[ 1 ] !== min[ 1 ] ? segments / ( max[ 1 ] - min[ 1 ] ) : 0 ] );
  349. for ( let i = 0; i < array.length; i += 2 ) {
  350. quantized[ i + 0 ] = Math.floor( ( array[ i + 0 ] - min[ 0 ] ) * multiplier[ 0 ] );
  351. quantized[ i + 1 ] = Math.floor( ( array[ i + 1 ] - min[ 1 ] ) * multiplier[ 1 ] );
  352. }
  353. return {
  354. quantized: quantized,
  355. decodeMat: decodeMat
  356. };
  357. }
  358. THREE.GeometryCompressionUtils = {};
  359. THREE.GeometryCompressionUtils.compressNormals = compressNormals;
  360. THREE.GeometryCompressionUtils.compressPositions = compressPositions;
  361. THREE.GeometryCompressionUtils.compressUvs = compressUvs;
  362. } )();