Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
bevyengine
GitHub Repository: bevyengine/bevy
Path: blob/main/crates/bevy_render/src/render_phase/draw.rs
6596 views
1
use crate::render_phase::{PhaseItem, TrackedRenderPass};
2
use bevy_app::{App, SubApp};
3
use bevy_ecs::{
4
entity::Entity,
5
query::{QueryEntityError, QueryState, ROQueryItem, ReadOnlyQueryData},
6
resource::Resource,
7
system::{ReadOnlySystemParam, SystemParam, SystemParamItem, SystemState},
8
world::World,
9
};
10
use bevy_utils::TypeIdMap;
11
use core::{any::TypeId, fmt::Debug, hash::Hash};
12
use std::sync::{PoisonError, RwLock, RwLockReadGuard, RwLockWriteGuard};
13
use thiserror::Error;
14
use variadics_please::all_tuples;
15
16
/// A draw function used to draw [`PhaseItem`]s.
17
///
18
/// The draw function can retrieve and query the required ECS data from the render world.
19
///
20
/// This trait can either be implemented directly or implicitly composed out of multiple modular
21
/// [`RenderCommand`]s. For more details and an example see the [`RenderCommand`] documentation.
22
pub trait Draw<P: PhaseItem>: Send + Sync + 'static {
23
/// Prepares the draw function to be used. This is called once and only once before the phase
24
/// begins. There may be zero or more [`draw`](Draw::draw) calls following a call to this function.
25
/// Implementing this is optional.
26
#[expect(
27
unused_variables,
28
reason = "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."
29
)]
30
fn prepare(&mut self, world: &'_ World) {}
31
32
/// Draws a [`PhaseItem`] by issuing zero or more `draw` calls via the [`TrackedRenderPass`].
33
fn draw<'w>(
34
&mut self,
35
world: &'w World,
36
pass: &mut TrackedRenderPass<'w>,
37
view: Entity,
38
item: &P,
39
) -> Result<(), DrawError>;
40
}
41
42
#[derive(Error, Debug, PartialEq, Eq)]
43
pub enum DrawError {
44
#[error("Failed to execute render command {0:?}")]
45
RenderCommandFailure(&'static str),
46
#[error("Failed to get execute view query")]
47
InvalidViewQuery,
48
#[error("View entity not found")]
49
ViewEntityNotFound,
50
}
51
52
// TODO: make this generic?
53
/// An identifier for a [`Draw`] function stored in [`DrawFunctions`].
54
#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Hash)]
55
pub struct DrawFunctionId(u32);
56
57
/// Stores all [`Draw`] functions for the [`PhaseItem`] type.
58
///
59
/// For retrieval, the [`Draw`] functions are mapped to their respective [`TypeId`]s.
60
pub struct DrawFunctionsInternal<P: PhaseItem> {
61
pub draw_functions: Vec<Box<dyn Draw<P>>>,
62
pub indices: TypeIdMap<DrawFunctionId>,
63
}
64
65
impl<P: PhaseItem> DrawFunctionsInternal<P> {
66
/// Prepares all draw function. This is called once and only once before the phase begins.
67
pub fn prepare(&mut self, world: &World) {
68
for function in &mut self.draw_functions {
69
function.prepare(world);
70
}
71
}
72
73
/// Adds the [`Draw`] function and maps it to its own type.
74
pub fn add<T: Draw<P>>(&mut self, draw_function: T) -> DrawFunctionId {
75
self.add_with::<T, T>(draw_function)
76
}
77
78
/// Adds the [`Draw`] function and maps it to the type `T`
79
pub fn add_with<T: 'static, D: Draw<P>>(&mut self, draw_function: D) -> DrawFunctionId {
80
let id = DrawFunctionId(self.draw_functions.len().try_into().unwrap());
81
self.draw_functions.push(Box::new(draw_function));
82
self.indices.insert(TypeId::of::<T>(), id);
83
id
84
}
85
86
/// Retrieves the [`Draw`] function corresponding to the `id` mutably.
87
pub fn get_mut(&mut self, id: DrawFunctionId) -> Option<&mut dyn Draw<P>> {
88
self.draw_functions.get_mut(id.0 as usize).map(|f| &mut **f)
89
}
90
91
/// Retrieves the id of the [`Draw`] function corresponding to their associated type `T`.
92
pub fn get_id<T: 'static>(&self) -> Option<DrawFunctionId> {
93
self.indices.get(&TypeId::of::<T>()).copied()
94
}
95
96
/// Retrieves the id of the [`Draw`] function corresponding to their associated type `T`.
97
///
98
/// Fallible wrapper for [`Self::get_id()`]
99
///
100
/// ## Panics
101
/// If the id doesn't exist, this function will panic.
102
pub fn id<T: 'static>(&self) -> DrawFunctionId {
103
self.get_id::<T>().unwrap_or_else(|| {
104
panic!(
105
"Draw function {} not found for {}",
106
core::any::type_name::<T>(),
107
core::any::type_name::<P>()
108
)
109
})
110
}
111
}
112
113
/// Stores all draw functions for the [`PhaseItem`] type hidden behind a reader-writer lock.
114
///
115
/// To access them the [`DrawFunctions::read`] and [`DrawFunctions::write`] methods are used.
116
#[derive(Resource)]
117
pub struct DrawFunctions<P: PhaseItem> {
118
internal: RwLock<DrawFunctionsInternal<P>>,
119
}
120
121
impl<P: PhaseItem> Default for DrawFunctions<P> {
122
fn default() -> Self {
123
Self {
124
internal: RwLock::new(DrawFunctionsInternal {
125
draw_functions: Vec::new(),
126
indices: Default::default(),
127
}),
128
}
129
}
130
}
131
132
impl<P: PhaseItem> DrawFunctions<P> {
133
/// Accesses the draw functions in read mode.
134
pub fn read(&self) -> RwLockReadGuard<'_, DrawFunctionsInternal<P>> {
135
self.internal.read().unwrap_or_else(PoisonError::into_inner)
136
}
137
138
/// Accesses the draw functions in write mode.
139
pub fn write(&self) -> RwLockWriteGuard<'_, DrawFunctionsInternal<P>> {
140
self.internal
141
.write()
142
.unwrap_or_else(PoisonError::into_inner)
143
}
144
}
145
146
/// [`RenderCommand`]s are modular standardized pieces of render logic that can be composed into
147
/// [`Draw`] functions.
148
///
149
/// To turn a stateless render command into a usable draw function it has to be wrapped by a
150
/// [`RenderCommandState`].
151
/// This is done automatically when registering a render command as a [`Draw`] function via the
152
/// [`AddRenderCommand::add_render_command`] method.
153
///
154
/// Compared to the draw function the required ECS data is fetched automatically
155
/// (by the [`RenderCommandState`]) from the render world.
156
/// Therefore the three types [`Param`](RenderCommand::Param),
157
/// [`ViewQuery`](RenderCommand::ViewQuery) and
158
/// [`ItemQuery`](RenderCommand::ItemQuery) are used.
159
/// They specify which information is required to execute the render command.
160
///
161
/// Multiple render commands can be combined together by wrapping them in a tuple.
162
///
163
/// # Example
164
///
165
/// The `DrawMaterial` draw function is created from the following render command
166
/// tuple. Const generics are used to set specific bind group locations:
167
///
168
/// ```
169
/// # use bevy_render::render_phase::SetItemPipeline;
170
/// # struct SetMeshViewBindGroup<const N: usize>;
171
/// # struct SetMeshViewBindingArrayBindGroup<const N: usize>;
172
/// # struct SetMeshBindGroup<const N: usize>;
173
/// # struct SetMaterialBindGroup<M, const N: usize>(std::marker::PhantomData<M>);
174
/// # struct DrawMesh;
175
/// pub type DrawMaterial<M> = (
176
/// SetItemPipeline,
177
/// SetMeshViewBindGroup<0>,
178
/// SetMeshViewBindingArrayBindGroup<1>,
179
/// SetMeshBindGroup<2>,
180
/// SetMaterialBindGroup<M, 3>,
181
/// DrawMesh,
182
/// );
183
/// ```
184
pub trait RenderCommand<P: PhaseItem> {
185
/// Specifies the general ECS data (e.g. resources) required by [`RenderCommand::render`].
186
///
187
/// When fetching resources, note that, due to lifetime limitations of the `Deref` trait,
188
/// [`SRes::into_inner`] must be called on each [`SRes`] reference in the
189
/// [`RenderCommand::render`] method, instead of being automatically dereferenced as is the
190
/// case in normal `systems`.
191
///
192
/// All parameters have to be read only.
193
///
194
/// [`SRes`]: bevy_ecs::system::lifetimeless::SRes
195
/// [`SRes::into_inner`]: bevy_ecs::system::lifetimeless::SRes::into_inner
196
type Param: SystemParam + 'static;
197
/// Specifies the ECS data of the view entity required by [`RenderCommand::render`].
198
///
199
/// The view entity refers to the camera, or shadow-casting light, etc. from which the phase
200
/// item will be rendered from.
201
/// All components have to be accessed read only.
202
type ViewQuery: ReadOnlyQueryData;
203
/// Specifies the ECS data of the item entity required by [`RenderCommand::render`].
204
///
205
/// The item is the entity that will be rendered for the corresponding view.
206
/// All components have to be accessed read only.
207
///
208
/// For efficiency reasons, Bevy doesn't always extract entities to the
209
/// render world; for instance, entities that simply consist of meshes are
210
/// often not extracted. If the entity doesn't exist in the render world,
211
/// the supplied query data will be `None`.
212
type ItemQuery: ReadOnlyQueryData;
213
214
/// Renders a [`PhaseItem`] by recording commands (e.g. setting pipelines, binding bind groups,
215
/// issuing draw calls, etc.) via the [`TrackedRenderPass`].
216
fn render<'w>(
217
item: &P,
218
view: ROQueryItem<'w, '_, Self::ViewQuery>,
219
entity: Option<ROQueryItem<'w, '_, Self::ItemQuery>>,
220
param: SystemParamItem<'w, '_, Self::Param>,
221
pass: &mut TrackedRenderPass<'w>,
222
) -> RenderCommandResult;
223
}
224
225
/// The result of a [`RenderCommand`].
226
#[derive(Debug)]
227
pub enum RenderCommandResult {
228
Success,
229
Skip,
230
Failure(&'static str),
231
}
232
233
macro_rules! render_command_tuple_impl {
234
($(#[$meta:meta])* $(($name: ident, $view: ident, $entity: ident)),*) => {
235
$(#[$meta])*
236
impl<P: PhaseItem, $($name: RenderCommand<P>),*> RenderCommand<P> for ($($name,)*) {
237
type Param = ($($name::Param,)*);
238
type ViewQuery = ($($name::ViewQuery,)*);
239
type ItemQuery = ($($name::ItemQuery,)*);
240
241
#[expect(
242
clippy::allow_attributes,
243
reason = "We are in a macro; as such, `non_snake_case` may not always lint."
244
)]
245
#[allow(
246
non_snake_case,
247
reason = "Parameter and variable names are provided by the macro invocation, not by us."
248
)]
249
fn render<'w>(
250
_item: &P,
251
($($view,)*): ROQueryItem<'w, '_, Self::ViewQuery>,
252
maybe_entities: Option<ROQueryItem<'w, '_, Self::ItemQuery>>,
253
($($name,)*): SystemParamItem<'w, '_, Self::Param>,
254
_pass: &mut TrackedRenderPass<'w>,
255
) -> RenderCommandResult {
256
match maybe_entities {
257
None => {
258
$(
259
match $name::render(_item, $view, None, $name, _pass) {
260
RenderCommandResult::Skip => return RenderCommandResult::Skip,
261
RenderCommandResult::Failure(reason) => return RenderCommandResult::Failure(reason),
262
_ => {},
263
}
264
)*
265
}
266
Some(($($entity,)*)) => {
267
$(
268
match $name::render(_item, $view, Some($entity), $name, _pass) {
269
RenderCommandResult::Skip => return RenderCommandResult::Skip,
270
RenderCommandResult::Failure(reason) => return RenderCommandResult::Failure(reason),
271
_ => {},
272
}
273
)*
274
}
275
}
276
RenderCommandResult::Success
277
}
278
}
279
};
280
}
281
282
all_tuples!(
283
#[doc(fake_variadic)]
284
render_command_tuple_impl,
285
0,
286
15,
287
C,
288
V,
289
E
290
);
291
292
/// Wraps a [`RenderCommand`] into a state so that it can be used as a [`Draw`] function.
293
///
294
/// The [`RenderCommand::Param`], [`RenderCommand::ViewQuery`] and
295
/// [`RenderCommand::ItemQuery`] are fetched from the ECS and passed to the command.
296
pub struct RenderCommandState<P: PhaseItem + 'static, C: RenderCommand<P>> {
297
state: SystemState<C::Param>,
298
view: QueryState<C::ViewQuery>,
299
entity: QueryState<C::ItemQuery>,
300
}
301
302
impl<P: PhaseItem, C: RenderCommand<P>> RenderCommandState<P, C> {
303
/// Creates a new [`RenderCommandState`] for the [`RenderCommand`].
304
pub fn new(world: &mut World) -> Self {
305
Self {
306
state: SystemState::new(world),
307
view: world.query(),
308
entity: world.query(),
309
}
310
}
311
}
312
313
impl<P: PhaseItem, C: RenderCommand<P> + Send + Sync + 'static> Draw<P> for RenderCommandState<P, C>
314
where
315
C::Param: ReadOnlySystemParam,
316
{
317
/// Prepares the render command to be used. This is called once and only once before the phase
318
/// begins. There may be zero or more [`draw`](RenderCommandState::draw) calls following a call to this function.
319
fn prepare(&mut self, world: &'_ World) {
320
self.view.update_archetypes(world);
321
self.entity.update_archetypes(world);
322
}
323
324
/// Fetches the ECS parameters for the wrapped [`RenderCommand`] and then renders it.
325
fn draw<'w>(
326
&mut self,
327
world: &'w World,
328
pass: &mut TrackedRenderPass<'w>,
329
view: Entity,
330
item: &P,
331
) -> Result<(), DrawError> {
332
let param = self.state.get(world);
333
let view = match self.view.get_manual(world, view) {
334
Ok(view) => view,
335
Err(err) => match err {
336
QueryEntityError::EntityDoesNotExist(_) => {
337
return Err(DrawError::ViewEntityNotFound)
338
}
339
QueryEntityError::QueryDoesNotMatch(_, _)
340
| QueryEntityError::AliasedMutability(_) => {
341
return Err(DrawError::InvalidViewQuery)
342
}
343
},
344
};
345
346
let entity = self.entity.get_manual(world, item.entity()).ok();
347
match C::render(item, view, entity, param, pass) {
348
RenderCommandResult::Success | RenderCommandResult::Skip => Ok(()),
349
RenderCommandResult::Failure(reason) => Err(DrawError::RenderCommandFailure(reason)),
350
}
351
}
352
}
353
354
/// Registers a [`RenderCommand`] as a [`Draw`] function.
355
/// They are stored inside the [`DrawFunctions`] resource of the app.
356
pub trait AddRenderCommand {
357
/// Adds the [`RenderCommand`] for the specified render phase to the app.
358
fn add_render_command<P: PhaseItem, C: RenderCommand<P> + Send + Sync + 'static>(
359
&mut self,
360
) -> &mut Self
361
where
362
C::Param: ReadOnlySystemParam;
363
}
364
365
impl AddRenderCommand for SubApp {
366
fn add_render_command<P: PhaseItem, C: RenderCommand<P> + Send + Sync + 'static>(
367
&mut self,
368
) -> &mut Self
369
where
370
C::Param: ReadOnlySystemParam,
371
{
372
let draw_function = RenderCommandState::<P, C>::new(self.world_mut());
373
let draw_functions = self
374
.world()
375
.get_resource::<DrawFunctions<P>>()
376
.unwrap_or_else(|| {
377
panic!(
378
"DrawFunctions<{}> must be added to the world as a resource \
379
before adding render commands to it",
380
core::any::type_name::<P>(),
381
);
382
});
383
draw_functions.write().add_with::<C, _>(draw_function);
384
self
385
}
386
}
387
388
impl AddRenderCommand for App {
389
fn add_render_command<P: PhaseItem, C: RenderCommand<P> + Send + Sync + 'static>(
390
&mut self,
391
) -> &mut Self
392
where
393
C::Param: ReadOnlySystemParam,
394
{
395
SubApp::add_render_command::<P, C>(self.main_mut());
396
self
397
}
398
}
399
400