Culling and the frame

Sorting on the GPU

A GPU-driven renderer decides on the GPU what to draw, so when the draws must be in an order (see-through surfaces back to front, for example), the GPU has to sort them too. A CPU sort compares and moves one pair at a time. A GPU sort needs a plan where thousands of threads each compare one pair, all at the same time, with no thread waiting for another. This page explains the bitonic sort, the classic such plan, and how it maps to compute dispatches. The last part shows how RASM sorts its see-through draws.

In short

  • Sort small keys: a number that gives the order, plus the item's index so equal numbers keep a fixed order.
  • A sorting network is a fixed list of compare-and-swap steps. It does not depend on the data, so every step can run one thread per pair.
  • The bitonic network sorts n = 2m keys in m(m + 1) / 2 steps of n / 2 compares each.
  • Steps that compare keys close together run inside one workgroup, in shared memory; steps with a long distance need a dispatch of their own and a barrier.
  • When only the GPU knows how many items there are, sort a fixed power of two and give the missing items the largest key: they end up last.
  • For very many keys a radix sort does less work; for a few thousand, bitonic is simple and fast.

1What to sort: keys

Moving whole items around is slow, so sort keys: one small value per item that says where it goes, and the item's index. After the sort, one more pass copies the items to their new places.

items keys sorted keys draw 0, depth 2 draw 1, depth 9 draw 2, depth 5 draw 3, depth 9 (2, 0) (9, 1) (5, 2) (9, 3) (9, 1) (9, 3) (5, 2) (2, 0) far first; equal depths by index
A key is (order, index). The index breaks ties, so two runs with the same input give the same output, which matters for blending: a different order of equal-depth panes would flicker.
A float as a sortable integer

For a float that is 0 or more, its bits read as an unsigned integer grow with the float. So asuint(depth) sorts like the depth. To sort far first with an ascending sort, use the complement, ~asuint(depth).

2Sorting networks

A compare-and-swap looks at two places and swaps them if they are out of order. A sorting network is a fixed list of such compares, grouped into steps; the compares of one step touch different places, so they can all run at once. Whatever the input, after the last step the list is sorted.

The bitonic network builds bigger and bigger sorted pieces. A merge of size k (2, 4, 8, …) takes two sorted halves that run in opposite directions, a bitonic sequence, and turns it into one sorted piece, in steps of distance j = k/2, k/4, …, 1. In each step, place i is compared with place i + j; the piece sorts up when bit k of i is 0 and down when it is 1, so the next merge again gets two halves in opposite directions.

0123 4567 k 2, j 1 k 4, j 2 k 4, j 1 k 8, j 4 k 8, j 2 k 8, j 1
The bitonic network for 8 keys. Each arrow is one compare: after it, the smaller key is at the arrow's tail and the larger at its head (green: up, amber: down). One step's compares touch different places, so a step is one parallel pass.

steps = m (m + 1) / 2, for n = 2m keys

compares per step
n / 2, one per thread.
8 keys
6 steps. 1024 keys: 55 steps. 4096 keys: 78 steps.
total work
about n log² n / 4 compares: more than a good CPU sort's n log n, but all in parallel.

Step through it with your own keys:

Press "Next step" and watch which pairs are compared. Change the step slider to go back. After the last step the keys are sorted, whatever you started with; "Shuffle" starts again.

3Steps as dispatches

Every step must see the result of the step before it, everywhere in the list. On a GPU that means a barrier between steps. Inside one workgroup a barrier is cheap: the group's threads sync on shared memory. Across workgroups it means ending the dispatch, a memory barrier, and a new dispatch.

a block in shared memory many steps, group barriers

Short steps: in a group

When the distance j is below the block size, both keys of every pair are in the same block. One dispatch runs all such steps of a merge in shared memory.

one step per dispatch

Long steps: one dispatch each

A distance of a block or more crosses blocks. Each such step is a dispatch over the whole list, reading and writing memory, then a barrier.

2048 keys, blocks of 1024: 4 dispatches instead of 66

The count

With blocks of B keys, the first log B merges are one dispatch. Each larger merge of size k takes log(k/B) long steps and one short-step dispatch.

When only the GPU knows the count

