2023-10-13 17:06:53 +00:00
|
|
|
//! Convenience logic for turning components from the main world into extracted
|
2023-10-08 10:34:44 +00:00
|
|
|
//! instances in the render world.
|
|
|
|
//!
|
|
|
|
//! This is essentially the same as the `extract_component` module, but
|
|
|
|
//! higher-performance because it avoids the ECS overhead.
|
|
|
|
|
2024-09-27 00:59:59 +00:00
|
|
|
use core::marker::PhantomData;
|
2023-10-08 10:34:44 +00:00
|
|
|
|
|
|
|
use bevy_app::{App, Plugin};
|
|
|
|
use bevy_derive::{Deref, DerefMut};
|
|
|
|
use bevy_ecs::{
|
|
|
|
prelude::Entity,
|
Rename `WorldQueryData` & `WorldQueryFilter` to `QueryData` & `QueryFilter` (#10779)
# Rename `WorldQueryData` & `WorldQueryFilter` to `QueryData` &
`QueryFilter`
Fixes #10776
## Solution
Traits `WorldQueryData` & `WorldQueryFilter` were renamed to `QueryData`
and `QueryFilter`, respectively. Related Trait types were also renamed.
---
## Changelog
- Trait `WorldQueryData` has been renamed to `QueryData`. Derive macro's
`QueryData` attribute `world_query_data` has been renamed to
`query_data`.
- Trait `WorldQueryFilter` has been renamed to `QueryFilter`. Derive
macro's `QueryFilter` attribute `world_query_filter` has been renamed to
`query_filter`.
- Trait's `ExtractComponent` type `Query` has been renamed to `Data`.
- Trait's `GetBatchData` types `Query` & `QueryFilter` has been renamed
to `Data` & `Filter`, respectively.
- Trait's `ExtractInstance` type `Query` has been renamed to `Data`.
- Trait's `ViewNode` type `ViewQuery` has been renamed to `ViewData`.
- Trait's `RenderCommand` types `ViewWorldQuery` & `ItemWorldQuery` has
been renamed to `ViewData` & `ItemData`, respectively.
## Migration Guide
Note: if merged before 0.13 is released, this should instead modify the
migration guide of #10776 with the updated names.
- Rename `WorldQueryData` & `WorldQueryFilter` trait usages to
`QueryData` & `QueryFilter` and their respective derive macro attributes
`world_query_data` & `world_query_filter` to `query_data` &
`query_filter`.
- Rename the following trait type usages:
- Trait's `ExtractComponent` type `Query` to `Data`.
- Trait's `GetBatchData` type `Query` to `Data`.
- Trait's `ExtractInstance` type `Query` to `Data`.
- Trait's `ViewNode` type `ViewQuery` to `ViewData`'
- Trait's `RenderCommand` types `ViewWolrdQuery` & `ItemWorldQuery` to
`ViewData` & `ItemData`, respectively.
```rust
// Before
#[derive(WorldQueryData)]
#[world_query_data(derive(Debug))]
struct EmptyQuery {
empty: (),
}
// After
#[derive(QueryData)]
#[query_data(derive(Debug))]
struct EmptyQuery {
empty: (),
}
// Before
#[derive(WorldQueryFilter)]
struct CustomQueryFilter<T: Component, P: Component> {
_c: With<ComponentC>,
_d: With<ComponentD>,
_or: Or<(Added<ComponentC>, Changed<ComponentD>, Without<ComponentZ>)>,
_generic_tuple: (With<T>, With<P>),
}
// After
#[derive(QueryFilter)]
struct CustomQueryFilter<T: Component, P: Component> {
_c: With<ComponentC>,
_d: With<ComponentD>,
_or: Or<(Added<ComponentC>, Changed<ComponentD>, Without<ComponentZ>)>,
_generic_tuple: (With<T>, With<P>),
}
// Before
impl ExtractComponent for ContrastAdaptiveSharpeningSettings {
type Query = &'static Self;
type Filter = With<Camera>;
type Out = (DenoiseCAS, CASUniform);
fn extract_component(item: QueryItem<Self::Query>) -> Option<Self::Out> {
//...
}
}
// After
impl ExtractComponent for ContrastAdaptiveSharpeningSettings {
type Data = &'static Self;
type Filter = With<Camera>;
type Out = (DenoiseCAS, CASUniform);
fn extract_component(item: QueryItem<Self::Data>) -> Option<Self::Out> {
//...
}
}
// Before
impl GetBatchData for MeshPipeline {
type Param = SRes<RenderMeshInstances>;
type Query = Entity;
type QueryFilter = With<Mesh3d>;
type CompareData = (MaterialBindGroupId, AssetId<Mesh>);
type BufferData = MeshUniform;
fn get_batch_data(
mesh_instances: &SystemParamItem<Self::Param>,
entity: &QueryItem<Self::Query>,
) -> (Self::BufferData, Option<Self::CompareData>) {
// ....
}
}
// After
impl GetBatchData for MeshPipeline {
type Param = SRes<RenderMeshInstances>;
type Data = Entity;
type Filter = With<Mesh3d>;
type CompareData = (MaterialBindGroupId, AssetId<Mesh>);
type BufferData = MeshUniform;
fn get_batch_data(
mesh_instances: &SystemParamItem<Self::Param>,
entity: &QueryItem<Self::Data>,
) -> (Self::BufferData, Option<Self::CompareData>) {
// ....
}
}
// Before
impl<A> ExtractInstance for AssetId<A>
where
A: Asset,
{
type Query = Read<Handle<A>>;
type Filter = ();
fn extract(item: QueryItem<'_, Self::Query>) -> Option<Self> {
Some(item.id())
}
}
// After
impl<A> ExtractInstance for AssetId<A>
where
A: Asset,
{
type Data = Read<Handle<A>>;
type Filter = ();
fn extract(item: QueryItem<'_, Self::Data>) -> Option<Self> {
Some(item.id())
}
}
// Before
impl ViewNode for PostProcessNode {
type ViewQuery = (
&'static ViewTarget,
&'static PostProcessSettings,
);
fn run(
&self,
_graph: &mut RenderGraphContext,
render_context: &mut RenderContext,
(view_target, _post_process_settings): QueryItem<Self::ViewQuery>,
world: &World,
) -> Result<(), NodeRunError> {
// ...
}
}
// After
impl ViewNode for PostProcessNode {
type ViewData = (
&'static ViewTarget,
&'static PostProcessSettings,
);
fn run(
&self,
_graph: &mut RenderGraphContext,
render_context: &mut RenderContext,
(view_target, _post_process_settings): QueryItem<Self::ViewData>,
world: &World,
) -> Result<(), NodeRunError> {
// ...
}
}
// Before
impl<P: CachedRenderPipelinePhaseItem> RenderCommand<P> for SetItemPipeline {
type Param = SRes<PipelineCache>;
type ViewWorldQuery = ();
type ItemWorldQuery = ();
#[inline]
fn render<'w>(
item: &P,
_view: (),
_entity: (),
pipeline_cache: SystemParamItem<'w, '_, Self::Param>,
pass: &mut TrackedRenderPass<'w>,
) -> RenderCommandResult {
// ...
}
}
// After
impl<P: CachedRenderPipelinePhaseItem> RenderCommand<P> for SetItemPipeline {
type Param = SRes<PipelineCache>;
type ViewData = ();
type ItemData = ();
#[inline]
fn render<'w>(
item: &P,
_view: (),
_entity: (),
pipeline_cache: SystemParamItem<'w, '_, Self::Param>,
pass: &mut TrackedRenderPass<'w>,
) -> RenderCommandResult {
// ...
}
}
```
2023-12-12 19:45:50 +00:00
|
|
|
query::{QueryFilter, QueryItem, ReadOnlyQueryData},
|
2024-10-09 17:12:27 +00:00
|
|
|
system::{Query, ResMut, Resource},
|
2023-10-08 10:34:44 +00:00
|
|
|
};
|
|
|
|
|
Type safe retained render world (#15756)
# Objective
In the Render World, there are a number of collections that are derived
from Main World entities and are used to drive rendering. The most
notable are:
- `VisibleEntities`, which is generated in the `check_visibility` system
and contains visible entities for a view.
- `ExtractedInstances`, which maps entity ids to asset ids.
In the old model, these collections were trivially kept in sync -- any
extracted phase item could look itself up because the render entity id
was guaranteed to always match the corresponding main world id.
After #15320, this became much more complicated, and was leading to a
number of subtle bugs in the Render World. The main rendering systems,
i.e. `queue_material_meshes` and `queue_material2d_meshes`, follow a
similar pattern:
```rust
for visible_entity in visible_entities.iter::<With<Mesh2d>>() {
let Some(mesh_instance) = render_mesh_instances.get_mut(visible_entity) else {
continue;
};
// Look some more stuff up and specialize the pipeline...
let bin_key = Opaque2dBinKey {
pipeline: pipeline_id,
draw_function: draw_opaque_2d,
asset_id: mesh_instance.mesh_asset_id.into(),
material_bind_group_id: material_2d.get_bind_group_id().0,
};
opaque_phase.add(
bin_key,
*visible_entity,
BinnedRenderPhaseType::mesh(mesh_instance.automatic_batching),
);
}
```
In this case, `visible_entities` and `render_mesh_instances` are both
collections that are created and keyed by Main World entity ids, and so
this lookup happens to work by coincidence. However, there is a major
unintentional bug here: namely, because `visible_entities` is a
collection of Main World ids, the phase item being queued is created
with a Main World id rather than its correct Render World id.
This happens to not break mesh rendering because the render commands
used for drawing meshes do not access the `ItemQuery` parameter, but
demonstrates the confusion that is now possible: our UI phase items are
correctly being queued with Render World ids while our meshes aren't.
Additionally, this makes it very easy and error prone to use the wrong
entity id to look up things like assets. For example, if instead we
ignored visibility checks and queued our meshes via a query, we'd have
to be extra careful to use `&MainEntity` instead of the natural
`Entity`.
## Solution
Make all collections that are derived from Main World data use
`MainEntity` as their key, to ensure type safety and avoid accidentally
looking up data with the wrong entity id:
```rust
pub type MainEntityHashMap<V> = hashbrown::HashMap<MainEntity, V, EntityHash>;
```
Additionally, we make all `PhaseItem` be able to provide both their Main
and Render World ids, to allow render phase implementors maximum
flexibility as to what id should be used to look up data.
You can think of this like tracking at the type level whether something
in the Render World should use it's "primary key", i.e. entity id, or
needs to use a foreign key, i.e. `MainEntity`.
## Testing
##### TODO:
This will require extensive testing to make sure things didn't break!
Additionally, some extraction logic has become more complicated and
needs to be checked for regressions.
## Migration Guide
With the advent of the retained render world, collections that contain
references to `Entity` that are extracted into the render world have
been changed to contain `MainEntity` in order to prevent errors where a
render world entity id is used to look up an item by accident. Custom
rendering code may need to be changed to query for `&MainEntity` in
order to look up the correct item from such a collection. Additionally,
users who implement their own extraction logic for collections of main
world entity should strongly consider extracting into a different
collection that uses `MainEntity` as a key.
Additionally, render phases now require specifying both the `Entity` and
`MainEntity` for a given `PhaseItem`. Custom render phases should ensure
`MainEntity` is available when queuing a phase item.
2024-10-10 18:47:04 +00:00
|
|
|
use crate::sync_world::MainEntityHashMap;
|
2023-10-08 10:34:44 +00:00
|
|
|
use crate::{prelude::ViewVisibility, Extract, ExtractSchedule, RenderApp};
|
|
|
|
|
|
|
|
/// Describes how to extract data needed for rendering from a component or
|
|
|
|
/// components.
|
|
|
|
///
|
|
|
|
/// Before rendering, any applicable components will be transferred from the
|
|
|
|
/// main world to the render world in the [`ExtractSchedule`] step.
|
|
|
|
///
|
|
|
|
/// This is essentially the same as
|
|
|
|
/// [`ExtractComponent`](crate::extract_component::ExtractComponent), but
|
|
|
|
/// higher-performance because it avoids the ECS overhead.
|
2023-10-13 17:06:53 +00:00
|
|
|
pub trait ExtractInstance: Send + Sync + Sized + 'static {
|
Rename `WorldQueryData` & `WorldQueryFilter` to `QueryData` & `QueryFilter` (#10779)
# Rename `WorldQueryData` & `WorldQueryFilter` to `QueryData` &
`QueryFilter`
Fixes #10776
## Solution
Traits `WorldQueryData` & `WorldQueryFilter` were renamed to `QueryData`
and `QueryFilter`, respectively. Related Trait types were also renamed.
---
## Changelog
- Trait `WorldQueryData` has been renamed to `QueryData`. Derive macro's
`QueryData` attribute `world_query_data` has been renamed to
`query_data`.
- Trait `WorldQueryFilter` has been renamed to `QueryFilter`. Derive
macro's `QueryFilter` attribute `world_query_filter` has been renamed to
`query_filter`.
- Trait's `ExtractComponent` type `Query` has been renamed to `Data`.
- Trait's `GetBatchData` types `Query` & `QueryFilter` has been renamed
to `Data` & `Filter`, respectively.
- Trait's `ExtractInstance` type `Query` has been renamed to `Data`.
- Trait's `ViewNode` type `ViewQuery` has been renamed to `ViewData`.
- Trait's `RenderCommand` types `ViewWorldQuery` & `ItemWorldQuery` has
been renamed to `ViewData` & `ItemData`, respectively.
## Migration Guide
Note: if merged before 0.13 is released, this should instead modify the
migration guide of #10776 with the updated names.
- Rename `WorldQueryData` & `WorldQueryFilter` trait usages to
`QueryData` & `QueryFilter` and their respective derive macro attributes
`world_query_data` & `world_query_filter` to `query_data` &
`query_filter`.
- Rename the following trait type usages:
- Trait's `ExtractComponent` type `Query` to `Data`.
- Trait's `GetBatchData` type `Query` to `Data`.
- Trait's `ExtractInstance` type `Query` to `Data`.
- Trait's `ViewNode` type `ViewQuery` to `ViewData`'
- Trait's `RenderCommand` types `ViewWolrdQuery` & `ItemWorldQuery` to
`ViewData` & `ItemData`, respectively.
```rust
// Before
#[derive(WorldQueryData)]
#[world_query_data(derive(Debug))]
struct EmptyQuery {
empty: (),
}
// After
#[derive(QueryData)]
#[query_data(derive(Debug))]
struct EmptyQuery {
empty: (),
}
// Before
#[derive(WorldQueryFilter)]
struct CustomQueryFilter<T: Component, P: Component> {
_c: With<ComponentC>,
_d: With<ComponentD>,
_or: Or<(Added<ComponentC>, Changed<ComponentD>, Without<ComponentZ>)>,
_generic_tuple: (With<T>, With<P>),
}
// After
#[derive(QueryFilter)]
struct CustomQueryFilter<T: Component, P: Component> {
_c: With<ComponentC>,
_d: With<ComponentD>,
_or: Or<(Added<ComponentC>, Changed<ComponentD>, Without<ComponentZ>)>,
_generic_tuple: (With<T>, With<P>),
}
// Before
impl ExtractComponent for ContrastAdaptiveSharpeningSettings {
type Query = &'static Self;
type Filter = With<Camera>;
type Out = (DenoiseCAS, CASUniform);
fn extract_component(item: QueryItem<Self::Query>) -> Option<Self::Out> {
//...
}
}
// After
impl ExtractComponent for ContrastAdaptiveSharpeningSettings {
type Data = &'static Self;
type Filter = With<Camera>;
type Out = (DenoiseCAS, CASUniform);
fn extract_component(item: QueryItem<Self::Data>) -> Option<Self::Out> {
//...
}
}
// Before
impl GetBatchData for MeshPipeline {
type Param = SRes<RenderMeshInstances>;
type Query = Entity;
type QueryFilter = With<Mesh3d>;
type CompareData = (MaterialBindGroupId, AssetId<Mesh>);
type BufferData = MeshUniform;
fn get_batch_data(
mesh_instances: &SystemParamItem<Self::Param>,
entity: &QueryItem<Self::Query>,
) -> (Self::BufferData, Option<Self::CompareData>) {
// ....
}
}
// After
impl GetBatchData for MeshPipeline {
type Param = SRes<RenderMeshInstances>;
type Data = Entity;
type Filter = With<Mesh3d>;
type CompareData = (MaterialBindGroupId, AssetId<Mesh>);
type BufferData = MeshUniform;
fn get_batch_data(
mesh_instances: &SystemParamItem<Self::Param>,
entity: &QueryItem<Self::Data>,
) -> (Self::BufferData, Option<Self::CompareData>) {
// ....
}
}
// Before
impl<A> ExtractInstance for AssetId<A>
where
A: Asset,
{
type Query = Read<Handle<A>>;
type Filter = ();
fn extract(item: QueryItem<'_, Self::Query>) -> Option<Self> {
Some(item.id())
}
}
// After
impl<A> ExtractInstance for AssetId<A>
where
A: Asset,
{
type Data = Read<Handle<A>>;
type Filter = ();
fn extract(item: QueryItem<'_, Self::Data>) -> Option<Self> {
Some(item.id())
}
}
// Before
impl ViewNode for PostProcessNode {
type ViewQuery = (
&'static ViewTarget,
&'static PostProcessSettings,
);
fn run(
&self,
_graph: &mut RenderGraphContext,
render_context: &mut RenderContext,
(view_target, _post_process_settings): QueryItem<Self::ViewQuery>,
world: &World,
) -> Result<(), NodeRunError> {
// ...
}
}
// After
impl ViewNode for PostProcessNode {
type ViewData = (
&'static ViewTarget,
&'static PostProcessSettings,
);
fn run(
&self,
_graph: &mut RenderGraphContext,
render_context: &mut RenderContext,
(view_target, _post_process_settings): QueryItem<Self::ViewData>,
world: &World,
) -> Result<(), NodeRunError> {
// ...
}
}
// Before
impl<P: CachedRenderPipelinePhaseItem> RenderCommand<P> for SetItemPipeline {
type Param = SRes<PipelineCache>;
type ViewWorldQuery = ();
type ItemWorldQuery = ();
#[inline]
fn render<'w>(
item: &P,
_view: (),
_entity: (),
pipeline_cache: SystemParamItem<'w, '_, Self::Param>,
pass: &mut TrackedRenderPass<'w>,
) -> RenderCommandResult {
// ...
}
}
// After
impl<P: CachedRenderPipelinePhaseItem> RenderCommand<P> for SetItemPipeline {
type Param = SRes<PipelineCache>;
type ViewData = ();
type ItemData = ();
#[inline]
fn render<'w>(
item: &P,
_view: (),
_entity: (),
pipeline_cache: SystemParamItem<'w, '_, Self::Param>,
pass: &mut TrackedRenderPass<'w>,
) -> RenderCommandResult {
// ...
}
}
```
2023-12-12 19:45:50 +00:00
|
|
|
/// ECS [`ReadOnlyQueryData`] to fetch the components to extract.
|
2024-01-22 15:01:55 +00:00
|
|
|
type QueryData: ReadOnlyQueryData;
|
2023-10-08 10:34:44 +00:00
|
|
|
/// Filters the entities with additional constraints.
|
2024-01-22 15:01:55 +00:00
|
|
|
type QueryFilter: QueryFilter;
|
2023-10-08 10:34:44 +00:00
|
|
|
|
|
|
|
/// Defines how the component is transferred into the "render world".
|
2024-01-22 15:01:55 +00:00
|
|
|
fn extract(item: QueryItem<'_, Self::QueryData>) -> Option<Self>;
|
2023-10-08 10:34:44 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// This plugin extracts one or more components into the "render world" as
|
2023-10-13 17:06:53 +00:00
|
|
|
/// extracted instances.
|
2023-10-08 10:34:44 +00:00
|
|
|
///
|
|
|
|
/// Therefore it sets up the [`ExtractSchedule`] step for the specified
|
2023-10-13 17:06:53 +00:00
|
|
|
/// [`ExtractedInstances`].
|
2023-10-08 10:34:44 +00:00
|
|
|
#[derive(Default)]
|
2023-10-13 17:06:53 +00:00
|
|
|
pub struct ExtractInstancesPlugin<EI>
|
2023-10-08 10:34:44 +00:00
|
|
|
where
|
2023-10-13 17:06:53 +00:00
|
|
|
EI: ExtractInstance,
|
2023-10-08 10:34:44 +00:00
|
|
|
{
|
|
|
|
only_extract_visible: bool,
|
2023-10-13 17:06:53 +00:00
|
|
|
marker: PhantomData<fn() -> EI>,
|
2023-10-08 10:34:44 +00:00
|
|
|
}
|
|
|
|
|
2023-10-13 17:06:53 +00:00
|
|
|
/// Stores all extract instances of a type in the render world.
|
2023-10-08 10:34:44 +00:00
|
|
|
#[derive(Resource, Deref, DerefMut)]
|
Type safe retained render world (#15756)
# Objective
In the Render World, there are a number of collections that are derived
from Main World entities and are used to drive rendering. The most
notable are:
- `VisibleEntities`, which is generated in the `check_visibility` system
and contains visible entities for a view.
- `ExtractedInstances`, which maps entity ids to asset ids.
In the old model, these collections were trivially kept in sync -- any
extracted phase item could look itself up because the render entity id
was guaranteed to always match the corresponding main world id.
After #15320, this became much more complicated, and was leading to a
number of subtle bugs in the Render World. The main rendering systems,
i.e. `queue_material_meshes` and `queue_material2d_meshes`, follow a
similar pattern:
```rust
for visible_entity in visible_entities.iter::<With<Mesh2d>>() {
let Some(mesh_instance) = render_mesh_instances.get_mut(visible_entity) else {
continue;
};
// Look some more stuff up and specialize the pipeline...
let bin_key = Opaque2dBinKey {
pipeline: pipeline_id,
draw_function: draw_opaque_2d,
asset_id: mesh_instance.mesh_asset_id.into(),
material_bind_group_id: material_2d.get_bind_group_id().0,
};
opaque_phase.add(
bin_key,
*visible_entity,
BinnedRenderPhaseType::mesh(mesh_instance.automatic_batching),
);
}
```
In this case, `visible_entities` and `render_mesh_instances` are both
collections that are created and keyed by Main World entity ids, and so
this lookup happens to work by coincidence. However, there is a major
unintentional bug here: namely, because `visible_entities` is a
collection of Main World ids, the phase item being queued is created
with a Main World id rather than its correct Render World id.
This happens to not break mesh rendering because the render commands
used for drawing meshes do not access the `ItemQuery` parameter, but
demonstrates the confusion that is now possible: our UI phase items are
correctly being queued with Render World ids while our meshes aren't.
Additionally, this makes it very easy and error prone to use the wrong
entity id to look up things like assets. For example, if instead we
ignored visibility checks and queued our meshes via a query, we'd have
to be extra careful to use `&MainEntity` instead of the natural
`Entity`.
## Solution
Make all collections that are derived from Main World data use
`MainEntity` as their key, to ensure type safety and avoid accidentally
looking up data with the wrong entity id:
```rust
pub type MainEntityHashMap<V> = hashbrown::HashMap<MainEntity, V, EntityHash>;
```
Additionally, we make all `PhaseItem` be able to provide both their Main
and Render World ids, to allow render phase implementors maximum
flexibility as to what id should be used to look up data.
You can think of this like tracking at the type level whether something
in the Render World should use it's "primary key", i.e. entity id, or
needs to use a foreign key, i.e. `MainEntity`.
## Testing
##### TODO:
This will require extensive testing to make sure things didn't break!
Additionally, some extraction logic has become more complicated and
needs to be checked for regressions.
## Migration Guide
With the advent of the retained render world, collections that contain
references to `Entity` that are extracted into the render world have
been changed to contain `MainEntity` in order to prevent errors where a
render world entity id is used to look up an item by accident. Custom
rendering code may need to be changed to query for `&MainEntity` in
order to look up the correct item from such a collection. Additionally,
users who implement their own extraction logic for collections of main
world entity should strongly consider extracting into a different
collection that uses `MainEntity` as a key.
Additionally, render phases now require specifying both the `Entity` and
`MainEntity` for a given `PhaseItem`. Custom render phases should ensure
`MainEntity` is available when queuing a phase item.
2024-10-10 18:47:04 +00:00
|
|
|
pub struct ExtractedInstances<EI>(MainEntityHashMap<EI>)
|
2023-10-08 10:34:44 +00:00
|
|
|
where
|
2023-10-13 17:06:53 +00:00
|
|
|
EI: ExtractInstance;
|
2023-10-08 10:34:44 +00:00
|
|
|
|
2023-10-13 17:06:53 +00:00
|
|
|
impl<EI> Default for ExtractedInstances<EI>
|
2023-10-08 10:34:44 +00:00
|
|
|
where
|
2023-10-13 17:06:53 +00:00
|
|
|
EI: ExtractInstance,
|
2023-10-08 10:34:44 +00:00
|
|
|
{
|
|
|
|
fn default() -> Self {
|
|
|
|
Self(Default::default())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-10-13 17:06:53 +00:00
|
|
|
impl<EI> ExtractInstancesPlugin<EI>
|
2023-10-08 10:34:44 +00:00
|
|
|
where
|
2023-10-13 17:06:53 +00:00
|
|
|
EI: ExtractInstance,
|
2023-10-08 10:34:44 +00:00
|
|
|
{
|
2023-10-13 17:06:53 +00:00
|
|
|
/// Creates a new [`ExtractInstancesPlugin`] that unconditionally extracts to
|
2023-10-08 10:34:44 +00:00
|
|
|
/// the render world, whether the entity is visible or not.
|
|
|
|
pub fn new() -> Self {
|
|
|
|
Self {
|
|
|
|
only_extract_visible: false,
|
|
|
|
marker: PhantomData,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-10-13 17:06:53 +00:00
|
|
|
/// Creates a new [`ExtractInstancesPlugin`] that extracts to the render world
|
2023-10-08 10:34:44 +00:00
|
|
|
/// if and only if the entity it's attached to is visible.
|
|
|
|
pub fn extract_visible() -> Self {
|
|
|
|
Self {
|
|
|
|
only_extract_visible: true,
|
|
|
|
marker: PhantomData,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-10-13 17:06:53 +00:00
|
|
|
impl<EI> Plugin for ExtractInstancesPlugin<EI>
|
2023-10-08 10:34:44 +00:00
|
|
|
where
|
2023-10-13 17:06:53 +00:00
|
|
|
EI: ExtractInstance,
|
2023-10-08 10:34:44 +00:00
|
|
|
{
|
|
|
|
fn build(&self, app: &mut App) {
|
2024-03-31 03:16:10 +00:00
|
|
|
if let Some(render_app) = app.get_sub_app_mut(RenderApp) {
|
2023-10-13 17:06:53 +00:00
|
|
|
render_app.init_resource::<ExtractedInstances<EI>>();
|
2023-10-08 10:34:44 +00:00
|
|
|
if self.only_extract_visible {
|
2023-10-13 17:06:53 +00:00
|
|
|
render_app.add_systems(ExtractSchedule, extract_visible::<EI>);
|
2023-10-08 10:34:44 +00:00
|
|
|
} else {
|
2023-10-13 17:06:53 +00:00
|
|
|
render_app.add_systems(ExtractSchedule, extract_all::<EI>);
|
2023-10-08 10:34:44 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-10-13 17:06:53 +00:00
|
|
|
fn extract_all<EI>(
|
|
|
|
mut extracted_instances: ResMut<ExtractedInstances<EI>>,
|
2024-01-22 15:01:55 +00:00
|
|
|
query: Extract<Query<(Entity, EI::QueryData), EI::QueryFilter>>,
|
2023-10-08 10:34:44 +00:00
|
|
|
) where
|
2023-10-13 17:06:53 +00:00
|
|
|
EI: ExtractInstance,
|
2023-10-08 10:34:44 +00:00
|
|
|
{
|
2023-10-13 17:06:53 +00:00
|
|
|
extracted_instances.clear();
|
2023-10-08 10:34:44 +00:00
|
|
|
for (entity, other) in &query {
|
2023-10-13 17:06:53 +00:00
|
|
|
if let Some(extract_instance) = EI::extract(other) {
|
Type safe retained render world (#15756)
# Objective
In the Render World, there are a number of collections that are derived
from Main World entities and are used to drive rendering. The most
notable are:
- `VisibleEntities`, which is generated in the `check_visibility` system
and contains visible entities for a view.
- `ExtractedInstances`, which maps entity ids to asset ids.
In the old model, these collections were trivially kept in sync -- any
extracted phase item could look itself up because the render entity id
was guaranteed to always match the corresponding main world id.
After #15320, this became much more complicated, and was leading to a
number of subtle bugs in the Render World. The main rendering systems,
i.e. `queue_material_meshes` and `queue_material2d_meshes`, follow a
similar pattern:
```rust
for visible_entity in visible_entities.iter::<With<Mesh2d>>() {
let Some(mesh_instance) = render_mesh_instances.get_mut(visible_entity) else {
continue;
};
// Look some more stuff up and specialize the pipeline...
let bin_key = Opaque2dBinKey {
pipeline: pipeline_id,
draw_function: draw_opaque_2d,
asset_id: mesh_instance.mesh_asset_id.into(),
material_bind_group_id: material_2d.get_bind_group_id().0,
};
opaque_phase.add(
bin_key,
*visible_entity,
BinnedRenderPhaseType::mesh(mesh_instance.automatic_batching),
);
}
```
In this case, `visible_entities` and `render_mesh_instances` are both
collections that are created and keyed by Main World entity ids, and so
this lookup happens to work by coincidence. However, there is a major
unintentional bug here: namely, because `visible_entities` is a
collection of Main World ids, the phase item being queued is created
with a Main World id rather than its correct Render World id.
This happens to not break mesh rendering because the render commands
used for drawing meshes do not access the `ItemQuery` parameter, but
demonstrates the confusion that is now possible: our UI phase items are
correctly being queued with Render World ids while our meshes aren't.
Additionally, this makes it very easy and error prone to use the wrong
entity id to look up things like assets. For example, if instead we
ignored visibility checks and queued our meshes via a query, we'd have
to be extra careful to use `&MainEntity` instead of the natural
`Entity`.
## Solution
Make all collections that are derived from Main World data use
`MainEntity` as their key, to ensure type safety and avoid accidentally
looking up data with the wrong entity id:
```rust
pub type MainEntityHashMap<V> = hashbrown::HashMap<MainEntity, V, EntityHash>;
```
Additionally, we make all `PhaseItem` be able to provide both their Main
and Render World ids, to allow render phase implementors maximum
flexibility as to what id should be used to look up data.
You can think of this like tracking at the type level whether something
in the Render World should use it's "primary key", i.e. entity id, or
needs to use a foreign key, i.e. `MainEntity`.
## Testing
##### TODO:
This will require extensive testing to make sure things didn't break!
Additionally, some extraction logic has become more complicated and
needs to be checked for regressions.
## Migration Guide
With the advent of the retained render world, collections that contain
references to `Entity` that are extracted into the render world have
been changed to contain `MainEntity` in order to prevent errors where a
render world entity id is used to look up an item by accident. Custom
rendering code may need to be changed to query for `&MainEntity` in
order to look up the correct item from such a collection. Additionally,
users who implement their own extraction logic for collections of main
world entity should strongly consider extracting into a different
collection that uses `MainEntity` as a key.
Additionally, render phases now require specifying both the `Entity` and
`MainEntity` for a given `PhaseItem`. Custom render phases should ensure
`MainEntity` is available when queuing a phase item.
2024-10-10 18:47:04 +00:00
|
|
|
extracted_instances.insert(entity.into(), extract_instance);
|
2023-10-08 10:34:44 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-10-13 17:06:53 +00:00
|
|
|
fn extract_visible<EI>(
|
|
|
|
mut extracted_instances: ResMut<ExtractedInstances<EI>>,
|
2024-01-22 15:01:55 +00:00
|
|
|
query: Extract<Query<(Entity, &ViewVisibility, EI::QueryData), EI::QueryFilter>>,
|
2023-10-08 10:34:44 +00:00
|
|
|
) where
|
2023-10-13 17:06:53 +00:00
|
|
|
EI: ExtractInstance,
|
2023-10-08 10:34:44 +00:00
|
|
|
{
|
2023-10-13 17:06:53 +00:00
|
|
|
extracted_instances.clear();
|
2023-10-08 10:34:44 +00:00
|
|
|
for (entity, view_visibility, other) in &query {
|
|
|
|
if view_visibility.get() {
|
2023-10-13 17:06:53 +00:00
|
|
|
if let Some(extract_instance) = EI::extract(other) {
|
Type safe retained render world (#15756)
# Objective
In the Render World, there are a number of collections that are derived
from Main World entities and are used to drive rendering. The most
notable are:
- `VisibleEntities`, which is generated in the `check_visibility` system
and contains visible entities for a view.
- `ExtractedInstances`, which maps entity ids to asset ids.
In the old model, these collections were trivially kept in sync -- any
extracted phase item could look itself up because the render entity id
was guaranteed to always match the corresponding main world id.
After #15320, this became much more complicated, and was leading to a
number of subtle bugs in the Render World. The main rendering systems,
i.e. `queue_material_meshes` and `queue_material2d_meshes`, follow a
similar pattern:
```rust
for visible_entity in visible_entities.iter::<With<Mesh2d>>() {
let Some(mesh_instance) = render_mesh_instances.get_mut(visible_entity) else {
continue;
};
// Look some more stuff up and specialize the pipeline...
let bin_key = Opaque2dBinKey {
pipeline: pipeline_id,
draw_function: draw_opaque_2d,
asset_id: mesh_instance.mesh_asset_id.into(),
material_bind_group_id: material_2d.get_bind_group_id().0,
};
opaque_phase.add(
bin_key,
*visible_entity,
BinnedRenderPhaseType::mesh(mesh_instance.automatic_batching),
);
}
```
In this case, `visible_entities` and `render_mesh_instances` are both
collections that are created and keyed by Main World entity ids, and so
this lookup happens to work by coincidence. However, there is a major
unintentional bug here: namely, because `visible_entities` is a
collection of Main World ids, the phase item being queued is created
with a Main World id rather than its correct Render World id.
This happens to not break mesh rendering because the render commands
used for drawing meshes do not access the `ItemQuery` parameter, but
demonstrates the confusion that is now possible: our UI phase items are
correctly being queued with Render World ids while our meshes aren't.
Additionally, this makes it very easy and error prone to use the wrong
entity id to look up things like assets. For example, if instead we
ignored visibility checks and queued our meshes via a query, we'd have
to be extra careful to use `&MainEntity` instead of the natural
`Entity`.
## Solution
Make all collections that are derived from Main World data use
`MainEntity` as their key, to ensure type safety and avoid accidentally
looking up data with the wrong entity id:
```rust
pub type MainEntityHashMap<V> = hashbrown::HashMap<MainEntity, V, EntityHash>;
```
Additionally, we make all `PhaseItem` be able to provide both their Main
and Render World ids, to allow render phase implementors maximum
flexibility as to what id should be used to look up data.
You can think of this like tracking at the type level whether something
in the Render World should use it's "primary key", i.e. entity id, or
needs to use a foreign key, i.e. `MainEntity`.
## Testing
##### TODO:
This will require extensive testing to make sure things didn't break!
Additionally, some extraction logic has become more complicated and
needs to be checked for regressions.
## Migration Guide
With the advent of the retained render world, collections that contain
references to `Entity` that are extracted into the render world have
been changed to contain `MainEntity` in order to prevent errors where a
render world entity id is used to look up an item by accident. Custom
rendering code may need to be changed to query for `&MainEntity` in
order to look up the correct item from such a collection. Additionally,
users who implement their own extraction logic for collections of main
world entity should strongly consider extracting into a different
collection that uses `MainEntity` as a key.
Additionally, render phases now require specifying both the `Entity` and
`MainEntity` for a given `PhaseItem`. Custom render phases should ensure
`MainEntity` is available when queuing a phase item.
2024-10-10 18:47:04 +00:00
|
|
|
extracted_instances.insert(entity.into(), extract_instance);
|
2023-10-08 10:34:44 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|