準(zhǔn)備環(huán)境
-
Mac
macOS Monterey 12.x俯逾,intel處理器,x86_64架構(gòu)
- VSCode
插件 C/C++和Code Runner - Xcode
AppStore最新版本即可 - GLFW
GLFW是一個(gè)免費(fèi)的匪蟀、開(kāi)源的当娱、多平臺(tái)的OpenGL、OpenGL ES和Vulkan應(yīng)用程序開(kāi)發(fā)庫(kù)。它提供了一個(gè)簡(jiǎn)單的皇钞、平臺(tái)獨(dú)立的API,用于創(chuàng)建窗口誉结、上下文和界面鹅士、讀取輸入、處理事件等惩坑。
打開(kāi)官網(wǎng)點(diǎn)擊Download掉盅,下載Mac版編譯好的library;
編碼
項(xiàng)目目錄
將下載好的glfw3.h以舒、glfw3native.h趾痘、libglfw3.a放到相應(yīng)目錄下
代碼
測(cè)試代碼如下
#include <GLFW/glfw3.h>
#include <iostream>
using namespace std;
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;
}
啟動(dòng)
按F5,選擇clang++的啟動(dòng)方式
tasks.json的配置如下
{
"tasks": [
{
"type": "cppbuild",
"label": "C/C++: clang++ 生成活動(dòng)文件",
"command": "/usr/bin/clang++",
"args": [
"-fdiagnostics-color=always",
"-g",
"${file}",
"${fileDirname}/depends/libglfw3.a", // 指定glfw包
"-o",
"${fileDirname}/${fileBasenameNoExtension}",
"--include-directory=${fileDirname}/depends/include", // 指定目錄
"-framework", "Cocoa", "-framework", "OpenGL", "-framework", "IOKit", "-framework", "CoreVideo" // 引入iOS框架
],
"options": {
"cwd": "${fileDirname}"
},
"problemMatcher": [
"$gcc"
],
"group": "build",
"detail": "調(diào)試器生成的任務(wù)蔓钟。"
}
],
"version": "2.0.0"
}
啟動(dòng)效果
出現(xiàn)如下效果永票,openGL的window已經(jīng)創(chuàng)建完畢,表示成功了~
我們嘗試著畫(huà)一個(gè)三角形滥沫,在這里加入如下代碼
while (!glfwWindowShouldClose(window))
{
/* Render here */
glClear(GL_COLOR_BUFFER_BIT);
// new code
glBegin(GL_TRIANGLES);
glVertex2f(-0.5f, -0.5f);
glVertex2f(0.0f, 0.5f);
glVertex2f(0.5f, -0.5f);
glEnd();
/* Swap front and back buffers */
glfwSwapBuffers(window);
/* Poll for and process events */
glfwPollEvents();
}
F5運(yùn)行侣集,awesome~
GLEW
不同的顯卡公司,也會(huì)發(fā)布一些只有自家顯卡才支 持的擴(kuò)展函數(shù)兰绣,你要想用這數(shù)涵數(shù)世分,不得不去尋找最新的glext.h,有了GLEW擴(kuò)展庫(kù),你就再也不用為找不到函數(shù)的接口而煩惱缀辩,因?yàn)镚LEW能自動(dòng)識(shí)別你的平臺(tái)所支持的全部OpenGL高級(jí)擴(kuò)展函數(shù)臭埋。也就是說(shuō),只要包含一個(gè)glew.h頭文件臀玄,你就能使用gl,glu,glext,wgl,glx的全部函數(shù)瓢阴。
下載
brew install glew
引入
下載好后在/usr/local/Cellar/中找到所需要的靜態(tài)庫(kù)然后新增如下代碼
F5運(yùn)行
awesome~