Skip to content

Cold Specialization - #17567

Merged
alice-i-cecile merged 35 commits into
bevyengine:mainfrom
tychedelia:cold-specialization-final
Feb 5, 2025
Merged

alice-i-cecile merged 35 commits into
bevyengine:mainfrom
tychedelia:cold-specialization-final

Conversation

@tychedelia

Copy link
Copy Markdown
Member

Cold Specialization

Objective

An ongoing part of our quest to retain everything in the render world, cold-specialization aims to cache pipeline specialization so that pipeline IDs can be recomputed only when necessary, rather than every frame. This approach reduces redundant work in stable scenes, while still accommodating scenarios in which materials, views, or visibility might change, as well as unlocking future optimization work like retaining render bins.

Solution

Queue systems are split into a specialization system and queue system, the former of which only runs when necessary to compute a new pipeline id. Pipelines are invalidated using a combination of change detection and ECS ticks.

The difficulty with change detection

Detecting “what changed” can be tricky because pipeline specialization depends not only on the entity’s components (e.g., mesh, material, etc.) but also on which view (camera) it is rendering in. In other words, the cache key for a given pipeline id is a view entity/render entity pair. As such, it's not sufficient simply to react to change detection in order to specialize -- an entity could currently be out of view or could be rendered in the future in camera that is currently disabled or hasn't spawned yet.

Why ticks?

Ticks allow us to ensure correctness by allowing us to compare the last time a view or entity was updated compared to the cached pipeline id. This ensures that even if an entity was out of view or has never been seen in a given camera before we can still correctly determine whether it needs to be re-specialized or not.

Testing

TODO: Tested a bunch of different examples, need to test more.

Migration Guide

TODO

  • AssetEvents has been moved into the PostUpdate schedule.

@tychedelia tychedelia added A-Rendering Drawing game state to the screen D-Complex Quite challenging from either a design or technical perspective. Ask for help! S-Needs-Review Needs reviewer attention (from anyone!) to move forward labels Jan 27, 2025

@pcwalton pcwalton left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A couple of comments to start with. I'll have more later when I take a closer look.

Comment thread crates/bevy_pbr/src/material.rs Resolved
Comment thread crates/bevy_pbr/src/material.rs Resolved
.render_lightmaps
.get(&entity)
.map(|lightmap| lightmap.slab_index);
self.shared.lightmap_slab_index = lightmap_slab_index;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Check pass ordering here. Are we sure that render_lightmaps is populated before this runs?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Okay, will check. I also think that Lightmap needs to be added to the invalidation logic.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks like we're good, as RenderLightmaps is populated during the extraction phase, and RenderMeshInstanceGpuBuilder::update is called during the collection subphase of the render phase.

@alice-i-cecile alice-i-cecile added C-Performance A change motivated by improving speed, memory usage or compile times M-Release-Note Work that should be called out in the blog due to impact labels Jan 27, 2025

@pcwalton pcwalton left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a more thorough review. I mostly just had some simplification suggestions that you can do if you want. This is great stuff.

Comment thread crates/bevy_pbr/src/material.rs Resolved
Comment thread crates/bevy_pbr/src/material.rs Resolved
Comment thread crates/bevy_pbr/src/material.rs Resolved
Comment thread crates/bevy_pbr/src/material.rs Resolved
Comment thread crates/bevy_pbr/src/prepass/mod.rs Resolved
Comment thread crates/bevy_sprite/src/mesh2d/mesh.rs Resolved
.render_lightmaps
.get(&entity)
.map(|lightmap| lightmap.slab_index);
self.shared.lightmap_slab_index = lightmap_slab_index;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks like we're good, as RenderLightmaps is populated during the extraction phase, and RenderMeshInstanceGpuBuilder::update is called during the collection subphase of the render phase.

