渲染正方形

时间:2017-12-31 00:07:10

标签: c++ opengl glfw

我正试图在linux上使用openGL和GLFW渲染一个红色方块。但是,下面的代码只生成一个黑色背景的窗口,我无法弄清楚原因。 GLCall宏仅用于错误检查,不是问题的原因。

int main(){

    Window window(1280, 720);

    float vertices[] = {-0.5f, -0.5f,
                         0.5f, -0.5f,
                         0.5f,  0.5f,
                         0.5f,  0.5f,
                        -0.5f,  0.5f,
                        -0.5f, -0.5f
                        };

    const char* vertexShader = "#version 330 core\n"
                         "layout (location = 0) in vec2 position;\n"
                         "void main(){\n"
                         "gl_Position = vec4(position, 0.0, 1.0);\n"
                         "}";

    const char* fragmentShader = "#version 330 core\n"
            "out vec4 color;\n"
            "void main(){\n"
            "color = vec4(1.0f, 0.0f, 0.0f, 1.0f);\n"
            "}";


    GLuint vao;
    GLCall(glGenVertexArrays(1, &vao));
    GLCall(glBindVertexArray(vao));

    GLuint vbo;
    GLCall(glGenBuffers(1, &vbo));
    GLCall(glBindBuffer(GL_ARRAY_BUFFER, vbo));
    GLCall(glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, (void*)0));
    GLCall(glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW));

    GLuint vshader = glCreateShader(GL_VERTEX_SHADER);
    GLCall(glShaderSource(vshader, 1, &vertexShader, NULL));
    GLCall(glCompileShader(vshader));

    GLuint fshader = glCreateShader(GL_FRAGMENT_SHADER);
    GLCall(glShaderSource(fshader, 1, &fragmentShader, NULL));
    GLCall(glCompileShader(fshader));

    GLuint shader = glCreateProgram();
    GLCall(glAttachShader(shader, vshader));
    GLCall(glAttachShader(shader, fshader));
    GLCall(glLinkProgram(shader));
    GLCall(glUseProgram(shader));

    while(window.isOpen()){
        glClear(GL_COLOR_BUFFER_BIT);
        GLCall(glDrawArrays(GL_TRIANGLES, 0, 6));
        glfwSwapBuffers(window.getPointer());
        glfwPollEvents();
    }

    return 0;
}

2 个答案:

答案 0 :(得分:1)

我确定您必须包含glEnableVertexAttribArray(0);

答案 1 :(得分:1)

尝试添加:

{% for item in featured %}
<p>Country: {{item.package.country}}</p>
<p>Price: {{item.package.price}}</p>
<p>Image: <img src="{{item.image.url}}"></p>
{% endfor %} 

后:

glEnableVertexAttribArray(0);