【问题标题】:How to cast int to float in GLSL (WebGL)?如何将 int 转换为在 GLSL(WebGL)中浮动?
【发布时间】:2015-10-21 23:15:20
【问题描述】:

我的代码是(在 void main 内):

float res;

for(int i=0; i<15; i++) {

    res = float(i)/15.0;

    //...

}

很遗憾,我在float(i)/15.0 收到语法错误

如果我只写i/15.0,那么错误是:

wrong operand types  no operation '/' exists that takes a left-hand operand of type 'mediump int' and a right operand of type 'const float' (or there is no acceptable conversion)

如果我只是尝试i/15,那么结果是一个整数,但我想得到一个浮点数。

如何将int 转换为float

【问题讨论】:

  • 在 javascript 中这个转换是自动完成的 - res = i / 15;
  • 这是 GLSL,不是 javascript
  • pasted your code above into glslsandbox.com and it works just fine。您确定没有从着色器中的其他行收到该错误吗?
  • “我在 float(i)/15.0 收到语法错误”你确定吗?这看起来很好,float(i) 是将 i 转换为 float 的正确方法。

标签: opengl-es glsl webgl


【解决方案1】:

It seems 不允许您在 GLSL 中进行投射。因此,“你必须使用a constructor

试试这个:

// http://www.shaderific.com/glsl-types/
// "Implicit type conversions are not supported.
// Type conversions can be done using constructors..."
float i_float = float(i);
res = i_float / 15.0;

PS:如果你看一下at the documentation,上面写着“......整数类型都可以转换成浮点数,整数和浮点数都可以转换成双精度数。” ...我觉得奇怪的是,GLSL 编译器不接受您的代码。(参见 Reto Koradi 的评论)

【讨论】:

  • 您正在查看完整 GLSL 的文档。与 WebGL 一起使用的 GLSL 版本基于 GLSL ES 1.00(与 OpenGL ES 2.0 一起使用的 GLSL 版本),不支持隐式类型转换。
  • 感谢您指出这一点。我添加了一个新的参考:shaderific.com/glsl-types
  • 由于某种原因我仍然遇到语法错误:An error occurred compiling the shaders: ERROR: 0:33: '1.0' : syntax error
  • 能否请您发布整个着色器代码,以便我们对问题有更具体的看法?
  • ...所以 float(x) 有效,但 (float)x 不...太棒了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-05
  • 2020-07-28
  • 2019-08-06
相关资源
最近更新 更多