Simple triangle using OpenGL and GLFW [duplicate]

╄→гoц情女王★ 提交于 2019-12-20 07:22:06

问题


I wrote a small program to display a simple triangle using vertex buffer. For the windowing i'm using glfw, my environment is Mac 10.9, XCode 5.

The window appears black but the triangle isn't paint.

Here the code:

#include <GLFW/glfw3.h>
#include <OpenGL/gl.h>
#include <iostream>

int main(int argc, const char * argv[])
{
    GLFWwindow* window;
    if (!glfwInit())
    {
        return -1;
    }

    glfwWindowHint (GLFW_CONTEXT_VERSION_MAJOR, 4);
    glfwWindowHint (GLFW_CONTEXT_VERSION_MINOR, 1);
    glfwWindowHint (GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
    glfwWindowHint (GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    window = glfwCreateWindow(640, 480, "Hello Triangle", NULL, NULL);
    if (!window) 
    {
        glfwTerminate();
        return -1;
    }

    glfwMakeContextCurrent(window);

    GLfloat verts[] =
    {
        0.0f,  0.5f,  0.0f,
        0.5f, -0.5f,  0.0f,
        -0.5f, -0.5f,  0.0f
    };

    //Generate a buffer id
    GLuint vboID;

    //Create a buffer on GPU memory
    glGenBuffers(1, &vboID);

    //Bind an arraybuffer to the ID
    glBindBuffer(GL_ARRAY_BUFFER, vboID);

    // Fill that buffer with the client vertex
    glBufferData(GL_ARRAY_BUFFER, sizeof(verts), verts, GL_STATIC_DRAW);

    //Enable attributes
    glEnableVertexAttribArray(0);

    // Setup a pointer to the attributes
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    while (!glfwWindowShouldClose(window))
    {
        glDrawArrays(GL_TRIANGLES, 0, 3);

        glfwPollEvents();
        glfwSwapBuffers(window);
    }

    glfwTerminate();
    return 0;
}

回答1:


You're choosing the OpenGL Core Profile for your rendering:

glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

Your code is missing a number of things to be Core Profile compliant:

  • You need to implement shader programs. The Core Profile does not support the old fixed pipeline anymore, and requires you to implement your own shaders in GLSL. Explaining how to do this in detail is beyond the scope of an answer, but you will be using calls like glCreateProgram, glCreateShader, glShaderSource, glCompileShader, glAttachShader, glLinkProgram. You should be able to find material online and in books.
  • You need to use Vertex Array Objects (VAO). Look up glGenVertexArrays and glBindVertexArray.


来源:https://stackoverflow.com/questions/24797999/simple-triangle-using-opengl-and-glfw

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!