Path: blob/main/crates/bevy_render/src/render_phase/draw.rs
6596 views
use crate::render_phase::{PhaseItem, TrackedRenderPass};1use bevy_app::{App, SubApp};2use bevy_ecs::{3entity::Entity,4query::{QueryEntityError, QueryState, ROQueryItem, ReadOnlyQueryData},5resource::Resource,6system::{ReadOnlySystemParam, SystemParam, SystemParamItem, SystemState},7world::World,8};9use bevy_utils::TypeIdMap;10use core::{any::TypeId, fmt::Debug, hash::Hash};11use std::sync::{PoisonError, RwLock, RwLockReadGuard, RwLockWriteGuard};12use thiserror::Error;13use variadics_please::all_tuples;1415/// A draw function used to draw [`PhaseItem`]s.16///17/// The draw function can retrieve and query the required ECS data from the render world.18///19/// This trait can either be implemented directly or implicitly composed out of multiple modular20/// [`RenderCommand`]s. For more details and an example see the [`RenderCommand`] documentation.21pub trait Draw<P: PhaseItem>: Send + Sync + 'static {22/// Prepares the draw function to be used. This is called once and only once before the phase23/// begins. There may be zero or more [`draw`](Draw::draw) calls following a call to this function.24/// Implementing this is optional.25#[expect(26unused_variables,27reason = "The parameters here are intentionally unused by the default implementation; however, putting underscores here will result in the underscores being copied by rust-analyzer's tab completion."28)]29fn prepare(&mut self, world: &'_ World) {}3031/// Draws a [`PhaseItem`] by issuing zero or more `draw` calls via the [`TrackedRenderPass`].32fn draw<'w>(33&mut self,34world: &'w World,35pass: &mut TrackedRenderPass<'w>,36view: Entity,37item: &P,38) -> Result<(), DrawError>;39}4041#[derive(Error, Debug, PartialEq, Eq)]42pub enum DrawError {43#[error("Failed to execute render command {0:?}")]44RenderCommandFailure(&'static str),45#[error("Failed to get execute view query")]46InvalidViewQuery,47#[error("View entity not found")]48ViewEntityNotFound,49}5051// TODO: make this generic?52/// An identifier for a [`Draw`] function stored in [`DrawFunctions`].53#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Hash)]54pub struct DrawFunctionId(u32);5556/// Stores all [`Draw`] functions for the [`PhaseItem`] type.57///58/// For retrieval, the [`Draw`] functions are mapped to their respective [`TypeId`]s.59pub struct DrawFunctionsInternal<P: PhaseItem> {60pub draw_functions: Vec<Box<dyn Draw<P>>>,61pub indices: TypeIdMap<DrawFunctionId>,62}6364impl<P: PhaseItem> DrawFunctionsInternal<P> {65/// Prepares all draw function. This is called once and only once before the phase begins.66pub fn prepare(&mut self, world: &World) {67for function in &mut self.draw_functions {68function.prepare(world);69}70}7172/// Adds the [`Draw`] function and maps it to its own type.73pub fn add<T: Draw<P>>(&mut self, draw_function: T) -> DrawFunctionId {74self.add_with::<T, T>(draw_function)75}7677/// Adds the [`Draw`] function and maps it to the type `T`78pub fn add_with<T: 'static, D: Draw<P>>(&mut self, draw_function: D) -> DrawFunctionId {79let id = DrawFunctionId(self.draw_functions.len().try_into().unwrap());80self.draw_functions.push(Box::new(draw_function));81self.indices.insert(TypeId::of::<T>(), id);82id83}8485/// Retrieves the [`Draw`] function corresponding to the `id` mutably.86pub fn get_mut(&mut self, id: DrawFunctionId) -> Option<&mut dyn Draw<P>> {87self.draw_functions.get_mut(id.0 as usize).map(|f| &mut **f)88}8990/// Retrieves the id of the [`Draw`] function corresponding to their associated type `T`.91pub fn get_id<T: 'static>(&self) -> Option<DrawFunctionId> {92self.indices.get(&TypeId::of::<T>()).copied()93}9495/// Retrieves the id of the [`Draw`] function corresponding to their associated type `T`.96///97/// Fallible wrapper for [`Self::get_id()`]98///99/// ## Panics100/// If the id doesn't exist, this function will panic.101pub fn id<T: 'static>(&self) -> DrawFunctionId {102self.get_id::<T>().unwrap_or_else(|| {103panic!(104"Draw function {} not found for {}",105core::any::type_name::<T>(),106core::any::type_name::<P>()107)108})109}110}111112/// Stores all draw functions for the [`PhaseItem`] type hidden behind a reader-writer lock.113///114/// To access them the [`DrawFunctions::read`] and [`DrawFunctions::write`] methods are used.115#[derive(Resource)]116pub struct DrawFunctions<P: PhaseItem> {117internal: RwLock<DrawFunctionsInternal<P>>,118}119120impl<P: PhaseItem> Default for DrawFunctions<P> {121fn default() -> Self {122Self {123internal: RwLock::new(DrawFunctionsInternal {124draw_functions: Vec::new(),125indices: Default::default(),126}),127}128}129}130131impl<P: PhaseItem> DrawFunctions<P> {132/// Accesses the draw functions in read mode.133pub fn read(&self) -> RwLockReadGuard<'_, DrawFunctionsInternal<P>> {134self.internal.read().unwrap_or_else(PoisonError::into_inner)135}136137/// Accesses the draw functions in write mode.138pub fn write(&self) -> RwLockWriteGuard<'_, DrawFunctionsInternal<P>> {139self.internal140.write()141.unwrap_or_else(PoisonError::into_inner)142}143}144145/// [`RenderCommand`]s are modular standardized pieces of render logic that can be composed into146/// [`Draw`] functions.147///148/// To turn a stateless render command into a usable draw function it has to be wrapped by a149/// [`RenderCommandState`].150/// This is done automatically when registering a render command as a [`Draw`] function via the151/// [`AddRenderCommand::add_render_command`] method.152///153/// Compared to the draw function the required ECS data is fetched automatically154/// (by the [`RenderCommandState`]) from the render world.155/// Therefore the three types [`Param`](RenderCommand::Param),156/// [`ViewQuery`](RenderCommand::ViewQuery) and157/// [`ItemQuery`](RenderCommand::ItemQuery) are used.158/// They specify which information is required to execute the render command.159///160/// Multiple render commands can be combined together by wrapping them in a tuple.161///162/// # Example163///164/// The `DrawMaterial` draw function is created from the following render command165/// tuple. Const generics are used to set specific bind group locations:166///167/// ```168/// # use bevy_render::render_phase::SetItemPipeline;169/// # struct SetMeshViewBindGroup<const N: usize>;170/// # struct SetMeshViewBindingArrayBindGroup<const N: usize>;171/// # struct SetMeshBindGroup<const N: usize>;172/// # struct SetMaterialBindGroup<M, const N: usize>(std::marker::PhantomData<M>);173/// # struct DrawMesh;174/// pub type DrawMaterial<M> = (175/// SetItemPipeline,176/// SetMeshViewBindGroup<0>,177/// SetMeshViewBindingArrayBindGroup<1>,178/// SetMeshBindGroup<2>,179/// SetMaterialBindGroup<M, 3>,180/// DrawMesh,181/// );182/// ```183pub trait RenderCommand<P: PhaseItem> {184/// Specifies the general ECS data (e.g. resources) required by [`RenderCommand::render`].185///186/// When fetching resources, note that, due to lifetime limitations of the `Deref` trait,187/// [`SRes::into_inner`] must be called on each [`SRes`] reference in the188/// [`RenderCommand::render`] method, instead of being automatically dereferenced as is the189/// case in normal `systems`.190///191/// All parameters have to be read only.192///193/// [`SRes`]: bevy_ecs::system::lifetimeless::SRes194/// [`SRes::into_inner`]: bevy_ecs::system::lifetimeless::SRes::into_inner195type Param: SystemParam + 'static;196/// Specifies the ECS data of the view entity required by [`RenderCommand::render`].197///198/// The view entity refers to the camera, or shadow-casting light, etc. from which the phase199/// item will be rendered from.200/// All components have to be accessed read only.201type ViewQuery: ReadOnlyQueryData;202/// Specifies the ECS data of the item entity required by [`RenderCommand::render`].203///204/// The item is the entity that will be rendered for the corresponding view.205/// All components have to be accessed read only.206///207/// For efficiency reasons, Bevy doesn't always extract entities to the208/// render world; for instance, entities that simply consist of meshes are209/// often not extracted. If the entity doesn't exist in the render world,210/// the supplied query data will be `None`.211type ItemQuery: ReadOnlyQueryData;212213/// Renders a [`PhaseItem`] by recording commands (e.g. setting pipelines, binding bind groups,214/// issuing draw calls, etc.) via the [`TrackedRenderPass`].215fn render<'w>(216item: &P,217view: ROQueryItem<'w, '_, Self::ViewQuery>,218entity: Option<ROQueryItem<'w, '_, Self::ItemQuery>>,219param: SystemParamItem<'w, '_, Self::Param>,220pass: &mut TrackedRenderPass<'w>,221) -> RenderCommandResult;222}223224/// The result of a [`RenderCommand`].225#[derive(Debug)]226pub enum RenderCommandResult {227Success,228Skip,229Failure(&'static str),230}231232macro_rules! render_command_tuple_impl {233($(#[$meta:meta])* $(($name: ident, $view: ident, $entity: ident)),*) => {234$(#[$meta])*235impl<P: PhaseItem, $($name: RenderCommand<P>),*> RenderCommand<P> for ($($name,)*) {236type Param = ($($name::Param,)*);237type ViewQuery = ($($name::ViewQuery,)*);238type ItemQuery = ($($name::ItemQuery,)*);239240#[expect(241clippy::allow_attributes,242reason = "We are in a macro; as such, `non_snake_case` may not always lint."243)]244#[allow(245non_snake_case,246reason = "Parameter and variable names are provided by the macro invocation, not by us."247)]248fn render<'w>(249_item: &P,250($($view,)*): ROQueryItem<'w, '_, Self::ViewQuery>,251maybe_entities: Option<ROQueryItem<'w, '_, Self::ItemQuery>>,252($($name,)*): SystemParamItem<'w, '_, Self::Param>,253_pass: &mut TrackedRenderPass<'w>,254) -> RenderCommandResult {255match maybe_entities {256None => {257$(258match $name::render(_item, $view, None, $name, _pass) {259RenderCommandResult::Skip => return RenderCommandResult::Skip,260RenderCommandResult::Failure(reason) => return RenderCommandResult::Failure(reason),261_ => {},262}263)*264}265Some(($($entity,)*)) => {266$(267match $name::render(_item, $view, Some($entity), $name, _pass) {268RenderCommandResult::Skip => return RenderCommandResult::Skip,269RenderCommandResult::Failure(reason) => return RenderCommandResult::Failure(reason),270_ => {},271}272)*273}274}275RenderCommandResult::Success276}277}278};279}280281all_tuples!(282#[doc(fake_variadic)]283render_command_tuple_impl,2840,28515,286C,287V,288E289);290291/// Wraps a [`RenderCommand`] into a state so that it can be used as a [`Draw`] function.292///293/// The [`RenderCommand::Param`], [`RenderCommand::ViewQuery`] and294/// [`RenderCommand::ItemQuery`] are fetched from the ECS and passed to the command.295pub struct RenderCommandState<P: PhaseItem + 'static, C: RenderCommand<P>> {296state: SystemState<C::Param>,297view: QueryState<C::ViewQuery>,298entity: QueryState<C::ItemQuery>,299}300301impl<P: PhaseItem, C: RenderCommand<P>> RenderCommandState<P, C> {302/// Creates a new [`RenderCommandState`] for the [`RenderCommand`].303pub fn new(world: &mut World) -> Self {304Self {305state: SystemState::new(world),306view: world.query(),307entity: world.query(),308}309}310}311312impl<P: PhaseItem, C: RenderCommand<P> + Send + Sync + 'static> Draw<P> for RenderCommandState<P, C>313where314C::Param: ReadOnlySystemParam,315{316/// Prepares the render command to be used. This is called once and only once before the phase317/// begins. There may be zero or more [`draw`](RenderCommandState::draw) calls following a call to this function.318fn prepare(&mut self, world: &'_ World) {319self.view.update_archetypes(world);320self.entity.update_archetypes(world);321}322323/// Fetches the ECS parameters for the wrapped [`RenderCommand`] and then renders it.324fn draw<'w>(325&mut self,326world: &'w World,327pass: &mut TrackedRenderPass<'w>,328view: Entity,329item: &P,330) -> Result<(), DrawError> {331let param = self.state.get(world);332let view = match self.view.get_manual(world, view) {333Ok(view) => view,334Err(err) => match err {335QueryEntityError::EntityDoesNotExist(_) => {336return Err(DrawError::ViewEntityNotFound)337}338QueryEntityError::QueryDoesNotMatch(_, _)339| QueryEntityError::AliasedMutability(_) => {340return Err(DrawError::InvalidViewQuery)341}342},343};344345let entity = self.entity.get_manual(world, item.entity()).ok();346match C::render(item, view, entity, param, pass) {347RenderCommandResult::Success | RenderCommandResult::Skip => Ok(()),348RenderCommandResult::Failure(reason) => Err(DrawError::RenderCommandFailure(reason)),349}350}351}352353/// Registers a [`RenderCommand`] as a [`Draw`] function.354/// They are stored inside the [`DrawFunctions`] resource of the app.355pub trait AddRenderCommand {356/// Adds the [`RenderCommand`] for the specified render phase to the app.357fn add_render_command<P: PhaseItem, C: RenderCommand<P> + Send + Sync + 'static>(358&mut self,359) -> &mut Self360where361C::Param: ReadOnlySystemParam;362}363364impl AddRenderCommand for SubApp {365fn add_render_command<P: PhaseItem, C: RenderCommand<P> + Send + Sync + 'static>(366&mut self,367) -> &mut Self368where369C::Param: ReadOnlySystemParam,370{371let draw_function = RenderCommandState::<P, C>::new(self.world_mut());372let draw_functions = self373.world()374.get_resource::<DrawFunctions<P>>()375.unwrap_or_else(|| {376panic!(377"DrawFunctions<{}> must be added to the world as a resource \378before adding render commands to it",379core::any::type_name::<P>(),380);381});382draw_functions.write().add_with::<C, _>(draw_function);383self384}385}386387impl AddRenderCommand for App {388fn add_render_command<P: PhaseItem, C: RenderCommand<P> + Send + Sync + 'static>(389&mut self,390) -> &mut Self391where392C::Param: ReadOnlySystemParam,393{394SubApp::add_render_command::<P, C>(self.main_mut());395self396}397}398399400