@alice-i-cecile alice-i-cecile added the S-Ready-For-Final-Review This PR has been approved by the community. It's ready for a maintainer to consider merging it label Feb 5, 2025
@alice-i-cecile
alice-i-cecile added this pull request to the merge queue Feb 5, 2025
@alice-i-cecile

Copy link
Copy Markdown
Member

@tychedelia when you get a chance could you please finish up the migration guide?

Merged via the queue into bevyengine:main with commit 2ea5e9b Feb 5, 2025
HackerFoo added a commit to HackerFoo/bevy that referenced this pull request Feb 6, 2025
HackerFoo added a commit to HackerFoo/bevy that referenced this pull request Feb 7, 2025
github-merge-queue Bot pushed a commit that referenced this pull request Feb 8, 2025
This PR makes Bevy keep entities in bins from frame to frame if they
haven't changed. This reduces the time spent in `queue_material_meshes`
and related functions to near zero for static geometry. This patch uses
the same change tick technique that #17567 uses to detect when meshes
have changed in such a way as to require re-binning.

In order to quickly find the relevant bin for an entity when that entity
has changed, we introduce a new type of cache, the *bin key cache*. This
cache stores a mapping from main world entity ID to cached bin key, as
well as the tick of the most recent change to the entity. As we iterate
through the visible entities in `queue_material_meshes`, we check the
cache to see whether the entity needs to be re-binned. If it doesn't,
then we mark it as clean in the `valid_cached_entity_bin_keys` bit set.
If it does, then we insert it into the correct bin, and then mark the
entity as clean. At the end, all entities not marked as clean are
removed from the bins.

This patch has a dramatic effect on the rendering performance of most
benchmarks, as it effectively eliminates `queue_material_meshes` from
the profile. Note, however, that it generally simultaneously regresses
`batch_and_prepare_binned_render_phase` by a bit (not by enough to
outweigh the win, however). I believe that's because, before this patch,
`queue_material_meshes` put the bins in the CPU cache for
`batch_and_prepare_binned_render_phase` to use, while with this patch,
`batch_and_prepare_binned_render_phase` must load the bins into the CPU
cache itself.

On Caldera, this reduces the time spent in `queue_material_meshes` from
5+ ms to 0.2ms-0.3ms. Note that benchmarking on that scene is very noisy
right now because of #17535.

