Foundations

Graphics APIs and the RHI

A graphics API is how a program talks to the GPU. The modern ones (Vulkan, Direct3D 12, Metal, WebGPU) share one model, with different names and different details. An engine that wants to run on several of them puts its own thin layer on top: a render hardware interface, or RHI. This page explains the shared model, the differences, and the choices an RHI has to make. The last part shows RASM's RHI.

In short

  • Explicit APIs move work from the driver to the application: memory, synchronization, pipeline creation and command recording.
  • All four have the same pieces: a device, queues, command buffers, pipelines, resources, a binding model, sync objects and a swapchain.
  • They differ most in binding, barriers, shader language and the platforms they run on.
  • An RHI is one interface above all of them. The engine is written once, against it. Each API gets a backend below it.
  • The main choices: how thin the layer is, virtual interfaces or a compile-time backend, how resources are named (handles or pointers), and who places the barriers.
  • A good RHI exposes what every planned backend can do, and never lets native types leak above it.

1What a graphics API does

A GPU is a separate processor with its own memory and its own command stream. A program cannot call it like a function. It writes commands into memory, hands them to the driver, and the GPU runs them later. The graphics API is the contract for this: how to create objects on the GPU, how to record commands, and how to know when they are done.

Older APIs: OpenGL, Direct3D 11 Application "draw this mesh with this texture" API calls: set state, draw Driver: does a lot, hidden · tracks every bound state · inserts barriers and cache flushes · places resources in memory · compiles shaders when first used (hitches) GPU Explicit APIs: Vulkan, D3D12, Metal Application (or engine): does a lot · records commands, on any thread · places barriers between uses · allocates memory, places resources · builds pipelines up front, at load time API calls: record, submit, wait Driver: thin translates, does not guess GPU
The same work has to happen in both. Explicit APIs only move it to the side that knows what the program will do next.

An older driver has to guess. When a texture is drawn into and then sampled, it must notice that, and flush caches in between. It does not know which shader combinations will be used, so it compiles them on the first draw, and the frame stutters.

Explicit APIs remove the guessing: the application says what it needs, when it needs it. That makes the driver smaller and faster, and it makes the application longer. An engine absorbs that extra code once, so games and tools built on it do not have to.

2The shared model

Vulkan, Direct3D 12, Metal and WebGPU were designed in the same years, for the same GPUs. Underneath their names, they have the same parts:

work on the CPU the GPU memory and sync objects shaders
Device creates objects Resources buffers, textures, samplers Pipelines shaders + fixed state Bindings which resources a shader sees used by Command buffer bind, draw, dispatch, copy, barrier submit Queue runs it on the GPU Fence "done" for the CPU Swapchain present an image
The CPU creates objects once and records commands every frame. The GPU only sees command buffers that were submitted to a queue.
ConceptVulkanDirect3D 12MetalWebGPU
DeviceVkDeviceID3D12DeviceMTLDeviceGPUDevice
QueueVkQueueID3D12CommandQueueMTLCommandQueueGPUQueue
Command recordingVkCommandBuffer, from a VkCommandPoolID3D12GraphicsCommandList, from an allocatorMTLCommandBuffer with encodersGPUCommandEncoder with pass encoders
PipelineVkPipeline + pipeline layoutpipeline state object + root signatureMTLRenderPipelineStateGPURenderPipeline
Bindingdescriptor setsdescriptor heaps and tablesargument buffers, or direct set callsbind groups
ResourcesVkBuffer, VkImage + memoryID3D12Resource in heapsMTLBuffer, MTLTextureGPUBuffer, GPUTexture
CPU waits for GPUVkFence, timeline semaphoreID3D12Fence (a counter)MTLSharedEvent, completion handlersonSubmittedWorkDone (a promise)
Ordering between usespipeline barriers, image layoutsresource barriers, resource statesautomatic by defaultautomatic, always
Window outputVkSwapchainKHRDXGI swap chainCAMetalLayer drawablescanvas context
Shader formatSPIR-VDXIL (from HLSL)MSL, or compiled metallibWGSL

The same picture, read in one API at a time. The parts and the arrows stay; only the names change, and one box.

the application does it the GPU memory and sync objects shaders bindings; in the box "Ordering between uses": the API does it
Choose each API and watch the box "Ordering between uses". On two of them the application does that work, on the other two the API does.

