關於SamplerObject
前言
SamplerObject是在OpenGL3.3以後新增的功能,可以用來簡化設定Texture參數的過程,在此將學習過程做個紀錄。內容
在OpenGL設定Texture的參數範例如下GLint textureLoc; GLenum textureType; GLuint texture; glActiveTexture(GL_TEXTURE0); glBindTexture(textureType,texture); glTexParameteri(textureType, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(textureType, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(textureType, GL_TEXTURE_WRAP_R, GL_REPEAT); glTexParameteri(textureType, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(textureType, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glUniform1i(textureLoc,(GLint)0);
這是在沒有SamplerObject的功能時必須要在每次設定Texture時都要經過的流程,在有SamplerObject後的範例如下
//Create sampler object GLuint samplerObject = 0; glGenSamplers(1,&samplerObject ); glSamplerParameteri(samplerObject , GL_TEXTURE_WRAP_S, GL_REPEAT); glSamplerParameteri(samplerObject , GL_TEXTURE_WRAP_T, GL_REPEAT); glSamplerParameteri(samplerObject , GL_TEXTURE_WRAP_R, GL_REPEAT); glSamplerParameteri(samplerObject , GL_TEXTURE_MAG_FILTER, GL_NEAREST); glSamplerParameteri(samplerObject , GL_TEXTURE_MIN_FILTER, GL_NEAREST); //On set up texture GLint textureLoc; GLenum textureType; GLuint texture; glActiveTexture(GL_TEXTURE0); glBindTexture(textureType,texture); glBindSampler(textureLoc,samplerObject ); glUniform1i(textureLoc,(GLint)0); //On delete glDeleteSamplers(1,&samplerObject );
要Create SamplerObject時,透過glGenSamplers()來製造,並透過glSamplerParameteri()來設定,設定完後,以後在設定Texture參數時透過glBindSampler(),要綁並到哪張Texture,會透過Texture的Location來決定,用起來相當容易,釋放的部分就和往常一樣,用glDeleteSamplers()來釋放即可。
2019/08/24更新
上述範例有錯,請更正為以下//Create sampler object GLuint samplerObject = 0; glGenSamplers(1,&samplerObject ); glSamplerParameteri(samplerObject , GL_TEXTURE_WRAP_S, GL_REPEAT); glSamplerParameteri(samplerObject , GL_TEXTURE_WRAP_T, GL_REPEAT); glSamplerParameteri(samplerObject , GL_TEXTURE_WRAP_R, GL_REPEAT); glSamplerParameteri(samplerObject , GL_TEXTURE_MAG_FILTER, GL_NEAREST); glSamplerParameteri(samplerObject , GL_TEXTURE_MIN_FILTER, GL_NEAREST); //On set up texture GLint textureLoc; GLenum textureType; GLuint texture; GLuint textureID=0; glActiveTexture(GL_TEXTURE0+textureID); glBindTexture(textureType,texture); glBindSampler(textureID,samplerObject ); glUniform1i(textureLoc,(GLint)0); //On delete glDeleteSamplers(1,&samplerObject );
舊的範例在 glBindSampler() 會使用 textureLoc 作為綁定,但這用法是錯的!正確的用法是用 textureID 來綁定, textureID 指的是 glActiveTexture() 所指定的ID,如當 ID 是 GL_TEXTURE0 對應的 textureID 就是0,當 ID 是 GL_TEXTURE1 對應的 textureID 就是1,其他依此類推。
參考資料
OpenGL 3D繪圖互動程式設計,出版者:旗標,作者:賴祐吉, 姚智原, 朱宏國作,ISBN-13:9789863125112
沒有留言:
張貼留言