![Screenshot 2025-02-05
153458](https://github.com/user-attachments/assets/e55f8134-b7e3-4b78-a5af-8d83e1e213b7)
mrchantey pushed a commit to mrchantey/bevy that referenced this pull request Feb 17, 2025
# Cold Specialization

## Objective

An ongoing part of our quest to retain everything in the render world,
cold-specialization aims to cache pipeline specialization so that
pipeline IDs can be recomputed only when necessary, rather than every
frame. This approach reduces redundant work in stable scenes, while
still accommodating scenarios in which materials, views, or visibility
might change, as well as unlocking future optimization work like
retaining render bins.

## Solution

Queue systems are split into a specialization system and queue system,
the former of which only runs when necessary to compute a new pipeline
id. Pipelines are invalidated using a combination of change detection
and ECS ticks.

### The difficulty with change detection

Detecting “what changed” can be tricky because pipeline specialization
depends not only on the entity’s components (e.g., mesh, material, etc.)
but also on which view (camera) it is rendering in. In other words, the
cache key for a given pipeline id is a view entity/render entity pair.
As such, it's not sufficient simply to react to change detection in
order to specialize -- an entity could currently be out of view or could
be rendered in the future in camera that is currently disabled or hasn't
spawned yet.

### Why ticks?

Ticks allow us to ensure correctness by allowing us to compare the last
time a view or entity was updated compared to the cached pipeline id.
This ensures that even if an entity was out of view or has never been
seen in a given camera before we can still correctly determine whether
it needs to be re-specialized or not.

## Testing

TODO: Tested a bunch of different examples, need to test more.

## Migration Guide

TODO

- `AssetEvents` has been moved into the `PostUpdate` schedule.

---------

Co-authored-by: Patrick Walton <pcwalton@mimiga.net>
mrchantey pushed a commit to mrchantey/bevy that referenced this pull request Feb 17, 2025
This PR makes Bevy keep entities in bins from frame to frame if they
haven't changed. This reduces the time spent in `queue_material_meshes`
and related functions to near zero for static geometry. This patch uses
the same change tick technique that bevyengine#17567 uses to detect when meshes
have changed in such a way as to require re-binning.

In order to quickly find the relevant bin for an entity when that entity
has changed, we introduce a new type of cache, the *bin key cache*. This
cache stores a mapping from main world entity ID to cached bin key, as
well as the tick of the most recent change to the entity. As we iterate
through the visible entities in `queue_material_meshes`, we check the
cache to see whether the entity needs to be re-binned. If it doesn't,
then we mark it as clean in the `valid_cached_entity_bin_keys` bit set.
If it does, then we insert it into the correct bin, and then mark the
entity as clean. At the end, all entities not marked as clean are
removed from the bins.

This patch has a dramatic effect on the rendering performance of most
benchmarks, as it effectively eliminates `queue_material_meshes` from
the profile. Note, however, that it generally simultaneously regresses
`batch_and_prepare_binned_render_phase` by a bit (not by enough to
outweigh the win, however). I believe that's because, before this patch,
`queue_material_meshes` put the bins in the CPU cache for
`batch_and_prepare_binned_render_phase` to use, while with this patch,
`batch_and_prepare_binned_render_phase` must load the bins into the CPU
cache itself.

On Caldera, this reduces the time spent in `queue_material_meshes` from
5+ ms to 0.2ms-0.3ms. Note that benchmarking on that scene is very noisy
right now because of bevyengine#17535.

![Screenshot 2025-02-05
153458](https://github.com/user-attachments/assets/e55f8134-b7e3-4b78-a5af-8d83e1e213b7)
@alice-i-cecile

Copy link
Copy Markdown
Member

Thank you to everyone involved with the authoring or reviewing of this PR! This work is relatively important and needs release notes! Head over to bevyengine/bevy-website#1989 if you'd like to help out.

morr added a commit to morr/bevy that referenced this pull request Jul 30, 2026
…ntities

# Objective

Fixes bevyengine#25163.

A 2D scene mixing blended `Mesh2d` entities with sprites starts blinking
out for single frames once the scene has been despawned and respawned a
few times, even though nothing in it moves. It never happens on the first
spawn.

`queue_material2d_meshes` is the only system that removes items from the
retained sorted `Transparent2d` phase (and from the binned 2D phases),
but it returns early when `render_material_instances` is empty — which is
exactly the frame the last entity using that material type is despawned.
Those items then stay in the phase forever: `removed_entities` and
`removed_renderables` are per-frame lists, so by the next frame there is
nothing left to act on.

A leftover item also keeps the `batch_range` it was last batched with,
because `batch_and_prepare_sorted_render_phase` only rewrites the range
of items that still have a `RenderMesh2dInstance`. And
`SortedRenderPhase::render_range` draws an item and then advances by
`batch_range.len()`, assuming the batch it just drew covers that many
following items:

```rust
if batch_range.is_empty() { index += 1; }
else { draw_function.draw(world, render_pass, view, item)?; index += batch_range.len(); }
```

So an item left behind by a batch of three steps over the two live items
sitting behind it, and they are never drawn. Which items those are
depends on the order among equal sort keys, which changes every frame, so
it reads as random flicker rather than a permanently missing object.

The early return predates the dequeue loop: it was added in bevyengine#17567, when
this system only ever added items, and the removal logic landed later in
bevyengine#23083 on top of it. `queue_material_meshes` on the 3D side dequeues
unconditionally and has no such early return.

## Solution

Keep the fast path where it is still valid — with no entity using the
material there is nothing to queue — but move it below the dequeue loop
and make it `continue` instead of `return`, so items of despawned
entities always leave the phase.

## Testing

Measured with a static scene (nothing moves, the camera never changes) of
7 permanent sprites, 7 more permanent sprites sorting before the churn,
and 3 blended `Mesh2d` quads sharing one mesh and one `ColorMaterial`
that are despawned and respawned every 30 frames. Instead of comparing
pixels, a system in `RenderSystems::Cleanup` walks the phase the way
`render_range` does and counts items that end up never drawn.

Over 240 frames on 0.19.0: the phase grows from 17 to 26 items, 12 of
them belonging to despawned entities, and 102 frames drop at least one
live item — 157 drops in total, every one of them a permanent sprite that
should never blink. With this change the phase stays at 14 items, no items
of despawned entities are left in it, and nothing is dropped. The sprites
that sort before the churn are never affected either way, which is what
points at the phase order rather than at the display.

macOS 15 on Apple Silicon, Metal.
morr added a commit to morr/bevy that referenced this pull request Jul 30, 2026
…25163)

# Objective

Fixes bevyengine#25163.

`queue_material2d_meshes` is the only system that removes items from the
retained 2D phases, but it returns early when
`render_material_instances`
is empty — the very frame the last entity of that material type is
despawned. Those items stay in the phase forever, keeping the
`batch_range` they were last batched with, and
`SortedRenderPhase::render_range` advances by `batch_range.len()` after
each draw, so a leftover batch leader steps over the live items behind
it.
Which items those are depends on the order among equal sort keys, and
that
changes every frame, so it reads as flicker.

The early return predates the dequeue loop: bevyengine#17567 added it when this
system only queued, bevyengine#23083 added removal on top of it. The 3D
`queue_material_meshes` dequeues unconditionally.

## Solution

Keep the fast path — with no entity using the material there is nothing
to
queue — but move it below the dequeue loop and make it `continue`.

## Testing

Static scene: 3 blended `Mesh2d` quads sharing a mesh and material,
respawned every 30 frames, next to permanent sprites. A system in
`RenderSystems::Cleanup` walks the phase the way `render_range` does and
counts items that end up never drawn.

Over 240 frames on 0.19.0 the phase grows from 17 to 26 items and 102
frames drop a live sprite (157 drops). With this change the phase stays
at
14 items and nothing is dropped. macOS on Apple Silicon, Metal.
morr added a commit to morr/bevy that referenced this pull request Jul 30, 2026
…25163)

