关于opengl的TextureUnit(使用opentk)

一般来说代码是这样的:

GL.AttiveTexture(TextureUnit.Texture0);

GL.BindTExture(TextureTarget.Texture2D,textureId);

shader.SetInt(uniformName,textureNumber);//shader是自定义的一个类,简单封装了shader的功能,跟opentk无关

TexutureUnit,opengl定义了32个。从0x84c0开始递增,十进制是33984。

于是可以写成这样:

public void Active(TextureUnit unit, Shader shader, string uniformName) {
GL.ActiveTexture(unit);
GL.BindTexture(TextureTarget.Texture2D, this.TextureId);
int textureNumber = (int)unit - (int)TextureUnit.Texture0;
shader.SetInt(uniformName, textureNumber);
}

进一步测试发现,实际上TextureUnit可以是任意数字,不仅限于33884之后的31个数字。虽然opentk设计了TextureUnit这个枚举,但我们都知道枚举本质上就是Int,可以强转的。把任意int数字转进去都可以。

看opengl官方文档是这样说的:

void glActiveTexture( GLenum texture);

Parameters

texture

Specifies which texture unit to make active. The number of texture units is implementation dependent, but must be at least 80. texture must be one of GL_TEXTUREi, where i ranges from zero to the value ofGL_MAX_COMBINED_TEXTURE_IMAGE_UNITS minus one. The initial value is GL_TEXTURE0.

Description

glActiveTexture selects which texture unit subsequent texture state calls will affect. The number of texture units an implementation supports is implementation dependent, but must be at least 80.

Errors

GL_INVALID_ENUM is generated if texture is not one of GL_TEXTUREi, where i ranges from zero to the value of GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS minus one.

它说,TextureUnit值最小是GL_Texture0,最大是GL_Texture0+GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS ,查opengl 的头文件定义,这个值是35661。

但实际的OpenGL实现,就是可以用任意值,int的最大值,最小值都试验过,没有问题。只要在设置shader参数的时候,减去GL_Texture0就行,连溢出都可以正常工作。看来opengl实现的时候,就是把它作为数字处理的,算法也是简单相减,所以这样才能正常工作。

不过,最好还是按照规范来。因为按照opengl的标准,设置过大过小的TextureUnit值,应该报错的。

猜你喜欢

转载自www.cnblogs.com/mooniscrazy/p/11280186.html