我一直在尝试创建一个结构来包含我的 WebGL 应用程序的所有灯光,但我在从 JS 设置它的值时遇到了麻烦。结构如下:
struct Light {
vec4 position;
vec4 ambient;
vec4 diffuse;
vec4 specular;
vec3 spotDirection;
float spotCutOff;
float constantAttenuation;
float linearAttenuation;
float quadraticAttenuation;
float spotExponent;
float spotLightCosCutOff;
};
uniform Light lights[numLights];
在测试了很多东西之后我让它工作了但是我对我写的代码不满意:
program.uniform.lights = [];
program.uniform.lights.push({
position: "",
diffuse: "",
specular: "",
ambient: "",
spotDirection: "",
spotCutOff: "",
constantAttenuation: "",
linearAttenuation: "",
quadraticAttenuation: "",
spotExponent: "",
spotLightCosCutOff: ""
});
program.uniform.lights[0].position = gl.getUniformLocation(program, "lights[0].position");
program.uniform.lights[0].diffuse = gl.getUniformLocation(program, "lights[0].diffuse");
program.uniform.lights[0].specular = gl.getUniformLocation(program, "lights[0].specular");
program.uniform.lights[0].ambient = gl.getUniformLocation(program, "lights[0].ambient");
... and so on
很抱歉让您看到这段代码,我知道这很糟糕,但我找不到更好的方法。
是否有正确执行此操作的标准或推荐方法?谁能启发我?
最佳答案
你做得对。你可以试着把它收紧一点,就像在
lightLocations = [
"position",
"diffuse",
"specular",
"ambient",
"spotDirection",
"spotCutOff",
"constantAttenuation",
"linearAttenuation",
"quadraticAttenuation",
"spotExponent",
"spotLightCosCutOff",
];
var program = {
uniform: {
lights: [];
}
};
for (var ll = 0; ll < numLights; ++ll) {
var locations = { };
for (var jj = 0; jj < lightLocations.length; ++jj) {
var name = lightLocaitons[jj];
locations = gl.getUniformLocation(program, "lights[" + ll + "]." + name);
}
program.uniform.lights[ll] = locations;
}
关于javascript - 将结构数组的值从 JS 设置为 GLSL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8202173/