【问题标题】:Shader - Object depth from camera in linear scale from 0 to 1着色器 - 从 0 到 1 的线性比例的相机对象深度
【发布时间】:2020-05-03 09:50:20
【问题描述】:

我正在尝试编写一个着色器,该着色器从具有从 0 到 1 的线性比例的相机计算网格的深度。

离相机最近的顶点的值为 0,而离相机最远的顶点的值为 1。此外,如果相机旋转,网格的深度值必须适应变化。

这是一个支持理解的图像。

从图像中,您可以看到最近的顶点 alpha 设置为 0,而最远的顶点的值为 1。

我想实现这个效果,即使相机旋转。

从这个Shader - Calculate depth relative to Object,我可以找到最近的顶点,但我发现很难计算网格离相机最远的点。

可以使用网格的边界框,但是如果我旋转相机,我需要重新计算边界框。因此,我想知道是否有任何解决方案可以使用可用的矩阵?

PS:我正在尝试在three.js和Unity中实现这个效果。

【问题讨论】:

标签: unity3d opengl three.js glsl shader


【解决方案1】:

至少在three.js 有一个官方演示可以产生你想要的效果(只是用倒色表示最接近白色):https://threejs.org/examples/webgl_depth_texture

这个想法是将深度渲染到纹理,然后在自定义着色器中使用此信息。片段着色器中的相关代码是:

float readDepth( sampler2D depthSampler, vec2 coord ) {
    float fragCoordZ = texture2D( depthSampler, coord ).x;
    float viewZ = perspectiveDepthToViewZ( fragCoordZ, cameraNear, cameraFar );
    return viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
}

void main() {
    // readDepth() will return a linearized depth value that will be used to compute the fragment's color value
    float depth = readDepth( tDepth, vUv );

    gl_FragColor.rgb = 1.0 - vec3( depth ); // change this bit to invert colors
    gl_FragColor.a = 1.0;
}

perspectiveDepthToViewZ()viewZToOrthographicDepth() 是定义在 packing 着色器块中的辅助函数,它包含在着色器源代码的顶部。

three.js R116

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-05
    • 2021-10-10
    • 1970-01-01
    • 1970-01-01
    • 2017-04-27
    • 1970-01-01
    相关资源
    最近更新 更多