簡體   English   中英

OpenGL ES2顏色和紋理着色器

[英]OpenGL ES2 color and texture shader

我想編寫一個頂點着色器來處理顏色和紋理,我使用了這段代碼

precision mediump float;
varying vec4 v_Color;
uniform sampler2D u_TextureUnit;
varying vec2 v_TextureCoordinates;

void main() {
    gl_FragColor= (v_Color*texture2D(u_TextureUnit, v_TextureCoordinates));
}

當模型具有紋理貼圖時可以使用,但是如果模型只有顏色則加載黑色,我想在放置u_TextureUnit之前檢查sampler2D gl_FragColor

您已經編寫了一個從紋理單元讀取的着色器。 通常應避免在着色器中使用條件,因為它可能會分割執行路徑。 通常,如果您要有條件地執行的操作是統一的,則編譯器可以弄清楚,但是每次設置統一后,您可能最終都要為重新編譯付費。 ES 2無法自檢采樣單元的當前屬性,因此表面上的解決方案可能類似於:

uniform bool u_ApplyTexture;
...
if(u_ApplyTexture)
    gl_FragColor = {what you already have};
else
    gl_FragColor = v_Color;

可以將概要文件作為替代方案的無條件替代方案可能是:

uniform float u_TextureWeight;
...
gl_FragColor = v_Color*
                   mix(vec4(1.0), 
                       texture2D(u_TextureUnit, v_TextureCoordinates), 
                       u_TextureWeight);

作為將評估為v_Color*vec4(1.0)u_TextureWeight0.0v_Color*texture2D(u_TextureUnit, v_TextureCoordinates)u_TextureWeight1.0

如果您真的想變黑,則可以將紋理作為負圖像上傳,然后在着色器中再次負它們:

gl_FragColor = v_Color*(vec4(1.0) - texture2D(u_TextureUnit, v_TextureCoordinates));

顯然,如果您由於沒有附着紋理而從采樣單元獲取vec4(0.0) ,則最終v_Color乘以1.0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM