shader中判断浮点型数值相等:round、floor

615 阅读1分钟

传递的顶点数据中vertices.z=1.0

image.png

使用gDebugger查看vbo中的数据z也是1.0

image.png

所有的顶点z都是一致的,当position.z=0、position.z=2时都正常,唯独position.z=1时异常

  • vertexes.shader
attribute vec2 a_position;
varying vec4 v_position;
void main(){
    v_position = a_position;
}
  • fragment.shader
varying vec4 v_position;
void main(){
    float textureID = v_position.z;
     if(0.0 == textureID){
         // 正常
     }else if(1.0 == textureID){
         // 唯独这个1.0无法正常响应
     }ese if(2.0 == textureID){
         // 正常
     }
}

为了防止是精度问题,特地转int,发现仍旧如此:

发现转int(z)后竟然等于0,可能这时的z是一个非常接近1的浮点数,比如:0.999999

varying vec4 v_position;
void main(){
    int textureID = int(v_position.z);
     if(0 == textureID){
         // 正常
     }else if(1 == textureID){
         // 唯独这个1.0无法正常响应
     }ese if(2 == textureID){
         // 正常
     }
}

答案

使用round转int

varying vec4 v_position;
void main(){
    int textureID = round(v_position.z);
     if(0 == textureID){
         // 正常
     }else if(1 == textureID){
         // 唯独这个1.0无法正常响应
     }ese if(2 == textureID){
         // 正常
     }
}

在某些环境中,round is undefined,可以使用floor(x+0.5)代替

shader函数

函数说明
floor返回小于等于x的最大整数
ceil返回大于或等于输入值的最小整数。
degrees弧度到角度的转换
fmod返回a / b的浮点余数。
round返回最接近于输入值的整数。
saturate把输入值限制到[0, 1]之间。

注意事项

在round的官方文档中会看到关于类型的说明

genType round( genType x)
  • genType对应的输入/输出参数可以是float,vec2,vec3或vec4。
  • genIType对应的输入/输出参数可以是int,ivec2,ivec3或ivec4。

举个例子:

int a = round(1.0); // 错误:Incompatible types in initialization (and no available implicit conversion)
float a = round(1.0); // 正确