OpenGL - 着色器中的顶点颜色被交换
问题描述:
我想向着色器发送颜色,但颜色被交换, 我发送0xFF00FFFF(洋红色),但我在着色器中得到0xFFFF00FF(黄色)。OpenGL - 着色器中的顶点颜色被交换
我认为正在发生的事情是这样的,通过实验:
我的顶点着色器:
#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);
下面是一些例子:
我无法弄清楚什么是错的。提前致谢。
答
您的代码将内存中的4个连续字节重新解释为int
。 int
(和所有其他类型)的内部编码是机器特定的。在你的情况下,你有32位整数存储在little endian字节顺序,这是个人电脑环境的典型案例。
您可以使用像GLubyte color[4]
这样的数组来明确获取已定义的内存布局。
如果您确实想要使用整数类型,则可以使用glVertexAttribIPointer
(请注意I there)的整数属性发送数据,并使用unpackUnorm4x8
om着色器来获取标准化的浮点向量。但是,这至少需要GLSL 4.10,并且可能比标准方法效率低。
谢谢,你说的对,我会用Vec4的颜色。 – Dementor