
# Objective Closes #19564. The current `Event` trait looks like this: ```rust pub trait Event: Send + Sync + 'static { type Traversal: Traversal<Self>; const AUTO_PROPAGATE: bool = false; fn register_component_id(world: &mut World) -> ComponentId { ... } fn component_id(world: &World) -> Option<ComponentId> { ... } } ``` The `Event` trait is used by both buffered events (`EventReader`/`EventWriter`) and observer events. If they are observer events, they can optionally be targeted at specific `Entity`s or `ComponentId`s, and can even be propagated to other entities. However, there has long been a desire to split the trait semantically for a variety of reasons, see #14843, #14272, and #16031 for discussion. Some reasons include: - It's very uncommon to use a single event type as both a buffered event and targeted observer event. They are used differently and tend to have distinct semantics. - A common footgun is using buffered events with observers or event readers with observer events, as there is no type-level error that prevents this kind of misuse. - #19440 made `Trigger::target` return an `Option<Entity>`. This *seriously* hurts ergonomics for the general case of entity observers, as you need to `.unwrap()` each time. If we could statically determine whether the event is expected to have an entity target, this would be unnecessary. There's really two main ways that we can categorize events: push vs. pull (i.e. "observer event" vs. "buffered event") and global vs. targeted: | | Push | Pull | | ------------ | --------------- | --------------------------- | | **Global** | Global observer | `EventReader`/`EventWriter` | | **Targeted** | Entity observer | - | There are many ways to approach this, each with their tradeoffs. Ultimately, we kind of want to split events both ways: - A type-level distinction between observer events and buffered events, to prevent people from using the wrong kind of event in APIs - A statically designated entity target for observer events to avoid accidentally using untargeted events for targeted APIs This PR achieves these goals by splitting event traits into `Event`, `EntityEvent`, and `BufferedEvent`, with `Event` being the shared trait implemented by all events. ## `Event`, `EntityEvent`, and `BufferedEvent` `Event` is now a very simple trait shared by all events. ```rust pub trait Event: Send + Sync + 'static { // Required for observer APIs fn register_component_id(world: &mut World) -> ComponentId { ... } fn component_id(world: &World) -> Option<ComponentId> { ... } } ``` You can call `trigger` for *any* event, and use a global observer for listening to the event. ```rust #[derive(Event)] struct Speak { message: String, } // ... app.add_observer(|trigger: On<Speak>| { println!("{}", trigger.message); }); // ... commands.trigger(Speak { message: "Y'all like these reworked events?".to_string(), }); ``` To allow an event to be targeted at entities and even propagated further, you can additionally implement the `EntityEvent` trait: ```rust pub trait EntityEvent: Event { type Traversal: Traversal<Self>; const AUTO_PROPAGATE: bool = false; } ``` This lets you call `trigger_targets`, and to use targeted observer APIs like `EntityCommands::observe`: ```rust #[derive(Event, EntityEvent)] #[entity_event(traversal = &'static ChildOf, auto_propagate)] struct Damage { amount: f32, } // ... let enemy = commands.spawn((Enemy, Health(100.0))).id(); // Spawn some armor as a child of the enemy entity. // When the armor takes damage, it will bubble the event up to the enemy. let armor_piece = commands .spawn((ArmorPiece, Health(25.0), ChildOf(enemy))) .observe(|trigger: On<Damage>, mut query: Query<&mut Health>| { // Note: `On::target` only exists because this is an `EntityEvent`. let mut health = query.get(trigger.target()).unwrap(); health.0 -= trigger.amount(); }); commands.trigger_targets(Damage { amount: 10.0 }, armor_piece); ``` > [!NOTE] > You *can* still also trigger an `EntityEvent` without targets using `trigger`. We probably *could* make this an either-or thing, but I'm not sure that's actually desirable. To allow an event to be used with the buffered API, you can implement `BufferedEvent`: ```rust pub trait BufferedEvent: Event {} ``` The event can then be used with `EventReader`/`EventWriter`: ```rust #[derive(Event, BufferedEvent)] struct Message(String); fn write_hello(mut writer: EventWriter<Message>) { writer.write(Message("I hope these examples are alright".to_string())); } fn read_messages(mut reader: EventReader<Message>) { // Process all buffered events of type `Message`. for Message(message) in reader.read() { println!("{message}"); } } ``` In summary: - Need a basic event you can trigger and observe? Derive `Event`! - Need the event to be targeted at an entity? Derive `EntityEvent`! - Need the event to be buffered and support the `EventReader`/`EventWriter` API? Derive `BufferedEvent`! ## Alternatives I'll now cover some of the alternative approaches I have considered and briefly explored. I made this section collapsible since it ended up being quite long :P <details> <summary>Expand this to see alternatives</summary> ### 1. Unified `Event` Trait One option is not to have *three* separate traits (`Event`, `EntityEvent`, `BufferedEvent`), and to instead just use associated constants on `Event` to determine whether an event supports targeting and buffering or not: ```rust pub trait Event: Send + Sync + 'static { type Traversal: Traversal<Self>; const AUTO_PROPAGATE: bool = false; const TARGETED: bool = false; const BUFFERED: bool = false; fn register_component_id(world: &mut World) -> ComponentId { ... } fn component_id(world: &World) -> Option<ComponentId> { ... } } ``` Methods can then use bounds like `where E: Event<TARGETED = true>` or `where E: Event<BUFFERED = true>` to limit APIs to specific kinds of events. This would keep everything under one `Event` trait, but I don't think it's necessarily a good idea. It makes APIs harder to read, and docs can't easily refer to specific types of events. You can also create weird invariants: what if you specify `TARGETED = false`, but have `Traversal` and/or `AUTO_PROPAGATE` enabled? ### 2. `Event` and `Trigger` Another option is to only split the traits between buffered events and observer events, since that is the main thing people have been asking for, and they have the largest API difference. If we did this, I think we would need to make the terms *clearly* separate. We can't really use `Event` and `BufferedEvent` as the names, since it would be strange that `BufferedEvent` doesn't implement `Event`. Something like `ObserverEvent` and `BufferedEvent` could work, but it'd be more verbose. For this approach, I would instead keep `Event` for the current `EventReader`/`EventWriter` API, and call the observer event a `Trigger`, since the "trigger" terminology is already used in the observer context within Bevy (both as a noun and a verb). This is also what a long [bikeshed on Discord](https://discord.com/channels/691052431525675048/749335865876021248/1298057661878898791) seemed to land on at the end of last year. ```rust // For `EventReader`/`EventWriter` pub trait Event: Send + Sync + 'static {} // For observers pub trait Trigger: Send + Sync + 'static { type Traversal: Traversal<Self>; const AUTO_PROPAGATE: bool = false; const TARGETED: bool = false; fn register_component_id(world: &mut World) -> ComponentId { ... } fn component_id(world: &World) -> Option<ComponentId> { ... } } ``` The problem is that "event" is just a really good term for something that "happens". Observers are rapidly becoming the more prominent API, so it'd be weird to give them the `Trigger` name and leave the good `Event` name for the less common API. So, even though a split like this seems neat on the surface, I think it ultimately wouldn't really work. We want to keep the `Event` name for observer events, and there is no good alternative for the buffered variant. (`Message` was suggested, but saying stuff like "sends a collision message" is weird.) ### 3. `GlobalEvent` + `TargetedEvent` What if instead of focusing on the buffered vs. observed split, we *only* make a distinction between global and targeted events? ```rust // A shared event trait to allow global observers to work pub trait Event: Send + Sync + 'static { fn register_component_id(world: &mut World) -> ComponentId { ... } fn component_id(world: &World) -> Option<ComponentId> { ... } } // For buffered events and non-targeted observer events pub trait GlobalEvent: Event {} // For targeted observer events pub trait TargetedEvent: Event { type Traversal: Traversal<Self>; const AUTO_PROPAGATE: bool = false; } ``` This is actually the first approach I implemented, and it has the neat characteristic that you can only use non-targeted APIs like `trigger` with a `GlobalEvent` and targeted APIs like `trigger_targets` with a `TargetedEvent`. You have full control over whether the entity should or should not have a target, as they are fully distinct at the type-level. However, there's a few problems: - There is no type-level indication of whether a `GlobalEvent` supports buffered events or just non-targeted observer events - An `Event` on its own does literally nothing, it's just a shared trait required to make global observers accept both non-targeted and targeted events - If an event is both a `GlobalEvent` and `TargetedEvent`, global observers again have ambiguity on whether an event has a target or not, undermining some of the benefits - The names are not ideal ### 4. `Event` and `EntityEvent` We can fix some of the problems of Alternative 3 by accepting that targeted events can also be used in non-targeted contexts, and simply having the `Event` and `EntityEvent` traits: ```rust // For buffered events and non-targeted observer events pub trait Event: Send + Sync + 'static { fn register_component_id(world: &mut World) -> ComponentId { ... } fn component_id(world: &World) -> Option<ComponentId> { ... } } // For targeted observer events pub trait EntityEvent: Event { type Traversal: Traversal<Self>; const AUTO_PROPAGATE: bool = false; } ``` This is essentially identical to this PR, just without a dedicated `BufferedEvent`. The remaining major "problem" is that there is still zero type-level indication of whether an `Event` event *actually* supports the buffered API. This leads us to the solution proposed in this PR, using `Event`, `EntityEvent`, and `BufferedEvent`. </details> ## Conclusion The `Event` + `EntityEvent` + `BufferedEvent` split proposed in this PR aims to solve all the common problems with Bevy's current event model while keeping the "weirdness" factor minimal. It splits in terms of both the push vs. pull *and* global vs. targeted aspects, while maintaining a shared concept for an "event". ### Why I Like This - The term "event" remains as a single concept for all the different kinds of events in Bevy. - Despite all event types being "events", they use fundamentally different APIs. Instead of assuming that you can use an event type with any pattern (when only one is typically supported), you explicitly opt in to each one with dedicated traits. - Using separate traits for each type of event helps with documentation and clearer function signatures. - I can safely make assumptions on expected usage. - If I see that an event is an `EntityEvent`, I can assume that I can use `observe` on it and get targeted events. - If I see that an event is a `BufferedEvent`, I can assume that I can use `EventReader` to read events. - If I see both `EntityEvent` and `BufferedEvent`, I can assume that both APIs are supported. In summary: This allows for a unified concept for events, while limiting the different ways to use them with opt-in traits. No more guess-work involved when using APIs. ### Problems? - Because `BufferedEvent` implements `Event` (for more consistent semantics etc.), you can still use all buffered events for non-targeted observers. I think this is fine/good. The important part is that if you see that an event implements `BufferedEvent`, you know that the `EventReader`/`EventWriter` API should be supported. Whether it *also* supports other APIs is secondary. - I currently only support `trigger_targets` for an `EntityEvent`. However, you can technically target components too, without targeting any entities. I consider that such a niche and advanced use case that it's not a huge problem to only support it for `EntityEvent`s, but we could also split `trigger_targets` into `trigger_entities` and `trigger_components` if we wanted to (or implement components as entities :P). - You can still trigger an `EntityEvent` *without* targets. I consider this correct, since `Event` implements the non-targeted behavior, and it'd be weird if implementing another trait *removed* behavior. However, it does mean that global observers for entity events can technically return `Entity::PLACEHOLDER` again (since I got rid of the `Option<Entity>` added in #19440 for ergonomics). I think that's enough of an edge case that it's not a huge problem, but it is worth keeping in mind. - ~~Deriving both `EntityEvent` and `BufferedEvent` for the same type currently duplicates the `Event` implementation, so you instead need to manually implement one of them.~~ Changed to always requiring `Event` to be derived. ## Related Work There are plans to implement multi-event support for observers, especially for UI contexts. [Cart's example](https://github.com/bevyengine/bevy/issues/14649#issuecomment-2960402508) API looked like this: ```rust // Truncated for brevity trigger: Trigger<( OnAdd<Pressed>, OnRemove<Pressed>, OnAdd<InteractionDisabled>, OnRemove<InteractionDisabled>, OnInsert<Hovered>, )>, ``` I believe this shouldn't be in conflict with this PR. If anything, this PR might *help* achieve the multi-event pattern for entity observers with fewer footguns: by statically enforcing that all of these events are `EntityEvent`s in the context of `EntityCommands::observe`, we can avoid misuse or weird cases where *some* events inside the trigger are targeted while others are not.
386 lines
13 KiB
Rust
386 lines
13 KiB
Rust
use crate::{
|
|
extract_component::ExtractComponentPlugin,
|
|
render_asset::RenderAssets,
|
|
render_resource::{
|
|
Buffer, BufferUsages, CommandEncoder, Extent3d, TexelCopyBufferLayout, Texture,
|
|
TextureFormat,
|
|
},
|
|
renderer::{render_system, RenderDevice},
|
|
storage::{GpuShaderStorageBuffer, ShaderStorageBuffer},
|
|
sync_world::MainEntity,
|
|
texture::GpuImage,
|
|
ExtractSchedule, MainWorld, Render, RenderApp, RenderSystems,
|
|
};
|
|
use async_channel::{Receiver, Sender};
|
|
use bevy_app::{App, Plugin};
|
|
use bevy_asset::Handle;
|
|
use bevy_derive::{Deref, DerefMut};
|
|
use bevy_ecs::{
|
|
change_detection::ResMut,
|
|
entity::Entity,
|
|
event::EntityEvent,
|
|
prelude::{Component, Resource, World},
|
|
system::{Query, Res},
|
|
};
|
|
use bevy_ecs::{event::Event, schedule::IntoScheduleConfigs};
|
|
use bevy_image::{Image, TextureFormatPixelInfo};
|
|
use bevy_platform::collections::HashMap;
|
|
use bevy_reflect::Reflect;
|
|
use bevy_render_macros::ExtractComponent;
|
|
use encase::internal::ReadFrom;
|
|
use encase::private::Reader;
|
|
use encase::ShaderType;
|
|
use tracing::warn;
|
|
|
|
/// A plugin that enables reading back gpu buffers and textures to the cpu.
|
|
pub struct GpuReadbackPlugin {
|
|
/// Describes the number of frames a buffer can be unused before it is removed from the pool in
|
|
/// order to avoid unnecessary reallocations.
|
|
max_unused_frames: usize,
|
|
}
|
|
|
|
impl Default for GpuReadbackPlugin {
|
|
fn default() -> Self {
|
|
Self {
|
|
max_unused_frames: 10,
|
|
}
|
|
}
|
|
}
|
|
|
|
impl Plugin for GpuReadbackPlugin {
|
|
fn build(&self, app: &mut App) {
|
|
app.add_plugins(ExtractComponentPlugin::<Readback>::default());
|
|
|
|
if let Some(render_app) = app.get_sub_app_mut(RenderApp) {
|
|
render_app
|
|
.init_resource::<GpuReadbackBufferPool>()
|
|
.init_resource::<GpuReadbacks>()
|
|
.insert_resource(GpuReadbackMaxUnusedFrames(self.max_unused_frames))
|
|
.add_systems(ExtractSchedule, sync_readbacks.ambiguous_with_all())
|
|
.add_systems(
|
|
Render,
|
|
(
|
|
prepare_buffers.in_set(RenderSystems::PrepareResources),
|
|
map_buffers
|
|
.after(render_system)
|
|
.in_set(RenderSystems::Render),
|
|
),
|
|
);
|
|
}
|
|
}
|
|
}
|
|
|
|
/// A component that registers the wrapped handle for gpu readback, either a texture or a buffer.
|
|
///
|
|
/// Data is read asynchronously and will be triggered on the entity via the [`ReadbackComplete`] event
|
|
/// when complete. If this component is not removed, the readback will be attempted every frame
|
|
#[derive(Component, ExtractComponent, Clone, Debug)]
|
|
pub enum Readback {
|
|
Texture(Handle<Image>),
|
|
Buffer(Handle<ShaderStorageBuffer>),
|
|
}
|
|
|
|
impl Readback {
|
|
/// Create a readback component for a texture using the given handle.
|
|
pub fn texture(image: Handle<Image>) -> Self {
|
|
Self::Texture(image)
|
|
}
|
|
|
|
/// Create a readback component for a buffer using the given handle.
|
|
pub fn buffer(buffer: Handle<ShaderStorageBuffer>) -> Self {
|
|
Self::Buffer(buffer)
|
|
}
|
|
}
|
|
|
|
/// An event that is triggered when a gpu readback is complete.
|
|
///
|
|
/// The event contains the data as a `Vec<u8>`, which can be interpreted as the raw bytes of the
|
|
/// requested buffer or texture.
|
|
#[derive(Event, EntityEvent, Deref, DerefMut, Reflect, Debug)]
|
|
#[reflect(Debug)]
|
|
pub struct ReadbackComplete(pub Vec<u8>);
|
|
|
|
impl ReadbackComplete {
|
|
/// Convert the raw bytes of the event to a shader type.
|
|
pub fn to_shader_type<T: ShaderType + ReadFrom + Default>(&self) -> T {
|
|
let mut val = T::default();
|
|
let mut reader = Reader::new::<T>(&self.0, 0).expect("Failed to create Reader");
|
|
T::read_from(&mut val, &mut reader);
|
|
val
|
|
}
|
|
}
|
|
|
|
#[derive(Resource)]
|
|
struct GpuReadbackMaxUnusedFrames(usize);
|
|
|
|
struct GpuReadbackBuffer {
|
|
buffer: Buffer,
|
|
taken: bool,
|
|
frames_unused: usize,
|
|
}
|
|
|
|
#[derive(Resource, Default)]
|
|
struct GpuReadbackBufferPool {
|
|
// Map of buffer size to list of buffers, with a flag for whether the buffer is taken and how
|
|
// many frames it has been unused for.
|
|
// TODO: We could ideally write all readback data to one big buffer per frame, the assumption
|
|
// here is that very few entities well actually be read back at once, and their size is
|
|
// unlikely to change.
|
|
buffers: HashMap<u64, Vec<GpuReadbackBuffer>>,
|
|
}
|
|
|
|
impl GpuReadbackBufferPool {
|
|
fn get(&mut self, render_device: &RenderDevice, size: u64) -> Buffer {
|
|
let buffers = self.buffers.entry(size).or_default();
|
|
|
|
// find an untaken buffer for this size
|
|
if let Some(buf) = buffers.iter_mut().find(|x| !x.taken) {
|
|
buf.taken = true;
|
|
buf.frames_unused = 0;
|
|
return buf.buffer.clone();
|
|
}
|
|
|
|
let buffer = render_device.create_buffer(&wgpu::BufferDescriptor {
|
|
label: Some("Readback Buffer"),
|
|
size,
|
|
usage: BufferUsages::COPY_DST | BufferUsages::MAP_READ,
|
|
mapped_at_creation: false,
|
|
});
|
|
buffers.push(GpuReadbackBuffer {
|
|
buffer: buffer.clone(),
|
|
taken: true,
|
|
frames_unused: 0,
|
|
});
|
|
buffer
|
|
}
|
|
|
|
// Returns the buffer to the pool so it can be used in a future frame
|
|
fn return_buffer(&mut self, buffer: &Buffer) {
|
|
let size = buffer.size();
|
|
let buffers = self
|
|
.buffers
|
|
.get_mut(&size)
|
|
.expect("Returned buffer of untracked size");
|
|
if let Some(buf) = buffers.iter_mut().find(|x| x.buffer.id() == buffer.id()) {
|
|
buf.taken = false;
|
|
} else {
|
|
warn!("Returned buffer that was not allocated");
|
|
}
|
|
}
|
|
|
|
fn update(&mut self, max_unused_frames: usize) {
|
|
for (_, buffers) in &mut self.buffers {
|
|
// Tick all the buffers
|
|
for buf in &mut *buffers {
|
|
if !buf.taken {
|
|
buf.frames_unused += 1;
|
|
}
|
|
}
|
|
|
|
// Remove buffers that haven't been used for MAX_UNUSED_FRAMES
|
|
buffers.retain(|x| x.frames_unused < max_unused_frames);
|
|
}
|
|
|
|
// Remove empty buffer sizes
|
|
self.buffers.retain(|_, buffers| !buffers.is_empty());
|
|
}
|
|
}
|
|
|
|
enum ReadbackSource {
|
|
Texture {
|
|
texture: Texture,
|
|
layout: TexelCopyBufferLayout,
|
|
size: Extent3d,
|
|
},
|
|
Buffer {
|
|
src_start: u64,
|
|
dst_start: u64,
|
|
buffer: Buffer,
|
|
},
|
|
}
|
|
|
|
#[derive(Resource, Default)]
|
|
struct GpuReadbacks {
|
|
requested: Vec<GpuReadback>,
|
|
mapped: Vec<GpuReadback>,
|
|
}
|
|
|
|
struct GpuReadback {
|
|
pub entity: Entity,
|
|
pub src: ReadbackSource,
|
|
pub buffer: Buffer,
|
|
pub rx: Receiver<(Entity, Buffer, Vec<u8>)>,
|
|
pub tx: Sender<(Entity, Buffer, Vec<u8>)>,
|
|
}
|
|
|
|
fn sync_readbacks(
|
|
mut main_world: ResMut<MainWorld>,
|
|
mut buffer_pool: ResMut<GpuReadbackBufferPool>,
|
|
mut readbacks: ResMut<GpuReadbacks>,
|
|
max_unused_frames: Res<GpuReadbackMaxUnusedFrames>,
|
|
) {
|
|
readbacks.mapped.retain(|readback| {
|
|
if let Ok((entity, buffer, result)) = readback.rx.try_recv() {
|
|
main_world.trigger_targets(ReadbackComplete(result), entity);
|
|
buffer_pool.return_buffer(&buffer);
|
|
false
|
|
} else {
|
|
true
|
|
}
|
|
});
|
|
|
|
buffer_pool.update(max_unused_frames.0);
|
|
}
|
|
|
|
fn prepare_buffers(
|
|
render_device: Res<RenderDevice>,
|
|
mut readbacks: ResMut<GpuReadbacks>,
|
|
mut buffer_pool: ResMut<GpuReadbackBufferPool>,
|
|
gpu_images: Res<RenderAssets<GpuImage>>,
|
|
ssbos: Res<RenderAssets<GpuShaderStorageBuffer>>,
|
|
handles: Query<(&MainEntity, &Readback)>,
|
|
) {
|
|
for (entity, readback) in handles.iter() {
|
|
match readback {
|
|
Readback::Texture(image) => {
|
|
if let Some(gpu_image) = gpu_images.get(image) {
|
|
let layout = layout_data(gpu_image.size, gpu_image.texture_format);
|
|
let buffer = buffer_pool.get(
|
|
&render_device,
|
|
get_aligned_size(
|
|
gpu_image.size,
|
|
gpu_image.texture_format.pixel_size() as u32,
|
|
) as u64,
|
|
);
|
|
let (tx, rx) = async_channel::bounded(1);
|
|
readbacks.requested.push(GpuReadback {
|
|
entity: entity.id(),
|
|
src: ReadbackSource::Texture {
|
|
texture: gpu_image.texture.clone(),
|
|
layout,
|
|
size: gpu_image.size,
|
|
},
|
|
buffer,
|
|
rx,
|
|
tx,
|
|
});
|
|
}
|
|
}
|
|
Readback::Buffer(buffer) => {
|
|
if let Some(ssbo) = ssbos.get(buffer) {
|
|
let size = ssbo.buffer.size();
|
|
let buffer = buffer_pool.get(&render_device, size);
|
|
let (tx, rx) = async_channel::bounded(1);
|
|
readbacks.requested.push(GpuReadback {
|
|
entity: entity.id(),
|
|
src: ReadbackSource::Buffer {
|
|
src_start: 0,
|
|
dst_start: 0,
|
|
buffer: ssbo.buffer.clone(),
|
|
},
|
|
buffer,
|
|
rx,
|
|
tx,
|
|
});
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
pub(crate) fn submit_readback_commands(world: &World, command_encoder: &mut CommandEncoder) {
|
|
let readbacks = world.resource::<GpuReadbacks>();
|
|
for readback in &readbacks.requested {
|
|
match &readback.src {
|
|
ReadbackSource::Texture {
|
|
texture,
|
|
layout,
|
|
size,
|
|
} => {
|
|
command_encoder.copy_texture_to_buffer(
|
|
texture.as_image_copy(),
|
|
wgpu::TexelCopyBufferInfo {
|
|
buffer: &readback.buffer,
|
|
layout: *layout,
|
|
},
|
|
*size,
|
|
);
|
|
}
|
|
ReadbackSource::Buffer {
|
|
src_start,
|
|
dst_start,
|
|
buffer,
|
|
} => {
|
|
command_encoder.copy_buffer_to_buffer(
|
|
buffer,
|
|
*src_start,
|
|
&readback.buffer,
|
|
*dst_start,
|
|
buffer.size(),
|
|
);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Move requested readbacks to mapped readbacks after commands have been submitted in render system
|
|
fn map_buffers(mut readbacks: ResMut<GpuReadbacks>) {
|
|
let requested = readbacks.requested.drain(..).collect::<Vec<GpuReadback>>();
|
|
for readback in requested {
|
|
let slice = readback.buffer.slice(..);
|
|
let entity = readback.entity;
|
|
let buffer = readback.buffer.clone();
|
|
let tx = readback.tx.clone();
|
|
slice.map_async(wgpu::MapMode::Read, move |res| {
|
|
res.expect("Failed to map buffer");
|
|
let buffer_slice = buffer.slice(..);
|
|
let data = buffer_slice.get_mapped_range();
|
|
let result = Vec::from(&*data);
|
|
drop(data);
|
|
buffer.unmap();
|
|
if let Err(e) = tx.try_send((entity, buffer, result)) {
|
|
warn!("Failed to send readback result: {}", e);
|
|
}
|
|
});
|
|
readbacks.mapped.push(readback);
|
|
}
|
|
}
|
|
|
|
// Utils
|
|
|
|
/// Round up a given value to be a multiple of [`wgpu::COPY_BYTES_PER_ROW_ALIGNMENT`].
|
|
pub(crate) const fn align_byte_size(value: u32) -> u32 {
|
|
RenderDevice::align_copy_bytes_per_row(value as usize) as u32
|
|
}
|
|
|
|
/// Get the size of a image when the size of each row has been rounded up to [`wgpu::COPY_BYTES_PER_ROW_ALIGNMENT`].
|
|
pub(crate) const fn get_aligned_size(extent: Extent3d, pixel_size: u32) -> u32 {
|
|
extent.height * align_byte_size(extent.width * pixel_size) * extent.depth_or_array_layers
|
|
}
|
|
|
|
/// Get a [`TexelCopyBufferLayout`] aligned such that the image can be copied into a buffer.
|
|
pub(crate) fn layout_data(extent: Extent3d, format: TextureFormat) -> TexelCopyBufferLayout {
|
|
TexelCopyBufferLayout {
|
|
bytes_per_row: if extent.height > 1 || extent.depth_or_array_layers > 1 {
|
|
// 1 = 1 row
|
|
Some(get_aligned_size(
|
|
Extent3d {
|
|
width: extent.width,
|
|
height: 1,
|
|
depth_or_array_layers: 1,
|
|
},
|
|
format.pixel_size() as u32,
|
|
))
|
|
} else {
|
|
None
|
|
},
|
|
rows_per_image: if extent.depth_or_array_layers > 1 {
|
|
let (_, block_dimension_y) = format.block_dimensions();
|
|
Some(extent.height / block_dimension_y)
|
|
} else {
|
|
None
|
|
},
|
|
offset: 0,
|
|
}
|
|
}
|