# Objective

Fixes bevyengine#25163.

`queue_material2d_meshes` is the only system that takes items out of the
retained 2D phases, and it returns early when `render_material_instances`
is empty. That is the frame the last entity using that material type gets
despawned, so its items never get removed and stay in the phase for good.

They also keep the `batch_range` they had when they were last batched,
since `batch_and_prepare_sorted_render_phase` only rewrites the range of
items that still have a `RenderMesh2dInstance`. `render_range` advances the
index by `batch_range.len()` after every draw, so an item left over from a
batch of three hides the two live items behind it. With equal sort keys the
order changes from frame to frame, which is why it shows up as flicker
instead of something permanently missing.

The early return is older than the dequeue loop (bevyengine#17567 added it back when
the system only queued, bevyengine#23083 added the removal). The 3D
`queue_material_meshes` doesn't have one.

## Solution

Move the check below the dequeue loop and make it a `continue`. There is
still nothing to queue when no entity uses the material, but removal now
always happens.

## Testing

3 blended `Mesh2d` quads sharing a mesh and material, respawned every 30
frames, plus a few permanent sprites. Nothing in the scene moves. I counted
items that never get drawn from a `RenderSystems::Cleanup` system that
walks the phase the same way `render_range` does.

240 frames on 0.19.0: the phase grows 17 -> 26 items, 102 frames drop a
live sprite, 157 drops in total. Same run with this patch: 14 items, no
drops. Tested on macOS/Metal (Apple Silicon).
morr added a commit to morr/bevy that referenced this pull request Jul 30, 2026
…25163)

