将颜色和位置从单独的VBO传递到着色器

本文关键字:VBO 颜色 位置 单独 | 更新日期: 2023-09-27 18:07:07

我试图从单独的VBO中绘制VAO。我的目标是让我的几何图形的每个顶点都有不同的颜色。但我的代码仍然是红色的。

我认为我的错误是这个代码片段。请帮我找到它。(我跳过了程序和矩阵设置)

            vao = new int[1];
            buffers = new int[2];
            GL.GenVertexArrays(1, vao);
            GL.GenBuffers(2, buffers);
            GL.BindVertexArray(vao[0]);
            GL.EnableVertexAttribArray(0);
            GL.BindBuffer(BufferTarget.ArrayBuffer, buffers[0]);
            unsafe
            {
                fixed (void* verts = quad_strip3)
                {
                    var prt = new IntPtr(verts);
                    GL.BufferData(BufferTarget.ArrayBuffer, new IntPtr(quad_strip3.Length * sizeof(float)), prt,
                        BufferUsageHint.StaticDraw);
                }
            }
            GL.VertexAttribPointer(0, 3, VertexAttribPointerType.Float, false, 0, new IntPtr(0));

            GL.BindBuffer(BufferTarget.ArrayBuffer, buffers[1]);
            var r = new Random();
            var colors = new float[quad_strip3.Length];
            for (int i = 0; i < colors.Length; i++)
            {
                colors[i] = (float)r.NextDouble();
            }

            unsafe
            {
                fixed (void* verts = colors)
                {
                    var prt = new IntPtr(verts);
                    GL.BufferData(BufferTarget.ArrayBuffer, new IntPtr(colors.Length * sizeof(float)), prt,
                        BufferUsageHint.StaticDraw);
                }
            }
            GL.VertexAttribPointer(1, 3, VertexAttribPointerType.Float, false, 0, new IntPtr(0));
<<p> 画代码/strong>
    GL.BindVertexArray(vao[0]);
    GL.DrawArrays(PrimitiveType.QuadStrip, 0, 26);

顶点着色器

#version 150 core
in vec3 in_Position;
in vec3 in_color;
out vec3 pass_Color;
uniform mat4 projectionMatrix;
uniform mat4 viewMatrix;
uniform mat4 modelMatrix;
void main(void) {
    gl_Position = projectionMatrix * viewMatrix * modelMatrix * vec4(in_Position, 1.0);
    pass_Color = in_color;
}

片段着色器

#version 150 core
in vec3 pass_Color;
out vec4 out_Color;
void main(void) {
    out_Color = vec4(pass_Color, 1.0);
}

将颜色和位置从单独的VBO传递到着色器

…解决方法很简单。我只是错过了EnableVertexAttribArray的颜色。

插入

        GL.EnableVertexAttribArray(1);

之前
        GL.BindBuffer(BufferTarget.ArrayBuffer, buffers[1]);

一切都运转起来了。