One frame, in any of them

  1. At load time. Create resources, upload data, and build pipelines from shaders.
  2. Wait. Each frame, wait until the GPU is done with the memory this frame will reuse (see frames in flight).
  3. Get an image. Take one from the swapchain to draw into (see the swapchain).
  4. Record. Fill a command buffer: begin a render pass, bind a pipeline and its resources, draw, end. Put barriers between uses of the same memory (see GPU synchronization).
  5. Submit and present. Hand the command buffer to a queue, with a fence to signal. Then present the image.

3Where they differ

The shared model hides real differences. Four of them at a glance:

the application does it the API does it, or does not have it the API has it
Vulkan Direct3D 12 Metal WebGPU Who places barriers the application the application the driver (opt out) always the API Raw pointers in shaders yes: device address no: descriptors yes no: bindings Shader format SPIR-V DXIL MSL WGSL Runs on Windows, Linux,Android Windows, Xbox Apple only browsers,native libraries
No column is the same as another. The table below has every area, and what each one means for an engine.

These are the ones an engine feels most:

AreaHow they differWhat it means for an engine
Binding modelVulkan has descriptor sets and layouts. D3D12 has one big descriptor heap and a root signature. Metal binds by slot or through argument buffers. WebGPU has fixed bind groups with strict limits.The hardest part to abstract. Many engines go bindless on the APIs that allow it, so there is little to bind per draw.
SynchronizationVulkan and D3D12 make the application place every barrier. Metal tracks hazards itself unless a resource opts out. WebGPU always tracks them.The interface needs barriers for two backends, and the other two can ignore them.
GPU pointersVulkan (buffer device address) and Metal let a shader follow a raw 64-bit buffer address. HLSL on D3D12 and WGSL on WebGPU have no pointers: buffers are reached through descriptors or bindings.A data layout built on pointers needs another way to reach buffers on D3D12 and WebGPU, such as indices into a bindless array.
Shader languageFour different formats.Write shaders once and cross-compile (Slang, HLSL with a converter, or similar).
Render passesMetal and WebGPU need explicit pass objects with load and store actions. Vulkan has render pass objects and, since 1.3, the simpler dynamic rendering. D3D12 has optional render passes.Model passes with load and store actions: that maps to every API.
MemoryVulkan lists memory types and heaps. D3D12 has heap types. Metal has storage modes. WebGPU hides memory.Ask for intent ("GPU only", "CPU writes often", "CPU reads back") and let each backend pick.
PlatformsVulkan: Windows, Linux, Android (macOS through a layer). D3D12: Windows, Xbox. Metal: Apple only. WebGPU: browsers and native libraries.Covering every platform natively needs more than one backend.

4Why put a layer on top

rendererVulkan passesVulkan uploadsVulkan sceneVulkan Vulkan a second API: rewrite all four

Vulkan calls everywhere

Every renderer feature, every pass and every upload is written in Vulkan terms. A second API means rewriting all of them.

renderer passes uploads scene RHI: neutral types Vulkan backend second backend a second API: one more box below

A line through the engine

Above the line, code knows only neutral types: a buffer, a texture, a pipeline, a command buffer. Below it, one backend per API turns them into native objects. That line is the RHI.

Engine code renderer, passes, scene, uploads: written once, with neutral types RHI interface device, buffer, texture, pipeline, command buffer, queue, fence, swapchain Vulkan backend D3D12 backend Metal backend WebGPU backend vkCmd…, VkImage ID3D12… MTL… GPU…, WGSL
Native types appear only below the line. Adding an API means writing one more box at the bottom, not touching the engine.

What an RHI gives

  • Portability: one engine, several APIs.
  • One place for the API's rules, so passes do not each get them slightly wrong.
  • A smaller surface: only the features the engine uses.
  • Tests: a fake backend can stand in for the GPU.

What it costs

  • A feature can only be used once every backend can implement it, or behind a "supported?" check.
  • Each backend is real code to write, test and keep in step.
  • A bad split (Vulkan ideas in the interface) makes the next backend hard.
  • A small cost per call, usually much less than the driver's.

5Design choices

How thin?

The first choice is the level of the interface. It ranges from "the same objects as the APIs" to "draw this mesh with this material".

