2017-10-19 109 views
1

我目前正在嘗試在glsl(使用SFML)中編寫簡單的輪廓着色器。如果問題很明顯,我對着色器程序設計很陌生,所以請原諒我。 無論如何,着色器對紋理內的邊緣檢測效果不錯,但未能檢測到紋理邊緣處的邊界。工作outlineShader
Picture of the working outlineShader如何檢查片段是否位於紋理的邊緣

圖片輪廓着色器的

圖片不能正常工作
Picture of the outline shader not working correctly

這裏是我的片段着色器的代碼(我只有一個片段着色器)

uniform sampler2D texture; 
uniform float outlineThickness; 
uniform vec2 textureSize; 
uniform vec3 outlineColor; 

void main() 
{ 
    vec2 offx = vec2(outlineThickness/textureSize.x, 0.0); 
    vec2 offy = vec2(0.0, outlineThickness/textureSize.y); 

    float surroundingAlphaSum = texture2D(texture, gl_TexCoord[0].xy + offx).a + 
     texture2D(texture, gl_TexCoord[0].xy - offx).a + 
     texture2D(texture, gl_TexCoord[0].xy + offy).a + 
     texture2D(texture, gl_TexCoord[0].xy - offy).a; 

    // This pixel 
    vec4 pixel = texture2D(texture, gl_TexCoord[0].xy); 

    // If one of the surrounding pixels is transparrent --> an edge is detected 
    if (4.0 * pixel.a - surroundingAlphaSum > 0.0) 
    pixel = vec4(outlineColor, 1.0); 
    else 
    pixel = vec4(0.0); // transparrent 

    gl_FragColor = pixel * gl_Color; 
} 

所以基本上我正在尋找的是一種方法來確定是否鄰近像素仍屬於紋理或不。

因爲gl_TexCoord[0].xy似乎在shadermodel #version 120之後被刪除,所以備選將是非常值得讚賞的。

感謝您的幫助,

阿德里安

回答

0

有幾種方法來detect edges。不幸的是,我剛剛在Matlab中與他們合作,但也許鏈接可以幫助你實現一些功能。

根據我以往的經驗,你必須用它包含圖像,然後矩陣工作,創造一個你計算每個像素的額外的矩陣,如果它是一個邊緣與否,與0或1

0

你試過採樣8個紋素?看起來你的內核在某些情況下是不完美的。

float surroundingAlphaSum = texture2D(texture, gl_TexCoord[0].xy + offx).a + 
    texture2D(texture, gl_TexCoord[0].xy - offx).a + 
    texture2D(texture, gl_TexCoord[0].xy + offy).a + 
    texture2D(texture, gl_TexCoord[0].xy - offy).a + 
    texture2D(texture, gl_TexCoord[0].xy + offx + offy).a + 
    texture2D(texture, gl_TexCoord[0].xy + offx - offy).a + 
    texture2D(texture, gl_TexCoord[0].xy - offx + offy).a + 
    texture2D(texture, gl_TexCoord[0].xy - offx - offy).a; 

// ... 

if (8.0 * pixel.a - surroundingAlphaSum > 0.0) 

// ... 
+0

是的,那是我的第一次嘗試。我通過首先在較大的(transparrent)渲染紋理上繪製,然後將該着色器應用於renderTexture,找到了解決方法。它的工作原理是邊緣不再位於紋理的邊緣,但坦克性能相當高。感謝您回覆^^ –