# Objective

Fixes bevyengine#25163.

`queue_material2d_meshes` is the only system that takes items out of the
retained 2D phases, and it returns early when `render_material_instances`
is empty. That is the frame the last entity using that material type gets
despawned, so its items never get removed and stay in the phase for good.

They also keep the `batch_range` they had when they were last batched,
since `batch_and_prepare_sorted_render_phase` only rewrites the range of
items that still have a `RenderMesh2dInstance`. `render_range` advances the
index by `batch_range.len()` after every draw, so an item left over from a
batch of three hides the two live items behind it. With equal sort keys the
order changes from frame to frame, which is why it shows up as flicker
instead of something permanently missing.

The early return is older than the dequeue loop (bevyengine#17567 added it back when
the system only queued, bevyengine#23083 added the removal). The 3D
`queue_material_meshes` doesn't have one.

## Solution

Move the check below the dequeue loop and make it a `continue`. There is
still nothing to queue when no entity uses the material, but removal now
always happens.

## Testing

Static scene, nothing moves: 7 permanent sprites at the same z as the
churn, 7 more permanent sprites sorting before it, and 3 blended `Mesh2d`
quads sharing a mesh and material that get despawned and respawned every 30
frames. From a `RenderSystems::Cleanup` system I walk the phase the way
`render_range` does and count the live items it steps over.

240 frames on 0.19.0: the phase ends up holding 26 items, 12 of which belong
to entities that no longer exist (3 more per respawn, and they are never
cleaned up), and 102 of those frames step over a live item, 157 in total.
Every one is a permanent sprite; never a quad from the churn, never a sprite
sorting ahead of it. One step usually costs a whole row on screen, because
the item skipped is the leader of a batch of 7 sprites.

Same run with this patch: 14 items in the phase, none of them dead, nothing
stepped over.
morr added a commit to morr/bevy that referenced this pull request Jul 30, 2026
…25163)

# Objective

Fixes bevyengine#25163.

`queue_material2d_meshes` is the only system that takes items out of the
retained 2D phases, and it returns early when
`render_material_instances`
is empty. That is the frame the last entity using that material type
gets
despawned, so its items never get removed and stay in the phase for
good.

They also keep the `batch_range` they had when they were last batched,
since `batch_and_prepare_sorted_render_phase` only rewrites the range of
items that still have a `RenderMesh2dInstance`. `render_range` advances
the
index by `batch_range.len()` after every draw, so an item left over from
a
batch of three hides the two live items behind it. With equal sort keys
the
order changes from frame to frame, which is why it shows up as flicker
instead of something permanently missing.

