material.onBeforeCompile = function (shader, renderer) {
const getFoot = `
uniform float top;
uniform float bottom;
uniform float time;
uniform mat4 cameraMatrix;
varying float depth;
varying vec2 depthUv;
#include <common>
float angle(float x, float y){
return atan(y, x);
}
vec2 getFoot(vec2 camera,vec2 normal,vec2 pos){
vec2 position;
float distanceLen = distance(pos, normal);
float a = angle(camera.x - normal.x, camera.y - normal.y);
pos.x > normal.x ? a -= 0.785 : a += 0.785;
position.x = cos(a) * distanceLen;
position.y = sin(a) * distanceLen;
return position + normal;
}
`;
const begin_vertex = `
vec2 foot = getFoot(vec2(cameraPosition.x, cameraPosition.z), vec2(normal.x, normal.z), vec2(position.x, position.z));
float height = top - bottom;
float y = normal.y - bottom - height * time;
y = y + (y < 0.0 ? height : 0.0);
float ratio = (1.0 - y / height) * (1.0 - y / height);
depth = ratio;
y = height * (1.0 - ratio);
y += bottom;
y += position.y - normal.y;
vec3 transformed = vec3( foot.x, y, foot.y );
vec4 cameraDepth = cameraMatrix * vec4(transformed, 1.0);
depthUv = cameraDepth.xy/2.0 + 0.5;
`;
const depth_vary = `
uniform sampler2D tDepth;
uniform float opacity;
varying float depth;
varying vec2 depthUv;
float decodeRGBA2Float(vec4 rgba)
{
return dot(rgba, vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0));
}
`;
const depth_frag = `
if(1.0 - depth < decodeRGBA2Float(texture2D( tDepth, depthUv ))) discard;
vec4 diffuseColor = vec4( diffuse, opacity );
`
shader.vertexShader = shader.vertexShader.replace(
"#include <common>",
getFoot
);
shader.vertexShader = shader.vertexShader.replace(
"#include <begin_vertex>",
begin_vertex
);
shader.fragmentShader = shader.fragmentShader.replace('uniform float opacity;', depth_vary)
shader.fragmentShader = shader.fragmentShader.replace('vec4 diffuseColor = vec4( diffuse, opacity );', depth_frag)
shader.uniforms.cameraPosition = {
value: new THREE.Vector3(0, 200, 0)
}
shader.uniforms.top = {
value: 2000
}
shader.uniforms.bottom = {
value: -2000
}
shader.uniforms.time = {
value: 0
}
shader.uniforms.cameraMatrix = {
value: new THREE.Matrix4()
}
shader.uniforms.tDepth = {
value: target.texture
}
material.uniforms = shader.uniforms;
};