我将如何在 OpenGL 中的 SPIR-V 着色器中设置 sampler2D 统一?

问题描述

我正在使用 glslangValidator 编译此着色器,并使用 OpenGL 4.3 核心配置文件和扩展 GL_ARB_gl_spirv,并使用 GLAD 网络服务生成函数指针以访问核心 OpenGL API,并使用 SDL2 创建上下文(如果是)随便用。

如果我有一个像这样的片段着色器:

#version 430 core

//output Fragment Color
layout (location = 0) out vec4 outFragColor;

//Texture coordinates passed from the vertex shader
layout (location = 0) in vec2 inTexCoord;

uniform sampler2D inTexture;

void main()
{
    outFragColor = texture(inTexture,inTexCoord);
}

如何设置 inTexture 使用的纹理单元?

从我通过文档在线阅读的内容来看,我无法使用 glGetUniformlocation获取要在 gluniform1i 中使用的制服的位置,因为我使用的是 SPIR-V,而不是 GLSL直接。

我需要怎么做才能像 gluniform1i 这样的方式设置它?我需要在布局修饰符中设置 location 吗? binding?我尝试使用统一缓冲区对象,但显然 sampler2D 只能是统一的。

解决方法

从 GLSL 4.20 开始,您可以直接从 GLSL 代码中为任何 opaque type 样例设置绑定点。这是通过 the binding layout qualifier 完成的:

schema.validate(req.body);

此处的 layout(binding = #) uniform sampler2D inTexture; 是您要使用的任何绑定索引。这是绑定纹理时使用的索引:#。也就是说,您不再需要使用 glActiveTexture(GL_TEXTURE0 + #) 来设置制服的值;您已经在着色器中设置了它。

如果您想动态修改绑定(而您不应该),GLSL 4.30 提供了通过 {{3 }}:

glProgramUniform

这使得 uniform 制服的位置,您可以传递给任何 layout(location = #) uniform sampler2D inTexture; 调用。