2014-10-18 19 views
0

我使用glDrawElements函數繪製我的場景。 由於我想要實現一個繪製調用繪製完整場景的情況,因此我需要在着色器中的「材質」之間切換着色器。 我決定用soubroutine做材料。這是我的片段着色器。使用soubroutine的opengl文物

#version 440 

layout(location = 0) flat in uvec2 inID_ShaderData; 
layout(location = 1) in vec4 inPosition; 
layout(location = 2) in vec2 inUV; 

subroutine void shaderType(void); 
subroutine uniform shaderType shaders[2]; 

uniform sampler2D texture0; 

layout(location = 0) out vec4 outColor; 
layout(location = 1) flat out uint outID; 

subroutine(shaderType) void shader_flatColor(void) 
{ 
outColor = vec4(1,0,0,1); // test red color 
// outColor = unpackUnorm4x8(inID_ShaderData.y & 0x00ffffff); // this should be here normally 
} 

subroutine(shaderType) void shader_flatTexture(void) 
{ 
    outColor = vec4(0,0,1,1); // test blue color 
// outColor = texture(texture0, inUV); // this should be here normally 
} 

void main() 

{  
    uint shader = (inID_ShaderData.y >> 24) & 0xff; // extract subroutine index from attributes 
    shaders[ shader ](); // call subroutine - not working, makes artifacts 

/* calling subroutine this way works ok 
    if (shader == 0) shaders[ 0 ](); 
    if (shader == 1) shaders[ 1 ](); 
*/ 

outID = inID_ShaderData.x; 

if (outID == -1) // this condition never happens 
    outColor = texture(texture0, inUV); // needed here to not to optimize out texture0, needed in soubroutine 

} 

問題1: 當使用shaders [ shader ]();然後有畫在四邊形像素的僞影。 使用IF時,它工作正常。它是驅動程序錯誤,還是我做錯了什麼? 如何使用子程序在沒有IF的情況下實現? (我在Windows 8 64位上有Radeon 7850)

問題2: 在第二個例程中,我想使用紋理。但是如果我在main()中不使用這個採樣變量 ,那麼編譯器「在子程序中看不到它」,並且在CPU端glUniform 函數失敗。 有沒有辦法怎麼做?沒有編譯器作弊,例如從未發生的情況?

P.S .:對不起,我不能發佈圖像與文物,但應該是紅色正方形 紅色正方形與5%的面積大部分在角落隨機藍色像素。 藍色方塊有紅色像素。

回答

0

你根本無法做到這一點。切換子程序不可能在每個屬性的基礎上進行。該GLSL規範有此說關於您的嘗試:

子程序變量可以聲明爲明確大小的數組,其中 只能與動態統一表達式進行索引。

考慮GPU如何工作,這個限制的確是有意義的。對於每個着色器調用,沒有單獨的控制流程,但僅適用於更大的組。

當您使用if嘗試時,您使用的是固定索引,當然這些索引也是動態均勻的。您當然可以嘗試根據您的輸入屬性進行提示,但您應該知道,強制使用非均勻控制流可能會完全破壞性能。在最糟糕的情況下,這並不比運行全部總是執行所有子例程函數,將結果存儲在某個數組中,然後使用索引從該數組中選擇最終結果。

+0

說到動態統一表達式,我查看了這篇文章 - https://www.opengl.org/wiki/Example/Dynamically_Uniform_Expression - 一切都很清楚。謝謝。 – quantumfoam 2014-10-18 19:10:46