// Vertex Shader
#version 330
layout (location = 0) in vec3 pos;
out vec4 vCol;
uniform mat4 model;
void main()
{
gl_Position = model * vec4(pos, 1.0f);
vCol = vec4(clamp(pos, 0.0f, 1.0f), 1.0f);
}
// Fragment Shader
#version 330
in vec4 vCol;
out vec4 Color;
void main()
{
color = vCol;
}
// main Program
...
GLfloat vertices[] = {
-1.0f, -1.0f, 0.0f, // (-1.0, -1.0, 0.0) RGB(0, 0, 0) 검정색
1.0f, -1.0f, 0.0f, // (1.0, -1.0, 0.0) RGB(1, 0, 0) 빨간색
0.0f, 1.0f, 0.0f // (0.0, 1.0, 0.0) RGB(0, 1, 0) 초록색
};
...

일반 드로잉 : 2개의 삼각형을 위해서는 6개의 정점 필요, 이 과정에서 2개의 정점은 중복해서 데이터에 포함됨.
인덱스 드로잉 : 고유한 정점 4개만 정의한 뒤, 어떤 순서로 이 정점들을 연결하여 삼각형을 만들지 인덱스로 알려줌.
void CreateTriangle() {
unsigned int indices[] = {
0, 3, 1,
1, 3, 2,
2, 3, 0,
0, 1, 2
};
GLfloat vertices[] = {
-1.0f, -1.0f, 0.0f,
0.0f, -1.0f, 1.0f,
1.0f, -1.0f, 0.0f,
0.0f, 1.0f, 0.0f
};
glGenVertexArrays(1, &VAO); // create VAO
glBindVertexArray(VAO); // bind VAO
glGenBuffers(1, &IBO); // create IBO
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IBO); // bind IBO
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
glGenBuffers(1, &VBO); // create VBO
glBindBuffer(GL_ARRAY_BUFFER, VBO); // bind VBO
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); // copy vertices to VBO
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, 0); // unbind VBO
glBindVertexArray(0); // unbind VAO
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); // unbind IBO
}
...
glEnable(GL_DEPTH_TEST); // Enable depth testing for 3D
...
// Clear window
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glBindVertexArray(VAO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IBO);
glDrawElements(GL_TRIANGLES, 12, GL_UNSIGNED_INT, 0);
glBindVertexArray(0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

gl_Position = projection * view * model * aPos;
// Vertex Shader
#version 330
layout (location = 0) in vec3 pos;
out vec4 vCol;
uniform mat4 model;
uniform mat4 projection;
void main()
{
gl_Position = projection * model * vec4(pos, 1.0f);
vCol = vec4(clamp(pos, 0.0f, 1.0f), 1.0f);
}
// main Program
GLuint uniformProjection = glGetUniformLocation(shader, "projection");
glm::mat4 projection = glm::perspective(45.0f, (GLfloat)bufferWidth / (GLfloat)bufferHeight, 0.1f, 100.0f);
glUniformMatrix4fv(uniformProjection, 1, GL_FALSE, glm::value_ptr(projection));