RHI API createBuffer barrier draw create buffer barrier draw

Thin: mirror the APIs

createBuffer, createPipeline, barrier, draw, submit. Full control, little overhead.

But: the engine places barriers, and the layer is close to one API's shape.

A B pass reads writes the barrier comes from that

Middle: resources and passes

"This pass reads A, writes B": barriers come from that. Hard to get sync wrong, and it maps well to every API.

But: some tracking cost.

mesh material light

Thick: a renderer

drawMesh, setMaterial, addLight. Each backend can optimize.

But: every feature is written N times. Not really a hardware layer.

Most engines pick the thin end or the middle. The thick end is a renderer per API, which is exactly the duplication an RHI should avoid.

A common mix: a thin RHI with explicit barriers, and above it a render graph that turns "reads" and "writes" into those barriers. The RHI stays simple, and passes still do not write barriers by hand.

Virtual interfaces or a compile-time backend?

Runtime: virtual functions device->createBuffer vtable Vulkan device D3D12 device both in one program; choose when it starts a fake device for tests is easy Compile time: one per build createBuffer direct call device_vk.cpp device_d3d12.cpp the build links one; calls can be inlined switching API means another build
A virtual call costs a few nanoseconds. A frame makes thousands of calls at most, so either choice is fast enough. The real question is whether one program must carry several backends.

Describing and naming resources

Almost every RHI creates objects from a plain descriptor struct: a list of fields such as size, format and usage. It is easy to read, easy to hash (for caches) and easy to store for debugging. The object it creates can be named in two ways:

engine: a pointer destroyed object a stale pointer still points here

Pointer

The engine holds a pointer to the RHI object. No lookup, simple. But a stale pointer crashes, or worse, works on a new object.

engine: 7 5 6 7 8 the object checked lookup

Handle

The engine holds a small integer, looked up in a table. It can be checked; it is safe to copy and store; it fits in GPU data. Costs one lookup per use.

A handle with a generation counter can tell a live object from a destroyed one: see generational handles. Under the handle, a backend usually keeps a neutral base struct and derives its own from it, adding the native members:

Buffer (neutral) desc: size, usage GPU address Vulkan buffer everything in Buffer, plus the native buffer and its memory derives engine: passes a Buffer pointer backend: casts back, no check needed Only the backend knows the right side. It made every object, so the cast is safe.
The engine never sees a native type. A second backend derives its own struct from the same base.

Recording commands

RHI bind RHI draw RHI copy native bind native draw native copy each call records at once

Direct

Each RHI call records the native command at once: draw becomes the API's draw. Simple and fast. The RHI's command buffer is a thin wrapper around the native one.

RHI bind RHI draw RHI copy own list later backendtranslates the list can be sorted, merged, replayed

Deferred

RHI calls write a compact list of the engine's own commands. Later, often on another thread, the backend translates the list. Costs a second pass, but the list can be sorted, merged, or replayed, and the engine does not depend on the API's threading rules.

Who places the barriers?

the caller use 1 use 2

The caller

The RHI has a barrier call, close to Vulkan's.

Fast and flexible. Every caller must know the rules from GPU synchronization.

resource · last use: written use 1 use 2

The RHI tracks state

Each resource remembers its last use. Each use records a barrier if needed.

Hard to get wrong. Costs a lookup per use, and knows only the past, not the future.

pass pass pass A B

A render graph

Passes declare reads and writes up front. The graph places barriers for the whole frame.

Sees the whole frame, so it can batch and move barriers. Needs a graph. See render graphs.

6How to add a backend

  1. Check the shaders first. Can the shader compiler target the new API, and does the shader code use only features it has (pointers, bindless arrays, subgroup operations)? This is usually the biggest job.
  2. Implement each interface. Device, command buffer, queue, swapchain, and one derived struct per resource. Keep native types in the backend's own files.
  3. Map the enums. Formats, usages, stages, filter modes: one function per enum, in one file, with an error for values the API does not have.
  4. Keep the contracts. The interface promises things the native API may not: for example "a fence is a growing 64-bit value". Build that from what the API has.
  5. Hook up the window. Each API connects to a window in its own way (a surface, a swap chain, a layer).
  6. Register it. Add it to the place that picks the backend, and to the build.
  7. Compare images. Render the same frames on the old and the new backend and diff them. Run each API's validation layer.

