Mac OpenGL入门:显示颜色

概述

这里以显示一个红色的窗口为例,展示Mac下运行OpenGL代码的一些配置项。这里采用c++ 和cmake来编译代码的方式,比用xcode更直观。

依赖安装

1
2
brew install glfw3 glew cmake

源代码

C++源码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <GL/glew.h>
#include <GLFW/glfw3.h>

#include <iostream>


using namespace std;

void init(GLFWwindow* window) {
}

void display(GLFWwindow* window, double currentTime) {
glClearColor(1.0, 0.0, 0.0, 1.0);
glClear(GL_COLOR_BUFFER_BIT);
}

int main() {
if (!glfwInit()) {
exit(EXIT_FAILURE);
}

glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1);

// mac增加的代码
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);

GLFWwindow* window = glfwCreateWindow(600, 600, "Chapter 2 - program1", NULL, NULL);
glfwMakeContextCurrent(window);

if (glewInit() != GLEW_OK) {
exit(EXIT_FAILURE);
}

glfwSwapInterval(1);

init(window);

while (!glfwWindowShouldClose(window)) {
display(window, glfwGetTime());

glfwSwapBuffers(window);
glfwPollEvents();
}

glfwDestroyWindow(window);
glfwTerminate();

exit(EXIT_SUCCESS);
}

cmake文件

cmake 代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
cmake_minimum_required(VERSION 3.10)
project(show_box)

include_directories(/usr/local/include)
link_directories(/usr/local/Cellar/glew/2.2.0_1/lib)
link_directories(/usr/local/Cellar/glfw/3.3.4/lib)

add_executable(${PROJECT_NAME} ch2.1.cpp)

target_link_libraries(${PROJECT_NAME}
GLEW
GLFW
"-framework OpenGL"
)

编译代码

1
2
3
4
5
mkdir build
cd build
cmake ..
make -j8
./show_box