问题描述
我正在为游戏引擎编写以下片段着色器:
I am writing the following fragment shader for a game engine:
#version 330 core
layout (location = 0) out vec4 color;
uniform vec4 colour;
uniform vec2 light_pos;
in DATA
{
vec4 position;
vec2 uv;
float tid;
vec4 color;
} fs_in;
uniform sampler2D textures[32];
void main()
{
float intensity = 1.0 / length(fs_in.position.xy - light_pos);
vec4 texColor = fs_in.color;
if(fs_in.tid > 0.0){
int tid = int(fs_in.tid + 0.5);
texColor = texture(textures[tid], fs_in.uv);
}
color = texColor * intensity;
}
texColor = texture(textures[tid], fs_in.uv);
行会导致在编译着色器时,在GLSL 1.30和更高版本中禁止使用非恒定表达式索引的采样器数组".
The line texColor = texture(textures[tid], fs_in.uv);
causes the 'sampler arrays indexed with non-constant expressions are forbidden in GLSL 1.30 and later' expression when compiling the shader.
顶点着色器(如果需要)是:
The vertex shader if needed is:
#version 330 core
layout (location = 0) in vec4 position;
layout (location = 1) in vec2 uv;
layout (location = 2) in float tid;
layout (location = 3) in vec4 color;
uniform mat4 pr_matrix;
uniform mat4 vw_matrix = mat4(1.0);
uniform mat4 ml_matrix = mat4(1.0);
out DATA
{
vec4 position;
vec2 uv;
float tid;
vec4 color;
} vs_out;
void main()
{
gl_Position = pr_matrix * vw_matrix * ml_matrix * position;
vs_out.position = ml_matrix * position;
vs_out.uv = uv;
vs_out.tid = tid;
vs_out.color = color;
}
推荐答案
在GLSL 3.3中,只有积分常量表达式(请参见 GLSL 3.3规范,第4.1.7节).
In GLSL 3.3 indexing for sampler arrays is only allowed by an integral constant expression (see GLSL 3.3 Spec, Section 4.1.7).
从GLSL 4.0开始,在更现代的版本中,允许动态统一表达式(请参见 GLSL 4.0规范,第4.1.7节)
In more modern version, starting from GLSL 4.0 it is allowed to index sampler arrays by dynamic uniform expressions (see GLSL 4.0 Spec, Section 4.1.7)
您实际上要尝试的是通过变化来索引数组,这根本是不可能的.如果这样做绝对是不可避免的,则可以将2d纹理打包为2d阵列纹理或3d纹理,然后使用索引来寻址纹理的层(或第3维).
What you actually are trying is to index the array by a varying which is simply impossible. If it is absolutely unavoidable to do that, you could pack the 2d textures into a 2d array texture or into a 3d texture and use the index to address the layer (or the 3rd dimension) of the texture.
这篇关于“错误:片段着色器中的GLSL 1.30及更高版本中禁止使用非恒定表达式索引的采样器数组"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!