In a fragment shader, why can't I use a flat input integer to index a uniform array of sampler2D?

↘锁芯ラ 提交于 2019-12-12 11:01:30

问题


new to shaders here, and a bit puzzled.

I want to specify textures to be used when I render an array of sprites. So I put a texture index in their vertex data, and pass it as a flat value from my vertex shader to my fragment shader, but can't use it to index an array of samplers as expected because compiler sees it as "non-constant". Instead I have to resort to the disgusting code below. Can anyone explain what is going on here?

const int numTextures = 2;

uniform sampler2D textures[numTextures];

in vec2 uv;
flat in int tex;
out vec4 colour;

void main(void)
{
    // this caused the compiler error 
        /// "sampler arrays indexed with non-constant expressions"
    // colour = texture( textures[ tex ], uv );

    // hence this (ugh) ...
    switch ( tex ) 
    {
        case 0:
            colour = texture( textures[0], uv );
            break;
        case 1:
            colour = texture( textures[1], uv );
            break;
        default:
            colour = vec4( 0.3f, 0.3f, 0.3f, 1.0f );
            break;
    };
} 


回答1:


[...] but can't use it to index an array of samplers as expected because compiler sees it as "non-constant" [...]

In GLSL up to version 3.30 respectively GLSL ES up to version 3.00, the index of an array of texture samplers has to be a constant expression:

GLSL 3.30 Specification - 4.1.7 Samplers (page 21)
GLSL ES 3.00 Specification - 4.1.7.1 Samplers (page 29):

Samplers aggregated into arrays within a shader (using square brackets [ ]) can only be indexed with integral constant expressions [...]


In later version, the index to an array of samplers has to be "dynamically uniform". This means the index has to be the "same" for all fragments (e.g. a constant or a uniform variable).

GLSL 4.60 Specification - 4.1.11. Opaque Types (page 31)
GLSL ES 3.20 Specification - 4.1.11. Opaque Types (page 32)

When aggregated into arrays within a shader, opaque types can only be indexed with a dynamically uniform integral expression. [...]

[...] Sampler types (e.g. sampler2D) are opaque types [...]

GLSL 4.60 Specification - 3.8.2. Dynamically Uniform Expressions (page 20)
GLSL ES 3.20 Specification - 3.9.3. Dynamically Uniform Expressions (page 22)

A fragment-shader expression is dynamically uniform if all fragments evaluating it get the same resulting value.



来源:https://stackoverflow.com/questions/54388274/in-a-fragment-shader-why-cant-i-use-a-flat-input-integer-to-index-a-uniform-ar

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!