c++ - 使用 OpenGL 和 GLFW 的简单三角形

标签 c++ xcode opengl glfw

<分区>

我编写了一个小程序来使用顶点缓冲区显示一个简单的三角形。对于窗口,我使用的是 glfw,我的环境是 Mac 10.9,XCode 5。

窗口显示为黑色,但三角形未绘制。

这里是代码:

#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;
}

最佳答案

您正在为您的渲染选择 OpenGL Core Profile:

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

您的代码缺少一些符合 Core Profile 的东西:

  • 您需要实现着色器程序。 Core Profile 不再支持旧的固定管道,需要您在 GLSL 中实现自己的着色器。详细解释如何执行此操作超出了答案的范围,但您将使用 glCreateProgramglCreateShaderglShaderSourceglCompileShaderglAttachShaderglLinkProgram。您应该能够在网上和书籍中找到资料。
  • 您需要使用顶点数组对象 (VAO)。查找 glGenVertexArraysglBindVertexArray

关于c++ - 使用 OpenGL 和 GLFW 的简单三角形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24797999/

相关文章:

opengl - (openGL) 是否应该避免使用不存在的制服的句柄?

opengl - 是否可以使用openGL绘制YUV422和YUV420纹理

C++ 模板实例 : using enable_if directly, 或带有辅助类

java - 我可以在 XCode 3.2.1 中编写 Java 代码吗?

c# - 您会使用哪种 C# 项目类型重新开发 MFC C++ activex 控件?

ios - 解析查询未按降序加载

objective-c - Objective-C 中 C 函数的重复符号错误

c++ - 为什么 glGetProgramiv GL_ACTIVE_UNIFORMS 偶尔会返回垃圾并使我的程序崩溃?

c++ - 如何将一个类的函数作为另一个类的另一个函数的参数传递

c++ - 无法解决构建 Android NDK 库时出现的 "undefined reference to"错误