Mac上搭建开发环境
搭建环境是参考的这篇文章,在这里记录一下。
创建窗口
基本步骤:
- 初始化GLFW库,函数:glfwInit;
- 设置GLFW参数, 函数:glfwWindowHint;
- 创建窗口,函数:glfwCreateWindow;
- 将创建的窗口设置为上下文环境, 函数:glfwMakeContextCurrent;
- 使用GLAD库中的函数绑定OpenGL函数, 函数:gladLoadGLLoader;
- 设置视图大小,函数:glViewport;
- 渲染屏幕,在本例中简单的把屏幕填充为一个颜色,函数:glClearColor,glClear;
- 展示屏幕,函数:glfwSwapBuffers;
- 监听键盘事件,函数:glfwPollEvents;
- 释放资源,退出窗口,函数:glfwTerminate;
关键函数
-
glfwInit
这个函数用来初始化GLFW库; -
glfwWindowHint
这个函数用来设置GLFW相关参数 - glfwCreatWindow
代码
//
// main.cpp
// firstOpenGL
//
// Created by woodlouse on 2019/10/25.
// Copyright © 2019年 woodlouse. All rights reserved.
//
#include <stdio.h>
#include <iostream>
#include <glad/glad.h>
#include <GLFW/glfw3.h>
int main() {
using std::cout;
using std::endl;
glfwInit();
// 主版本
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
// 次版本
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
//
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
//向前兼容
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
GLFWwindow *window = glfwCreateWindow(800, 600, "LearOpenGL", NULL, NULL);
if (window == NULL) {
std::cout<<"Failed to creat GLFW window"<<std::endl;
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) {
std::cout<<"Failed to initalize GLAD"<<std::endl;
return -1;
}
glViewport(0, 0, 800, 600);
void framebuffer_size_callback(GLFWwindow *window, int width, int height);
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
void processInput(GLFWwindow *window);
while (!glfwWindowShouldClose(window)) {
processInput(window);
glClearColor(0.5f, 0.1f, 0.0f, 0.1f);
glClear(GL_COLOR_BUFFER_BIT);
glfwSwapBuffers(window);
glfwPollEvents();
}
glfwTerminate();
// printf("%s", "Hello world");
return 0;
}
void framebuffer_size_callback(GLFWwindow* window, int width, int height) {
glViewport(0, 0, width, height);
}
void processInput(GLFWwindow *window) {
if (glfwGetKey(window, GLFW_KEY_ESCAPE)==GLFW_PRESS) {
glfwSetWindowShouldClose(window, true);
}
}