Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use EntityHashMap<Entity, T> for render world entity storage for better performance #9903

Merged
merged 15 commits into from
Sep 27, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion crates/bevy_asset/src/id.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::{Asset, AssetIndex, Handle, UntypedHandle};
use bevy_ecs::component::Component;
use bevy_reflect::{Reflect, Uuid};
use std::{
any::TypeId,
Expand All @@ -13,7 +14,7 @@ use std::{
/// For an identifier tied to the lifetime of an asset, see [`Handle`].
///
/// For an "untyped" / "generic-less" id, see [`UntypedAssetId`].
#[derive(Reflect)]
#[derive(Component, Reflect)]
Copy link
Contributor

@nicopap nicopap Sep 26, 2023

Choose a reason for hiding this comment

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

This shouldn't be a Component though. I'd prefer if it was newtyped

#[derive(Component)]
struct RenderAssetId<A: Asset>(AssetId<A>);

making this a component may be misleading for users, they might accidentally insert an AssetId when they mean to insert a Handle

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I had discussed this with Cart and we thought it should become a component. The only reason I needed to change it was because ExtractComponent is implemented for Handle<T> and is supposed to extract to a Handle<T> at the moment, and we rather thought it should extract to an AssetId<T>.

Copy link
Contributor

Choose a reason for hiding this comment

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

I still think it should be a newtype. I can see the the disadvantages but not the advantages (apart from expediency, I'd be glad to open a PR after this one is merged if that's the only problem). Maybe there is an advantage I'm missing. Could you link me to the conversation?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I can't as it was in DMs on Discord. On the batching PR, Cart mentioned that AssetId<T> should be used if a weak handle is desired, such as how I was using it there. It felt appropriate to also switch to AssetId<T> as part of this PR.

I am happy to wrap AssetId<T> in a newtype, but I don't understand why I would do it. I hear that you think a user might insert an AssetId<T> when they should have used a Handle<T> but I don't understand why wrapping it in a newtype would make much difference to that.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

You mentioned on Discord that it's easy for someone to see Handle and AssetId are both Components and think they can use either, whereas a newtype wrapper around AssetId gives a bit more friction. I decided to revert the change that made AssetId a Component and revert the change to the ExtractComponent impl for Handle. I think it's better taken in a separate PR. :) Thanks for noticing it!

pub enum AssetId<A: Asset> {
/// A small / efficient runtime identifier that can be used to efficiently look up an asset stored in [`Assets`]. This is
/// the "default" identifier used for assets. The alternative(s) (ex: [`AssetId::Uuid`]) will only be used if assets are
Expand Down
95 changes: 50 additions & 45 deletions crates/bevy_pbr/src/material.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::{
render, AlphaMode, DrawMesh, DrawPrepass, EnvironmentMapLight, MeshPipeline, MeshPipelineKey,
MeshTransforms, PrepassPipelinePlugin, PrepassPlugin, ScreenSpaceAmbientOcclusionSettings,
PrepassPipelinePlugin, PrepassPlugin, RenderMeshInstances, ScreenSpaceAmbientOcclusionSettings,
SetMeshBindGroup, SetMeshViewBindGroup, Shadow,
};
use bevy_app::{App, Plugin};
Expand All @@ -14,10 +14,7 @@ use bevy_core_pipeline::{
use bevy_derive::{Deref, DerefMut};
use bevy_ecs::{
prelude::*,
system::{
lifetimeless::{Read, SRes},
SystemParamItem,
},
system::{lifetimeless::SRes, SystemParamItem},
};
use bevy_render::{
mesh::{Mesh, MeshVertexBufferLayout},
Expand All @@ -37,7 +34,7 @@ use bevy_render::{
view::{ExtractedView, Msaa, ViewVisibility, VisibleEntities},
Extract, ExtractSchedule, Render, RenderApp, RenderSet,
};
use bevy_utils::{tracing::error, HashMap, HashSet};
use bevy_utils::{tracing::error, HashMap, HashSet, PassHashMap};
use std::hash::Hash;
use std::marker::PhantomData;

Expand Down Expand Up @@ -190,6 +187,7 @@ where
.add_render_command::<AlphaMask3d, DrawMaterial<M>>()
.init_resource::<ExtractedMaterials<M>>()
.init_resource::<RenderMaterials<M>>()
.init_resource::<RenderMaterialInstances<M>>()
.init_resource::<SpecializedMeshPipelines<MaterialPipeline<M>>>()
.add_systems(
ExtractSchedule,
Expand Down Expand Up @@ -226,26 +224,6 @@ where
}
}

fn extract_material_meshes<M: Material>(
mut commands: Commands,
mut previous_len: Local<usize>,
query: Extract<Query<(Entity, &ViewVisibility, &Handle<M>)>>,
) {
let mut values = Vec::with_capacity(*previous_len);
for (entity, view_visibility, material) in &query {
if view_visibility.get() {
// NOTE: MaterialBindGroupId is inserted here to avoid a table move. Upcoming changes
// to use SparseSet for render world entity storage will do this automatically.
values.push((
entity,
(material.clone_weak(), MaterialBindGroupId::default()),
));
}
}
*previous_len = values.len();
commands.insert_or_spawn_batch(values);
}

/// A key uniquely identifying a specialized [`MaterialPipeline`].
pub struct MaterialPipelineKey<M: Material> {
pub mesh_key: MeshPipelineKey,
Expand Down Expand Up @@ -368,24 +346,53 @@ type DrawMaterial<M> = (
/// Sets the bind group for a given [`Material`] at the configured `I` index.
pub struct SetMaterialBindGroup<M: Material, const I: usize>(PhantomData<M>);
impl<P: PhaseItem, M: Material, const I: usize> RenderCommand<P> for SetMaterialBindGroup<M, I> {
type Param = SRes<RenderMaterials<M>>;
type Param = (SRes<RenderMaterials<M>>, SRes<RenderMaterialInstances<M>>);
type ViewWorldQuery = ();
type ItemWorldQuery = Read<Handle<M>>;
type ItemWorldQuery = ();

#[inline]
fn render<'w>(
_item: &P,
item: &P,
_view: (),
material_handle: &'_ Handle<M>,
materials: SystemParamItem<'w, '_, Self::Param>,
_item_query: (),
(materials, material_instances): SystemParamItem<'w, '_, Self::Param>,
pass: &mut TrackedRenderPass<'w>,
) -> RenderCommandResult {
let material = materials.into_inner().get(&material_handle.id()).unwrap();
let materials = materials.into_inner();
let material_instances = material_instances.into_inner();

let Some(material_asset_id) = material_instances.get(&item.entity()) else {
return RenderCommandResult::Failure;
};
let Some(material) = materials.get(material_asset_id) else {
return RenderCommandResult::Failure;
};
pass.set_bind_group(I, &material.bind_group, &[]);
RenderCommandResult::Success
}
}

#[derive(Resource, Deref, DerefMut)]
pub struct RenderMaterialInstances<M: Material>(PassHashMap<Entity, AssetId<M>>);

impl<M: Material> Default for RenderMaterialInstances<M> {
fn default() -> Self {
Self(Default::default())
}
}

fn extract_material_meshes<M: Material>(
mut material_instances: ResMut<RenderMaterialInstances<M>>,
query: Extract<Query<(Entity, &ViewVisibility, &Handle<M>)>>,
) {
material_instances.clear();
for (entity, view_visibility, handle) in &query {
if view_visibility.get() {
material_instances.insert(entity, handle.id());
}
}
}

const fn alpha_mode_pipeline_key(alpha_mode: AlphaMode) -> MeshPipelineKey {
match alpha_mode {
// Premultiplied and Add share the same pipeline key
Expand Down Expand Up @@ -424,12 +431,8 @@ pub fn queue_material_meshes<M: Material>(
msaa: Res<Msaa>,
render_meshes: Res<RenderAssets<Mesh>>,
render_materials: Res<RenderMaterials<M>>,
mut material_meshes: Query<(
&Handle<M>,
&mut MaterialBindGroupId,
&Handle<Mesh>,
&MeshTransforms,
)>,
mut render_mesh_instances: ResMut<RenderMeshInstances>,
render_material_instances: Res<RenderMaterialInstances<M>>,
images: Res<RenderAssets<Image>>,
mut views: Query<(
&ExtractedView,
Expand Down Expand Up @@ -493,15 +496,16 @@ pub fn queue_material_meshes<M: Material>(
}
let rangefinder = view.rangefinder3d();
for visible_entity in &visible_entities.entities {
let Ok((material_handle, mut material_bind_group_id, mesh_handle, mesh_transforms)) =
material_meshes.get_mut(*visible_entity)
else {
let Some(material_asset_id) = render_material_instances.get(visible_entity) else {
continue;
};
let Some(mesh_instance) = render_mesh_instances.get_mut(visible_entity) else {
continue;
};
let Some(mesh) = render_meshes.get(mesh_handle) else {
let Some(mesh) = render_meshes.get(mesh_instance.mesh_asset_id) else {
continue;
};
let Some(material) = render_materials.get(&material_handle.id()) else {
let Some(material) = render_materials.get(material_asset_id) else {
continue;
};
let mut mesh_key = view_key;
Expand Down Expand Up @@ -530,9 +534,10 @@ pub fn queue_material_meshes<M: Material>(
}
};

*material_bind_group_id = material.get_bind_group_id();
mesh_instance.material_bind_group_id = material.get_bind_group_id();

let distance = rangefinder.distance_translation(&mesh_transforms.transform.translation)
let distance = rangefinder
.distance_translation(&mesh_instance.transforms.transform.translation)
+ material.properties.depth_bias;
match material.properties.alpha_mode {
AlphaMode::Opaque => {
Expand Down
25 changes: 14 additions & 11 deletions crates/bevy_pbr/src/prepass/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,8 @@ use bevy_utils::tracing::error;
use crate::{
prepare_materials, setup_morph_and_skinning_defs, AlphaMode, DrawMesh, Material,
MaterialPipeline, MaterialPipelineKey, MeshLayouts, MeshPipeline, MeshPipelineKey,
MeshTransforms, RenderMaterials, SetMaterialBindGroup, SetMeshBindGroup,
RenderMaterialInstances, RenderMaterials, RenderMeshInstances, SetMaterialBindGroup,
SetMeshBindGroup,
};

use std::{hash::Hash, marker::PhantomData};
Expand Down Expand Up @@ -755,8 +756,9 @@ pub fn queue_prepass_material_meshes<M: Material>(
pipeline_cache: Res<PipelineCache>,
msaa: Res<Msaa>,
render_meshes: Res<RenderAssets<Mesh>>,
render_mesh_instances: Res<RenderMeshInstances>,
render_materials: Res<RenderMaterials<M>>,
material_meshes: Query<(&Handle<M>, &Handle<Mesh>, &MeshTransforms)>,
render_material_instances: Res<RenderMaterialInstances<M>>,
mut views: Query<(
&ExtractedView,
&VisibleEntities,
Expand Down Expand Up @@ -801,16 +803,16 @@ pub fn queue_prepass_material_meshes<M: Material>(
let rangefinder = view.rangefinder3d();

for visible_entity in &visible_entities.entities {
let Ok((material_handle, mesh_handle, mesh_transforms)) =
material_meshes.get(*visible_entity)
else {
let Some(material_asset_id) = render_material_instances.get(visible_entity) else {
continue;
};

let (Some(material), Some(mesh)) = (
render_materials.get(&material_handle.id()),
render_meshes.get(mesh_handle),
) else {
let Some(mesh_instance) = render_mesh_instances.get(visible_entity) else {
continue;
};
let Some(material) = render_materials.get(material_asset_id) else {
continue;
};
let Some(mesh) = render_meshes.get(mesh_instance.mesh_asset_id) else {
continue;
};

Expand Down Expand Up @@ -846,7 +848,8 @@ pub fn queue_prepass_material_meshes<M: Material>(
}
};

let distance = rangefinder.distance_translation(&mesh_transforms.transform.translation)
let distance = rangefinder
.distance_translation(&mesh_instance.transforms.transform.translation)
+ material.properties.depth_bias;
match alpha_mode {
AlphaMode::Opaque => {
Expand Down
21 changes: 14 additions & 7 deletions crates/bevy_pbr/src/render/light.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,9 @@ use crate::{
CascadeShadowConfig, Cascades, CascadesVisibleEntities, Clusters, CubemapVisibleEntities,
DirectionalLight, DirectionalLightShadowMap, DrawPrepass, EnvironmentMapLight,
GlobalVisiblePointLights, Material, MaterialPipelineKey, MeshPipeline, MeshPipelineKey,
NotShadowCaster, PointLight, PointLightShadowMap, PrepassPipeline, RenderMaterials, SpotLight,
VisiblePointLights,
PointLight, PointLightShadowMap, PrepassPipeline, RenderMaterialInstances, RenderMaterials,
RenderMeshInstances, SpotLight, VisiblePointLights,
};
use bevy_asset::Handle;
use bevy_core_pipeline::core_3d::Transparent3d;
use bevy_ecs::prelude::*;
use bevy_math::{Mat4, UVec3, UVec4, Vec2, Vec3, Vec3Swizzles, Vec4, Vec4Swizzles};
Expand Down Expand Up @@ -1549,9 +1548,10 @@ pub fn prepare_clusters(
pub fn queue_shadows<M: Material>(
shadow_draw_functions: Res<DrawFunctions<Shadow>>,
prepass_pipeline: Res<PrepassPipeline<M>>,
casting_meshes: Query<(&Handle<Mesh>, &Handle<M>), Without<NotShadowCaster>>,
render_meshes: Res<RenderAssets<Mesh>>,
render_mesh_instances: Res<RenderMeshInstances>,
render_materials: Res<RenderMaterials<M>>,
render_material_instances: Res<RenderMaterialInstances<M>>,
mut pipelines: ResMut<SpecializedMeshPipelines<PrepassPipeline<M>>>,
pipeline_cache: Res<PipelineCache>,
view_lights: Query<(Entity, &ViewLightEntities)>,
Expand Down Expand Up @@ -1594,15 +1594,22 @@ pub fn queue_shadows<M: Material>(
// NOTE: Lights with shadow mapping disabled will have no visible entities
// so no meshes will be queued
for entity in visible_entities.iter().copied() {
let Ok((mesh_handle, material_handle)) = casting_meshes.get(entity) else {
let Some(mesh_instance) = render_mesh_instances.get(&entity) else {
continue;
};
let Some(mesh) = render_meshes.get(mesh_handle) else {
if !mesh_instance.shadow_caster {
continue;
}
let Some(material_asset_id) = render_material_instances.get(&entity) else {
continue;
};
let Some(material) = render_materials.get(&material_handle.id()) else {
let Some(material) = render_materials.get(material_asset_id) else {
continue;
};
let Some(mesh) = render_meshes.get(mesh_instance.mesh_asset_id) else {
continue;
};

let mut mesh_key =
MeshPipelineKey::from_primitive_topology(mesh.primitive_topology)
| MeshPipelineKey::DEPTH_PREPASS;
Expand Down
Loading