Can the height, width, and depth of the current mesh be obtained in the shader

I created a terrain using a height map and then wrote a shader to color it according to different heights. I need to input a set of colors, each containing RGB color values and percentage height values. I need to obtain the height of the mesh in the shader and calculate the color of the current position y. How can I obtain the height of the mesh,

The height passed in the fragment below is a specific height value, and I want to change it to a percentage before calculating it

#include<sceneUboDeclaration>
#include<meshUboDeclaration>

varying localPosition: vec3f;
varying vUV : vec2<f32>;
uniform colorLength: i32;

uniform colors: array<vec3f, 20>;

uniform colorsY: array<f32, 20>;

var diffuse : texture_2d<f32>;
var textureSampler : sampler;

@fragment
fn main(input : FragmentInputs) -> FragmentOutputs {
    var fromColor: vec3f;
    var toColor: vec3f;
    var fromY: f32 = 0;
    var toY: f32 = 1;

    for (var i = 0; i < uniforms.colorLength; i++) {
        if (fragmentInputs.localPosition.y > uniforms.colorsY[i]) {
            fromColor = uniforms.colors[i];
            fromY = uniforms.colorsY[i];
        } else {
            toColor = uniforms.colors[i];
            toY = uniforms.colorsY[i];
            break;
        }
    }
    var r = (fragmentInputs.localPosition.y - fromY) / (toY - fromY);
    let color: vec3f = fromColor + (toColor - fromColor) * r;
//    fragmentOutputs.color = vec4(color, 1.);
    fragmentOutputs.color = textureSample(diffuse, textureSampler, fragmentInputs.vUV) * vec4(color, 1.);
    return fragmentOutputs;
}

do you need the height of the mesh for this, is using the height from the height map not feasible?

like so,

I have carefully considered the method you provided, and it does not apply to other meshes. I have looked at the source code of babylonjs and found the way. I defined a ShaderMaterial and rewrote the bind method to solve this problem

1 Like