简体   繁体   English

绑定OpenGL纹理采样器

[英]Binding an OpenGL Texture Sampler

I'm a tad confused about how to bind a texture to a slot in GLSL. 我对如何将纹理绑定到GLSL中的插槽感到困惑。 Here are my shaders: 这是我的着色器:

#version 330

layout(location=0) in vec4 in_Position;
layout(location=1) in vec4 texCoords;
out vec4 ex_texCoords;

uniform mat4 ModelMatrix;
uniform mat4 ViewMatrix;
uniform mat4 ProjectionMatrix;

void main(void)
{
    gl_Position = (ProjectionMatrix * ViewMatrix * ModelMatrix) * in_Position;
    ex_texCoords = texCoords;
}


#version 330

in vec4 ex_texCoords;
out vec4 out_Color;

uniform sampler2D textureSampler;

void main(void)
{
    out_Color = texture(textureSampler2, ex_texCoords.xy);
}

When I set my matrices up, I need to query the uniform location, and then manually set the values at that location, doing something like this: 当我设置矩阵时,我需要查询统一位置,然后在该位置手动设置值,执行以下操作:

modelMatrixUniformLocation = glGetUniformLocation(ShaderIds[0], "ModelMatrix");
...
glUniformMatrix4fv(modelMatrixUniformLocation, 1, GL_FALSE, modelMatrix.data);

However, as far as I can tell, I don't need to do that to initialize my texture sampler. 但是,据我所知,我不需要这样做来初始化我的纹理采样器。 At set-up time, all I seem to need to do is this: 在设置时,我似乎需要做的就是:

glGenTextures(1, &TextureID);
glBindTexture(GL_TEXTURE_2D, TextureID);
glTexImage2D(...);

So, my questions are, why don't I need to do the same process for textures that I need to do for matrices? 所以,我的问题是,为什么我不需要为矩阵做我需要做的纹理处理呢? How does the OpenGL runtime "know" that the texture I've bound is supposed to be the sampler I defined? OpenGL运行时如何“知道”我绑定的纹理应该是我定义的采样器? If I wanted to have multiple textures, how would I go about doing this? 如果我想要多个纹理,我该怎么做呢?

OpenGL dosen't know which sampler to use, you must bind it manualy using glActiveTexture(GL_TEXTUREi) (where i from 0 to GL_MAX_TEXTURES ). OpenGL不知道要使用哪个采样器,你必须使用glActiveTexture(GL_TEXTUREi) (其中i0GL_MAX_TEXTURESglActiveTexture(GL_TEXTUREi)绑定它。 Your code works because default sampler is GL_TEXTURE0 . 您的代码有效,因为默认采样器是GL_TEXTURE0 Obviously you are lucky enough and shader linker set textureSampler to 0. 显然你很幸运,着色器链接器将textureSampler设置为0。

Also, there is a new functionality in OpenGL API of version 3 and higher - glGenSamplers , glBindSampler . 此外,OpenGL API版本3及更高版本中还有一项新功能 - glGenSamplersglBindSampler It allow you to use texture-independent sampler configuration! 它允许您使用与纹理无关的采样器配置! You can read http://www.g-truc.net/post-0267.html for more details. 您可以阅读http://www.g-truc.net/post-0267.html了解更多详情。

And I recommend you to download samples from http://www.g-truc.net/project-0026.html 我建议您从http://www.g-truc.net/project-0026.html下载样本

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM