使用顶点着色器的 WebGL 高度图,使用 32 位而不是 8 位

WebGL heightmap using vertex shader, using 32 bits instead of 8 bits

我正在使用以下顶点着色器(由 http://stemkoski.github.io/Three.js/Shader-Heightmap-Textures.html 提供)从灰度高度图生成地形:

uniform sampler2D bumpTexture;
uniform float bumpScale;

varying float vAmount;
varying vec2 vUV;

void main()
{
  vUV = uv;
  vec4 bumpData = texture2D( bumpTexture, uv );

  vAmount = bumpData.r; // assuming map is grayscale it doesn't matter if you use r, g, or b.

  // move the position along the normal
  vec3 newPosition = position + normal * bumpScale * vAmount;

  gl_Position = projectionMatrix * modelViewMatrix * vec4( newPosition, 1.0);
}

我想要 32 位分辨率,并生成了一个将高度编码为 RGBA 的高度图。我不知道如何更改着色器代码以适应这种情况。有任何指导或帮助吗?

bumpData.r.g.b.a 都是 [0.0, 1.0] 范围内的量,相当于原始字节值除以 255.0.

因此,根据您的字节顺序,回到原始 int 的简单转换可能是:

(bumpData.r * 255.0) + 
(bumpdata.g * 255.0 * 256.0) + 
(bumpData.b * 255.0 * 256.0 * 256.0) + 
(bumpData.a * 255.0 * 256.0 * 256.0 * 256.0)

所以这与向量 (255.0, 65280.0, 16711680.0, 4278190080.0) 的点积相同,这可能是更有效的实现方式。

用threejs

const generateHeightTexture = (width) => {
  // let max_texture_width = RENDERER.capabilities.maxTextureSize;
  let pixels = new Float32Array(width * width)
  pixels.fill(0, 0, pixels.length);
  let texture = new THREE.DataTexture(pixels, width, width, THREE.AlphaFormat, THREE.FloatType);

  texture.magFilter = THREE.LinearFilter;
  texture.minFilter = THREE.NearestFilter;
  // texture.anisotropy = RENDERER.capabilities.getMaxAnisotropy();
  texture.needsUpdate = true;
  console.log('Built Physical Texture:', width, 'x', width)
  return texture;
}