前期的准备工作详见LearnOpenGL CN
看这篇教程的前提是假设你已经编译好了GLFW文件夹以及下载好了GLAD,不会的话可以看我的另一篇
文章的前部分: 配置
Clion新建一个项目,CMakeLists.txt请按照下面的填写:
1 cmake_minimum_required(VERSION 3.12) 2 project(OpenGL) #OpenGL是我的项目名称 3 4 set(CMAKE_CXX_STANDARD 11) 5 set(HEADERS /Users/1kasshole/Documents/libs/include) #只有这两个路径需要 6 set(GLFW_LINK /Users/1kasshole/Documents/libs/lib/libglfw3.a) #你自己设置 7 set(FRAMEWORKS_1 /System/Library/Frameworks/Cocoa.framework) 8 set(FRAMEWORKS_2 /System/Library/Frameworks/OpenGL.framework) 9 set(FRAMEWORKS_3 /System/Library/Frameworks/GLUT.framework) 10 set(FRAMEWORKS_4 /System/Library/Frameworks/CoreVideo.framework) 11 set(FRAMEWORKS_5 /System/Library/Frameworks/IOKit.framework) 12 13 include_directories(${HEADERS}) 14 15 link_libraries(${GLFW_LINK} ${FRAMEWORKS_1} ${FRAMEWORKS_2} ${FRAMEWORKS_3} ${FRAMEWORKS_4} ${FRAMEWORKS_5}) 16 17 add_executable(OpenGL main.cpp glad.c)
注意,HEADERS的路径include文件夹里请包含GLFW文件夹和glad文件夹
记得把你的GLAD文件夹里的glad.c放进你的项目目录中
测试代码:
// System Headers
#include
#include
// Standard Headers
#include
#include
#include
void framebuffer_size_callback(GLFWwindow* window, int width, int height);//回调函数原型声明
void processInput(GLFWwindow *window);
// settings
const unsigned int SCR_WIDTH = 800;
const unsigned int SCR_HEIGHT = 600;
int main(int argc, char * argv[]) {
//初始化GLFW
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
#ifdef __APPLE__
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // uncomment this statement to fix compilation on OS X
#endif
//创建一个窗口对象
GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "FirstGL", NULL, NULL);
if (window == NULL)
{
std::cout << "Failed to create GLFW window" << std::endl;
glfwTerminate();
return -1;
}
//通知GLFW将我们窗口的上下文设置为当前线程的主上下文
glfwMakeContextCurrent(window);
//对窗口注册一个回调函数,每当窗口改变大小,GLFW会调用这个函数并填充相应的参数供你处理
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
//初始化GLAD用来管理OpenGL的函数指针
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
{
std::cout << "Failed to initialize GLAD" << std::endl;
return -1;
}
//渲染循环
while(!glfwWindowShouldClose(window))
{
// 输入
processInput(window);
// 渲染指令
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
// 检查并调用事件,交换缓冲
glfwSwapBuffers(window);//检查触发事件
glfwPollEvents(); //交换颜色缓冲
}
//释放/删除之前的分配的所有资源
glfwTerminate();
return EXIT_SUCCESS;
}
//输入控制,检查用户是否按下了返回键(Esc)
void processInput(GLFWwindow *window)
{
if(glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
glfwSetWindowShouldClose(window, true);
}
// 当用户改变窗口的大小的时候,视口也应该被调整
void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
// 注意:对于视网膜(Retina)显示屏,width和height都会明显比原输入值更高一点。
glViewport(0, 0, width, height);
}
---------------------
作者:milletluo
来源:CSDN
原文:https://blog.csdn.net/lm409/article/details/78420044
运行效果: