opengl 来画个三角形
这次我们通过顶点数组的方式来画三角形。
#include "glew.h"
#include <glfw3.h>
int main(void)
{
GLFWwindow* window;
/* Initialize the library */
if (!glfwInit())
return -1;
/* Create a windowed mode window and its OpenGL context */
window = glfwCreateWindow(480, 320, "Hello World", NULL, NULL);
if (!window)
{
glfwTerminate();
return -1;
}
/* Make the window's context current */
glfwMakeContextCurrent(window);
// Needed in core profile
if( glewInit() != GLEW_OK)
{
glfwTerminate();
return -1;
}
// An array of 3 vectors which represents 3 vertices
static const GLfloat g_vertex_buffer_data[] = {
-1.0f,-1.0f,0.0f,
1.0f,-1.0f,0.0f,
0.0f,1.0f,0.0f,
};
//This will identify our vertex buffer
GLuint vertexbuffer;
//Generate 1 buffer,put the resulting identifier in vertexbuffer
glGenBuffers(1,&vertexbuffer);
//The following commands will talk about our 'vertexbuffer' buffer
glBindBuffer(GL_ARRAY_BUFFER,vertexbuffer);
//Give our vertices to OpenGL.
glBufferData(GL_ARRAY_BUFFER,sizeof(g_vertex_buffer_data),g_vertex_buffer_data,GL_STATIC_DRAW);
/* Loop until the user closes the window */
while (!glfwWindowShouldClose(window))
{
glEnableVertexAttribArray(0);
glVertexAttribPointer(
0, // attribute 0. No particular reason for 0, but must match the layout in the shader.
3, // size
GL_FLOAT, // type
GL_FALSE, // normalized?
0, // stride
(void*)0 // array buffer offset
);
glDrawArrays(GL_TRIANGLES,0,3);// Starting from vertex 0; 3 vertices total -> 1 triangle
glDisableVertexAttribArray(0);
/* Swap front and back buffers */
glfwSwapBuffers(window);
/* Poll for and process events */
glfwPollEvents();
}
glfwTerminate();
return 0;
}
首先工程里添加glew32.lib,cpp里添加#include "glew.h",引入glew库。glewInit(),glew库初始化。
const GLfloat g_vertex_buffer_data[] 顶点数组。glGenBuffers创建buffer,glBindBuffer激活buffer(指定是哪种类型的buffer),glBufferData传入数据,glEnableVertexAttribArray开户顶点数组属性,glVertexAttribPointer设置顶点数组属性,glDrawArrays画数组,glDisableVertexAttribArray关闭顶点数组属性