Culling and the frame
Picking
Picking answers "what is under this pixel?": the object, the part of it, and the point in the world. An editor selects with it, a game aims with it, a map app asks which road the mouse is on. This page explains how to get the answer from the GPU: draw object ids into a small image, only for the pixels you ask about, and read it back without a stall. The last part shows how RASM does it.
In short
- An ID buffer is an image whose pixels hold numbers, not colors: which object drew the pixel, and where it hit it.
- Draw it with the same vertex code as the image, so it sees exactly what the user sees: animated, deformed, spread on screen.
- Draw it only for the rect you ask about: a narrow frustum through those pixels culls almost everything, and a shifted viewport puts the view's pixels in a tiny target.
- Read it back a few frames later, when the GPU is done. Never wait for it in the frame that asked.
- Write the hit point relative to the camera in floats, and add the camera's position in doubles on the CPU: exact in a planet-sized world.
- A rect gives many pixels: group them by object, nearest the rect's centre first.
1Two ways to ask
There are two classic answers. One asks the CPU's copy of the scene, the other asks the GPU's picture of it.
Ray cast on the CPU
Needs the triangles on the CPU, and a copy of every rule that moves them: skinning, morphs, terrain heights, lines spread to a width in pixels. Any difference picks the wrong thing.
ID buffer on the GPU
Draw the scene again with each object's id as its "color". The pixel holds the answer, and it is what was drawn, whatever the vertex shader did.
The ID buffer is the one to use when the GPU moves or builds geometry. The rest of this page is about doing it well.
2The ID buffer
Each pixel of the ID buffer holds integers, in an integer format (four 32-bit words a pixel): an id of the object that drew it, and a word or two more, such as the part of a mesh or a map feature's own id. 0 means "nothing": the background.
The same draw can also write where it hit the surface: the point, and the surface's normal. That turns "which object" into "which object, and where on it", for placing things, measuring and snapping.
3Draw only the pixels you ask about
An ID buffer of the whole screen costs a whole extra frame of drawing, and most of it is never read. The question is about one pixel, or a small rect around the mouse. Two tricks make the work follow the rect:
A narrow frustum
Cull with the frustum through the rect, not the view's. Its four side planes come from the rect's edges. In a big scene it keeps a handful of objects.
A shifted viewport
Keep the view's whole viewport, W × H, but start it at (−x, −y). The rect's pixels land on a target the size of the rect, and the rasterizer clips the rest.
The same pixels
The projection, the viewport size and every pixel-size rule stay the view's, so lines keep their width in pixels and LODs stay the same. The samples fall exactly where the view's did.
The narrow frustum is the view's projection with a stretch in front of it. The rect covers x0…x1 and y0…y1 of normalized device coordinates; the stretch maps that range to −1…1, and the usual plane extraction (the rows of the matrix) gives the rect's planes:
x′ = sx·x + tx·w
sx = 2 / (x1 − x0)
tx = −(x1 + x0) / (x1 − x0)
planes: rows of S · P · V
- x, w
- a point's clip coordinates; NDC x = x / w
- x0, x1
- the rect's edges in NDC: 2 · pixel / width − 1 (and 1 − 2 · pixel / height for y, rows down from the top)
- S, P, V
- the stretch (the same for y), the projection, the view; the planes x′ ≥ −w, x′ ≤ w and the same for y bound the rect, and near and far stay the view's
4What one pixel holds
Two integer texels per pixel, 32 bytes, are enough for a rich answer. The second texel keeps a float's bits as an integer, so no value is changed on the way.
Relative to the camera
A float keeps 24 bits: 0.5 m at 6 000 km, 0.06 mm at 1 km. Written relative to the camera and added to its position in doubles, the point is exact anywhere.
Octahedral normal
Fold the unit sphere onto an octahedron, then flat: two 16-bit numbers, a precision of about 0.005°.
Ids that outlive the frame
The answer comes frames later. Name the object with a handle that has a generation, so an object destroyed since reads as dead, never as its successor.
5When the answer comes
The GPU runs a frame or two behind the CPU (frames in flight). The pick is drawn at the end of the next frame, copied to memory the CPU can read, and read when that frame's fence has passed. Waiting at once would stall the CPU until the GPU catches up.
The copy lives in the frame slot's memory, and so does anything the ids refer to (a table of objects per slot). Read the answer, and turn ids into handles, before that slot records its next frame. After that, the bytes are another frame's.
6See-through, cut-out, MSAA and TAA
The ID draw follows the image's rules where they make sense, and picks a rule of its own where a pixel has no single answer.
Cut-outs
Discard below the cutoff, as the image does: a click through a hole in a leaf hits what is behind it.
See-through
No blending in an id. A see-through surface is picked where its alpha reaches a threshold: an editor sets it low to select glass, a game high to aim through it. Drawn in the image's blend order without writing depth, the one shown on top writes last.
MSAA and TAA
One sample per pixel, at its centre, with no jitter. An edge pixel of the image blends two surfaces; the pick names the one at the centre, the same every frame.
Kinds the user wants to look through, such as labels over a map or every object but the ground, are best left out in the vertex stage: their triangles collapse and draw nothing, at no cost.
7A rect: many pixels, one list
A pick of a rect, say 7 × 7 pixels around the mouse to catch a thin line, gives up to 49 answers. Group the pixels by what they show, and order the groups by the pixel nearest the rect's centre, then by distance from the camera.
8Pitfalls
- The pick names the wrong object at an edge
- The image was jittered (TAA) or multisampled, and the ID draw was not. Pick at the pixel's centre without jitter, and accept that an edge pixel belongs to one surface.
- Thin lines are hard to hit
- A one-pixel line is missed by a one-pixel pick most of the time. Pick a small rect (5 × 5, 7 × 7) and take the nearest group of the kind you want.
- The position jumps in steps far from the origin
- The point was written in world coordinates as floats. Write it relative to the camera and add the camera's position in doubles.
- The frame stalls when the user clicks
- The answer was read in the frame that asked, so the CPU waited for the GPU. Read it two frames later, when it is ready.
- A deleted object comes back from a click
- The id was a bare slot, reused by a new object. Keep a generation with it, and map it with the table the frame drew with.
- The pick costs a frame
- The ID buffer covered the whole screen, or drew every visible object. Cull with the rect's frustum and draw into a rect-sized target.
9In RASM
Renderer::pick takes a view of Renderer::render(views, count), or a scene, camera and render target of the application's own graph, and a PickDesc: the rect in the view's pixels (ViewPixels, at most MAX_PICK_SIZE on each side), minAlpha and the skip mask. It returns a PickHandle. The next endFrame records it, isPickReady says when the answer is in, and takePick fills an array of PickHits. Nothing runs while nobody picks: no pass, no barrier, no memory.
| This page | RASM |
|---|---|
| A narrow frustum | getPickClipMatrix stretches the rect to −1…1; getFrustumPlanes of it times the view's unjittered projection and view gives the planes. The cull is countMain and writeMain of shaders/passes/cull.slang with hizLevelCount 0 and no meshlets: frustum only, the view's LODs and vector padding. |
| A shifted viewport | The viewport is (column − x, −y, W, H) on the slot's targets, the scissor the pick's column. Up to MAX_FRAME_PICKS picks a frame sit side by side in one row up to MAX_PICK_ROW_WIDTH pixels; the others wait a frame. |
| The same vertex code | shaders/passes/rasm.slang compiled with RASM_PICK: vertMain as the image's, pickMain instead of fragMain, one pipeline per alpha mode, made on the first pick (P31). |
| Two integer texels | R32G32B32A32_UINT ids (instance row + 1, feature id, PICK_HIT_* flags, the material row) and positions (render-space float bits, packPickNormal), with a D32_SFLOAT depth. |
| Relative to the camera | The view's render space (Large worlds); toWorldPosition with the view's origin of that frame. A vector feature writes its own point under the pixel without its depth bias, so an overlay or a label gives the ground under it. |
| Ids that outlive the frame | The GPU writes the instance row. InstanceOwners keeps, per frame slot, which entity's sub-mesh each row holds as that slot's table does; readPicks maps the rows before the slot's next sync, so a destroyed entity's row reused at once still names the old EntityHandle, which Renderer::isAlive then calls dead. |
| See-through and cut-outs | MASK cuts at the material's cutoff; BLEND meshes and every vector feature (lines, points, polygons, labels) are picked where their alpha as drawn reaches PickDesc::minAlpha (0.5 by default, a line's drawn edge; 1/255 steps, rounded down). The blend run is sorted as the view sorts it (draw order, then back to front: recordBlendSort on the pick's SceneData) and drawn last without writing depth, so the feature the view shows on top writes the pixel last. Overlays stay on top, as on screen. |
| Weighted and additive | Their runs are not sorted, so their pick pipeline (rasmPickBlend shaders) writes depth: the nearest surface whose alpha is at least PickDesc::minAlpha is hit, under the sorted ones in front. A weighted glyph tests its alpha too (weighted blended transparency). |
| Kinds to look through | PICK_SKIP_MESHES, PICK_SKIP_BLEND, PICK_SKIP_TERRAIN, PICK_SKIP_VECTORS, PICK_SKIP_LABELS, PICK_SKIP_OVERLAYS, PICK_SKIP_POINTS, PICK_SKIP_GLYPHS: their triangles collapse in the vertex stage. |
| Instances of one draw | A glyph is an instance of its shape, so the row names only its chunk: the glyph's index goes in the feature (PICK_HIT_GLYPH), the index in the arrays it was built from. A view that drew glyphs culls them again through the rect into the pick slot's own glyph buffer (PickSlot::glyphCull) and draws them with rasm.slang compiled with RASM_PICK and RASM_GLYPHS (Instanced glyphs). |
| A rect, grouped | groupPickSamples: a PickHit per (row, feature) with its pixel count and its pixel nearest the centre, then nearest the camera. |
| No allocation, no stall | Requests, their hit vectors and the scratch keep their capacity, so a hover pick every frame allocates nothing (the image tests count it). takePick waits only when called before the frame is done. |
Code map
| What | Where |
|---|---|
| The API | include/rasm/picking.h (PickDesc, PickHit, the flags), Renderer::pick, isPickReady, takePick in include/rasm/renderer.h; getViewPixel in include/rasm/view.h |
| Requests, recording, read-out | src/renderer/picking.cpp: queuePick, recordPicks (from endFrame), finishPickSubmit, readPicks (from beginFrame after the fence, and isPickReady) |
| The view's frame data | prepareSceneView keeps SceneView::sceneData, its unjittered projection and its origin; ViewGraph::getSceneTarget finds a view's scene target |
| The shader | pickMain, isPickSkipped, packPickNormal in shaders/passes/rasm.slang; VectorVertex::depthPoint in shaders/lib/vector.slang |
| The C API | rasm_pick_view, rasm_pick_target, rasm_is_pick_ready, rasm_take_pick in src/c/cPicking.cpp |
| Example | examples/26_picking/main.cpp: hover, click and box picks in two views, and scripted checks far from the origin |
| Tests | tests/pickingTests.cpp (the rect's matrix, the grouping, the normal, the row owners); the image tests picking, picking_msaa4, picking_taa, far_picking pick known points |
A pick reads only what its frame drew: the view's SceneData of that frame and the slot's tables. Read a slot's picks before that slot records new ones or syncs its instance rows. Keep the pick draw's vertex code the image's: a rule added to vertMain reaches the pick by itself.
Further reading
- Vulkan specification, "Viewport": the viewport's bounds range, which allows a negative origin.
- Cigolle et al., "A Survey of Efficient Representations for Independent Unit Vectors" (octahedral normals).
- Frustum culling, Headless rendering and readback, Large worlds, Generational handles.