GeometryPackingUtils.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  1. /**
  2. * @author YY
  3. */
  4. import * as THREE from "../../../build/three.module.js";
  5. var GeometryPackingUtils = {
  6. packNormals: function (mesh, encodeMethod) {
  7. if (!mesh.geometry) {
  8. console.error("Mesh must contain geometry property. ");
  9. }
  10. let normal = mesh.geometry.attributes.normal;
  11. if (!normal) {
  12. console.error("Geometry must contain normal attribute. ");
  13. }
  14. if (normal.isPacked) return;
  15. if (normal.itemSize != 3) {
  16. console.error("normal.itemSize is not 3, which cannot be packed. ");
  17. }
  18. let array = normal.array;
  19. let count = normal.count;
  20. let result;
  21. if (encodeMethod == "BASIC") {
  22. result = new Uint16Array(count * 2);
  23. for (let idx = 0; idx < array.length; idx += 3) {
  24. let encoded;
  25. encoded = uInt16Encode(array[idx], array[idx + 1], array[idx + 2]);
  26. result[idx / 3 * 2 + 0] = encoded[0];
  27. result[idx / 3 * 2 + 1] = encoded[1];
  28. }
  29. } else if (encodeMethod == "OCT") {
  30. result = new Int8Array(count * 2);
  31. var oct, dec, best, currentCos, bestCos;
  32. for (let idx = 0; idx < array.length; idx += 3) {
  33. let encoded;
  34. encoded = octEncodeBest(array[idx], array[idx + 1], array[idx + 2]);
  35. result[idx / 3 * 2 + 0] = encoded[0];
  36. result[idx / 3 * 2 + 1] = encoded[1];
  37. }
  38. } else {
  39. console.error("Unrecognized encoding method, should be `BASIC` or `OCT`. ");
  40. }
  41. mesh.geometry.setAttribute('normal', new THREE.BufferAttribute(result, 2, true));
  42. mesh.geometry.attributes.normal.needsUpdate = true;
  43. mesh.geometry.attributes.normal.isPacked = true;
  44. mesh.geometry.attributes.normal.packingMethod = encodeMethod;
  45. // modify material
  46. if (!(mesh.material instanceof PackedPhongMaterial)) {
  47. mesh.material = new PackedPhongMaterial().copy(mesh.material);
  48. }
  49. if (encodeMethod == "BASIC") {
  50. mesh.material.defines.USE_PACKED_NORMAL = 0;
  51. }
  52. if (encodeMethod == "OCT") {
  53. mesh.material.defines.USE_PACKED_NORMAL = 1;
  54. }
  55. /**
  56. *
  57. * Encoding functions: Basic, OCT
  58. *
  59. */
  60. // for `Basic` encoding
  61. function uInt16Encode(x, y, z) {
  62. let normal0 = parseInt(0.5 * (1.0 + Math.atan2(y, x) / Math.PI) * 65535);
  63. let normal1 = parseInt(0.5 * (1.0 + z) * 65535);
  64. return new Uint16Array([normal0, normal1]);
  65. }
  66. // for `OCT` encoding
  67. function octEncodeBest(x, y, z) {
  68. // Test various combinations of ceil and floor
  69. // to minimize rounding errors
  70. best = oct = octEncodeVec3(x, y, z, "floor", "floor");
  71. dec = octDecodeVec2(oct);
  72. currentCos = bestCos = dot(x, y, z, dec);
  73. oct = octEncodeVec3(x, y, z, "ceil", "floor");
  74. dec = octDecodeVec2(oct);
  75. currentCos = dot(x, y, z, dec);
  76. if (currentCos > bestCos) {
  77. best = oct;
  78. bestCos = currentCos;
  79. }
  80. oct = octEncodeVec3(x, y, z, "floor", "ceil");
  81. dec = octDecodeVec2(oct);
  82. currentCos = dot(x, y, z, dec);
  83. if (currentCos > bestCos) {
  84. best = oct;
  85. bestCos = currentCos;
  86. }
  87. oct = octEncodeVec3(x, y, z, "ceil", "ceil");
  88. dec = octDecodeVec2(oct);
  89. currentCos = dot(x, y, z, dec);
  90. if (currentCos > bestCos) {
  91. best = oct;
  92. bestCos = currentCos;
  93. }
  94. var angle = Math.acos(bestCos) * 180 / Math.PI;
  95. if (angle > 10){
  96. console.log(angle)
  97. oct = octEncodeVec3(x, y, z, "floor", "floor"); dec = octDecodeVec2(oct);
  98. console.log([x, y, z], octDecodeVec2(octEncodeVec3(x, y, z, "floor", "floor")))
  99. console.log([x, y, z], octDecodeVec2(octEncodeVec3(x, y, z, "ceil", "floor")))
  100. console.log([x, y, z], octDecodeVec2(octEncodeVec3(x, y, z, "floor", "ceil")))
  101. console.log([x, y, z], octDecodeVec2(octEncodeVec3(x, y, z, "ceil", "ceil")))
  102. }
  103. return best;
  104. }
  105. function octEncodeVec3(x, y, z, xfunc, yfunc) {
  106. var x = x / (Math.abs(x) + Math.abs(y) + Math.abs(z));
  107. var y = y / (Math.abs(x) + Math.abs(y) + Math.abs(z));
  108. if (z < 0) {
  109. var tempx = x;
  110. var tempy = y;
  111. tempx = (1 - Math.abs(y)) * (x >= 0 ? 1 : -1);
  112. tempy = (1 - Math.abs(x)) * (y >= 0 ? 1 : -1);
  113. x = tempx;
  114. y = tempy;
  115. }
  116. return new Int8Array([
  117. Math[xfunc](x * 127.5 + (x < 0 ? 1 : 0)),
  118. Math[yfunc](y * 127.5 + (y < 0 ? 1 : 0))
  119. ]);
  120. }
  121. function octDecodeVec2(oct) {
  122. var x = oct[0];
  123. var y = oct[1];
  124. x /= x < 0 ? 127 : 128;
  125. y /= y < 0 ? 127 : 128;
  126. var z = 1 - Math.abs(x) - Math.abs(y);
  127. if (z < 0) {
  128. var tmpx = x;
  129. x = (1 - Math.abs(y)) * (x >= 0 ? 1 : -1);
  130. y = (1 - Math.abs(tmpx)) * (y >= 0 ? 1 : -1);
  131. }
  132. var length = Math.sqrt(x * x + y * y + z * z);
  133. return [
  134. x / length,
  135. y / length,
  136. z / length
  137. ];
  138. }
  139. function dot(x, y, z, vec3) {
  140. return x * vec3[0] + y * vec3[1] + z * vec3[2];
  141. }
  142. },
  143. packPositions: function (mesh) {
  144. if (!mesh.geometry) {
  145. console.error("Mesh must contain geometry property. ");
  146. }
  147. let position = mesh.geometry.attributes.position;
  148. if (!position) {
  149. console.error("Geometry must contain position attribute. ");
  150. }
  151. if (position.isPacked) return;
  152. if (position.itemSize != 3) {
  153. console.error("position.itemSize is not 3, which cannot be packed. ");
  154. }
  155. let array = position.array;
  156. let count = position.count;
  157. let quantized = new Uint16Array(array.length);
  158. let decodeMat4 = new THREE.Matrix4();
  159. let min = new Float32Array(3);
  160. let max = new Float32Array(3);
  161. min[0] = min[1] = min[2] = Number.MAX_VALUE;
  162. max[0] = max[1] = max[2] = -Number.MAX_VALUE;
  163. for (let i = 0; i < array.length; i += 3) {
  164. min[0] = Math.min(min[0], array[i + 0]);
  165. min[1] = Math.min(min[1], array[i + 1]);
  166. min[2] = Math.min(min[2], array[i + 2]);
  167. max[0] = Math.max(max[0], array[i + 0]);
  168. max[1] = Math.max(max[1], array[i + 1]);
  169. max[2] = Math.max(max[2], array[i + 2]);
  170. }
  171. decodeMat4.scale(new THREE.Vector3(
  172. (max[0] - min[0]) / 65535,
  173. (max[1] - min[1]) / 65535,
  174. (max[2] - min[2]) / 65535
  175. ));
  176. decodeMat4.elements[12] = min[0];
  177. decodeMat4.elements[13] = min[1];
  178. decodeMat4.elements[14] = min[2];
  179. decodeMat4.transpose();
  180. let multiplier = new Float32Array([
  181. max[0] !== min[0] ? 65535 / (max[0] - min[0]) : 0,
  182. max[1] !== min[1] ? 65535 / (max[1] - min[1]) : 0,
  183. max[2] !== min[2] ? 65535 / (max[2] - min[2]) : 0
  184. ]);
  185. for (let i = 0; i < array.length; i += 3) {
  186. quantized[i + 0] = Math.floor((array[i + 0] - min[0]) * multiplier[0]);
  187. quantized[i + 1] = Math.floor((array[i + 1] - min[1]) * multiplier[1]);
  188. quantized[i + 2] = Math.floor((array[i + 2] - min[2]) * multiplier[2]);
  189. }
  190. // IMPORTANT: calculate original geometry bounding info first, before updating packed positions
  191. if (mesh.geometry.boundingBox == null) mesh.geometry.computeBoundingBox();
  192. if (mesh.geometry.boundingSphere == null) mesh.geometry.computeBoundingSphere();
  193. mesh.geometry.setAttribute('position', new THREE.BufferAttribute(quantized, 3));
  194. mesh.geometry.attributes.position.isPacked = true;
  195. mesh.geometry.attributes.position.needsUpdate = true;
  196. // modify material
  197. if (!(mesh.material instanceof PackedPhongMaterial)) {
  198. mesh.material = new PackedPhongMaterial().copy(mesh.material);
  199. }
  200. mesh.material.defines.USE_PACKED_POSITION = 0;
  201. mesh.material.uniforms.quantizeMat.value = decodeMat4;
  202. mesh.material.uniforms.quantizeMat.needsUpdate = true;
  203. },
  204. changeShaderChunk: function () {
  205. THREE.ShaderChunk.beginnormal_vertex = `
  206. vec3 objectNormal = vec3( normal );
  207. #ifdef USE_TANGENT
  208. vec3 objectTangent = vec3( tangent.xyz );
  209. #endif
  210. #ifdef USE_PACKED_NORMAL
  211. #ifdef USE_PACKED_NORMAL == 0 // basicEncode
  212. float x = objectNormal.x * 2.0 - 1.0;
  213. float y = objectNormal.y * 2.0 - 1.0;
  214. vec2 scth = vec2(sin(x * PI), cos(x * PI));
  215. vec2 scphi = vec2(sqrt(1.0 - y * y), y);
  216. objectNormal = normalize( vec3(scth.y * scphi.x, scth.x * scphi.x, scphi.y) );
  217. #endif
  218. #ifdef USE_PACKED_NORMAL == 1 // octEncode
  219. vec3 v = vec3(objectNormal.xy, 1.0 - abs(objectNormal.x) - abs(objectNormal.y));
  220. if (v.z < 0.0)
  221. {
  222. v.xy = (1.0 - abs(v.yx)) * vec2((v.x >= 0.0) ? +1.0 : -1.0, (v.y >= 0.0) ? +1.0 : -1.0);
  223. }
  224. objectNormal = normalize(v);
  225. #endif
  226. #endif
  227. `;
  228. }
  229. };
  230. /**
  231. * PackedPhongMaterial inherited from THREE.MeshPhongMaterial
  232. *
  233. * @param {*} parameters
  234. */
  235. function PackedPhongMaterial(parameters) {
  236. THREE.MeshPhongMaterial.call(this);
  237. this.defines = {};
  238. this.type = 'PackedPhongMaterial';
  239. this.uniforms = PackedPhongShader.uniforms;
  240. this.vertexShader = PackedPhongShader.vertexShader;
  241. this.fragmentShader = PackedPhongShader.fragmentShader;
  242. this.setValues(parameters);
  243. }
  244. var PackedPhongShader = {
  245. uniforms: THREE.UniformsUtils.merge([
  246. THREE.ShaderLib.phong.uniforms,
  247. {
  248. quantizeMat: { value: null }
  249. }
  250. ]),
  251. vertexShader: [
  252. "#define PHONG",
  253. "varying vec3 vViewPosition;",
  254. "#ifndef FLAT_SHADED",
  255. "varying vec3 vNormal;",
  256. "#endif",
  257. THREE.ShaderChunk.common,
  258. THREE.ShaderChunk.uv_pars_vertex,
  259. THREE.ShaderChunk.uv2_pars_vertex,
  260. THREE.ShaderChunk.displacementmap_pars_vertex,
  261. THREE.ShaderChunk.envmap_pars_vertex,
  262. THREE.ShaderChunk.color_pars_vertex,
  263. THREE.ShaderChunk.fog_pars_vertex,
  264. THREE.ShaderChunk.morphtarget_pars_vertex,
  265. THREE.ShaderChunk.skinning_pars_vertex,
  266. THREE.ShaderChunk.shadowmap_pars_vertex,
  267. THREE.ShaderChunk.logdepthbuf_pars_vertex,
  268. THREE.ShaderChunk.clipping_planes_pars_vertex,
  269. `#ifdef USE_PACKED_NORMAL
  270. vec3 basicDecode(vec3 packedNormal)
  271. {
  272. float x = packedNormal.x * 2.0 - 1.0;
  273. float y = packedNormal.y * 2.0 - 1.0;
  274. vec2 scth = vec2(sin(x * PI), cos(x * PI));
  275. vec2 scphi = vec2(sqrt(1.0 - y * y), y);
  276. return normalize( vec3(scth.y * scphi.x, scth.x * scphi.x, scphi.y) );
  277. }
  278. vec3 octDecode(vec3 packedNormal)
  279. {
  280. vec3 v = vec3(packedNormal.xy, 1.0 - abs(packedNormal.x) - abs(packedNormal.y));
  281. if (v.z < 0.0)
  282. {
  283. v.xy = (1.0 - abs(v.yx)) * vec2((v.x >= 0.0) ? +1.0 : -1.0, (v.y >= 0.0) ? +1.0 : -1.0);
  284. }
  285. return normalize(v);
  286. }
  287. #endif`,
  288. `#ifdef USE_PACKED_POSITION
  289. #if USE_PACKED_POSITION == 0
  290. uniform mat4 quantizeMat;
  291. #endif
  292. #endif`,
  293. "void main() {",
  294. THREE.ShaderChunk.uv_vertex,
  295. THREE.ShaderChunk.uv2_vertex,
  296. THREE.ShaderChunk.color_vertex,
  297. THREE.ShaderChunk.beginnormal_vertex,
  298. `#ifdef USE_PACKED_NORMAL
  299. #if USE_PACKED_NORMAL == 0
  300. objectNormal = basicDecode(objectNormal);
  301. #endif
  302. #if USE_PACKED_NORMAL == 1
  303. objectNormal = octDecode(objectNormal);
  304. #endif
  305. #endif
  306. #ifdef USE_TANGENT
  307. vec3 objectTangent = vec3( tangent.xyz );
  308. #endif
  309. `,
  310. THREE.ShaderChunk.morphnormal_vertex,
  311. THREE.ShaderChunk.skinbase_vertex,
  312. THREE.ShaderChunk.skinnormal_vertex,
  313. THREE.ShaderChunk.defaultnormal_vertex,
  314. "#ifndef FLAT_SHADED",
  315. "vNormal = normalize( transformedNormal );",
  316. "#endif",
  317. THREE.ShaderChunk.begin_vertex,
  318. `#ifdef USE_PACKED_POSITION
  319. #if USE_PACKED_POSITION == 0
  320. transformed = ( vec4(transformed, 1.0) * quantizeMat ).xyz;
  321. #endif
  322. #endif`,
  323. THREE.ShaderChunk.morphtarget_vertex,
  324. THREE.ShaderChunk.skinning_vertex,
  325. THREE.ShaderChunk.displacementmap_vertex,
  326. THREE.ShaderChunk.project_vertex,
  327. THREE.ShaderChunk.logdepthbuf_vertex,
  328. THREE.ShaderChunk.clipping_planes_vertex,
  329. "vViewPosition = - mvPosition.xyz;",
  330. THREE.ShaderChunk.worldpos_vertex,
  331. THREE.ShaderChunk.envmap_vertex,
  332. THREE.ShaderChunk.shadowmap_vertex,
  333. THREE.ShaderChunk.fog_vertex,
  334. "}",
  335. ].join("\n"),
  336. fragmentShader: [
  337. "#define PHONG",
  338. "uniform vec3 diffuse;",
  339. "uniform vec3 emissive;",
  340. "uniform vec3 specular;",
  341. "uniform float shininess;",
  342. "uniform float opacity;",
  343. THREE.ShaderChunk.common,
  344. THREE.ShaderChunk.packing,
  345. THREE.ShaderChunk.dithering_pars_fragment,
  346. THREE.ShaderChunk.color_pars_fragment,
  347. THREE.ShaderChunk.uv_pars_fragment,
  348. THREE.ShaderChunk.uv2_pars_fragment,
  349. THREE.ShaderChunk.map_pars_fragment,
  350. THREE.ShaderChunk.alphamap_pars_fragment,
  351. THREE.ShaderChunk.aomap_pars_fragment,
  352. THREE.ShaderChunk.lightmap_pars_fragment,
  353. THREE.ShaderChunk.emissivemap_pars_fragment,
  354. THREE.ShaderChunk.envmap_common_pars_fragment,
  355. THREE.ShaderChunk.envmap_pars_fragment,
  356. THREE.ShaderChunk.cube_uv_reflection_fragment,
  357. THREE.ShaderChunk.fog_pars_fragment,
  358. THREE.ShaderChunk.bsdfs,
  359. THREE.ShaderChunk.lights_pars_begin,
  360. THREE.ShaderChunk.lights_phong_pars_fragment,
  361. THREE.ShaderChunk.shadowmap_pars_fragment,
  362. THREE.ShaderChunk.bumpmap_pars_fragment,
  363. THREE.ShaderChunk.normalmap_pars_fragment,
  364. THREE.ShaderChunk.specularmap_pars_fragment,
  365. THREE.ShaderChunk.logdepthbuf_pars_fragment,
  366. THREE.ShaderChunk.clipping_planes_pars_fragment,
  367. "void main() {",
  368. THREE.ShaderChunk.clipping_planes_fragment,
  369. "vec4 diffuseColor = vec4( diffuse, opacity );",
  370. "ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );",
  371. "vec3 totalEmissiveRadiance = emissive;",
  372. THREE.ShaderChunk.logdepthbuf_fragment,
  373. THREE.ShaderChunk.map_fragment,
  374. THREE.ShaderChunk.color_fragment,
  375. THREE.ShaderChunk.alphamap_fragment,
  376. THREE.ShaderChunk.alphatest_fragment,
  377. THREE.ShaderChunk.specularmap_fragment,
  378. THREE.ShaderChunk.normal_fragment_begin,
  379. THREE.ShaderChunk.normal_fragment_maps,
  380. THREE.ShaderChunk.emissivemap_fragment,
  381. // accumulation
  382. THREE.ShaderChunk.lights_phong_fragment,
  383. THREE.ShaderChunk.lights_fragment_begin,
  384. THREE.ShaderChunk.lights_fragment_maps,
  385. THREE.ShaderChunk.lights_fragment_end,
  386. // modulation
  387. THREE.ShaderChunk.aomap_fragment,
  388. "vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;",
  389. THREE.ShaderChunk.envmap_fragment,
  390. "gl_FragColor = vec4( outgoingLight, diffuseColor.a );",
  391. THREE.ShaderChunk.tonemapping_fragment,
  392. THREE.ShaderChunk.encodings_fragment,
  393. THREE.ShaderChunk.fog_fragment,
  394. THREE.ShaderChunk.premultiplied_alpha_fragment,
  395. THREE.ShaderChunk.dithering_fragment,
  396. "}",
  397. ].join("\n")
  398. };
  399. PackedPhongMaterial.prototype = Object.create(THREE.MeshPhongMaterial.prototype);
  400. export { GeometryPackingUtils, PackedPhongMaterial };