docs.GL 国内镜像
LearnOpenGL CN 国内镜像
opengl-tutorial.org 国内镜像
Opengl 4.x Reference 国内镜像
- 镜像地址:https://qingcms.gitee.io/Opengl%204.x%20Reference
- 源地址:https://www.khronos.org/registry/OpenGL-Refpages/gl4/
第一课:打开一个窗口(节选)
打开一个窗口
终于到了写OpenGL代码的时刻!
呵呵,其实还没到真正写OpenGL代码的时刻。有些教程喜欢讲一些“底层”的细节,好让您清楚每一步的原理。这些内容往往索然无味,而且用处也不大。因此,我们直接把窗口、键盘消息等细节交给第三方库GLFW来处理。您也可以使用Windows的Win32 API、Linux的X11 API,或Mac的Cocoa API;或者SFML、FreeGLUT、SDL等库,请参见链接页。
开工啦。从处理依赖库开始:我们要用一些基本库在控制台显示消息:
// Include standard headers
#include <stdio.h>
#include <stdlib.h>
然后是GLEW库。其原理我们以后再说。
// Include GLEW. Always include it before gl.h and glfw3.h, since it's a bit magic.
#include <GL/glew.h>
我们使用GLFW库处理窗口和键盘消息,把它也包含进来:
// Include GLFW
#include <GLFW/glfw3.h>
下文中的GLM是个很有用3D数学库,我们暂时用不到,但很快就会派上用场。GLM库很好用,但也没什么神奇的,您不妨自己试着写一个。添加“using namespace”,这样就可以不用写“glm::vec3”,直接写“vec3”。
// Include GLM
#include <glm/glm.hpp>
using namespace glm;
把这些#include都粘贴到playground.cpp。编译时编译器报错,说缺少main函数,那就创建一个呗:
int main(){
首先初始化GLFW :
// Initialise GLFW
if( !glfwInit() )
{
fprintf( stderr, "Failed to initialize GLFW\n" );
return -1;
}
终于可以创建我们的第一个OpenGL窗口啦!
glfwWindowHint(GLFW_SAMPLES, 4); // 4x antialiasing
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); // We want OpenGL 3.3
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // To make MacOS happy; should not be needed
glfwWindowHint(GLFW_CONTEXT_PROFILE, GLFW_OPENGL_CORE_PROFILE); //We don't want the old OpenGL
// Open a window and create its OpenGL context
GLFWwindow* window;
window = glfwCreateWindow(1024, 768, "Totorial 01", NULL, NULL);
if (window == NULL)
{
fprintf( stderr, "Failed to open GLFW window\n" );
glfwTerminate();
return -1;
}
// Initialize GLEW
glfwMakeContextCurrent(window);
glewExperimental=true; // Needed in core profile
if (glewInit() != GLEW_OK) {
fprintf(stderr, "Failed to initialize GLEW\n");
return -1;
}
生成并运行。一个窗口弹出后立即关闭了。可不是嘛,还没设置等待用户按Esc键再关闭呢:
// Ensure we can capture the escape key being pressed below
glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE);
do{
// Draw nothing, see you in tutorial 2 !
// Swap buffers
glfwSwapBuffers(window);
} // Check if the ESC key was pressed or the window was closed
while( glfwGetKey(window, GLFW_KEY_ESCAPE) != GLFW_PRESS &&
glfwWindowShouldClose(window) == 0);