2017-02-15 23 views
-1

在OpenGL中編寫簡單的計算着色器以瞭解其工作原理,但無法獲得想要的結果。將結構數組轉換爲計算明暗器

我想傳遞給我的計算着色器一個結構colourStruct的數組來爲輸出紋理着色。

我想有一個紅色的圖像時,「wantedColor」在我的計算着色器= 0和綠色形象「wantedColor」 = 1,藍色爲2

但我其實只有紅時「wantedColor」 = 1或2或3,黑色當「wantedColor」> 2 ...

如果有人有一個想法,或者我不明白計算着色器輸入的想法。

感謝您的幫助,下面是我的代碼中有趣的部分。

我的計算着色器:

#version 430 compatibility 

layout(std430, binding=4) buffer Couleureuh 
{ 
    vec3 Coul[3]; // array of structures 
}; 

layout(local_size_x = 1, local_size_y = 1) in; 
layout(rgba32f, binding = 0) uniform image2D img_output; 

void main() { 

    // base pixel colour for image 
    vec4 pixel = vec4(0.0, 0.0, 0.0, 1.0); 

    // get index in global work group i.e x,y, position 
    ivec2 pixel_coords = ivec2(gl_GlobalInvocationID.xy); 
    ivec2 dims = imageSize (img_output); 


    int colorWanted = 0; 
    pixel = vec4(Coul[colorWanted], 1.0); 

    // output to a secific pixel in the image 
    imageStore (img_output, pixel_coords, pixel); 

} 

計算着色器和SSBO初始化:

GLuint structBuffer; 
    glGenBuffers(1, &structBuffer); 
    glBindBuffer(GL_SHADER_STORAGE_BUFFER, structBuffer); 
    glBufferData(GL_SHADER_STORAGE_BUFFER, 3*sizeof(colorStruct), NULL, GL_STATIC_DRAW); 

     GLint bufMask = GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT; // invalidate makes a ig difference when re-writting 

    colorStruct *coul; 
    coul = (colorStruct *) glMapBufferRange(GL_SHADER_STORAGE_BUFFER, 0, 3*sizeof(colorStruct), bufMask); 


    coul[0].r = 1.0f; 
    coul[0].g = 0.0f; 
    coul[0].b = 0.0f; 

    coul[1].r = 0.0f; 
    coul[1].g = 1.0f; 
    coul[1].b = 0.0f; 

    coul[2].r = 0.0f; 
    coul[2].g = 0.0f; 
    coul[2].b = 1.0f; 

    glUnmapBuffer(GL_SHADER_STORAGE_BUFFER); 

    glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 4, structBuffer); 

    m_out_texture.bindImage(); 

    // Launch compute shader 
    m_shader.use(); 

    glDispatchCompute(m_tex_w, m_tex_h, 1); 

    // Prevent samplign before all writes to image are done 
    glMemoryBarrier(GL_SHADER_IMAGE_ACCESS_BARRIER_BIT); 

回答

0

vec3始終是16字節對齊。因此,當他們在陣列中時,他們的行爲就像vec4 s。即使有std430佈局。

Never use vec3 in interface blocks。你應該使用一個float的數組(單獨訪問你想要的3個成員)或者一個vec4(帶有一個未使用的元素)的數組。

+0

它正在使用浮動和vec4!非常感謝你! :)。 – bRiocHe