结论: w是顶点距离相机的距离。
geometry:
const size = 10
var geometry = new THREE.BoxBufferGeometry(size, size, size);
var material = new THREE.ShaderMaterial({
uniforms: {
camPos: { type: "f", value: this.stage.camera.position.z }
},
vertexShader: vertex,
fragmentShader: fragment
});
var cube = new THREE.Mesh(geometry, material);
vertexShader:
varying float w;
varying vec3 pos;
void main() {
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
w = gl_Position.w;
pos = position;
}`;
fragmentShader:
varying float w;
varying vec3 pos;
uniform float camPos;
void main() {
float z = pos.z;
gl_FragColor = vec4(vec3(pos.z-9., 0., 0.), 1.);
}
gl_FragColor = vec4(vec3(pos.z-9., 0., 0.), 1.);
顶点在z轴的分布是:
z <-----------------
10 0 -10
z轴最前面的点pos.z = 10
gl_FragColor = vec4(vec3(camPos - 50. + 0.5, 0., 0.), 1.);
相机位置camPos.z = 50
gl_FragColor = vec4(vec3(w - 40. + 0.5, 0., 0.), 1.);
w沿着z轴分布是:
z<---------------------
40 50 60
也就是说,w是顶点距离相机的距离。
pos.z
z <-----------------
10 0 -10
pos.z += 10
z <-----------------
20 10 0
w
z<---------------------
40 50 60
gl_FragColor = vec4(vec3((pos.z+10.)/w+0.5, 0., 0.), 1.);
距离越近,颜色越深。