Chapter 7: The baroque world of computer graphics
The chapter introduces hardware-accelerated graphics as a visible form of systems programming and explains why working with GPUs is demanding.
After this chapter you will be able to
- Systems demands of GPU programming. Explain why programming GPUs calls for systems knowledge as well as graphics-specific learning.
- OpenGL’s common graphics interface. Explain why OpenGL emerged and how its standard interface lets programmers target different graphics hardware without writing for each device and operating system.
- OpenGL’s historical baggage. Explain why OpenGL can feel inconsistent and arbitrary despite having been redesigned many times.
- Reasons to learn OpenGL. Justify learning OpenGL despite its awkwardness, including what it offers beyond writing portable code.
- OpenGL 3.3 Core choice. Explain why the chapter chooses OpenGL 3.3 Core rather than pursuing a newer, more hardware-focused option.
- OpenGL rasterization model. Explain what rasterization does and how OpenGL’s pipeline differs from Raylib’s ready-made drawing functions.
- Pipeline stages and data. Trace the section’s high-level path from vertices and a draw call to a finished image.
- Programmable shader roles. Distinguish what the vertex shader and fragment shader do, and explain why shaders are not limited to lighting.
- OpenGL specification and implementations. Explain why OpenGL alone does not provide a working graphics implementation, and distinguish its specification from the implementations supplied for particular systems.
- GLFW platform support. Explain what GLFW handles for an OpenGL application across operating systems.
- Glad and consistent headers. Justify using the OpenGL loader library glad alongside GLFW rather than relying on operating-system OpenGL headers.
- C Library Build Dependencies. Explain why GLFW and glad complicate the Zig project’s build setup and identify an alternative to managing them manually.
- Project Run Workflow. Describe the initial project layout and explain how the build-and-run command supports rapid iteration.
- Static and dynamic linking. Explain why static linking is often preferred in Zig and why GLFW still relies on dynamic system libraries.
- GLFW header translation. Describe how the project makes GLFW’s C declarations available to Zig, from a root header to an importable module.
- Glad generator configuration. Explain how glad is generated and describe the configuration chosen for this project.
- Vendored source benefits. Explain what vendoring glad means and why the section recommends it.
- Glad build integration. Describe how glad is made available to Zig and compiled as part of the C module.
- Framebuffer swapping and visibility. Explain what a framebuffer holds and how GLFW’s default double buffering prevents users from seeing incomplete frames.
- GLFW error queries. Describe how to inspect a previous GLFW error with glfwGetError.
- GLFW error callback. Explain why an error callback suits this program as an alternative to manually querying GLFW errors.
- C compatible calling convention. Explain how callconv(.c) makes the Zig error callback compatible with the C ABI without exposing it as a library function.
- Context and pipeline state. Explain how an OpenGL context holds state used to configure a draw call.
- Pipeline data and objects. Describe what OpenGL objects hold, why the implementation manages their storage, and what binding does to their state.
- Integer object names. Explain how a program refers to OpenGL objects without touching them directly.
- Screen and normalized coordinates. Distinguish screen space from normalized device coordinates and explain the vertex shader’s role in relating coordinates to the rasterizer.
- Clip space and clipping. Explain how vertex shader output in clip space becomes normalized device coordinates and what clipping means.
- Triangle winding and culling. Explain how vertex winding distinguishes front-facing and back-facing triangles and how face culling affects visibility.
- Shader Compilation and Linking. Trace how the shader sources are compiled and linked into a program, including error checks and when initialization performs the work.
- Zig Multiline Shader Strings. Explain how Zig multiline strings represent the shader sources and how their line syntax works.
- Per Vertex Attribute Inputs. Explain how draw calls and vertex attributes supply input to vertex processing.
- Vertex Array Object State. Explain why OpenGL preserves attribute state in a vertex array object.
- Vertex data and buffers. Explain how a VBO stores vertex data and why a VAO needs to be told what that data represents.
- Object name binding hygiene. Explain how object name binding selects a buffer for operations and how to limit unintended side effects.
- VAO attribute configuration. Trace how the bound VBO is connected to the bound VAO’s shader attribute and how that attribute is enabled.
- Draw calls and bound objects. Explain how glDrawArrays uses the currently bound VAO and program object to draw a primitive.
- Per-frame framebuffer clearing. Explain why the screen is conventionally cleared each frame before drawing.
- Graphics exploration tools. Distinguish how RenderDoc and Shadertoy can help you explore graphics: RenderDoc lets you inspect a captured program, while Shadertoy offers examples of GLSL shader techniques and creative work.
What it builds on
- Our build script (chapter 3) · The earlier introduction to a Zig build script.
- So, what is the C ABI, and why do we care about it? (chapter 5) · The C ABI and why compatibility with it matters
- Strings without slices (chapter 5) · C strings and their representation across the C interface
Section by section
Introduction
The chapter introduces hardware-accelerated graphics as a visible form of systems programming and explains why working with GPUs is demanding.
- Systems demands of GPU programming: Explain why programming GPUs calls for systems knowledge as well as graphics-specific learning.
Why it matters: It explains why graphics work draws on familiar systems-programming skills while presenting new difficulties. - Visibility of graphics work: Distinguish hardware-accelerated graphics from the less visible work systems programmers often do.
Why it matters: The contrast frames graphics as a different, highly visible application of systems programming.
Key terms: GPUs, hardware accelerated graphics, graphics APIs, resources with connected lifetimes, invisible computing
7.1 Designed by aliens, for aliens
The section explains why OpenGL provides a common interface across competing graphics hardware and distinguishes graphics from window and input management.
- OpenGL’s common graphics interface: Explain why OpenGL emerged and how its standard interface lets programmers target different graphics hardware without writing for each device and operating system.
Why it matters: This explains the practical problem OpenGL solves before the chapter uses it. - Graphics and window management: Distinguish OpenGL’s graphics interface from the management of windows and input.
Why it matters: The distinction helps explain why graphics code and window or input code appear separately. - Meaning of hardware acceleration: Describe hardware acceleration and identify the GPU as specialized hardware for graphics.
Why it matters: This clarifies what the section means by hardware-accelerated graphics.
Key terms: OpenGL, standard interface, device drivers, graphics, windows, input, hardware acceleration, GPUs
7.1.1 Unfortunately, the history of graphics APIs matters
The section explains why OpenGL can feel awkward yet remains worth learning, why the chapter uses OpenGL 3.3 Core, and where readers can look for further help.
- OpenGL’s historical baggage: Explain why OpenGL can feel inconsistent and arbitrary despite having been redesigned many times.
Why it matters: Its history gives you a reason for some of the awkwardness you will encounter. - Reasons to learn OpenGL: Justify learning OpenGL despite its awkwardness, including what it offers beyond writing portable code.
Why it matters: The effort has value both for broad compatibility and for understanding what graphics frameworks do for you. - OpenGL 3.3 Core choice: Explain why the chapter chooses OpenGL 3.3 Core rather than pursuing a newer, more hardware-focused option.
Why it matters: The chosen version balances the chapter’s graphics needs with access to older hardware. - Further OpenGL resources: Distinguish the suggested resources by what they offer and any cautions the section gives about using them.
Why it matters: These distinctions help you choose useful help without mistaking a different API version or toolchain for the chapter’s setup.
Key terms: OpenGL, boilerplate, build integration, Raylib, Unity, Unreal Engine, OpenGL 3.3 Core, Vulkan, hardware, official reference material
7.1.2 The rasterization pipeline
This section maps how OpenGL turns vertex data into an image through the rasterization pipeline.
- OpenGL rasterization model: Explain what rasterization does and how OpenGL’s pipeline differs from Raylib’s ready-made drawing functions.
Why it matters: This distinction explains why OpenGL drawing is discussed as a pipeline rather than a call to draw a particular shape. - Pipeline stages and data: Trace the section’s high-level path from vertices and a draw call to a finished image.
Why it matters: The order of these stages is the map for where later OpenGL code fits. - Programmable shader roles: Distinguish what the vertex shader and fragment shader do, and explain why shaders are not limited to lighting.
Why it matters: Knowing which stage each shader programs helps explain how geometry changes and visual effects are produced.
Key terms: OpenGL, Raylib, rasterization, rasterization pipeline, vertices, draw call, vertex shader, rasterizer, fragments, fragment shader
7.1.3 Actually getting access to the pipeline
This section explains why reaching an OpenGL draw call requires platform-specific implementations, desktop-environment support, and libraries that bridge those differences.
- OpenGL specification and implementations: Explain why OpenGL alone does not provide a working graphics implementation, and distinguish its specification from the implementations supplied for particular systems.
Why it matters: It explains why writing OpenGL calls is not, by itself, enough to draw on every system. - Desktop environment responsibilities: Describe why a graphical application must deal with the desktop environment and why that complicates cross-platform development.
Why it matters: A portable graphics application has to handle windows and input as well as graphics calls. - GLFW platform support: Explain what GLFW handles for an OpenGL application across operating systems.
Why it matters: GLFW supplies the platform-facing pieces that the OpenGL specification does not. - Glad and consistent headers: Justify using the OpenGL loader library glad alongside GLFW rather than relying on operating-system OpenGL headers.
Why it matters: It explains why GLFW alone is not the chosen solution for compiling and running across as many systems as possible.
Key terms: OpenGL, specification, driver implementation, platform agnostic, desktop environment, GUI window, user input, GLFW, OpenGL context, OpenGL features
7.2 A minimally messy build process
This section introduces a Zig graphics project’s dependency-management challenge and a basic build-and-run workflow.
- C Library Build Dependencies: Explain why GLFW and glad complicate the Zig project’s build setup and identify an alternative to managing them manually.
Why it matters: This explains why the graphics project needs more build setup than a standalone Zig program. - Project Run Workflow: Describe the initial project layout and explain how the build-and-run command supports rapid iteration.
Why it matters: A short edit-and-run cycle helps you see the effects of graphics changes without losing focus. - Generalized Build Run Steps: Describe how run steps can be used beyond launching the project executable from the command line.
Why it matters: Run steps can automate programs within a build, not just launch the application for a developer.
Key terms: dependency management, GLFW, glad, build.zig, bindings, src/, main.zig, zig build run, edit-compile-run cycle, run steps
7.2.1 Translating GLFW
This section explains linking GLFW and translating its C headers into a Zig-importable module.
- Static and dynamic linking: Explain why static linking is often preferred in Zig and why GLFW still relies on dynamic system libraries.
Why it matters: This explains both the portability motivation for static linking and the constraint GLFW introduces. - GLFW header translation: Describe how the project makes GLFW’s C declarations available to Zig, from a root header to an importable module.
Why it matters: This connects the GLFW C interface to code the Zig application can import. - Build script helper import: Explain why the translation setup imports a helper struct in the build script and what build-script imports can access.
Why it matters: This clarifies an unusual-looking import in the translation setup.
Key terms: static linking, dynamic linking, system libraries, C translation, root source file, header files, glfw3 system library, module, translate-c, helper struct
7.2.2 glad
This section generates a project-specific glad library, vendors its source, and integrates it into the Zig build.
- Glad generator configuration: Explain how glad is generated and describe the configuration chosen for this project.
Why it matters: The generated library must match the OpenGL functionality the project intends to use. - Vendored source benefits: Explain what vendoring glad means and why the section recommends it.
Why it matters: Keeping the source in the project gives the team control over its availability and changes. - Glad build integration: Describe how glad is made available to Zig and compiled as part of the C module.
Why it matters: Both the translated declarations and the compiled C implementation are needed to include glad in the project.
Key terms: glad, OpenGL 3.3, core profile, compatibility profile, extensions, vendoring, vendor code, src/c.h, GLFW, translate-c
7.3 The canvas
7.3.1 Creating a window with GLFW
This section introduces the GLFW window application pattern, C-style error checks, and double buffering for displaying complete frames.
- GLFW application structure: Describe the basic structure of a GLFW application that opens a blank window.
Why it matters: This pattern provides the starting point for a windowed graphics application. - GLFW error return checks: Explain how the GLFW C interface signals success or failure and what a Zig program must do to check it.
Why it matters: Checking GLFW’s return values helps a Zig program detect failures when using the C library. - Framebuffer swapping and visibility: Explain what a framebuffer holds and how GLFW’s default double buffering prevents users from seeing incomplete frames.
Why it matters: Buffer swapping lets an application show finished frames rather than partially drawn images.
Key terms: GLFW, loop, frame, GLFW_TRUE, GLFW_FALSE, NULL, error sets, framebuffer, double buffered, front buffer
7.3.2 Don’t we care about error handling?
This section explains how to inspect and report GLFW errors from Zig and configure the requested OpenGL version before window creation.
- GLFW error queries: Describe how to inspect a previous GLFW error with glfwGetError.
Why it matters: Error queries let you obtain diagnostic information when a GLFW operation goes wrong. - GLFW error callback: Explain why an error callback suits this program as an alternative to manually querying GLFW errors.
Why it matters: A callback makes GLFW errors visible without requiring this program to implement specific recovery for each one. - C compatible calling convention: Explain how callconv(.c) makes the Zig error callback compatible with the C ABI without exposing it as a library function.
Why it matters: A callback passed to a C library needs a calling convention compatible with that library. - C string pointer choice: Explain the author's preference for a [*c]const u8 error-description pointer over a sentinel-terminated pointer.
Why it matters: The pointer choice reflects caution about assumptions made at a C library boundary. - OpenGL version window hints: Describe how the program requests OpenGL 3.3 Core before creating its GLFW window.
Why it matters: Requesting the intended OpenGL version helps reveal when the platform cannot provide it.
Key terms: glfwGetError, error code, out parameter, error callback, error inspection, callconv(.c), C ABI, calling convention, [*c]const u8, [*:0]const u8
7.4 Painting with pixels
7.4.1 Important things with frighteningly vague names
This section introduces OpenGL contexts and objects as stateful, opaque abstractions used to configure the pipeline and manage its data.
- Context and pipeline state: Explain how an OpenGL context holds state used to configure a draw call.
Why it matters: This state-based model helps make sense of subsequent OpenGL calls. - Pipeline data and objects: Describe what OpenGL objects hold, why the implementation manages their storage, and what binding does to their state.
Why it matters: Objects are the way this chapter organizes data used by the graphics pipeline. - Integer object names: Explain how a program refers to OpenGL objects without touching them directly.
Why it matters: Recognizing names as identifiers makes OpenGL object-manipulation code easier to follow. - Window context initialization: Describe the steps the section gives for starting to use the window’s OpenGL context.
Why it matters: These steps prepare the existing window context for OpenGL use.
Key terms: context, state, pipeline, draw call, framebuffer, object, binding, object name, integer identifier, GLFW
7.4.2 Going to space
This section explains the coordinate systems, vertex representation, and winding order used to define a triangle for OpenGL.
- Screen and normalized coordinates: Distinguish screen space from normalized device coordinates and explain the vertex shader’s role in relating coordinates to the rasterizer.
Why it matters: Knowing which coordinate system a position uses helps you predict where it appears on screen. - Clip space and clipping: Explain how vertex shader output in clip space becomes normalized device coordinates and what clipping means.
Why it matters: This explains why shader output may change before rasterization or fail to appear. - Triangle winding and culling: Explain how vertex winding distinguishes front-facing and back-facing triangles and how face culling affects visibility.
Why it matters: Vertex order can determine whether a triangle appears at all. - Flat vertex data: Describe why the triangle’s floating-point vertex data is stored in a flat array.
Why it matters: The representation is a practical choice for communicating vertex data to the API.
Key terms: coordinate system, screen space, normalized device coordinates, vertex shader, clip space, w, clipped, winding order, counter-clockwise, back-facing
7.4.3 There is no shader build system
This section defines simple GLSL shaders as Zig strings and manually compiles and links them into an OpenGL program.
- Shader Compilation and Linking: Trace how the shader sources are compiled and linked into a program, including error checks and when initialization performs the work.
Why it matters: This sequence turns shader source strings into a program OpenGL can use. - Zig Multiline Shader Strings: Explain how Zig multiline strings represent the shader sources and how their line syntax works.
Why it matters: Multiline strings make the embedded shader source readable without changing its basic string semantics. - Example Shader Roles: Describe the language and basic behavior of the two example shaders.
Why it matters: These simple shaders keep the focus on building the program rather than on shader logic. - Shader Helper Resource Handling: Explain the role of Zig errors and defer in the shader helper code.
Why it matters: The helpers need to handle failed compilation and object lifetimes without assuming every OpenGL object follows the same pattern.
Key terms: shader object, program object, compile, link, glad, multiline string, global constants, @embedFile, GLSL, vertex shader
7.4.4 An object for managing objects
This section connects vertex and fragment processing to vertex attributes and introduces vertex array objects for preserving attribute state.
- Triangle Processing Stages: Trace how a triangle passes through vertex processing, geometry assembly, and fragment processing.
Why it matters: This connects the data supplied for vertices to the later processing of fragments. - Per Vertex Attribute Inputs: Explain how draw calls and vertex attributes supply input to vertex processing.
Why it matters: This explains how a shader receives the per-vertex inputs needed to process a draw. - Vertex Array Object State: Explain why OpenGL preserves attribute state in a vertex array object.
Why it matters: A VAO makes managing different arrangements of vertex attributes practical. - OpenGL Object Name Interface: Describe the conventional paired interface for generating and deleting OpenGL object names.
Why it matters: Recognizing this naming convention helps make OpenGL object-management calls easier to read.
Key terms: vertex shader, geometry, rasterized, fragment shader, fragments, draw calls, vertex attributes, buffers, position, vertex array object
7.4.5 Vexing vertices
This section explains how to store triangle vertices in a VBO and configure a VAO to supply them to a vertex shader.
- Vertex data and buffers: Explain how a VBO stores vertex data and why a VAO needs to be told what that data represents.
Why it matters: Separating data storage from its interpretation helps you understand why both a VBO and a VAO are needed. - Object name binding hygiene: Explain how object name binding selects a buffer for operations and how to limit unintended side effects.
Why it matters: Managing implicit bindings carefully helps prevent buffer operations from affecting the wrong object. - Buffer usage hints: Describe what the glBufferData usage hint communicates and what GL_STATIC_DRAW means.
Why it matters: The hint tells OpenGL how the data is expected to be used without guaranteeing a particular optimization. - VAO attribute configuration: Trace how the bound VBO is connected to the bound VAO’s shader attribute and how that attribute is enabled.
Why it matters: This configuration tells the VAO how to supply the stored vertices to the shader.
Key terms: vertex buffer object, VBO, VAO, vertex shader, vertex attributes, object name binding, targets, GL_ARRAY_BUFFER, defer, glBufferData
7.4.6 The payoff
This section draws a triangle by invoking the rasterization pipeline with bound OpenGL objects and clearing the framebuffer each frame.
- Draw calls and bound objects: Explain how glDrawArrays uses the currently bound VAO and program object to draw a primitive.
Why it matters: This connects the prepared graphics objects to the draw call that produces the triangle. - Per-frame framebuffer clearing: Explain why the screen is conventionally cleared each frame before drawing.
Why it matters: Clearing prevents remnants of earlier frames from appearing alongside the current drawing.
Key terms: VAO, program object, glUseProgram, glDrawArrays, rasterization pipeline, primitives, framebuffer, draw calls, clear the screen
7.5 Next steps
The section suggests two tools for exploring graphics programs and GLSL shaders beyond the chapter’s triangle example.
- Graphics exploration tools: Distinguish how RenderDoc and Shadertoy can help you explore graphics: RenderDoc lets you inspect a captured program, while Shadertoy offers examples of GLSL shader techniques and creative work.
Why it matters: These tools offer different ways to keep learning: inspect a running graphics program or explore shader examples.
Key terms: RenderDoc, Shadertoy, GLSL, vertex attributes
7.6 Summary
Concepts explained in this chapter
- OpenGLOpenGL 3.3 Core is an OpenGL version and core profile specifying a standardized set of graphics-rendering functionality.
- GLFWGLFW is a cross-platform library for creating windows and OpenGL contexts and handling input and related application events.
- draw callA draw call is a graphics API command that instructs the graphics system to render geometry using configured state.
- vertex shaderA vertex shader is a programmable graphics pipeline stage that processes individual vertices and outputs their transformed positions.
- OpenGL contextAn OpenGL context is the state container associated with an OpenGL connection to a display system and its rendering resources.
- rasterization pipelineA rasterization pipeline is a graphics-processing sequence that converts geometric primitives into shaded fragments and writes them to a framebuffer.
- GPUA graphics processing unit is a processor specialized for highly parallel graphics and compute operations.
- shaderA shader is a specialized program that performs a stage of graphics processing, such as transforming vertices or shading fragments.
- gladglad is a generator for libraries that load graphics API functions for specified API versions and extensions.
- GUI windowA graphical window is a bounded on-screen region managed by a windowing system for displaying and interacting with application content.
- vertex attributeA vertex attribute is a piece of per-vertex data, such as position, color, or texture coordinates, supplied to a graphics pipeline.
- vertex array objectA vertex array object is an OpenGL object that stores vertex attribute configuration and associated buffer bindings.
- coordinate systemA coordinate system is a framework that assigns numerical coordinates to positions in a geometric space.
- OpenGL objectAn OpenGL object is an OpenGL-managed construct that contains state and is referenced by a name.
- rasterizationRasterization is the process of converting geometric representations into pixels on a grid.
- C ABI compatibilityThe C ABI is the platform-specific binary interface convention commonly designed around the C language's stable data representation and expected by a computer system's operating system and CPU.
- error codeAn error code is a value returned or stored to indicate that an operation failed and often identify the failure kind.
- pixelA pixel is an individual addressable picture element in a raster image or display.
- @import@import is a Zig builtin function and expression that loads Zig code from a module or file and returns a type containing its declarations.
- build scriptA build script is a program or declarative specification that defines how source code and dependencies are configured and compiled.
- dynamic linkingDynamic linking is a linking technique in which an executable records its dependency on a separately provided library that is loaded at runtime.
- Zig compilerThe Zig compiler translates Zig programs and performs compile-time validation and optimization.
- nullNull is a value representing the absence of an object or valid pointed-to item.
These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.
