youtube博主The Cherno,播放列表在这 https://thecherno.com/opengl 。
代码位置:https://github.com/Niap/opengldemo
OpenGL环境搭建
首先,opengl只是一个标准,每个显卡厂商都有自己的实现,而且,opengl的open并不是指开源。其次,本文使用GLFW,GLFW就是一个对各个平台窗口,事件的一个实现,youtube教程上是在window上实现的,本文在macOS上实现
- 下载GLFW,点击箭头位置就行,会根据你的系统版本下载对应的包
- 目录介绍,include里面是头文件,因为在macOS上使用,关心一下lib-x86_64目录即可,文件夹中有两个文件,libglfw.3.dylib和libglfw3.a,前者是动态库,后者是静态库。本文用动态库,原因是静态库要链接的东西更多,比较费事。
- 创建一个文件夹作为项目目录,创建目录结构,如下图,拷贝GLFW的include到项目的include目录,拷贝lib-x86_64目录下的libglfw.3.dylib到lib目录下,
- 这里使用cmeke管理项目,所以在根目录下创建CMakeLists.txt,内容如下。如果有兴趣的话,可以把libglfw.3.dylib改成libglfw3.a,你会发现,整个项目需要objective-c的支持,虽然也可以通过cmake命令-G xcode来解决,但这个是另外一个话题了。
cmake_minimum_required (VERSION 2.8)
project (opengldemo)
include_directories (${CMAKE_CURRENT_LIST_DIR}/deps/include())
add_executable(main main.c)
target_link_libraries (main "-framework OpenGL" ${CMAKE_CURRENT_LIST_DIR}/deps/lib/libglfw.3.dylib)
- 创建main.c文件。内容从官网的 Documentation 中找到。
#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, "Hello World", NULL, NULL);
if (!window)
{
glfwTerminate();
return -1;
}
/* Make the window's context current */
glfwMakeContextCurrent(window);
/* Loop until the user closes the window */
while (!glfwWindowShouldClose(window))
{
/* Render here */
glClear(GL_COLOR_BUFFER_BIT);
/* Swap front and back buffers */
glfwSwapBuffers(window);
/* Poll for and process events */
glfwPollEvents();
}
glfwTerminate();
return 0;
}
- 根目录下输入如下命令,创建makefile,生成二进制文件。
cmake . & make