Mini Project 2: Camera, Mesh and Lighting
In part 1 you opened a window and drew a triangle in normalized device coordinates. Now the engine gets a real 3D pipeline: a camera with view and projection matrices, meshes with index buffers loaded from OBJ files, a depth buffer, and Blinn-Phong lighting. These are roadmap steps 4, 5 and 7: camera and transformations, load a mesh, basic lighting.
The math behind every matrix here (model, view, projection, normal matrix) is explained in Math for Games, in particular Perspective and Orthographic Projection and Local, World and View Space. The lighting model is covered in depth in Shaders & Graphics Programming. This lesson wires them into the engine.
Step 4: A camera
The renderer needs two matrices per frame: view (world → camera space) and projection (camera space → clip space). glm builds both:
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp> // perspective, lookAt, translate, rotate
#include <glm/gtc/type_ptr.hpp> // value_ptr
struct FlyCamera {
glm::vec3 position{0.0f, 1.5f, 5.0f};
float yaw = -90.0f, pitch = -10.0f; // degrees; yaw -90 looks down -Z
float fovY = 60.0f;
glm::vec3 forward() const {
float y = glm::radians(yaw), p = glm::radians(pitch);
return glm::normalize(glm::vec3(std::cos(y) * std::cos(p), std::sin(p), std::sin(y) * std::cos(p)));
}
glm::mat4 view() const { return glm::lookAt(position, position + forward(), glm::vec3(0, 1, 0)); }
glm::mat4 projection(float aspect) const {
return glm::perspective(glm::radians(fovY), aspect, 0.1f, 200.0f);
}
};Drive it from SDL: WASD by scancode for movement, relative mouse mode for looking around. Movement uses the frame's dt here because the camera is presentation, not simulation; gameplay moves in fixed steps (part 3).
SDL_SetWindowRelativeMouseMode(window, true); // hide the cursor, report raw motion
// in the event loop
if (e.type == SDL_EVENT_MOUSE_MOTION) {
camera.yaw += e.motion.xrel * 0.1f; // xrel/yrel are floats in SDL3
camera.pitch = glm::clamp(camera.pitch - e.motion.yrel * 0.1f, -89.0f, 89.0f);
}
// once per frame
const bool* keys = SDL_GetKeyboardState(nullptr);
glm::vec3 fwd = camera.forward();
glm::vec3 right = glm::normalize(glm::cross(fwd, glm::vec3(0, 1, 0)));
float speed = 4.0f * dt;
if (keys[SDL_SCANCODE_W]) camera.position += fwd * speed;
if (keys[SDL_SCANCODE_S]) camera.position -= fwd * speed;
if (keys[SDL_SCANCODE_D]) camera.position += right * speed;
if (keys[SDL_SCANCODE_A]) camera.position -= right * speed;Clamping the pitch below 90° keeps lookAt from receiving a forward vector parallel to the up vector, where the cross product (and the camera) collapses.
Step 5: Meshes with index buffers
A cube has 8 corners but 24 distinct vertices, because each corner belongs to three faces with three different normals. An index buffer (EBO) lets triangles share vertices: 24 vertices and 36 indices instead of 36 full vertices. The GPU also caches recently transformed vertices, so shared indices save vertex shader work.
struct Vertex { glm::vec3 position; glm::vec3 normal; };
struct Mesh {
GLuint vao = 0, vbo = 0, ebo = 0;
GLsizei indexCount = 0;
};
Mesh uploadMesh(const std::vector<Vertex>& vertices, const std::vector<std::uint32_t>& indices) {
Mesh m;
m.indexCount = GLsizei(indices.size());
glGenVertexArrays(1, &m.vao);
glGenBuffers(1, &m.vbo);
glGenBuffers(1, &m.ebo);
glBindVertexArray(m.vao);
glBindBuffer(GL_ARRAY_BUFFER, m.vbo);
glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(Vertex), vertices.data(), GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m.ebo); // recorded in the VAO
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(std::uint32_t), indices.data(), GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, position));
glEnableVertexAttribArray(0);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, normal));
glEnableVertexAttribArray(1);
glBindVertexArray(0);
return m;
}
void drawMesh(const Mesh& m) {
glBindVertexArray(m.vao);
glDrawElements(GL_TRIANGLES, m.indexCount, GL_UNSIGNED_INT, nullptr);
}Loading OBJ files
Wavefront OBJ is a text format every 3D tool exports. It is a poor runtime format (slow to parse, no materials worth the name), but perfect for a first engine. A face corner like 3//2 means "position 3, no texture coordinate, normal 2" (1-based). Each unique position/normal pair becomes one vertex; repeated pairs reuse it. Polygons with more than three corners are split into a triangle fan.
This loader is engine code with no OpenGL in it, so it runs here. The input is a unit cube with one normal per face:
#include <cstdint>
#include <cstdio>
#include <map>
#include <sstream>
#include <string>
#include <utility>
#include <vector>
struct Vec3 { float x, y, z; };
struct Vertex { Vec3 position, normal; };
struct MeshData {
std::vector<Vertex> vertices;
std::vector<std::uint32_t> indices;
};
// Supports "v", "vn" and "f" with v//vn or v/vt/vn corners; enough for simple exports.
bool loadObj(const std::string& text, MeshData& out, std::string& error) {
std::vector<Vec3> positions, normals;
std::map<std::pair<int, int>, std::uint32_t> cache; // (pos, normal) -> vertex index
std::istringstream in(text);
std::string line;
int lineNo = 0;
while (std::getline(in, line)) {
lineNo++;
std::istringstream ls(line);
std::string tag;
ls >> tag;
if (tag == "v") { Vec3 p; ls >> p.x >> p.y >> p.z; positions.push_back(p); }
else if (tag == "vn") { Vec3 n; ls >> n.x >> n.y >> n.z; normals.push_back(n); }
else if (tag == "f") {
std::vector<std::uint32_t> corners;
std::string c;
while (ls >> c) {
int vi = 0, ni = 0;
std::size_t s1 = c.find('/'), s2 = c.rfind('/');
vi = std::stoi(c.substr(0, s1));
if (s1 != std::string::npos && s2 + 1 < c.size()) ni = std::stoi(c.substr(s2 + 1));
if (vi < 1 || vi > int(positions.size()) || ni < 1 || ni > int(normals.size())) {
error = "line " + std::to_string(lineNo) + ": bad index in '" + c + "'";
return false;
}
auto key = std::make_pair(vi, ni);
auto it = cache.find(key);
if (it == cache.end()) {
it = cache.emplace(key, std::uint32_t(out.vertices.size())).first;
out.vertices.push_back({positions[vi - 1], normals[ni - 1]});
}
corners.push_back(it->second);
}
for (std::size_t i = 1; i + 1 < corners.size(); i++) // triangle fan
out.indices.insert(out.indices.end(), {corners[0], corners[i], corners[i + 1]});
}
// other tags (vt, o, s, usemtl, #) are ignored
}
return true;
}
const char* kCube = R"(# unit cube, counter-clockwise faces seen from outside
v -0.5 -0.5 0.5
v 0.5 -0.5 0.5
v 0.5 0.5 0.5
v -0.5 0.5 0.5
v -0.5 -0.5 -0.5
v 0.5 -0.5 -0.5
v 0.5 0.5 -0.5
v -0.5 0.5 -0.5
vn 0 0 1
vn 0 0 -1
vn 1 0 0
vn -1 0 0
vn 0 1 0
vn 0 -1 0
f 1//1 2//1 3//1 4//1
f 6//2 5//2 8//2 7//2
f 2//3 6//3 7//3 3//3
f 5//4 1//4 4//4 8//4
f 4//5 3//5 7//5 8//5
f 5//6 6//6 2//6 1//6
)";
int main() {
MeshData mesh;
std::string error;
if (!loadObj(kCube, mesh, error)) { std::printf("error: %s\n", error.c_str()); return 1; }
std::printf("cube: %zu vertices, %zu indices (%zu triangles)\n", mesh.vertices.size(), mesh.indices.size(),
mesh.indices.size() / 3);
std::printf("first triangle: %u %u %u\n", mesh.indices[0], mesh.indices[1], mesh.indices[2]);
std::printf("bytes: %zu indexed vs %zu unindexed\n",
mesh.vertices.size() * sizeof(Vertex) + mesh.indices.size() * 4, mesh.indices.size() * sizeof(Vertex));
MeshData broken;
if (!loadObj("v 0 0 0\nvn 0 1 0\nf 1//1 2//1 3//1\n", broken, error)) std::printf("broken file: %s\n", error.c_str());
}cube: 24 vertices, 36 indices (12 triangles)
first triangle: 0 1 2
bytes: 720 indexed vs 864 unindexed
broken file: line 3: bad index in '2//1'
The loader reports a bad index with a line number instead of crashing: asset files come from outside the program, so treat them as untrusted input. For real projects, use cgltf or fastgltf to load glTF 2.0 (meshes, materials, skins and animations in one format), or tinyobjloader if you must read OBJ, and convert assets to a binary runtime format offline (see Binary Serialization).
Step 6: Depth and transforms
With more than one object, triangles must hide each other correctly. Enable the depth test once, clear depth every frame, and turn on back-face culling now that meshes are closed and wound counter-clockwise:
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE); // OpenGL's default: cull back faces, CCW = front
// per frame
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glm::mat4 viewProj = camera.projection(float(w) / float(h)) * camera.view();Step 7: Blinn-Phong lighting
The shaders transform positions to clip space and normals to world space, then light each pixel with an ambient term, a Lambert diffuse term and a Blinn-Phong specular highlight from one directional light:
// vertex shader
#version 330 core
layout(location = 0) in vec3 aPos;
layout(location = 1) in vec3 aNormal;
uniform mat4 uModel;
uniform mat4 uViewProj;
uniform mat3 uNormalMatrix; // transpose(inverse(mat3(model))), computed on the CPU
out vec3 vWorldPos;
out vec3 vNormal;
void main() {
vec4 world = uModel * vec4(aPos, 1.0);
vWorldPos = world.xyz;
vNormal = uNormalMatrix * aNormal;
gl_Position = uViewProj * world;
}// fragment shader
#version 330 core
in vec3 vWorldPos;
in vec3 vNormal;
uniform vec3 uBaseColor;
uniform vec3 uLightDir; // direction TOWARD the light, normalized
uniform vec3 uCameraPos;
out vec4 fragColor;
void main() {
vec3 n = normalize(vNormal); // interpolation shortens normals: renormalize
vec3 v = normalize(uCameraPos - vWorldPos);
vec3 h = normalize(uLightDir + v);
float diffuse = max(dot(n, uLightDir), 0.0);
float specular = diffuse > 0.0 ? pow(max(dot(n, h), 0.0), 32.0) : 0.0;
vec3 color = uBaseColor * (0.15 + 0.85 * diffuse) + vec3(0.25) * specular;
fragColor = vec4(color, 1.0);
}Setting the uniforms for each object:
glUseProgram(litProgram);
glUniformMatrix4fv(glGetUniformLocation(litProgram, "uViewProj"), 1, GL_FALSE, glm::value_ptr(viewProj));
glUniform3fv(glGetUniformLocation(litProgram, "uLightDir"), 1, glm::value_ptr(glm::normalize(glm::vec3(0.4f, 1.0f, 0.3f))));
glUniform3fv(glGetUniformLocation(litProgram, "uCameraPos"), 1, glm::value_ptr(camera.position));
for (const auto& object : objects) {
glm::mat3 normalMatrix = glm::transpose(glm::inverse(glm::mat3(object.model)));
glUniformMatrix4fv(glGetUniformLocation(litProgram, "uModel"), 1, GL_FALSE, glm::value_ptr(object.model));
glUniformMatrix3fv(glGetUniformLocation(litProgram, "uNormalMatrix"), 1, GL_FALSE, glm::value_ptr(normalMatrix));
glUniform3fv(glGetUniformLocation(litProgram, "uBaseColor"), 1, glm::value_ptr(object.color));
drawMesh(object.mesh);
}Look up uniform locations once after linking and store them; glGetUniformLocation per draw is a string lookup in the driver.
The lighting formula is ordinary math, so you can check it on the CPU. This model evaluates the same three terms for a few surface normals and shows why the normal matrix matters for non-uniformly scaled objects:
#include <cmath>
#include <cstdio>
struct V3 { double x, y, z; };
V3 operator+(V3 a, V3 b) { return {a.x + b.x, a.y + b.y, a.z + b.z}; }
double dot(V3 a, V3 b) { return a.x * b.x + a.y * b.y + a.z * b.z; }
V3 normalize(V3 v) { double l = std::sqrt(dot(v, v)); return {v.x / l, v.y / l, v.z / l}; }
double shade(V3 n, V3 lightDir, V3 viewDir) { // returns brightness for a white base color
n = normalize(n);
V3 h = normalize(lightDir + viewDir);
double diffuse = std::fmax(dot(n, lightDir), 0.0);
double specular = diffuse > 0 ? std::pow(std::fmax(dot(n, h), 0.0), 32.0) : 0.0;
return 0.15 + 0.85 * diffuse + 0.25 * specular;
}
int main() {
V3 light = normalize({0.4, 1.0, 0.3});
V3 view = normalize({0.0, 0.3, 1.0});
struct { const char* name; V3 n; } faces[] = {
{"top (0,1,0)", {0, 1, 0}}, {"front (0,0,1)", {0, 0, 1}}, {"right (1,0,0)", {1, 0, 0}},
{"bottom (0,-1,0)", {0, -1, 0}}, {"slope (0,1,1)", {0, 1, 1}},
};
for (auto& f : faces) std::printf("%-16s brightness %.3f\n", f.name, shade(f.n, light, view));
// A 45-degree slope on an object scaled by (1, 4, 1): stretched tall.
V3 n{0, 1, 1};
V3 wrong{n.x * 1, n.y * 4, n.z * 1}; // transformed like a position: tilts the wrong way
V3 right{n.x / 1, n.y / 4, n.z / 1}; // inverse-transpose of a diagonal scale = 1/scale
std::printf("normal after scale, model matrix : (%.3f, %.3f, %.3f)\n", normalize(wrong).x, normalize(wrong).y, normalize(wrong).z);
std::printf("normal after scale, normal matrix: (%.3f, %.3f, %.3f)\n", normalize(right).x, normalize(right).y, normalize(right).z);
}top (0,1,0) brightness 0.910
front (0,0,1) brightness 0.378
right (1,0,0) brightness 0.454
bottom (0,-1,0) brightness 0.150
slope (0,1,1) brightness 0.973
normal after scale, model matrix : (0.000, 0.970, 0.243)
normal after scale, normal matrix: (0.000, 0.243, 0.970)
Stretching the object vertically makes the slope steeper, so its true normal tilts toward the horizontal (y shrinks). Multiplying the normal by the model matrix tilts it the wrong way, and the lighting looks subtly off. The inverse-transpose gets it right.
Checkpoint 3: a ground plane (a flattened cube scaled to (20, 0.2, 20)) and a few colored cubes and OBJ models, lit from one direction, with a fly camera. Resize the window: nothing stretches anymore, because the projection uses the current aspect ratio.
Extensions before part 3
- Textures (roadmap step 6): add texture coordinates to
Vertex, load images withstb_image, upload withglTexImage2D, callglGenerateMipmap, sample in the fragment shader. - Several lights: pass arrays of light uniforms, or a uniform buffer object (UBO) shared by all programs.
- A debug draw API (
debugLine(a, b, color)) collected into one dynamic vertex buffer per frame. It pays for itself the first time you need to see a collision normal. - Render commands: instead of drawing inside the object loop, collect draw items, sort them by program and mesh, then draw. That is the Command Buffers and Sort Keys lesson in practice.
Test yourself
Why does a cube with flat-shaded faces need 24 vertices rather than 8?
- OpenGL needs at least 24 vertices
- Each corner is shared by three faces with different normals, and a vertex is a unique combination of position and normal
- Indices are limited to 8 values
- For the depth buffer
Why are normals transformed by the inverse-transpose of the model matrix?
- It is faster
- Under non-uniform scaling the plain model matrix tilts normals the wrong way; the inverse-transpose keeps them perpendicular to the surface
- Because normals are in clip space
- To normalize them
The camera's pitch is clamped to ±89°. What would go wrong at exactly 90°?
- Nothing
- The forward vector becomes parallel to the up vector, so lookAt's cross product degenerates
- The projection matrix fails
- The depth test flips