PART ONE
Step1: Run the IDE “Microsoft Visual Studio”, then click the “创建新项目” to create a “控制台应用” program with the “name" you like. Making sure that your IDE had already downloaded the "使用C++的桌面开发" components by the "Visual Studio installer".
Step2 : Delete the original codes that you can see and Copy&Paste the codes in the PART TWO, then right-click the program‘s name, here is "Triangle". Selecting the "管理NuGet程序包(N)", then type the "nupengl" like showing in the Image below. Clicking the "安装" button to install the packpage to use OpenGL with initializing the "glut and glfw". Now run the program, a triangle will be in the window which created by the "glut".
PART TWO
codes.cpp
#include <stdio.h>
#include <GL/glew.h>
#include <GL/freeglut.h>
struct Vector3f {
float x;
float y;
float z;
};
int width = 222;
int height = 207;
GLuint VBO;
void initVBO()
{
Vector3f Vertices[3];
Vertices[0] = { -1.0f, -1.0f, 0.0f }; // bottom left
Vertices[1] = { 1.0f, -1.0f, 0.0f }; // bottom right
Vertices[2] = {0.0f, 1.0f, 0.0f}; // top
glGenBuffers(1, &VBO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(Vertices), Vertices, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
void render()
{
glClear(GL_COLOR_BUFFER_BIT);
glClearColor(0.3f, 0.3f, 0.3f, 1.0f);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
glDrawArrays(GL_TRIANGLES, 0, 3);
glDisableVertexAttribArray(0);
glutSwapBuffers();
}
int main(int argc, char** argv)
{
// init GLUT
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA);
glutInitWindowSize(width, height);
glutInitWindowPosition(200, 100);
int id = glutCreateWindow("Triangle");
//printf("window id: %d\n", win);
// init GLEW after GLUT
GLenum err = glewInit();
if (err != GLEW_OK) {
fprintf(stderr, "Error: '%s'\n", glewGetErrorString(err));
return 1;
}
initVBO();
glutDisplayFunc(render);
glutMainLoop();
return 0;
}
部分三
代码分析
1、基本符合C++编程习惯,包含头文件、函数、主函数。
2、OpenGL是一个State Machine(状态机),SM渲染用的是OpenGL默认的渲染管线(DRPL:Default Rendering Pipeline),简称为DR(默认渲染版本)。在DR下,很多功能的实现是封装在GPU端,需要构建OpenGL Centext(上下文),给用户提供接口函数进行使用,接口函数主要是OpenGL的核心库中以”gl“开头命名,如gl<······>形式的函数。与DR相对应的是用户自定义的渲染管线(CRLP:Custom Rendering Pipeline)或软渲染管线(SRPL:Soft Rendering Pipeline),具体实现什么功能由用户自己完成,可以更加灵活的实现一些计算机图形学中的算法,简称为CR(自定义渲染版本)或SR。
3、主函数中包含glut的初始化(创建窗口等),glew的初始化(调用opengl变量、函数等)。
4、将CPU端数据(Vector3f Vertices[3])加载到GPU端的buffer中,此处使用的是顶点缓冲区VBO,因为对应的绑定点为GL_ARRAY_BUFFER。
5、render()渲染函数中,首先清空颜色缓冲区并设置一个背景色(默认为黑色),之后通过相关函数调用与VBO中数据相对应的属性点(默认为"0"),最后使用OpenGL中的绘制函数进行绘制后释放属性点,再使用双缓存技术将后面绘制端缓冲区中的数据交换到前端可以显示到屏幕的缓冲区进行显示。