

Purpose of the Sample:
Demonstrate how to map data from the CPU to a buffer that lives on the GPU. This sample is based on the learnopengl.com tutorial.
CGame.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
#ifndef __CGAME__ #define __CGAME__ #include <glad/glad.h> #include "shader_s.h" class CGame { public: CGame() {}; void Initialize(); void Shutdown(); void Render(); void OnResize(int width, int height); private: void SetupVAO(); void SetupGPUProgram(); unsigned int m_VBO; unsigned int m_VAO; Shader* m_pShader; }; #endif |
CGame.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
#include "CGame.h" void CGame::Initialize() { SetupGPUProgram(); SetupVAO(); } void CGame::Shutdown() { } void CGame::OnResize(int width, int height) { glViewport(0, 0, width, height); } void CGame::Render() { glClearColor(0.2f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); m_pShader->use(); glBindVertexArray(m_VBO); glDrawArrays(GL_TRIANGLES, 0, 3); } void CGame::SetupVAO() { float vertices[] = { -0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.5f, 0.0f, 0.0f, 0.0f, 1.0f }; glGenBuffers(1, &m_VBO); glGenVertexArrays(1, &m_VAO); // 1. bind Vertex Array Object glBindVertexArray(m_VAO); // 2. copy our vertices array in a buffer for OpenGL to use glBindBuffer(GL_ARRAY_BUFFER, m_VBO); // Allocate enough memory to hold our vertex buffer. // Don't forget the GL_MAP_WRITE_BIT! glBufferStorage(GL_ARRAY_BUFFER, sizeof(vertices), NULL, GL_MAP_WRITE_BIT); // Map the vertex data from the CPU to the GPU buffer. int count = sizeof(vertices); void* data = glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY); memcpy(data, vertices, count); glUnmapBuffer(GL_ARRAY_BUFFER); // 3. then set our vertex attributes pointers // Position Attribute. The offset is 0 since the position is at the start of thr array. glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)0); glEnableVertexAttribArray(0); // Color Attribute. The offset is 3 * sizeof(float) because the first color comes after the // first vertex position which is of size 3 * sizeof(float). glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)(3 * sizeof(float))); glEnableVertexAttribArray(1); } void CGame::SetupGPUProgram() { m_pShader = new Shader("vertex.glsl", "fragment.glsl"); } |
vertex.glsl
1 2 3 4 5 6 7 8 9 10 11 |
#version 330 core layout (location = 0) in vec3 aPos; layout(location = 1) in vec3 aColor; out vec3 vertexColor; void main() { vertexColor = aColor; gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0); } |
fragment.glsl
1 2 3 4 5 6 7 8 9 |
#version 330 core out vec4 FragColor; in vec3 vertexColor; void main() { FragColor = vec4(vertexColor.rgb, 1.0f); } |
Download Sample App

