forked from bevyengine/bevy
-
Notifications
You must be signed in to change notification settings - Fork 0
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
Generic batching #34
Merged
Merged
Generic batching #34
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,11 +1,15 @@ | ||
use bevy_asset::AssetId; | ||
use bevy_ecs::component::Component; | ||
use bevy_ecs::{ | ||
component::Component, | ||
prelude::Res, | ||
query::{ReadOnlyWorldQuery, WorldQuery}, | ||
system::{Query, ResMut}, | ||
}; | ||
use nonmax::NonMaxU32; | ||
|
||
use crate::{ | ||
mesh::Mesh, | ||
render_phase::{CachedRenderPipelinePhaseItem, DrawFunctionId, RenderPhase}, | ||
render_resource::CachedRenderPipelineId, | ||
render_resource::{CachedRenderPipelineId, GpuArrayBuffer, GpuArrayBufferable}, | ||
renderer::{RenderDevice, RenderQueue}, | ||
}; | ||
|
||
/// Add this component to mesh entities to disable automatic batching | ||
|
@@ -25,65 +29,107 @@ pub struct NoAutomaticBatching; | |
/// result of the `prepare_and_batch_meshes` system, e.g. due to having to split | ||
/// data across separate uniform bindings within the same buffer due to the | ||
/// maximum uniform buffer binding size. | ||
pub struct BatchMeta<T: PartialEq> { | ||
struct BatchMeta<T: PartialEq> { | ||
/// The pipeline id encompasses all pipeline configuration including vertex | ||
/// buffers and layouts, shaders and their specializations, bind group | ||
/// layouts, etc. | ||
pub pipeline_id: CachedRenderPipelineId, | ||
/// The draw function id defines the RenderCommands that are called to | ||
/// set the pipeline and bindings, and make the draw command | ||
pub draw_function_id: DrawFunctionId, | ||
pub material_bind_group_id: Option<T>, | ||
pub mesh_asset_id: AssetId<Mesh>, | ||
pub dynamic_offset: Option<NonMaxU32>, | ||
pub user_data: T, | ||
} | ||
|
||
impl<T: PartialEq> PartialEq for BatchMeta<T> { | ||
#[inline] | ||
fn eq(&self, other: &BatchMeta<T>) -> bool { | ||
self.pipeline_id == other.pipeline_id | ||
&& self.draw_function_id == other.draw_function_id | ||
&& self.mesh_asset_id == other.mesh_asset_id | ||
&& self.dynamic_offset == other.dynamic_offset | ||
&& self.material_bind_group_id == other.material_bind_group_id | ||
&& self.user_data == other.user_data | ||
} | ||
} | ||
|
||
pub trait GetBatchData { | ||
type Query: ReadOnlyWorldQuery; | ||
type CompareData: PartialEq; | ||
type BufferData: GpuArrayBufferable + Sync + Send + 'static; | ||
fn get_batch_data( | ||
batch_data: <Self::Query as WorldQuery>::Item<'_>, | ||
) -> (Self::CompareData, Self::BufferData); | ||
} | ||
|
||
/// Batch the items in a render phase. This means comparing metadata needed to draw each phase item | ||
/// and trying to combine the draws into a batch. | ||
pub fn batch_render_phase< | ||
I: CachedRenderPipelinePhaseItem, | ||
T: PartialEq, // Batch metadata used for distinguishing batches | ||
>( | ||
phase: &mut RenderPhase<I>, | ||
mut get_batch_meta: impl FnMut(&I) -> Option<(T, NonMaxU32, Option<NonMaxU32>)>, | ||
pub fn batch_render_phase<I: CachedRenderPipelinePhaseItem, F: GetBatchData>( | ||
gpu_array_buffer: ResMut<GpuArrayBuffer<F::BufferData>>, | ||
mut views: Query<&mut RenderPhase<I>>, | ||
query: Query<(Option<&NoAutomaticBatching>, F::Query)>, | ||
) { | ||
let mut items = phase.items.iter_mut().peekable(); | ||
let mut batch_start_item = None; | ||
let mut batch_start_index = 0; | ||
let mut next_batch = items.peek().and_then(|item| get_batch_meta(item)); | ||
while let Some(item) = items.next() { | ||
// Get the current batch meta and update the next batch meta | ||
let Some((batch_meta, index, dynamic_offset)) = std::mem::replace( | ||
&mut next_batch, | ||
items.peek().and_then(|item| get_batch_meta(item)), | ||
) else { | ||
// If the current phase item doesn't match the query, we don't modify it | ||
continue; | ||
let gpu_array_buffer = gpu_array_buffer.into_inner(); | ||
|
||
let mut process_item = |item: &mut I| -> Option<BatchMeta<F::CompareData>> { | ||
let Ok((no_batching, batch_data)) = query.get(item.entity()) else { | ||
return None; | ||
}; | ||
|
||
// If we are beginning a new batch, record the start item and index | ||
if batch_start_item.is_none() { | ||
batch_start_item = Some(item); | ||
batch_start_index = index.get(); | ||
let (user_data, buffer_data) = F::get_batch_data(batch_data); | ||
|
||
let buffer_index = gpu_array_buffer.push(buffer_data); | ||
*item.batch_range_mut() = buffer_index.index.get()..buffer_index.index.get() + 1; | ||
*item.dynamic_offset_mut() = buffer_index.dynamic_offset; | ||
|
||
if no_batching.is_some() { | ||
None | ||
} else { | ||
Some(BatchMeta { | ||
pipeline_id: item.cached_pipeline(), | ||
draw_function_id: item.draw_function(), | ||
dynamic_offset: buffer_index.dynamic_offset, | ||
user_data, | ||
}) | ||
} | ||
}; | ||
|
||
if Some(&batch_meta) != next_batch.as_ref().map(|(meta, ..)| meta) { | ||
// The next item doesn't match the current batch (or doesn't exist). | ||
// Update the phase item to render this batch. | ||
let batch_start_item = batch_start_item.take().unwrap(); | ||
*batch_start_item.batch_range_mut() = batch_start_index..index.get() + 1; | ||
*batch_start_item.dynamic_offset_mut() = dynamic_offset; | ||
for mut phase in &mut views { | ||
let mut items = phase.items.iter_mut().peekable(); | ||
let mut batch_start_item = None; | ||
let mut next_batch = items.peek_mut().and_then(|i| process_item(i)); | ||
while let Some(item) = items.next() { | ||
// Get the current batch meta and update the next batch meta | ||
let Some(batch_meta) = std::mem::replace( | ||
&mut next_batch, | ||
items.peek_mut().and_then(|i| process_item(i)), | ||
) else { | ||
// If the current phase item doesn't match the query or has NoAutomaticBatching, | ||
// we don't modify it any further | ||
continue; | ||
}; | ||
|
||
let batch_end_item = item.batch_range().end; | ||
|
||
// If we are beginning a new batch, record the start item | ||
if batch_start_item.is_none() { | ||
batch_start_item = Some(item); | ||
} | ||
|
||
if Some(&batch_meta) != next_batch.as_ref() { | ||
// The next item doesn't match the current batch (or doesn't exist). | ||
// Update the first phase item to render the full batch. | ||
let batch_start_item = batch_start_item.take().unwrap(); | ||
batch_start_item.batch_range_mut().end = batch_end_item; | ||
} | ||
} | ||
} | ||
} | ||
|
||
pub fn flush_buffer<F: GetBatchData>( | ||
render_device: Res<RenderDevice>, | ||
render_queue: Res<RenderQueue>, | ||
gpu_array_buffer: ResMut<GpuArrayBuffer<F::BufferData>>, | ||
) { | ||
let gpu_array_buffer = gpu_array_buffer.into_inner(); | ||
gpu_array_buffer.write_buffer(&render_device, &render_queue); | ||
gpu_array_buffer.clear(); | ||
} | ||
Comment on lines
+127
to
+135
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Good! I wanted to separate this out so we could allow others to append stuff to the buffer for their own purposes. |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Hmm, what should this anonymous lifetime be? Seems a bit sus in an API?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I guess it doesn't matter as it's only borrowed for the duration of get_batch_data, for now?