7Pitfalls

One API's shape in the interface
Vulkan's layouts or descriptor sets appear above the line. The next backend has to fake them. Instead: design each call from what all planned APIs can do. Ask "how would Metal do this?"
Native types leak up
A VkImage in an engine header. Now the engine depends on Vulkan again. Instead: native types only in the backend's files.
Lowest common denominator
The engine cannot use a feature because one API lacks it. Instead: capability tiers: a "supported?" query, and a fallback path.
Hidden work in the RHI
A simple-looking call allocates, waits or flushes. Instead: make expensive things look expensive: separate calls, clear names.
Only one backend tested
The interface "works", but only for the API that exists. Instead: a fake backend in unit tests, image tests per backend.

8In RASM

RASM has a thin RHI with virtual interfaces and one backend, Vulkan 1.4. Above it sits RenderContext, which turns handles into RHI pointers and checks every call. The engine and the render graph use only RenderContext.

Application examples, games, tools Engine RenderGraph RenderContext · handles in, rhi pointers out · handle → rhi pointer tables · argument checks (checkArgument) · dedup of shaders, pipelines, layouts · render targets, bindless slots, samplers · TextureStates · UploadManager · the swapchain, or with no window an OffscreenSwapchain on the Device rhi:: · src/rhi/device.h Device, CommandBuffer, Queue, Swapchain: virtual · Buffer, Texture, Pipeline, Fence, ...: plain structs createDevice(backend) VulkanDevice ... src/rhi/vulkan/ volk, VMA, vk-bootstrap DX12 logs, returns null METAL logs, returns null WEBGPU logs, returns null
EngineConfig::preferredBackend picks the backend when the engine starts. Vulkan headers stay in the Vulkan files, with three exceptions: src/rhi/device.cpp, the KTX2 format constants in src/assets/ktxImage.cpp, and src/thirdparty_impl.cpp. The platform layer hands the device a NativeWindow, which has no Vulkan type.

Here is one buffer, from creation to use. The handle lives above the line; the native buffer lives below it.

create createBuffer(desc) RenderContext Device::createBuffer virtual call new VulkanBuffer VMA memory, address BufferHandle → rhi::Buffer* use bindIndexBuffer(h) RenderContext lookup(buffers, h) error if unknown VulkanCommandBuffer static_cast to VulkanBuffer vkCmdBindIndexBuffer recorded at once
Recording is direct: each call records its Vulkan command right away. There is no RASM command list in between.

Where RASM follows the textbook, and where it differs

