Picking with framebuffer objects
To find what is under the mouse, draw the scene again off-screen with every object (or face) in a colour that identifies it, and read back the one pixel under the mouse. This page combines pickCube to pickCube6, and on every pick runs each way of doing it side by side, checked against a ray cast on the CPU.
| Method | Pixel read | Result | Agrees with the ray cast | ms |
|---|
What the samples do, and what this page changes
- Window coordinates.
x = event.clientX; y = canvas.height − event.clientYmeasures from the window, not the canvas. On the samples' bare pages the canvas starts 8 px in, so every pick is read 8 px right of and 8 px above the click; anything that moves or scales the canvas (scrolling, CSS) makes it worse. UsegetBoundingClientRect()and scale bycanvas.width / rect.width. - No depth buffer. The pick framebuffer has only a colour attachment, so the last object drawn wins. A single convex cube with back faces culled never overlaps itself, which is why the samples work.
- pickCube2's face names do not match
colorCube(): front is called "right", right "top", top "front", back "left", left "back"; only bottom is right. pickCube3 names faces by their drawn colour, which is consistent. - pickCube5's handler is
function()with no parameter and uses the globalevent; pickCube6 sets a uniform named"i"that does not exist (harmless, because the click handler resetsuColorIndexto 0 itself). - Colours are ids. Six colours can only name six faces. An id per object and face fits in the 24 bits of an RGBA8 colour, or exactly in an R32UI integer target.
- Cheaper picking. A 1 × 1 framebuffer with a pick matrix draws only the pixel that is read. Writing ids to a second render target in the main pass avoids the extra pass altogether, at the cost of an id write every frame.
- Reading a pixel waits for the GPU. The times in the table include that wait.