In a GPU-driven frame the number of items to sort comes from an earlier GPU pass, and the CPU records the dispatches before that pass runs. So the CPU sizes the sort for the most items there can be, rounded up to a power of two, and the threads past the real count write the largest key. Those keys sort to the end, and the copy pass stops at the count.

Pad with the largest key, index included

A padding key with the largest order value but a small index could tie with a real item at that value and land in front of it. Make the padding key the largest in every part, (max, max), and give real items indices below the padding's.

4Other GPU sorts

Bitonic

Simple, no atomics, fixed work. Best for up to some tens of thousands of keys.

n log² n compares.

count, scan, scatter per digit

Radix

Sorts by a few bits at a time with histograms and prefix sums. The fastest for millions of keys.

n × (bits / digit size) passes.

each tile on its own

Sort per tile only

Particles or a tiled renderer may only need each tile in order: one shared-memory sort per group and no global steps.

One dispatch.

5In RASM

RASM sorts the see-through (BLEND) draws of each shaded view back to front, after culling has packed the visible ones (see transparency and stream compaction). The plan is made on the CPU from the size of the blend run, which the CPU knows; the count of visible draws is read on the GPU.

writeMainpacks, counts sortKeysMainkeys, block sorts sortMergeMainone long step sortLocalMergeMainshort steps of a merge sortWriteMaincopies back for each merge of 2048 keys and more sort buffer: keys (uint2 × capacity), then the copied draws (DrawInfo × capacity)
The sort inside the cull pass that keeps the blend run: Cull 2 with occlusion culling, or the only Cull pass. One COMPUTE → COMPUTE barrier before each dispatch.
2dispatches up to 1024 drawskeys + block sort, write
4for 2048+ 1 long step, 1 short-step pass
7for 4096+ 2 long steps, 1 short-step pass
0.025 ms1537 draws, RTX 306009_gltf_materials, Blend Sort timer; 0.018 ms for 501

Where RASM follows the page, and where it differs

PartThis pageRASM
Key(order, index)(the draw's order in the top 8 bits, then the top 24 bits of ~asuint(view depth); place in the run): the order is a vector layer's drawOrder around the scene's see-through draws (vector features), the view depth the draw's bounding sphere center, clamped at 0, so within an order the farthest draw comes first.
Sizea power of two, at least a blockgetBlendSortCapacity: the blend run's size rounded up to a power of two, at least BLEND_SORT_BLOCK (1024). The visible count is read on the GPU (drawCountsPtr[blendRun]).
Blocka workgroup in shared memory1024 keys per group of BLEND_SORT_GROUP_SIZE (256) threads, each doing 2 of the 512 compares per step.
Plana list of dispatchesgetBlendSortDispatches: keys, then per merge past a block its long steps and one local merge, then write. The step's sizes go in the push constant's argument as log2 k and log2 j.
Moving the itemssort keys, copy onceThe draws are copied aside first (sortDrawsPtr), and sortWriteMain writes them back into the visible draw list, so the Transparent pass draws the run as it is.
Which views—Only views that draw the blend run: shaded views (SceneView::sortBlend). Shadow maps need no order. With culling frozen (Renderer::setCullingFrozen), a view with occlusion culling runs only its early cull pass, which then also culls the blend run, and those draws go unsorted.

Where it lives in code

WhatWhere
The entry pointssortKeysMain, sortMergeMain, sortLocalMergeMain, sortWriteMain in shaders/passes/sort.slang
The plan and its sizesgetBlendSortCapacity, getBlendSortDispatches in src/renderer/blendSort.cpp; tested by tests/blendSortTests.cpp, which runs the plan on the CPU
Recording the dispatchesRenderer::recordBlendSort in src/renderer/gpuScene.cpp
The sort buffers, their growth and the pointersSceneView::sortBuffers, Renderer::prepareSceneView; SceneData::sortKeysPtr, sortDrawsPtr, sortCapacity
Keep these true
  • BLEND_SORT_BLOCK and BLEND_SORT_GROUP_SIZE are in blendSort.h and, as SORT_BLOCK and SORT_GROUP_SIZE, in sort.slang. Change both.
  • The step's direction uses the element's place in the whole list ((i & k) == 0), also inside a block: the blocks must alternate direction for the next merge.
  • The sort size covers the whole run, not the visible count, and padding keys are (0xFFFFFFFF, 0xFFFFFFFF).

Further reading