PartThis pageRASM
Thicknessthin, middle or thickThin, shaped like Vulkan 1.3+ with dynamic rendering. Two things are simpler than Vulkan: barriers name three coarse PipelineStage sets, and textures name a TextureUsage instead of a layout.
Polymorphismvirtual or compile timeVirtual: Device, CommandBuffer, Queue and Swapchain are abstract classes. rhi::createDevice switches on Backend at runtime.
Resourcesdescriptor struct, derived backend structThe same. rhi::Buffer keeps its BufferDesc; VulkanBuffer adds VkBuffer and its VmaAllocation. The backend casts back with static_cast.
Namingpointers or handlesBoth: handles (BufferHandle) above RenderContext, pointers below it. A destroyed object's handle is invalid at once, and the object is freed after the frames in flight (deferred destruction).
Recordingdirect or deferredDirect. Each VulkanCommandBuffer owns its own command pool, reset in begin.
Barrierscaller, state tracking, or graphAll three, in layers. The RHI has explicit memoryBarrier and transitionTexture. RenderContext tracks each texture's state (TextureStates). RenderGraph derives barriers from declared reads and writes. See GPU synchronization.
CPU–GPU syncfences or countersOnly counters: an rhi::Fence is a timeline, a Vulkan timeline semaphore. A submit signals one and can wait for up to four others, three on the compute queue, which keeps one for the uploads (SubmitInfo::waits, FenceValue, MAX_SUBMIT_WAITS), which is how the two queues wait for each other. See frames in flight.
Swapchain syncsemaphores in the interfaceNone cross it. VulkanSwapchain owns its semaphores, and a SubmitDesc just names the swapchains: acquireSwapchains to wait for their images, presentSwapchains to present them, one per window. See the swapchain.
Queuesgraphics, compute, transferGraphics, and compute when asked. QueueType has GRAPHICS, COMPUTE and TRANSFER. With EngineConfig::asyncCompute, VulkanDevice takes a compute queue from a family without graphics, and hasAsyncCompute says whether it found one. Without one, compute command buffers and submits use the graphics queue. With one, every buffer and image is shared by both families, so no ownership moves. With EngineConfig::transferQueue it also takes a queue of a family that only copies, for the loads' copies (transfer queues). See async compute.
Shadersone language, cross-compiledSlang, compiled at runtime and kept in a shader cache. getShaderCompilerTarget in src/renderer/renderer.cpp maps each backend to SPIR-V, HLSL, MSL or WGSL. But the shaders use device addresses and spirv_asm, so only SPIR-V works today (D12).
Windowone hook per APIThe window and its input are behind a private Platform interface (src/platform/platform.h): SDL, the application's own window, or headless (EngineConfig::platform). Every window reaches the device as the same API-neutral NativeWindow (DeviceDesc::window): an HWND, a CAMetalLayer, an X11 window or a Wayland surface. The Vulkan backend makes its surface from it in createVulkanSurface (src/rhi/vulkan/vulkanSurface.cpp); a D3D12 or Metal backend reads the same handle (The platform layer). A headless engine has no surface: RenderContext renders into an OffscreenSwapchain, a Swapchain made of plain Device textures, so every backend gets it for free (headless rendering).
Checksone place for the rulesRenderContext checks public API misuse with checkArgument: an error log, an assert in debug builds, and the call does nothing. For example, no draw outside a rendering scope and no barrier or dispatch inside one.
Testsa fake backendtests/uploadManagerTests.cpp and tests/textureStatesTests.cpp implement a fake Device or CommandBuffer, with no GPU.

Where it lives in code

WhatWhere
The interfacesrc/rhi/device.h
Descriptor structs, TextureUsage, PipelineStageinclude/rasm/render/resource.h; their hashes in src/rhi/resource.cpp
Backend choicerhi::createDevice in src/rhi/device.cpp
Handle tables, checks, cachesRenderContext in src/rhi/renderContext.cpp, public header include/rasm/render/renderContext.h
Native structssrc/rhi/vulkan/vulkanTypes.h
Device and resourcesVulkanDevice in src/rhi/vulkan/vulkanDevice.cpp
Loading Vulkan, the device's function tableloadVulkan and VulkanDevice::initialize in src/rhi/vulkan/vulkanDevice.cpp; see the Vulkan loader
RecordingVulkanCommandBuffer in src/rhi/vulkan/vulkanCommandBuffer.cpp
Queue typesQueueType, QUEUE_COUNT in include/rasm/render/resource.h; the compute queue in VulkanDevice::initialize
SubmitSubmitInfo, RenderContext::submit in include/rasm/render/renderContext.h; SubmitDesc in src/rhi/device.h; VulkanQueue::submit in src/rhi/vulkan/vulkanQueue.cpp
Shader target per backendgetShaderCompilerTarget in src/renderer/renderer.cpp
Keep these true
  • Vulkan calls and types stay under src/rhi/vulkan/. From outside, only src/rhi/device.cpp, the surface hook in src/platform/, the KTX2 reader src/assets/ktxImage.cpp (for the file's VkFormat numbers) and src/thirdparty_impl.cpp (the VMA implementation) include them.
  • A new GPU feature goes into src/rhi/device.h in terms that Vulkan, D3D12, Metal and WebGPU can all implement, never as a Vulkan-only path above the RHI.
  • Public API misuse is checked in RenderContext with checkArgument. Inside the backend, use plain assert.
  • Check every VkResult and log it with toVkResultString. Every Vulkan object gets a debug name (setObjectName).
  • Test with enableValidation on. A change that adds validation messages is not done.
Not done yet

A second backend needs, in this order: shaders without raw pointers and spirv_asm (D12), a window hook that takes native handles (D7), and its own copy queue, or the graphics queue in its place, for the loads' uploads (transfer queues). Buffers, textures and render targets are freed once the frame fences pass the frames that may use them (deferred destruction); the other objects live as long as the device. There is no pipeline cache (P8).

Further reading