4.4 Multiple Meshes
https://www.khronos.org/opengl/wiki/Vertex_Specification_Best_Practices
https://www.khronos.org/opengl/wiki/Vertex_Rendering#Base_Index
Download
Complete Source Code:
BufferData.h
#ifndef BUFFERDATA_H
#define BUFFERDATA_H
/* these objects collect the vertex and index data for all meshes with the same vertex layout */
#include <vector>
#include "DrawCommands.h"
#include "Mesh.h"
template<typename T>
class ArrayBufferData
{
protected:
std::vector<T> m_vertices;
public:
ArrayBufferData() {}
virtual ~ArrayBufferData() {}
std::vector<T> Vertices() const { return m_vertices; }
void Clear()
{
m_vertices.clear();
}
DrawArrays AddMesh(const Mesh<T>& mesh)
{
DrawArrays cmd = { mode, (GLint)m_vertices.size(), mesh.Vertices.size() };
m_vertices.insert(m_vertices.end(), mesh.Vertices.begin(), mesh.Vertices.end());
return cmd;
}
};
template<typename T> /* indices = GLuint by default */
class IndexedBufferData
{
protected:
std::vector<T> m_vertices;
std::vector<GLuint> m_indices;
public:
IndexedBufferData() {}
virtual ~IndexedBufferData() {}
std::vector<T> Vertices() const { return m_vertices; }
std::vector<GLuint> Indices() const { return m_indices; }
void Clear()
{
m_vertices.clear();
m_indices.clear();
}
DrawElementsBaseVertex AddMesh(const Mesh<T>& mesh, GLenum mode)
{
std::vector<GLuint> indices;
for (auto& face : mesh.Faces)
{
indices.push_back(face.VertexIndexA);
indices.push_back(face.VertexIndexB);
indices.push_back(face.VertexIndexC);
}
DrawElementsBaseVertex cmd = { mode, (GLint)indices.size(), GL_UNSIGNED_INT, reinterpret_cast<GLvoid*>(m_indices.size() * sizeof(GLuint)), (GLint)m_vertices.size() };
m_vertices.insert(m_vertices.end(), mesh.Vertices.begin(), mesh.Vertices.end());
m_indices.insert(m_indices.end(), indices.begin(), indices.end());
return cmd;
}
};
#endif /* BUFFERDATA_H */
Graphics.cpp
#include "Graphics.h"
#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/transform.hpp>
#include <iostream>
#include <vector>
#include "Shader.h"
#include "DrawCommands.h"
#include "Mesh.h"
#include "BufferData.h"
using namespace std;
using namespace glm;
struct Vertex
{
vec3 Position;
vec4 Color;
};
uvec2 framebuffersize(0, 0);
GLuint program = 0;
GLuint vertexshader = 0;
GLuint fragmentshader = 0;
GLuint vertexarray = 0;
GLuint vertexbuffer = 0;
GLuint elementbuffer = 0;
DrawElementsBaseVertex drawelementsbasevertex_mesh;
/* collects multiple meshes, returns draw calls */
IndexedBufferData<Vertex> meshdata;
bool Graphics::Initialize(unsigned int width, unsigned int height)
{
/* set view port */
Resize(width, height);
/* general settings */
glClearColor(0.3f, 0.3f, 0.3f, 0.0f); /* background gray */
glEnable(GL_DEPTH_TEST);
/* create all objects */
program = glCreateProgram();
vertexshader = glCreateShader(GL_VERTEX_SHADER);
fragmentshader = glCreateShader(GL_FRAGMENT_SHADER);
glGenVertexArrays(1, &vertexarray);
glGenBuffers(1, &vertexbuffer);
glGenBuffers(1, &elementbuffer);
/* shader source */
string vertexshader_source(
"#version 450 core\n"
"layout (location = 0) in vec3 in_position;"
"layout (location = 1) in vec4 in_color;"
"layout (location = 0) uniform mat4 Model = mat4(1);"
"layout (location = 4) uniform mat4 View = mat4(1);"
"layout (location = 8) uniform mat4 Projection = mat4(1);"
"smooth out vec4 color;"
"void main() {"
"mat4 MVP = Projection * View * Model;"
"gl_Position = MVP * vec4(in_position, 1);"
"color = in_color;"
"}"
);
string fragmentshader_source(
"#version 450 core\n"
"smooth in vec4 color;"
"layout (location = 0) out vec4 out_color;"
"void main() {"
"out_color = color;"
"}"
);
/* compile shaders */
if (!CompileShader(vertexshader, vertexshader_source))
return false;
if (!CompileShader(fragmentshader, fragmentshader_source))
return false;
/* link program */
if (!LinkProgram(program, { vertexshader, fragmentshader }))
return false;
/* setup vertexarray */
glBindVertexArray(vertexarray);
glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), reinterpret_cast<void*>(offsetof(Vertex, Position)));
glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), reinterpret_cast<void*>(offsetof(Vertex, Color)));
glBindBuffer(GL_ARRAY_BUFFER, 0);
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
/* NOTE: the elementbuffer is also part of the vertex array */
/* while the VAO is bound, bind the element buffer */
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementbuffer);
glBindVertexArray(0);
/* anf after VAO is setup and unbound, savely unbind the elementbuffer again */
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
/* in OpenGL 4.5, there is a more "modern" way to do that */
/* glVertexArrayElementBuffer(vertexarray, elementbuffer); */
/* ... and another way to specify vertexbuffer: */
/* https://www.khronos.org/opengl/wiki/Vertex_Specification#Separate_attribute_format */
/* use a "Mesh" instead */
Mesh<Vertex> mesh;
mesh.Name = "triangle"; /* not really needed ... however */
mesh.Vertices.push_back({ { 0, 0, 0}, { 1, 0, 0, 1 } });
mesh.Vertices.push_back({ { 1, 0, 0}, { 0, 1, 0, 1 } });
mesh.Vertices.push_back({ { 0, 1, 0}, { 0, 0, 1, 1 } });
mesh.Faces.push_back({});
mesh.Faces.back().VertexIndexA = 0; /* index 0: first triangle vertex */
mesh.Faces.back().VertexIndexB = 1; /* index 1: second triangle vertex */
mesh.Faces.back().VertexIndexC = 2; /* index 2: third triangle vertex */
/* the parameters for a "glDrawElements(...)" call */
drawelementsbasevertex_mesh = meshdata.AddMesh(mesh, GL_TRIANGLES);
/* get mesh data */
vector<Vertex> vertices = meshdata.Vertices();
vector<GLuint> indices = meshdata.Indices();
/* setup vertexbuffer */
glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(Vertex) * vertices.size(), vertices.data(), GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
/* setup elementbuffer */
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementbuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLuint) * indices.size(), indices.data(), GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
/* successfully initialized */
return true;
}
void Graphics::CleanUp()
{
/* destroy all objects */
glDeleteProgram(program);
glDeleteShader(vertexshader);
glDeleteShader(fragmentshader);
glDeleteVertexArrays(1, &vertexarray);
glDeleteBuffers(1, &vertexbuffer);
glDeleteBuffers(1, &elementbuffer);
}
void Graphics::Render(const Scene& scene)
{
float aspectratio= (float)framebuffersize.x / framebuffersize.y;
mat4 View = scene.camera.View();
mat4 Projection = scene.camera.Projection(aspectratio);
/* view and projection matrix */
glProgramUniformMatrix4fv(program, 4, 1, GL_FALSE, value_ptr(View));
glProgramUniformMatrix4fv(program, 8, 1, GL_FALSE, value_ptr(Projection));
/* clear framebuffer */
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
/* draw triangles */
glUseProgram(program);
glBindVertexArray(vertexarray);
for (auto& object : scene.triangles)
{
mat4 Model = object.Transformation();
glUniformMatrix4fv(0, 1, GL_FALSE, value_ptr(Model));
/* render triangle */
Draw(drawelementsbasevertex_mesh);
}
glBindVertexArray(0);
glUseProgram(0);
CheckForGLError();
}
void Graphics::Resize(unsigned int width, unsigned int height)
{
framebuffersize = uvec2(width, height);
glViewport(0, 0, width, height);
}
GLContextInfo Graphics::GetContextInfos()
{
GLContextInfo infos;
glGetIntegerv(GL_MAJOR_VERSION, &infos.Version.Major);
glGetIntegerv(GL_MINOR_VERSION, &infos.Version.Minor);
infos.Version.Driver = (const char*)glGetString(GL_VERSION);
infos.Vendor = (const char*)glGetString(GL_VENDOR);
infos.Renderer = (const char*)glGetString(GL_RENDERER);
infos.Version.ShadingLanguage = (const char*)glGetString(GL_SHADING_LANGUAGE_VERSION);
GLint numberofextensions = 0;
glGetIntegerv(GL_NUM_EXTENSIONS, &numberofextensions);
for (int i = 0; i < numberofextensions; i++)
infos.SupportedExtensions.push_back((const char*)glGetStringi(GL_EXTENSIONS, i));
GLint numberofsupportedglslversions = 0;
glGetIntegerv(GL_NUM_SHADING_LANGUAGE_VERSIONS, &numberofsupportedglslversions);
for (int i = 0; i < numberofsupportedglslversions; i++)
infos.SupportedGLSLVersions.push_back((const char*)glGetStringi(GL_SHADING_LANGUAGE_VERSION, i));
return infos;
}
void Graphics::CheckForGLError()
{
for (GLenum error; (error = glGetError()) != GL_NO_ERROR;)
{
cout << "OpenGL Error: \t";
if (error == GL_INVALID_ENUM)
cout << "GL_INVALID_ENUM";
if (error == GL_INVALID_VALUE)
cout << "GL_INVALID_VALUE";
if (error == GL_INVALID_OPERATION)
cout << "GL_INVALID_OPERATION";
if (error == GL_STACK_OVERFLOW)
cout << "GL_STACK_OVERFLOW";
if (error == GL_STACK_UNDERFLOW)
cout << "GL_STACK_UNDERFLOW";
if (error == GL_OUT_OF_MEMORY)
cout << "GL_OUT_OF_MEMORY";
if (error == GL_INVALID_FRAMEBUFFER_OPERATION)
cout << "GL_INVALID_FRAMEBUFFER_OPERATION";
if (error == GL_CONTEXT_LOST)
cout << "GL_CONTEXT_LOST";
cout << (char)7 << endl; /*play sound*/
cin.get();
}
}