Culling and the frame
Multiple render targets
Often one pass must produce several images for the same pixels: a color, a normal, a material, a mask. Multiple render targets (MRT) let one draw write all of them at once. The fragment shader returns several values, and each one goes to its own texture. This page explains how that works, what it costs, and where it goes wrong. The last part shows how RASM does it.
In short
- A pass can have N color attachments. The fragment shader returns N values; output i goes to attachment i.
- The geometry is drawn once: vertex work, rasterization and the depth test happen one time for all N images.
- All attachments have the same size. Each one has its own format, and can have its own blend state and write mask. There is one depth attachment for all of them.
- The pipeline is built for the exact list of formats, in order. A pass with other formats cannot use it.
- APIs allow 4 to 8 color attachments. The real limit is bytes per pixel: every byte is written and later read, for every pixel, every frame.
- The classic use is deferred shading: a G-buffer pass writes surface data, a lighting pass reads it.
1The problem: several images per pixel
Many techniques need more than one value per pixel:
Deferred shading
Needs the surface color, the normal and the material of every pixel.
Motion blur, temporal anti-aliasing
Need a velocity per pixel.
Object picking
Needs an object ID per pixel.
Post effects
Often need a mask that says which pixels belong to what.
A pass with one output can only write one of these images. To get three, you draw the scene three times, with three shaders. Every draw reads the vertices again, runs the vertex shader again, builds the triangles again and runs the depth test again. Only the last step, the fragment shader, does different work.
There is a second problem with the top way. The three passes must agree exactly on which surface is in front at each pixel. With the same depth test and the same vertices they usually do, but it is easy to break:
Three passes can disagree
A shader that moves vertices a little differently, or a different depth state, and the normal image shows a different surface than the albedo image.
One pass cannot
The surface is found once per pixel, and every image gets its value from it (section 2).
2The idea: one pass, N outputs
A render pass does not have to draw into one image. It can have a list of color attachments: textures numbered 0, 1, 2 and so on. The fragment shader then returns one value per attachment. The GPU writes output 0 to attachment 0, output 1 to attachment 1, and so on, all for the same pixel.
In the shader, each output is marked with its attachment number. In Slang and HLSL the fragment shader returns a struct, and each field has a semantic with the number. (In Slang, fragMain also gets the [shader("fragment")] attribute; it is left out here.)
struct GBufferOutput
{
float4 albedo : SV_TARGET0;
float4 normal : SV_TARGET1;
float4 material : SV_TARGET2;
};
GBufferOutput fragMain(VSOutput input)
{
GBufferOutput output;
output.albedo = float4(baseColor, ambientOcclusion);
output.normal = float4(normalize(input.normal) * 0.5 + 0.5, 0.0);
output.material = float4(metallic, roughness, 0.0, 0.0);
return output;
}
Other shading languages spell the number differently, but the idea is the same:
| Language | Output 1 is written as |
|---|---|
| Slang, HLSL | float4 normal : SV_Target1; (the case of the semantic does not matter) |
| GLSL | layout(location = 1) out vec4 normal; |
| Metal (MSL) | float4 normal [[color(1)]]; |
| WGSL | @location(1) normal: vec4f |
Everything before the fragment shader is shared. The rasterizer finds the pixels once. The depth test runs once, and if it fails, none of the outputs are written. If it passes, all of them are. So the images can never disagree about which surface is visible.
Here is one such pass on a small scene. Each pixel finds its surface once and writes three outputs. There is no lighting: the images hold raw surface data.
3The rules
The attachments of one pass are not fully free. They share some things and keep others apart:
| Property | Per attachment, or shared? | Why |
|---|---|---|
| Size (width, height) | shared: all the same | One pixel position (x, y) must mean the same place in every texture. |
| Sample count (MSAA) | shared | The rasterizer makes one set of samples for all of them. |
| Format | per attachment | A color can be 8-bit sRGB, a normal 10-bit, a velocity 16-bit float, an ID a 32-bit integer. |
| Blend state | per attachment, if the GPU supports independent blend | Without it, all attachments must use the same blend state (Vulkan: the independentBlend feature; D3D12: IndependentBlendEnable). Desktop GPUs all support it. |
| Write mask | per attachment (also under independent blend) | Turns off writes to some channels, or to the whole attachment. |
| Load and store, clear value | per attachment | One attachment can be cleared and another kept; see Load and store ops. |
| Depth (and stencil) | one for the pass | Visibility is decided once per pixel, for all outputs. |
The pipeline is built for exact formats
A graphics pipeline is compiled for a fixed list of attachment formats: how many there are, in which order, and which format each one has. The driver bakes the conversion from the shader's output (a float4) to each format into the pipeline. So a pipeline can only draw in a pass whose attachments have exactly those formats.
So one shader often needs several pipelines: one per list of formats it draws into. A material shader that draws both into a G-buffer and into a forward HDR target is two pipelines.
Limits
| API | Color attachments per pass | Notes |
|---|---|---|
| Vulkan | maxColorAttachments: at least 4, 8 on almost every GPU | Query it on the device. Some mobile GPUs report only 4. |
| Direct3D 12 | 8 | Fixed by the API. |
| Metal | 8 | 4 on the oldest Apple GPUs. |
| WebGPU | 8 by default | Also limits the total size: by default at most 32 bytes per sample over all attachments. |
In practice the count is rarely the limit. The bytes are.
4The cost: bytes per pixel
Every attachment is written for every pixel the pass covers, and some later pass reads it back. So the cost of MRT is simple to estimate: add up the bytes per pixel of all attachments, and multiply by the number of pixels.
Worked example: a G-buffer at 1080p
A 1920 × 1080 image has 2,073,600 pixels. Take the packed layout: four 4-byte color attachments and a 4-byte depth, 20 bytes per pixel.
memory 20 B × 2,073,600 px = 41,472,000 B ≈ 39.6 MiB
write 41.5 MB per frame × 60 frames/s ≈ 2.5 GB/s
write+read 83 MB per frame × 60 frames/s ≈ 5.0 GB/s
| Layout | B/pixel | Memory at 1080p | Write + read, 60 fps, 1080p | Memory at 4K | Write + read, 60 fps, 4K |
|---|---|---|---|---|---|
| packed | 20 | 39.6 MiB | 5.0 GB/s | 158.2 MiB | 19.9 GB/s |
| fat | 36 | 71.2 MiB | 9.0 GB/s | 284.8 MiB | 35.8 GB/s |
These are lower bounds. A pixel covered by several triangles is written several times (overdraw), the depth test also reads depth, and later passes may read the images more than once. A mid-range GPU has a few hundred GB/s in total, so a fat G-buffer at 4K takes a real part of the frame.
Build a layout yourself. The bar starts as the fat layout from the picture above.
Packing: fewer bytes for the same data
Position
Naive: RGBA32F, 16 B. Packed: 0 B.
Do not store it. Rebuild it from the depth and the pixel position with the inverse view-projection matrix.
Normal
Naive: RGBA16F, 8 B. Packed: RG16, 4 B, or RGB10A2, 4 B.
Octahedral encoding: fold the unit sphere onto a square, and store 2 numbers instead of 3. Or store 3 numbers in 10 bits each.
Metallic, roughness, AO, flags
Naive: one attachment each. Packed: one RGBA8, 4 B.
Put small values that are used together into the channels of one attachment.
Velocity
Naive: RGBA16F, 8 B. Packed: RG16F, 4 B.
Screen-space motion has 2 parts; the other channels were empty.
Most mobile GPUs, Apple's included, draw the screen in small tiles and keep the tile's attachments in fast on-chip memory. Writing many attachments is cheap there, as long as they fit in that memory and the pass does not store the ones nobody reads later. If all attachments together are too big for a tile, the GPU uses smaller tiles, which costs more. See Load and store ops.
5The classic use: deferred shading
Where the lighting runs is the difference between forward and deferred shading:
Forward shading
Every triangle computes its lighting while it is drawn. A pixel that is covered five times is lit five times, and every object's shader must loop over every light.
Deferred shading
Splits the work in two passes. Lighting is computed only for the surface that is really visible.
The first pass, the geometry pass, uses MRT to store what is needed for lighting: the G-buffer (geometry buffer). The second pass, the lighting pass, runs once per pixel and reads the G-buffer as textures.
What it gives
- Lighting runs once per visible pixel, not once per covered triangle.
- Many lights are cheap: each light only touches the pixels it reaches.
- Other screen effects (ambient occlusion, reflections, decals) can read the same normals and depth.
What it costs
- The G-buffer memory and bandwidth from section 4, every frame.
- One surface per pixel: transparent objects need a forward pass after.
- MSAA is hard: every attachment would need all its samples.
- All materials must fit the same G-buffer layout.
MRT is not only for deferred shading. A forward pass can also write a velocity image for temporal effects (see History buffers), an object ID for picking, or a mask for a later post effect, next to its color.
6Variants
Unused slots
Some APIs allow an empty attachment in the middle of the list (a null view in Vulkan dynamic rendering, a null target in D3D12). The shader output for that slot is dropped.
Use: one shader for several passes that use different subsets of the outputs.
Write mask 0
The attachment is bound, but its write mask turns all channels off.
Use: a pass that leaves one image untouched while it writes the others.
Subpasses, input attachments, local read
A later step of the same pass reads the value an earlier step wrote at the same pixel, without a round trip to memory (Vulkan subpasses and dynamic rendering local read, Metal tile memory).
Use: deferred shading on tile-based GPUs: the G-buffer never leaves the chip.
Storage images
The shader writes images directly, with no attachment: any pixel, any number of images.
Use: compute passes, or writes to other pixels than the current one. There is no blending and no depth test, and the shader must handle ordering itself.
Visibility buffer
The geometry pass writes only a triangle ID and an instance ID (one 32- or 64-bit attachment). A later pass fetches the triangle and computes the rest.
Use: very dense geometry, where even a packed G-buffer is too big.
Dual-source blending
Two shader outputs feed the blend of one attachment. Not MRT; see below.
Use: per-channel alpha, for example subpixel text.
7Pitfalls
- Normals show up in the color image, or masks in the albedo
- The output number and the attachment order differ. Nothing crashes: all are float4. Keep one list of the attachments and build both the pass and the shader struct from it.
- Garbage in one image at some pixels
- An output is not written on some path. A missing output (or a missing channel) is undefined, not 0. Write every output in every branch. Use a write mask if the image should keep its old value.
- Normals and masks come back bent
- Data in an sRGB format: the GPU applied the sRGB curve on write. Use UNORM or float formats for data. Only colors get sRGB. See Color spaces.
- Validation error, or the pipeline fails
- Blending on a format that cannot blend. Integer formats never blend, and 32-bit float often cannot. Turn blending off for that attachment (needs independent blend), or pick another format.
- A mask or roughness stored in alpha also changes how the color mixes
- Blending is on with data in alpha. Keep blending off on data attachments, or move the data out of alpha.
- At edges a mask is 0.3 or 0.7, not 0 or 1
- The mask is read with a linear filter, and the reader's size or position differs. Compare against 0.5, or sample with a nearest filter.
- The pass is bandwidth-bound; on tile-based GPUs it is slower than expected
- Too many bytes. Pack (section 4), and do not store attachments that no later pass reads.
8In RASM
A RASM render target has up to MAX_COLOR_ATTACHMENTS (4) color textures and one depth texture. Its formats are listed in RenderTargetDesc::colorFormats. A pipeline that draws into it takes its formats from the target, and every color is a bindless texture that later passes can sample. examples/01_render_graph uses two colors.
The fragment shader of the Background pass, as in the example (where fragMain also has the [shader("fragment")] attribute):
struct Targets
{
float4 color : SV_TARGET0;
float4 mask : SV_TARGET1;
};
Targets fragMain(VSOutput input)
{
Targets targets;
targets.color = gTextures[pc.indices[0]].Sample(input.UV);
targets.mask = float4(targets.color.a < 0.5 ? 0.0 : 1.0);
return targets;
}
The target lists the two formats in the same order, and the pipeline is made from the target, so the formats always match:
compositeHandle = builder.createRenderTarget({
.name = "composite_rt",
.swapchainScale = 1.0f,
.colorFormats = {colorFormat, rasm::Format::R8G8B8A8_UNORM},
.depthFormat = rasm::Format::D32_SFLOAT,
});
// later: a pipeline with the target's formats
auto pipeline = engine.createPipeline("background", source, compositeHandle);
What happens to the formats
bindPipeline checks it again for every pass.Where RASM follows the textbook, and where it differs
| Part | This page | RASM |
|---|---|---|
| Number of colors | 4 to 8, from the device | MAX_COLOR_ATTACHMENTS = 4, the minimum Vulkan guarantees, so no device query is needed. |
| The list of formats | some APIs allow empty slots | No gaps. The list ends at the first Format::UNKNOWN (colorAttachmentCount). checkRenderTargetDesc rejects a desc with a gap, or without a depth format. A depth-only target (a shadow map) has no color. |
| Depth | optional | Needed by every render target that passes draw into, even when no pass tests depth, as in the example. Only a storage target, which compute passes write, has none. |
| Blend state, write mask | per attachment, with independent blend | The same for every color: one BlendMode per pipeline, all four channels written (VulkanDevice::createGraphicsPipeline). So no independent blend is needed. A pipeline from Renderer::createPipeline has blending off; only pipelines the engine makes itself blend, such as the transparent scene draws. |
| Clear value | per attachment | One RenderTargetDesc::clearColor for all colors. |
| Load and store | per attachment | One load op for all colors (AttachmentOps::loadColor, set per pass by the render graph); colors are always stored. See Load and store ops. |
| Pipeline formats | exact list, in order | Renderer::createPipeline with a target copies its color and depth formats. RenderContext::bindPipeline compares all of them with the pass's; a mismatch logs an error and skips the pass's draws. |
| Reading the result | sample as textures | Every color is bindless with LINEAR_CLAMP. endPass moves each to SAMPLED; getRenderTargetTexture with the attachment index returns it. |
| Formats for packing | RG16, RGB10A2, RG16F | Only RG16F is in Format: R16G16_SFLOAT, the scene's MOTION_FORMAT. The other 4-byte color formats are R8G8B8A8_UNORM, R8G8B8A8_SRGB, B8G8R8A8_SRGB and B8G8R8A8_UNORM; the example's 1-bit mask takes 4 bytes. |
| G-buffer from the scene | section 5 | None. addScenePasses needs a target with a SCENE_COLOR_FORMAT color and D32_SFLOAT depth; it logs an error and adds no passes otherwise. The scene writes a second color only for TAA: a MOTION_FORMAT color, with one sample, gets each pixel's motion (RASM_MOTION_VECTORS, TAA). Its passes shade as they draw, so this is forward shading with two outputs, not a G-buffer. |
| Subpasses, local read | section 6 | None. Each pass is its own dynamic rendering scope; a later pass reads the colors as textures. |
| Memory | section 4 | All colors and the depth of a transient target share heaps with other transient targets (D9). See Transient memory and aliasing. A history target has two copies of every color (History buffers). A history or readable target has memory of its own. |
Where it lives in code
| What | Where |
|---|---|
| The limit | MAX_COLOR_ATTACHMENTS in include/rasm/types.h |
| The format list | RenderTargetDesc::colorFormats in include/rasm/render/resource.h; colorAttachmentCount in src/rhi/resource.cpp |
| The target's data | RenderTarget, RenderTargetAttachments in include/rasm/types.h |
| Desc checks | checkRenderTargetDesc in src/rhi/renderContext.cpp |
| One texture per color | createAttachments in src/rhi/renderContext.cpp |
| Pipeline formats from a target | Renderer::createPipeline in src/renderer/renderer.cpp, into PipelineDesc::colorAttachmentFormats |
| Blend state for every color | VulkanDevice::createGraphicsPipeline in src/rhi/vulkan/vulkanDevice.cpp |
| Starting the pass | Renderer::beginPass in src/renderer/renderer.cpp; RenderContext::beginRendering; VulkanCommandBuffer::beginRendering in src/rhi/vulkan/vulkanCommandBuffer.cpp |
| The format check | RenderContext::bindPipeline in src/rhi/renderContext.cpp |
| Reading color i | Renderer::endPass, Renderer::getRenderTargetTexture in src/renderer/renderer.cpp |
| The scene's colors: color, and motion | Renderer::addScenePasses in src/renderer/gpuScene.cpp; RASM_MOTION_VECTORS in shaders/passes/rasm.slang |
| The example | the Background and Present passes in examples/01_render_graph/main.cpp |
- The shader's
SV_TARGET0,SV_TARGET1, … follow the order of the target'scolorFormats. Make the pipeline withcreatePipeline(name, source, renderTarget), so its formats come from the target. - A render target desc has no gap in
colorFormats, and a depth format; astorageone has colors and no depth.checkRenderTargetDescrejects anything else. - Data attachments (masks, normals, IDs) use a UNORM or float format, never sRGB.
- Write every output on every path. Blending is off, so an output the shader skips leaves undefined values.
addScenePassesdraws only into a target with aSCENE_COLOR_FORMATcolor (and, with one sample, an optional secondMOTION_FORMATcolor) andD32_SFLOATdepth, or a depth-only one.- A pipeline that draws into a render target comes from
createPipeline(name, source, renderTarget), even for one color: the two-argument overload is for the swapchain, which has no depth. - A new per-attachment field in
PipelineDesc(a blend state, a write mask) must also go into its hash insrc/rhi/resource.cpp, or two different pipelines are merged.
Further reading
- Shawn Hargreaves and Mark Harris, Deferred Shading, NVIDIA (2004): the G-buffer idea and its costs.
- Zina H. Cigolle and others, A Survey of Efficient Representations for Independent Unit Vectors, JCGT (2014): octahedral normals.
- Christopher A. Burns and Warren A. Hunt, The Visibility Buffer: A Cache-Friendly Approach to Deferred Shading, JCGT (2013).
- The Vulkan specification: the chapters on dynamic rendering, fragment output interface, and color blending (independentBlend, dual-source blending).
- Render graphs, Load and store ops, Transient memory and aliasing.