bevy/pipelined/bevy_render2/src/render_component.rs

163 lines
4.3 KiB
Rust
Raw Normal View History

Modular Rendering (#2831) This changes how render logic is composed to make it much more modular. Previously, all extraction logic was centralized for a given "type" of rendered thing. For example, we extracted meshes into a vector of ExtractedMesh, which contained the mesh and material asset handles, the transform, etc. We looked up bindings for "drawn things" using their index in the `Vec<ExtractedMesh>`. This worked fine for built in rendering, but made it hard to reuse logic for "custom" rendering. It also prevented us from reusing things like "extracted transforms" across contexts. To make rendering more modular, I made a number of changes: * Entities now drive rendering: * We extract "render components" from "app components" and store them _on_ entities. No more centralized uber lists! We now have true "ECS-driven rendering" * To make this perform well, I implemented #2673 in upstream Bevy for fast batch insertions into specific entities. This was merged into the `pipelined-rendering` branch here: #2815 * Reworked the `Draw` abstraction: * Generic `PhaseItems`: each draw phase can define its own type of "rendered thing", which can define its own "sort key" * Ported the 2d, 3d, and shadow phases to the new PhaseItem impl (currently Transparent2d, Transparent3d, and Shadow PhaseItems) * `Draw` trait and and `DrawFunctions` are now generic on PhaseItem * Modular / Ergonomic `DrawFunctions` via `RenderCommands` * RenderCommand is a trait that runs an ECS query and produces one or more RenderPass calls. Types implementing this trait can be composed to create a final DrawFunction. For example the DrawPbr DrawFunction is created from the following DrawCommand tuple. Const generics are used to set specific bind group locations: ```rust pub type DrawPbr = ( SetPbrPipeline, SetMeshViewBindGroup<0>, SetStandardMaterialBindGroup<1>, SetTransformBindGroup<2>, DrawMesh, ); ``` * The new `custom_shader_pipelined` example illustrates how the commands above can be reused to create a custom draw function: ```rust type DrawCustom = ( SetCustomMaterialPipeline, SetMeshViewBindGroup<0>, SetTransformBindGroup<2>, DrawMesh, ); ``` * ExtractComponentPlugin and UniformComponentPlugin: * Simple, standardized ways to easily extract individual components and write them to GPU buffers * Ported PBR and Sprite rendering to the new primitives above. * Removed staging buffer from UniformVec in favor of direct Queue usage * Makes UniformVec much easier to use and more ergonomic. Completely removes the need for custom render graph nodes in these contexts (see the PbrNode and view Node removals and the much simpler call patterns in the relevant Prepare systems). * Added a many_cubes_pipelined example to benchmark baseline 3d rendering performance and ensure there were no major regressions during this port. Avoiding regressions was challenging given that the old approach of extracting into centralized vectors is basically the "optimal" approach. However thanks to a various ECS optimizations and render logic rephrasing, we pretty much break even on this benchmark! * Lifetimeless SystemParams: this will be a bit divisive, but as we continue to embrace "trait driven systems" (ex: ExtractComponentPlugin, UniformComponentPlugin, DrawCommand), the ergonomics of `(Query<'static, 'static, (&'static A, &'static B, &'static)>, Res<'static, C>)` were getting very hard to bear. As a compromise, I added "static type aliases" for the relevant SystemParams. The previous example can now be expressed like this: `(SQuery<(Read<A>, Read<B>)>, SRes<C>)`. If anyone has better ideas / conflicting opinions, please let me know! * RunSystem trait: a way to define Systems via a trait with a SystemParam associated type. This is used to implement the various plugins mentioned above. I also added SystemParamItem and QueryItem type aliases to make "trait stye" ecs interactions nicer on the eyes (and fingers). * RenderAsset retrying: ensures that render assets are only created when they are "ready" and allows us to create bind groups directly inside render assets (which significantly simplified the StandardMaterial code). I think ultimately we should swap this out on "asset dependency" events to wait for dependencies to load, but this will require significant asset system changes. * Updated some built in shaders to account for missing MeshUniform fields
2021-09-23 06:16:11 +00:00
use crate::{
render_resource::DynamicUniformVec,
renderer::{RenderDevice, RenderQueue},
RenderApp, RenderStage,
};
use bevy_app::{App, Plugin};
use bevy_asset::{Asset, Handle};
use bevy_ecs::{
component::Component,
prelude::*,
query::{FilterFetch, QueryItem, ReadOnlyFetch, WorldQuery},
system::{
lifetimeless::{Read, SCommands, SQuery},
RunSystem, SystemParamItem,
},
};
use crevice::std140::AsStd140;
use std::{marker::PhantomData, ops::Deref};
pub struct DynamicUniformIndex<C: Component> {
index: u32,
marker: PhantomData<C>,
}
impl<C: Component> DynamicUniformIndex<C> {
#[inline]
pub fn index(&self) -> u32 {
self.index
}
}
pub trait ExtractComponent: Component {
type Query: WorldQuery;
type Filter: WorldQuery;
fn extract_component(item: QueryItem<Self::Query>) -> Self;
}
/// Extracts assets into gpu-usable data
pub struct UniformComponentPlugin<C>(PhantomData<fn() -> C>);
impl<C> Default for UniformComponentPlugin<C> {
fn default() -> Self {
Self(PhantomData)
}
}
impl<C: Component + AsStd140 + Clone> Plugin for UniformComponentPlugin<C> {
fn build(&self, app: &mut App) {
app.sub_app(RenderApp)
.insert_resource(ComponentUniforms::<C>::default())
.add_system_to_stage(
RenderStage::Prepare,
prepare_uniform_components::<C>.system(),
);
}
}
pub struct ComponentUniforms<C: Component + AsStd140> {
uniforms: DynamicUniformVec<C>,
}
impl<C: Component + AsStd140> Deref for ComponentUniforms<C> {
type Target = DynamicUniformVec<C>;
#[inline]
fn deref(&self) -> &Self::Target {
&self.uniforms
}
}
impl<C: Component + AsStd140> ComponentUniforms<C> {
#[inline]
pub fn uniforms(&self) -> &DynamicUniformVec<C> {
&self.uniforms
}
}
impl<C: Component + AsStd140> Default for ComponentUniforms<C> {
fn default() -> Self {
Self {
uniforms: Default::default(),
}
}
}
fn prepare_uniform_components<C: Component>(
mut commands: Commands,
render_device: Res<RenderDevice>,
render_queue: Res<RenderQueue>,
mut component_uniforms: ResMut<ComponentUniforms<C>>,
components: Query<(Entity, &C)>,
) where
C: AsStd140 + Clone,
{
let len = components.iter().len();
component_uniforms
.uniforms
.reserve_and_clear(len, &render_device);
for (entity, component) in components.iter() {
commands
.get_or_spawn(entity)
.insert(DynamicUniformIndex::<C> {
index: component_uniforms.uniforms.push(component.clone()),
marker: PhantomData,
});
}
component_uniforms.uniforms.write_buffer(&render_queue);
}
pub struct ExtractComponentPlugin<C, F = ()>(PhantomData<fn() -> (C, F)>);
impl<C, F> Default for ExtractComponentPlugin<C, F> {
fn default() -> Self {
Self(PhantomData)
}
}
impl<C: ExtractComponent> Plugin for ExtractComponentPlugin<C>
where
<C::Query as WorldQuery>::Fetch: ReadOnlyFetch,
<C::Filter as WorldQuery>::Fetch: FilterFetch,
{
fn build(&self, app: &mut App) {
let system = ExtractComponentSystem::<C>::system(&mut app.world);
let render_app = app.sub_app(RenderApp);
render_app.add_system_to_stage(RenderStage::Extract, system);
}
}
impl<T: Asset> ExtractComponent for Handle<T> {
type Query = Read<Handle<T>>;
type Filter = ();
#[inline]
fn extract_component(handle: QueryItem<Self::Query>) -> Self {
handle.clone_weak()
}
}
pub struct ExtractComponentSystem<C: ExtractComponent>(PhantomData<C>);
impl<C: ExtractComponent> RunSystem for ExtractComponentSystem<C>
where
<C::Filter as WorldQuery>::Fetch: FilterFetch,
<C::Query as WorldQuery>::Fetch: ReadOnlyFetch,
{
type Param = (
SCommands,
Local<'static, usize>,
SQuery<(Entity, C::Query), C::Filter>,
);
fn run((mut commands, mut previous_len, query): SystemParamItem<Self::Param>) {
let mut values = Vec::with_capacity(*previous_len);
for (entity, query_item) in query.iter() {
values.push((entity, (C::extract_component(query_item),)));
}
*previous_len = values.len();
commands.insert_or_spawn_batch(values);
}
}