2016-03-05 289 views
0

我想向着色器發送顏色,但顏色被交換, 我發送0xFF00FFFF(洋紅色),但我在着色器中得到0xFFFF00FF(黃色)。OpenGL - 着色器中的頂點顏色被交換

我認爲正在發生的事情是這樣的,通過實驗:

Image

我的頂點着色器:

#version 330 core 

layout(location = 0) in vec4 position; 
layout(location = 1) in vec3 normal; 
layout(location = 2) in vec4 color; 

uniform mat4 pr_matrix; 
uniform mat4 vw_matrix = mat4(1.0); 
uniform mat4 ml_matrix = mat4(1.0); 

out DATA 
{ 
    vec4 position; 
    vec3 normal; 
    vec4 color; 
} vs_out; 

void main() 
{ 
    gl_Position = pr_matrix * vw_matrix * ml_matrix * position; 

    vs_out.position = position; 
    vs_out.color = color; 
    vs_out.normal = normalize(mat3(ml_matrix) * normal); 
} 

而片段着色器:

#version 330 core 

layout(location = 0) out vec4 out_color; 

in DATA 
{ 
    vec3 position; 
    vec3 normal; 
    vec4 color; 
} fs_in; 

void main() 
{ 
    out_color = fs_in.color; 

    //out_color = vec4(fs_in.color.y, 0, 0, 1); 
    //out_color = vec4((fs_in.normal + 1/2.0), 1.0); 
} 

這裏是如何我設置了網格:

struct Vertex_Color { 
    Vec3 vertex; 
    Vec3 normal; 
    GLint color; // GLuint tested 
}; 


std::vector<Vertex_Color> verts = std::vector<Vertex_Color>(); 

[loops] 
    int color = 0xFF00FFFF; // magenta, uint tested 
    verts.push_back({ vert, normal, color }); 


glBufferData(GL_ARRAY_BUFFER, verts.size() * sizeof(Vertex_Color), &verts[0], GL_DYNAMIC_DRAW); 

glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex_Color), (const GLvoid*)0); 
glEnableVertexAttribArray(0); 
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex_Color), (const GLvoid*)(offsetof(Vertex_Color, normal))); 
glEnableVertexAttribArray(1); 
glVertexAttribPointer(2, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(Vertex_Color), (const GLvoid*)(offsetof(Vertex_Color, color))); 
glEnableVertexAttribArray(2); 

下面是一些例子:

Examples

我無法弄清楚什麼是錯的。提前致謝。

回答

4

您的代碼將內存中的4個連續字節重新解釋爲intint(和所有其他類型)的內部編碼是機器特定的。在你的情況下,你有32位整數存儲在little endian字節順序,這是個人電腦環境的典型案例。

您可以使用像GLubyte color[4]這樣的數組來明確獲取已定義的內存佈局。

如果您確實想要使用整數類型,則可以使用glVertexAttribIPointer(請注意I there)的整數屬性發送數據,並使用unpackUnorm4x8 om着色器來獲取標準化的浮點向量。但是,這至少需要GLSL 4.10,並且可能比標準方法效率低。

+0

謝謝,你說的對,我會用Vec4的顏色。 – Dementor