Three.js Occlusion Queries (WebGL2 ANY_SAMPLES_PASSED)
Hardware occlusion queries in Three.js, wrapping each object's draw in a WebGL2 query via onBeforeRender/onAfterRender, reading results asynchronously and showing visible, occluded and frustum-culled objects in a top-down inset.
Key topics: three.js occlusion query, webgl2 query, visibility, any samples passed, onbeforerender, culling
Game Over
What this code does
- Queries: `beginQuery(ANY_SAMPLES_PASSED_CONSERVATIVE)` around a draw asks the GPU whether any pixel passed the depth test.
- Hooks: `mesh.onBeforeRender` and `onAfterRender` bracket three.js's own draw call, with no renderer changes.
- Asynchronous: results arrive a frame or more later and are polled with QUERY_RESULT_AVAILABLE so the CPU never stalls.
- States: visible, occluded by the wall, frustum-culled (never drawn, so never queried) and pending.
- Overview: a second camera in a scissor viewport colours objects by their latest query result, with queries off for that pass.
- Controls: occluder width, occluder motion and overview inset.
Related Demos
Continue Learning
JavaScript Implementation
// Wrap a mesh's draw call in a WebGL2 occlusion query
const gl = renderer.getContext()
let query = null
let visible = true
mesh.onBeforeRender = () => {
if (query) return // previous result still pending
query = gl.createQuery()
gl.beginQuery(gl.ANY_SAMPLES_PASSED_CONSERVATIVE, query)
}
mesh.onAfterRender = () => { gl.endQuery(gl.ANY_SAMPLES_PASSED_CONSERVATIVE) }
// later (next frame) — never block waiting:
if (query && gl.getQueryParameter(query, gl.QUERY_RESULT_AVAILABLE)) {
visible = gl.getQueryParameter(query, gl.QUERY_RESULT) > 0
gl.deleteQuery(query)
query = null
}