JS - 未声明的标识符:GLSL脚本中的'var'

Tac*_*B0t 5 html javascript glsl webgl

我对HTML和Javascript有点新,在我的html中,我有以下代码:

        <script id="fragmentShader" type="x-shader/x-fragment">
                precision mediump float;

                //varying vec3 fragmentColor;  //not needed?
                varying vec3 fragmentNormal;
                varying vec3 fragmentLight;
                varying vec3 fragmentView;

                uniform vec3 modelColor;
                uniform vec3 lightColor;

                void main() {
                        var m = normalize(fragmentNormal);
                        var l = normalize(fragmentLight);
                        var v = normalize(fragmentView);
                        var h = normalize(l + v);

                        var d = Math.max(l * m , 0);
                        var s = Math.pow(Math.max(h * m, 0), 10);

                        fragmentColor = modelColor * lightColor * d + lightColor * s;

                        gl_FragColor = vec4(fragmentColor, 1.0);
                }
        </script>
Run Code Online (Sandbox Code Playgroud)

然而,它返回

Failed to compile shader: ERROR: 0:13: 'var' : undeclared identifier 
ERROR: 0:13: 'm' : syntax error 
Run Code Online (Sandbox Code Playgroud)

我不允许在HTML中的脚本标签内声明/定义变量吗?

gma*_*man 2

上面的代码不是 JavaScript,而是GLSL。它是用于编写在 GPU 上运行的程序的语言。它没有关键字var。要在 GLSL 中声明变量,您需要在它们前面放置一个类型

vec3 m = normalize(fragmentNormal);

vec3 l = normalize(fragmentLight);
vec3 v = normalize(fragmentView);
vec3 h = normalize(l + v);

vec3 d = max(l * m , 0.0);
vec3 s = pow(max(h * m, 0.0), vec3(10));
Run Code Online (Sandbox Code Playgroud)

我不确定你上面想做什么,但你所有的方程都会产生vec3.

GLSL 1.00 es 对类型也很严格。您不能将 vec3 与整数一起使用。您必须使用浮点数。0.0代替0。最后一行没有函数pow在左边接受 vec3 ,在右边接受单个值,因此vec3(10)接受整数10并将其转换为vec3。说的也是一样的vec3(10, 10, 10)

而且 GLSL 没有Math.库。它的内置函数是全局的。