Mac OpenGL 001.环境搭建及Hello,World

1.选择对应的工程MacOS 下的CommandLineTool工程,Next
First Step

2.填写工程名,以及选择语言C++,Next
2rd Step
3.单击工程名字,选择Build Phases,选择Link Binary Libraries,添加OpenGL.framework和GLUT.framework
3rd step
4.选择Build Setting 标签下搜索Macro,添加预编译宏去除后续OpenGL函数警告
4rd step
5.环境上述四步就可以了。然后修改main.cpp代码如下:

#include <iostream>
#include <OpenGL/gl.h>
#include <OpenGL/glu.h>
#include <GLUT/glut.h>

void myDisplay(void)
{
    glClear(GL_COLOR_BUFFER_BIT);
    glRectf(-0.5f, -0.5f, 0.5f, 0.5f);
    glFlush();
}
int main(int argc, char *argv[])
{
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE);
    glutInitWindowPosition(100, 100);
    glutInitWindowSize(400, 400);
    glutCreateWindow("第一个OpenGL程序");
    glutDisplayFunc(&myDisplay);

    const GLubyte* vendorName = glGetString(GL_VENDOR);    //返回负责GL实现的厂商名字
    const GLubyte* renderName = glGetString(GL_RENDERER);  //返回渲染器名称,通常是个硬件平台
    const GLubyte* OpenGLVersion =glGetString(GL_VERSION); //返回OpenGL版本号
    const GLubyte* gluVersion= gluGetString(GLU_VERSION);  //返回GLU工具库版本
    printf("GL实现的厂商名字:%s\n", vendorName);
    printf("渲染器名称:%s\n", renderName);
    printf("OpenGL版本号:%s\n",OpenGLVersion );
    printf("GLU工具库版本:%s\n", gluVersion);

    glutMainLoop();
    return 0;
}

6.运行查看效果绘制了一个矩形:
5rd step

7.也可以使用glfw库进行开发
需要记得安装好glfw库
6rd step

#include <iostream>
#include <GL/glew.h>
#include <GLFW/glfw3.h>

int main(void)
{
    GLFWwindow* window;
    
    /* Initialize the library */
    if (!glfwInit())
        return -1;
    
    /* Create a windowed mode window and its OpenGL context */
    window = glfwCreateWindow(640, 480, "Show Me Window", NULL, NULL);
    if (!window)
    {
        glfwTerminate();
        return -1;
    }
    
    fprintf(stdout, "Status: Using GLEW %s\n", glewGetString(GLEW_VERSION));
    
    glfwMakeContextCurrent(window);
    const GLubyte* OpenGLVersion =glGetString(GL_VERSION); //返回OpenGL版本号
    printf("OpenGL版本号:%s\n",OpenGLVersion );
    /* Initialize the library */
    GLenum err = glewInit();
    if (GLEW_OK != err) {
        fprintf(stderr, "Error: %s\n", glewGetErrorString(err));
    }
    if (GLEW_VERSION_4_1) {
        std::cout << "Yay! OpenGL 4.1 is supported!" << std::endl;
    }
    
    while (!glfwWindowShouldClose(window))
    {
        glClear(GL_COLOR_BUFFER_BIT);
        
        glfwSwapBuffers(window);
        glfwPollEvents();
    }
    
    glfwTerminate();
    return 0;
}

8.一般情况下都需要按键支持进行测试,下面是glfw按键处理回调设置

static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
    // 设置按键
    if( key == GLFW_KEY_ESCAPE && action == GLFW_PRESS )
        glfwSetWindowShouldClose(window, GL_TRUE);
    else if(key == GLFW_KEY_A && action == GLFW_RELEASE)
        printf("key A is released");
}

glfwSetKeyCallback(window, key_callback);
发布了90 篇原创文章 · 获赞 26 · 访问量 10万+

猜你喜欢

转载自blog.csdn.net/sky_person/article/details/100765370