SIGN IN SIGN UP
bevyengine / bevy UNCLAIMED

A refreshingly simple data-driven game engine built in Rust

0 0 59 Rust

Stabilize VisibilityRange buffer indices to fix stale HLOD culling in the GPU-driven path (#24381)

# Objective

Continuously-visible meshes using VisibilityRange (HLOD) intermittently
vanish or render with the wrong LOD/crossfade when other VisibilityRange
entities spawn or despawn, on the GPU-driven mesh path. Forcing
NoIndirectDrawing, calling set_changed on the affected Mesh3d, or moving
the camera all make it go away.

The cause is a stale index. RenderVisibilityRanges assigns each distinct
VisibilityRange value a buffer_index into the GPU visibility_ranges
buffer. That index is baked into each mesh's MeshInputUniform flags at
extraction (extract_meshes_for_gpu_building), and the GPU preprocessing
pass reads visibility_ranges[index] to do the range cull/crossfade. But
extract_visibility_ranges calls clear() and rebuilds the whole table —
reassigning indices by first-encounter order — whenever any
VisibilityRange changes or is removed. Meanwhile the per-mesh flags are
only refreshed when that mesh is re-extracted (the Changed<…> filter).
So a mesh that didn't change keeps an index that, after a rebuild
reorders the buffer, now points at a different range — it gets wrongly
culled (vanishes) or wrongly crossfaded. The CPU/direct path rebuilds
the flags for all visible meshes every frame, which is why
NoIndirectDrawing masks it.

## Solution

Make a given VisibilityRange value keep the same buffer index for the
lifetime of the app, so a baked index never goes stale:

- clear() now clears only the per-frame entities table; range_to_index
and the GPU buffer persist across frames.
- insert() allocates a stable, never-reused slot per distinct range
value, marking the buffer dirty only when a genuinely new value first
appears.
- A new rebuild_buffer_if_dirty() repopulates the GPU buffer in index
order when (and only when) a new value was added.

Indices are dense and never reused, so the buffer grows only with the
number of distinct range values ever seen (bounded in practice by the
small set of LOD configurations an app uses). No change to the public
API or the shader.

## Testing

Reproduced in an app that streams chunked terrain (3-tier HLOD via
VisibilityRange) in and out during movement on the default GPU-driven
path: unchanged, in-frustum chunks would drop out or pop to the wrong
LOD as neighbors streamed. With this change the corruption no longer
occurs, with indirect drawing left enabled. Confirmed NoIndirectDrawing
was the only prior workaround and is no longer needed.
S
Stuart Parmenter committed
0972fd9f85e9bbcb584f4fe2624fa221615c54c0
Parent: 467b2e5
Committed by GitHub <noreply@github.com> on 5/31/2026, 5:00:06 PM