Choosing Depth of Field Methods and Building Velocity Maps: Real-Time Rendering Post-Processing Practices
Real-time rendering requires generating photorealistic images within strict frame budgets. This article explores common post-processing techniques, including Depth of Field (DoF), motion blur, color space management, particle rendering, and normal map baking. It provides practical guidelines for DoF method selection, Circle of Confusion calculation, velocity map reconstruction from depth buffers, and depth-aware particle upsampling, accompanied by formulas, pseudocode, and checklists to avoid visual artifacts and performance bottlenecks.
1. Why These Techniques Require Separate Discussion
Real-time rendering must generate photorealistic images within limited frame times. A pinhole camera model produces uniformly sharp images, whereas real lenses only keep objects within a specific distance range in focus, causing others to become defocused. Depth of Field (DoF) and motion blur simulate lens defocus and motion integration during the shutter time, respectively. While they enhance spatial depth and dynamic perception, improper implementation can lead to significant performance overhead or visual artifacts.
Color space processing, particle rendering, and normal map baking are also common steps in post-processing and asset generation. Their shared challenges include: which space the data resides in, where the computation cost concentrates, and how the results return to the display. How to select a DoF method, how to generate a velocity map, and why a linear color space is necessary are three frequently asked questions in this field. This article answers these questions sequentially, providing formulas, steps, and checklists.
2. DoF Classification and Method Selection
Real-time DoF is generally categorized into five types based on how pixels acquire or distribute color:
- Ray Tracing: Emits rays from different positions on the lens aperture into the scene and averages the results. Offers the highest accuracy, but the sampling count directly dictates the cost, making it typically unaffordable for real-time scenarios.
- Accumulation Buffer: Renders the scene multiple times, offsetting the camera position within the lens aperture each time, and blends multiple pinhole images. Produces natural results, but render count is proportional to scene complexity.
- Multi-focal Compositing: Renders layers at different focal distances and merges them by depth. Handles foreground occlusion well but requires multiple renders and extra VRAM.
- Forward Mapping (Scatter): Each pixel spreads its color to neighboring pixels based on its Circle of Confusion (CoC) size. Occlusion requires extra handling; otherwise, sharp foregrounds can be incorrectly covered by blurred backgrounds.
- Reverse Mapping (Gather): Each pixel collects color samples from its neighborhood and blends them by weight. Easy to implement, suitable for pixel shaders, and currently the most common choice for real-time post-processing.
The trade-offs for each method are summarized below. The costs are relative comparisons; actual values depend on resolution, sample count, and hardware.
| Method | Quality | Extra Full-Scene Render | Sampling Cost | Occlusion Handling | Implementation Difficulty |
|---|---|---|---|---|---|
| Ray Tracing | Highest | None | Extremely high, depends on sample count | Naturally correct | High |
| Accumulation Buffer | High | Yes, increases with sample count | High | Naturally correct | Medium |
| Multi-focal Compositing | High | Yes, once per layer | Medium to High | Good | High |
| Forward Mapping | Medium | None | Medium | Requires dedicated handling | Medium |
| Reverse Mapping | Medium | None | Low to medium, depends on sample count | Edge artifacts on foreground | Low |
Selection guidelines:
- For tight frame budgets requiring integration into a post-processing pipeline, choose reverse gathering and apply foreground compensation.
- For high foreground occlusion requirements on platforms that can afford multiple renders, consider multi-focal compositing.
- For static cameras or cutscenes allowing higher costs, accumulation buffers can yield natural results.
- Ray tracing is suitable as a reference baseline or offline validation tool, and should not be the default option unless hardware and sampling budgets explicitly allow it.
3. First-Person DoF: Circle of Confusion, Sampling, and Foreground Separation
In first-person perspectives, camera position and orientation change frequently, with foreground objects like arms or weapons near the camera and large background areas further away. Such scenes require DoF to remain stable between frames without random flickering, while properly handling near-view occlusion. Therefore, a suitable approach is to base the implementation on reverse gathering with specific compensation for the foreground.
Implementation consists of four steps:
Step 1: Calculate the Circle of Confusion (CoC). The thin lens model provides:
c = A · f · |z − s| / (z · (s − f))
Parameter conventions:
- A is aperture diameter, f is focal length, s is focus distance, and z is the linear view-space depth of the pixel. These four quantities use the same length unit, e.g., meters.
- z must be a positive linear depth. Hardware depth buffers store non-linear values; they must be restored to linear depth before applying the formula.
- s must be greater than f, or the formula fails. Parameter settings need clamping.
- c is the CoC diameter on the sensor plane, in the same length unit as above.
The thin lens assumes an ideal lens and paraxial imaging, ignoring aberrations and distortion. Games typically treat A and f as adjustable parameters. The sensor width is set to a fixed value (e.g., scaled to 36mm full-frame), then c is converted to screen pixels, and the radius is taken for sampling:
function ComputeCoCRadiusPixels(z):c = A * f * abs(z - s) / (z * (s - f)) // Diameter, unit: meterscPx = c / sensorWidth * viewportWidthPx // Convert to screen pixelsreturn min(cPx * 0.5, maxRadiusPx) // Divide by 2 for radius, clamp upper limit
The maximum radius should be determined empirically based on resolution and sample count; there is no universal fixed value. If the radius is too large, a fixed number of samples becomes sparse, causing noise in the image, making clamping necessary.
Step 2: Limit Sampling Range. The current pixel’s radius is used as the radius of the sampling disk. Sampling points use a pre-arranged Poisson disk distributed within the unit circle. The sample count N is usually between a dozen to several dozen, depending on the budget. The sampling pattern remains fixed across frames to avoid flickering caused by random jittering.
Step 3: Weighted Sampling. Each sample uses its own CoC to determine weight. A sample only contributes to the result if its CoC covers the current pixel. This prevents sharp foreground colors from contaminating the background. Hard weights (0 or 1) produce distinct ringing artifacts at edges, so a smooth transition function is used instead.
function DepthOfFieldPS(uv):z = LinearDepth(uv)radius = ComputeCoCRadiusPixels(z)colorSum = 0weightSum = 0for k in 0 .. N - 1:offset = PoissonDisk[k] // Inside unit circlesampleUV = uv + offset * radius * texelSizesampleColor = SampleColor(sampleUV) // Linear space colorsampleZ = LinearDepth(sampleUV)sampleRadius = ComputeCoCRadiusPixels(sampleZ)dist = length(offset) * radius // Distance from sample to current pixel, in pixelsw = smoothstep(dist - 1.0, dist + 1.0, sampleRadius)colorSum += sampleColor * wweightSum += wreturn colorSum / max(weightSum, epsilon) // epsilon is a small positive number, e.g., 1e-5
The pseudocode above only accumulates one set of colors and does not yet distinguish the foreground.
Step 4: Separate Foreground and Background. Accumulate samples with depths less than the focus distance (foreground) and the rest (background) separately to obtain foreground color, foreground coverage, and background color, then composite:
final = foreground + background × (1 − foregroundCoverage)
If the foreground and background are averaged together, the blurred foreground edges will absorb dark background colors, forming dark halos around object edges.
4. Color Space: Linear Calculation, Encode at the End
Lighting, blending, and blurring all require linear luminance. Averaging directly on sRGB encoded values makes results too dark and grays out light-dark transitions. The correct workflow is:
- Decode sRGB to linear values during texture sampling. Using sRGB format textures allows the hardware to decode automatically.
- Perform DoF, motion blur, and particle blending in linear space.
- Encode back to sRGB after tone mapping.
The exact function for sRGB to linear conversion is as follows, where c is the encoded value between 0 and 1:
c_linear = c ≤ 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055)^2.4
Common errors fall into two categories. First, performing DoF in gamma space causes dark foreground colors to bleed into the background. Second, sRGB decoding non-color data like normals or roughness leads to distorted lighting values.
5. Motion Blur: Reconstructing Velocity Maps from Depth Buffers
Motion blur samples and blends colors along the velocity vector of each pixel. Velocity map generation consists of two parts: camera motion can be reconstructed from depth and camera matrices, while object motion requires a separate velocity buffer.
Steps to reconstruct camera motion using only depth:
- Read the current frame’s depth d, and get the normalized device coordinates from screen UV: ndc.xy = uv × 2 − 1, ndc.z = d. The depth range must match the graphics API ([-1, 1] for OpenGL, [0, 1] for Direct3D).
- Restore world coordinates using the current frame’s inverse view-projection matrix: worldPos = invViewProj × ndc, then divide by the w component.
- Reproject using the previous frame’s view-projection matrix: prevClip = prevViewProj × worldPos, prevUV = (prevClip.xy / prevClip.w) × 0.5 + 0.5.
- Velocity v = uv − prevUV, in screen UV units. Multiply by a shutter coefficient to get the blur length.
This method has clear limitations. Depth precision drops at a distance, causing reconstructed velocity to jitter. The sky or far plane lacks valid geometry, so velocity is usually set to zero or calculated using pure camera matrix differences. Dynamic objects cannot be explained by camera matrices alone; each object needs to store its previous frame’s world matrix to write velocity into a separate velocity buffer. During composition, object velocity takes precedence.
To reduce sampling, the velocity map typically undergoes two maximum value processing steps: taking the maximum velocity per tile (TileMax), and then taking the maximum velocity within the neighborhood (NeighborMax). The tile size needs adjustment based on resolution.
function MotionBlurPS(uv):maxV = NeighborMax(uv) // Max velocity in the neighborhood, in screen UV unitslen = length(maxV * screenSizePx) // Blur length, in pixelsn = clamp(ceil(len), 1, maxSamples)colorSum = SampleColor(uv) // Linear space colorfor i in 1 .. n - 1:t = lerp(-0.5, 0.5, i / (n - 1)) // Symmetric sampling along the velocity directioncolorSum += SampleColor(uv + maxV * t)return colorSum / n
6. Particles: Low-Resolution Rendering and Depth-Aware Upsampling
Particles have high overdraw and are often rendered at half or quarter resolution, then upsampled and composited. Low-resolution rendering causes two issues: edge aliasing and depth inconsistency between particles and geometry, resulting in bright or dark edges where they intersect.
Handling methods:
- Save premultiplied alpha particle color and depth during rendering. Premultiplied alpha avoids black edges during compositing.
- Check the depth of the low-resolution neighborhood during upsampling, and only use samples with depths close to the current pixel.
- Transparent particles require sorting, drawn from back to front. If sorting costs are too high, consider weighted Order-Independent Transparency (weighted OIT).
function UpsampleParticlePS(uv):hiDepth = FullResDepth(uv)sum = 0wsum = 0for each low-res sample s in the 2x2 neighborhood of uv:lowDepth = LowResDepth(s)depthW = abs(lowDepth - hiDepth) < depthThreshold ? 1.0 : 0.0w = BilinearWeight(s, uv) * depthWsum += LowResParticle(s) * wwsum += wreturn wsum > 0 ? sum / wsum : 0
depthThreshold needs to be empirically determined based on the scene’s depth range and depth precision.
7. Normal Map Baking: High-Poly to Low-Poly Engineering Essentials
When baking normal maps, the following points are most prone to errors:
- Unify the tangent space. Use the same tangent generation method for both baking and runtime, such as MikkTSpace. Otherwise, lighting directions will be offset.
- The cage determines the start and end points of the projection rays. A cage that is too small will miss baking, while one that is too large will mix distant geometry into the result. It needs to be checked piece by piece in the baking preview.
- Baking
