Occlusion Query?

Godot Version

4.x

Question

I have been hitting my head against a problem that I just found is long solved in upstream graphics APIs we’ve been using for decades.

Problem: precise measuring of light source occlusion by any solid a fragment, used to draw suitable glow sprite and /or lens flare effect.

Solution: Turns our Vulkan has a special tool for that - an OcclusionQuery

I’ve seen this working in Source engine games (namely Black Mesa) but when I looked at footage even super old Half-Life: Source has this working.

Basically this render a small shape (sphere) around light source and counts pixels that pass a depth test. Then returns percentage as occlusion factor. This is smoothed in time to avoid single-frame jitter, and as a result a nice halo/flare sprite can be drawn that behaves naturally and responds to any solid geometry occluding the light source in full or partially.

Pros:

  • the expensive stuff happens on the GPU
  • supports alpha-tested transparency
  • native support in Vulkan and OpenGL

Cons:

  • Godot doesn’t expose this, so unless a GDextension can rectify that, we’re out of luck

Workarounds:

  1. Use one or more raycasts to approximate occclusion (only works with collision shapes, expensive, no support fro alpha-tested materials)
  2. (untested) Setup an extra camera and viewport (one for each light source, argh!) that will draw a circle around the light source, and the count fragments (pixels) in resulting frame buffer that passed depth test… That would be pretty much the same as what OcclusionQuery already does, but super slow and cumbersome… possibly not scaling well to multiple light sources etc. but that’s the only real solution I see that is doable right now.

So I have decided to try and workaround this problem and this is what I managed to do in pure GDScript:

So what’s the approach you ended up using?

Each flare generates a pseudo-random ID and passes it to two shaders.

One shader draws a circle through walls - that marks occluded pixels with red at 1.0, green is ID, blue is 0. It marks 64 in the stencil buffer.
Another shader draws a circle over the first one this time only drawing over occluded parts using the stencil buffer 64, this one marks the red as 0, green as ID again and blue at 1.0.

Lastly a fullscreen quad draws pure black over the whole frame wherever the stencil buffer is not 64.
This clears the rest of the frame of any trash.

I have a 2ndary viewport and camera that keep the camera in sync with the main one and count pixels, computing occlusion for each flare.

Then each flare looks up it’s calculated occlusion in a static dictionary and uses the occlusion to scale it’s billboard.

Then I made the pixel counting deduce ID from partial values for RED or BLUE. Because a pixel will be occluded uniformly, if RED is at 0.5 and GREEN is 0.1 then, the actual ID was 0.2, this way I can increase the precision of occlusion calculation a lot without having to count more pixels.
8xMSAA + 2x supersampling does the trick. You can try TAA or FSR 2 but they can be a little jittery.

The code is well commented (I hope) so if you want to try this yourself, here it is:

How are pixels counted?

Here’s the source code, I’ve moved this feature form experiments to framewrok’s core as OcclusionQuery core service.

Source code I wrote (MIT, no LLMs involved):

All pixel counting is done in the _compute_occlusions() method: { + unsigned char sha1[20]; + struct commit.

It counts how many pixels total were drawn for a given occlusion_query ID, and how much of that was occluded.

The green channel stores the query ID, red indicates occluded pixels, blue channel indicates unoccluded ones. By dividing non-zero green values by largest among red and blue values I can recover the original ID from partially occluded pixels. This is a big improvement over counting pixels in a binary fashion as on/off, because using 8xMSAA together with 2x supersampling we can get a really good smooth occlusion detection without increasing the number of pixels to analyze.

The pixel counting is now also moved to a separate thread so that it doesn’t stall the main thread and you can have slower updates on occlusion, but the rest of the game will not suffer form that as much.

The slowest remaining bottleneck is probably copying the viewport image from VRAM to RAM.
Further improvements here could be made by moving all pixel counting to a compute shader running as a compositor effect on the 2ndary viewport. Then it could work on the original frame buffer without copying to CPU. But that’s a bit much for me to figure out now, so I’ll leave that for future research.

I need to check how many unique IDs can I really reliably track. With maximum of 16x AA that’s 4-bits of depth, so in a 16-bit buffer I should still have 12 bits to store IDs that should not meld together even when partially occluded…

In practice I’d not bet that I have more than 10 bits (1024) unique IDs before things will start to become very shaky.

I need to implement a system to rotate unused IDs and gracefully handle removing or temporarily disabling occlusion queries.

The cool thing is this could be used for gameplay logic to ensure a player has seen something on screen unoccluded at a specified size.

Godot has a VisibilityNotifier node but it only checks frustum, culling, no occlusion. We could maybe use that as a heuristic check to avoid more costly occlusion tests if something is out of frustum anyway, that’d help cut down on needed amount of unique IDs too…