The early return is older than the dequeue loop (bevyengine#17567 added it back
when
the system only queued, bevyengine#23083 added the removal). The 3D
`queue_material_meshes` doesn't have one.

## Solution

Move the check below the dequeue loop and make it a `continue`. There is
still nothing to queue when no entity uses the material, but removal now
always happens.
mirsella pushed a commit to mirsella/bevy that referenced this pull request Aug 16, 2026
…25163) (bevyengine#25253)

# Objective

Fixes bevyengine#25163.

`queue_material2d_meshes` is the only system that takes items out of the
retained 2D phases, and it returns early when
`render_material_instances`
is empty. That is the frame the last entity using that material type
gets
despawned, so its items never get removed and stay in the phase for
good.

They also keep the `batch_range` they had when they were last batched,
since `batch_and_prepare_sorted_render_phase` only rewrites the range of
items that still have a `RenderMesh2dInstance`. `render_range` advances
the
index by `batch_range.len()` after every draw, so an item left over from
a
batch of three hides the two live items behind it. With equal sort keys
the
order changes from frame to frame, which is why it shows up as flicker
instead of something permanently missing.

The early return is older than the dequeue loop
(bevyengine#17567 added it back when
the system only queued, bevyengine#23083
added the removal). The 3D
`queue_material_meshes` doesn't have one.

## Solution

Move the check below the dequeue loop and make it a `continue`. There is
still nothing to queue when no entity uses the material, but removal now
always happens.

## Testing

In my own app after applying the patch tree shadows stopped flickering
<img width="1717" height="1224" alt="image"
src="https://github.com/user-attachments/assets/26022cbc-bc82-4894-9d43-5fffa311cedd"
/>
joelawm pushed a commit to joelawm/bevy that referenced this pull request Sep 8, 2026
…25163) (bevyengine#25253)

# Objective

Fixes bevyengine#25163.

`queue_material2d_meshes` is the only system that takes items out of the
retained 2D phases, and it returns early when
`render_material_instances`
is empty. That is the frame the last entity using that material type
gets
despawned, so its items never get removed and stay in the phase for
good.

They also keep the `batch_range` they had when they were last batched,
since `batch_and_prepare_sorted_render_phase` only rewrites the range of
items that still have a `RenderMesh2dInstance`. `render_range` advances
the
index by `batch_range.len()` after every draw, so an item left over from
a
batch of three hides the two live items behind it. With equal sort keys
the
order changes from frame to frame, which is why it shows up as flicker
instead of something permanently missing.

The early return is older than the dequeue loop
(bevyengine#17567 added it back when
the system only queued, bevyengine#23083
added the removal). The 3D
`queue_material_meshes` doesn't have one.

## Solution

Move the check below the dequeue loop and make it a `continue`. There is
still nothing to queue when no entity uses the material, but removal now
always happens.

## Testing

In my own app after applying the patch tree shadows stopped flickering
<img width="1717" height="1224" alt="image"
src="https://github.com/user-attachments/assets/26022cbc-bc82-4894-9d43-5fffa311cedd"
/>
pull Bot pushed a commit to VitalyAnkh/bevy that referenced this pull request Sep 28, 2026
…gine#25926)

bevyengine#17567 introduced a bug where we always queue alpha masked meshes in the
AlphaMask3d phase, even when they're intended to be rendered as
deferred.

This means we end up drawing the alpha masked mesh in the deferred
prepass, shading it, and then it gets redrawn again in the forward pass.

I fixed the system to skip queuing into the AlphaMask3d phase when it's
intended for deferred, mirroring what we do in the opaque phase in the
same file.

Tested in a branch of solari I'm working on that supports alpha masks.
Before the fix, it would render with solari, then re-render in the
forward pass and overwrite the pixels. With this PR, it looks correct,
as solari is the only one to render it.

(bug found and fixed by AI, with me checking that it makes sense)
mockersf pushed a commit that referenced this pull request Sep 28, 2026
#17567 introduced a bug where we always queue alpha masked meshes in the
AlphaMask3d phase, even when they're intended to be rendered as
deferred.

This means we end up drawing the alpha masked mesh in the deferred
prepass, shading it, and then it gets redrawn again in the forward pass.

I fixed the system to skip queuing into the AlphaMask3d phase when it's
intended for deferred, mirroring what we do in the opaque phase in the
same file.

Tested in a branch of solari I'm working on that supports alpha masks.
Before the fix, it would render with solari, then re-render in the
forward pass and overwrite the pixels. With this PR, it looks correct,
as solari is the only one to render it.

(bug found and fixed by AI, with me checking that it makes sense)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

A-Rendering Drawing game state to the screen C-Performance A change motivated by improving speed, memory usage or compile times D-Complex Quite challenging from either a design or technical perspective. Ask for help! M-Release-Note Work that should be called out in the blog due to impact S-Ready-For-Final-Review This PR has been approved by the community. It's ready for a maintainer to consider merging it

Projects

No open projects
Status: Done

Development

Successfully merging this pull request may close these issues.

5 participants