OpenGL 是一種跨平台的圖形渲染API, 使用OpenGL 可以開發跨平台的圖形應用程序。在OpenGL 的世界裡,圖像是被分為許多紋理的。
在這些紋理中,glActiveTexture 作為 OpenGL 函數之一,對於處理多個紋理非常重要。
一、glActiveTexture是什麼
glActiveTexture 是一個 OpenGL 函數,用於指定當前活動的紋理單元。
void glActiveTexture(GLenum texture);
其中,texture 是一個 GLenum 類型的參數,指定一個紋理單元,可以是下面這個參數之一:
- GL_TEXTUREi
- GL_TEXTURE0 + i
其中 i 的範圍是從 0 到當前 OpenGL 實現支持的最大紋理單元數。
二、glActiveTexture的用途
1. 處理多紋理
OpenGL 允許用戶綁定多個紋理到多個紋理單元上,glActiveTexture 函數就可以用於指定當前活動的紋理單元。
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture1);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, texture2);
上面的例子中,我們綁定了一個名為 texture1 的 2D 紋理到紋理單元 GL_TEXTURE0 中,以及一個名為 texture2 的 2D 紋理到紋理單元 GL_TEXTURE1 中。
2. 定義紋理單元
在顯卡硬體資源有限的情況下,我們不可能無限制地向顯卡中增加新的緩存區。為了最優化紋理的使用,我們可以將一張大的圖像分成幾部分儲存在不同的紋理空間中。 glActiveTexture 可以用於定義紋理單元。
GLuint textures[3];
glGenTextures(3, textures);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, textures[0]);
...
上面的例子中,我們首先生成了 3 個紋理緩存,然後定義了紋理空間0 的緩存。
3. 顯卡性能優化
我們使用多個紋理單元來提高顯示性能,這是實現紋理功能的一種方法。
因為紋理一般儲存在顯存當中,顯存的空間有限,所以我們在使用多紋理的時候,需要動態的開闢儲存空間。
因此,合理使用 glActiveTexture 函數可以有效地避免空間浪費。
三、附加代碼示例
// OpenGL 初始化紋理
GLuint texture1, texture2;
glGenTextures(1, &texture1);
glBindTexture(GL_TEXTURE_2D, texture1);
// 設置紋理參數
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
// 載入紋理圖像
int width, height, nrChannels;
unsigned char *data = stbi_load("container.jpg", &width, &height, &nrChannels, 0);
if (data)
{
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
glGenerateMipmap(GL_TEXTURE_2D);
}
else
{
std::cout << "Failed to load texture" << std::endl;
}
stbi_image_free(data);
glGenTextures(1, &texture2);
glBindTexture(GL_TEXTURE_2D, texture2);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
data = stbi_load("awesomeface.png", &width, &height, &nrChannels, 0);
if (data)
{
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
glGenerateMipmap(GL_TEXTURE_2D);
}
else
{
std::cout << "Failed to load texture" << std::endl;
}
stbi_image_free(data);
// 在shader中,使用下面的語句分別綁定紋理單元
uniform sampler2D texture1;
uniform sampler2D texture2;
...
glUseProgram(shaderProgram);
glUniform1i(glGetUniformLocation(shaderProgram, "texture1"), 0);
glUniform1i(glGetUniformLocation(shaderProgram, "texture2"), 1);
// 在繪製之前,將紋理關聯到指定的紋理單元上
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture1);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, texture2);
...
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/285040.html
微信掃一掃
支付寶掃一掃