This commit is contained in:
1 parent
f29712d158
commit
3e053a81ab
123 files changed
+31930
-1404
No files matched your search
@@ -0,0 +1,274 @@
|
||||
use crate::{
|
||||
render_resource::*,
|
||||
renderer::{RenderDevice, RenderQueue},
|
||||
texture::{DefaultImageSampler, GpuImage},
|
||||
};
|
||||
use bevy_asset::RenderAssetUsages;
|
||||
use bevy_derive::{Deref, DerefMut};
|
||||
use bevy_ecs::{
|
||||
prelude::{FromWorld, Res, ResMut},
|
||||
resource::Resource,
|
||||
system::SystemParam,
|
||||
};
|
||||
use bevy_image::{BevyDefault, Image, ImageSampler, TextureFormatPixelInfo};
|
||||
use bevy_platform::collections::HashMap;
|
||||
|
||||
/// A [`RenderApp`](crate::RenderApp) resource that contains the default "fallback image",
|
||||
/// which can be used in situations where an image was not explicitly defined. The most common
|
||||
/// use case is [`AsBindGroup`] implementations (such as materials) that support optional textures.
|
||||
///
|
||||
/// Defaults to a 1x1 fully opaque white texture, (1.0, 1.0, 1.0, 1.0) which makes multiplying
|
||||
/// it with other colors a no-op.
|
||||
#[derive(Resource)]
|
||||
pub struct FallbackImage {
|
||||
/// Fallback image for [`TextureViewDimension::D1`].
|
||||
pub d1: GpuImage,
|
||||
/// Fallback image for [`TextureViewDimension::D2`].
|
||||
pub d2: GpuImage,
|
||||
/// Fallback image for [`TextureViewDimension::D2Array`].
|
||||
pub d2_array: GpuImage,
|
||||
/// Fallback image for [`TextureViewDimension::Cube`].
|
||||
pub cube: GpuImage,
|
||||
/// Fallback image for [`TextureViewDimension::CubeArray`].
|
||||
pub cube_array: GpuImage,
|
||||
/// Fallback image for [`TextureViewDimension::D3`].
|
||||
pub d3: GpuImage,
|
||||
}
|
||||
|
||||
impl FallbackImage {
|
||||
/// Returns the appropriate fallback image for the given texture dimension.
|
||||
pub fn get(&self, texture_dimension: TextureViewDimension) -> &GpuImage {
|
||||
match texture_dimension {
|
||||
TextureViewDimension::D1 => &self.d1,
|
||||
TextureViewDimension::D2 => &self.d2,
|
||||
TextureViewDimension::D2Array => &self.d2_array,
|
||||
TextureViewDimension::Cube => &self.cube,
|
||||
TextureViewDimension::CubeArray => &self.cube_array,
|
||||
TextureViewDimension::D3 => &self.d3,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A [`RenderApp`](crate::RenderApp) resource that contains a _zero-filled_ "fallback image",
|
||||
/// which can be used in place of [`FallbackImage`], when a fully transparent or black fallback
|
||||
/// is required instead of fully opaque white.
|
||||
///
|
||||
/// Defaults to a 1x1 fully transparent black texture, (0.0, 0.0, 0.0, 0.0) which makes adding
|
||||
/// or alpha-blending it to other colors a no-op.
|
||||
#[derive(Resource, Deref)]
|
||||
pub struct FallbackImageZero(GpuImage);
|
||||
|
||||
/// A [`RenderApp`](crate::RenderApp) resource that contains a "cubemap fallback image",
|
||||
/// which can be used in situations where an image was not explicitly defined. The most common
|
||||
/// use case is [`AsBindGroup`] implementations (such as materials) that support optional textures.
|
||||
#[derive(Resource, Deref)]
|
||||
pub struct FallbackImageCubemap(GpuImage);
|
||||
|
||||
fn fallback_image_new(
|
||||
render_device: &RenderDevice,
|
||||
render_queue: &RenderQueue,
|
||||
default_sampler: &DefaultImageSampler,
|
||||
format: TextureFormat,
|
||||
dimension: TextureViewDimension,
|
||||
samples: u32,
|
||||
value: u8,
|
||||
) -> GpuImage {
|
||||
// TODO make this configurable per channel
|
||||
|
||||
let extents = Extent3d {
|
||||
width: 1,
|
||||
height: 1,
|
||||
depth_or_array_layers: match dimension {
|
||||
TextureViewDimension::Cube | TextureViewDimension::CubeArray => 6,
|
||||
_ => 1,
|
||||
},
|
||||
};
|
||||
|
||||
// We can't create textures with data when it's a depth texture or when using multiple samples
|
||||
let create_texture_with_data = !format.is_depth_stencil_format() && samples == 1;
|
||||
|
||||
let image_dimension = dimension.compatible_texture_dimension();
|
||||
let mut image = if create_texture_with_data {
|
||||
let data = vec![value; format.pixel_size().unwrap_or(0)];
|
||||
Image::new_fill(
|
||||
extents,
|
||||
image_dimension,
|
||||
&data,
|
||||
format,
|
||||
RenderAssetUsages::RENDER_WORLD,
|
||||
)
|
||||
} else {
|
||||
let mut image = Image::default_uninit();
|
||||
image.texture_descriptor.dimension = TextureDimension::D2;
|
||||
image.texture_descriptor.size = extents;
|
||||
image.texture_descriptor.format = format;
|
||||
image
|
||||
};
|
||||
image.texture_descriptor.sample_count = samples;
|
||||
if image_dimension == TextureDimension::D2 {
|
||||
image.texture_descriptor.usage |= TextureUsages::RENDER_ATTACHMENT;
|
||||
}
|
||||
|
||||
let texture = if create_texture_with_data {
|
||||
render_device.create_texture_with_data(
|
||||
render_queue,
|
||||
&image.texture_descriptor,
|
||||
TextureDataOrder::default(),
|
||||
&image.data.expect("Image has no data"),
|
||||
)
|
||||
} else {
|
||||
render_device.create_texture(&image.texture_descriptor)
|
||||
};
|
||||
|
||||
let texture_view = texture.create_view(&TextureViewDescriptor {
|
||||
dimension: Some(dimension),
|
||||
array_layer_count: Some(extents.depth_or_array_layers),
|
||||
..TextureViewDescriptor::default()
|
||||
});
|
||||
let sampler = match image.sampler {
|
||||
ImageSampler::Default => (**default_sampler).clone(),
|
||||
ImageSampler::Descriptor(ref descriptor) => {
|
||||
render_device.create_sampler(&descriptor.as_wgpu())
|
||||
}
|
||||
};
|
||||
GpuImage {
|
||||
texture,
|
||||
texture_view,
|
||||
texture_format: image.texture_descriptor.format,
|
||||
texture_view_format: image.texture_view_descriptor.and_then(|v| v.format),
|
||||
sampler,
|
||||
size: image.texture_descriptor.size,
|
||||
mip_level_count: image.texture_descriptor.mip_level_count,
|
||||
had_data: true,
|
||||
}
|
||||
}
|
||||
|
||||
impl FromWorld for FallbackImage {
|
||||
fn from_world(world: &mut bevy_ecs::prelude::World) -> Self {
|
||||
let render_device = world.resource::<RenderDevice>();
|
||||
let render_queue = world.resource::<RenderQueue>();
|
||||
let default_sampler = world.resource::<DefaultImageSampler>();
|
||||
Self {
|
||||
d1: fallback_image_new(
|
||||
render_device,
|
||||
render_queue,
|
||||
default_sampler,
|
||||
TextureFormat::bevy_default(),
|
||||
TextureViewDimension::D1,
|
||||
1,
|
||||
255,
|
||||
),
|
||||
d2: fallback_image_new(
|
||||
render_device,
|
||||
render_queue,
|
||||
default_sampler,
|
||||
TextureFormat::bevy_default(),
|
||||
TextureViewDimension::D2,
|
||||
1,
|
||||
255,
|
||||
),
|
||||
d2_array: fallback_image_new(
|
||||
render_device,
|
||||
render_queue,
|
||||
default_sampler,
|
||||
TextureFormat::bevy_default(),
|
||||
TextureViewDimension::D2Array,
|
||||
1,
|
||||
255,
|
||||
),
|
||||
cube: fallback_image_new(
|
||||
render_device,
|
||||
render_queue,
|
||||
default_sampler,
|
||||
TextureFormat::bevy_default(),
|
||||
TextureViewDimension::Cube,
|
||||
1,
|
||||
255,
|
||||
),
|
||||
cube_array: fallback_image_new(
|
||||
render_device,
|
||||
render_queue,
|
||||
default_sampler,
|
||||
TextureFormat::bevy_default(),
|
||||
TextureViewDimension::CubeArray,
|
||||
1,
|
||||
255,
|
||||
),
|
||||
d3: fallback_image_new(
|
||||
render_device,
|
||||
render_queue,
|
||||
default_sampler,
|
||||
TextureFormat::bevy_default(),
|
||||
TextureViewDimension::D3,
|
||||
1,
|
||||
255,
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl FromWorld for FallbackImageZero {
|
||||
fn from_world(world: &mut bevy_ecs::prelude::World) -> Self {
|
||||
let render_device = world.resource::<RenderDevice>();
|
||||
let render_queue = world.resource::<RenderQueue>();
|
||||
let default_sampler = world.resource::<DefaultImageSampler>();
|
||||
Self(fallback_image_new(
|
||||
render_device,
|
||||
render_queue,
|
||||
default_sampler,
|
||||
TextureFormat::bevy_default(),
|
||||
TextureViewDimension::D2,
|
||||
1,
|
||||
0,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
impl FromWorld for FallbackImageCubemap {
|
||||
fn from_world(world: &mut bevy_ecs::prelude::World) -> Self {
|
||||
let render_device = world.resource::<RenderDevice>();
|
||||
let render_queue = world.resource::<RenderQueue>();
|
||||
let default_sampler = world.resource::<DefaultImageSampler>();
|
||||
Self(fallback_image_new(
|
||||
render_device,
|
||||
render_queue,
|
||||
default_sampler,
|
||||
TextureFormat::bevy_default(),
|
||||
TextureViewDimension::Cube,
|
||||
1,
|
||||
255,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
/// A Cache of fallback textures that uses the sample count and `TextureFormat` as a key
|
||||
///
|
||||
/// # WARNING
|
||||
/// Images using MSAA with sample count > 1 are not initialized with data, therefore,
|
||||
/// you shouldn't sample them before writing data to them first.
|
||||
#[derive(Resource, Deref, DerefMut, Default)]
|
||||
pub struct FallbackImageFormatMsaaCache(HashMap<(u32, TextureFormat), GpuImage>);
|
||||
|
||||
#[derive(SystemParam)]
|
||||
pub struct FallbackImageMsaa<'w> {
|
||||
cache: ResMut<'w, FallbackImageFormatMsaaCache>,
|
||||
render_device: Res<'w, RenderDevice>,
|
||||
render_queue: Res<'w, RenderQueue>,
|
||||
default_sampler: Res<'w, DefaultImageSampler>,
|
||||
}
|
||||
|
||||
impl<'w> FallbackImageMsaa<'w> {
|
||||
pub fn image_for_samplecount(&mut self, sample_count: u32, format: TextureFormat) -> &GpuImage {
|
||||
self.cache.entry((sample_count, format)).or_insert_with(|| {
|
||||
fallback_image_new(
|
||||
&self.render_device,
|
||||
&self.render_queue,
|
||||
&self.default_sampler,
|
||||
format,
|
||||
TextureViewDimension::D2,
|
||||
sample_count,
|
||||
255,
|
||||
)
|
||||
})
|
||||
}
|
||||
}
|
||||
+153
@@ -0,0 +1,153 @@
|
||||
use crate::{
|
||||
render_asset::{AssetExtractionError, PrepareAssetError, RenderAsset},
|
||||
render_resource::{DefaultImageSampler, Sampler, Texture, TextureView},
|
||||
renderer::{RenderDevice, RenderQueue},
|
||||
};
|
||||
use bevy_asset::{AssetId, RenderAssetUsages};
|
||||
use bevy_ecs::system::{lifetimeless::SRes, SystemParamItem};
|
||||
use bevy_image::{Image, ImageSampler};
|
||||
use bevy_math::{AspectRatio, UVec2};
|
||||
use tracing::warn;
|
||||
use wgpu::{Extent3d, TextureFormat, TextureViewDescriptor};
|
||||
|
||||
/// The GPU-representation of an [`Image`].
|
||||
/// Consists of the [`Texture`], its [`TextureView`] and the corresponding [`Sampler`], and the texture's size.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct GpuImage {
|
||||
pub texture: Texture,
|
||||
pub texture_view: TextureView,
|
||||
pub texture_format: TextureFormat,
|
||||
pub texture_view_format: Option<TextureFormat>,
|
||||
pub sampler: Sampler,
|
||||
pub size: Extent3d,
|
||||
pub mip_level_count: u32,
|
||||
pub had_data: bool,
|
||||
}
|
||||
|
||||
impl RenderAsset for GpuImage {
|
||||
type SourceAsset = Image;
|
||||
type Param = (
|
||||
SRes<RenderDevice>,
|
||||
SRes<RenderQueue>,
|
||||
SRes<DefaultImageSampler>,
|
||||
);
|
||||
|
||||
#[inline]
|
||||
fn asset_usage(image: &Self::SourceAsset) -> RenderAssetUsages {
|
||||
image.asset_usage
|
||||
}
|
||||
|
||||
fn take_gpu_data(
|
||||
source: &mut Self::SourceAsset,
|
||||
previous_gpu_asset: Option<&Self>,
|
||||
) -> Result<Self::SourceAsset, AssetExtractionError> {
|
||||
let data = source.data.take();
|
||||
|
||||
// check if this image originally had data and no longer does, that implies it
|
||||
// has already been extracted
|
||||
let valid_upload = data.is_some() || previous_gpu_asset.is_none_or(|prev| !prev.had_data);
|
||||
|
||||
valid_upload
|
||||
.then(|| Self::SourceAsset {
|
||||
data,
|
||||
..source.clone()
|
||||
})
|
||||
.ok_or(AssetExtractionError::AlreadyExtracted)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn byte_len(image: &Self::SourceAsset) -> Option<usize> {
|
||||
image.data.as_ref().map(Vec::len)
|
||||
}
|
||||
|
||||
/// Converts the extracted image into a [`GpuImage`].
|
||||
fn prepare_asset(
|
||||
image: Self::SourceAsset,
|
||||
_: AssetId<Self::SourceAsset>,
|
||||
(render_device, render_queue, default_sampler): &mut SystemParamItem<Self::Param>,
|
||||
previous_asset: Option<&Self>,
|
||||
) -> Result<Self, PrepareAssetError<Self::SourceAsset>> {
|
||||
let had_data = image.data.is_some();
|
||||
let texture = if let Some(ref data) = image.data {
|
||||
render_device.create_texture_with_data(
|
||||
render_queue,
|
||||
&image.texture_descriptor,
|
||||
image.data_order,
|
||||
data,
|
||||
)
|
||||
} else {
|
||||
let new_texture = render_device.create_texture(&image.texture_descriptor);
|
||||
if image.copy_on_resize {
|
||||
if let Some(previous) = previous_asset {
|
||||
let mut command_encoder =
|
||||
render_device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
|
||||
label: Some("copy_image_on_resize"),
|
||||
});
|
||||
let copy_size = Extent3d {
|
||||
width: image.texture_descriptor.size.width.min(previous.size.width),
|
||||
height: image
|
||||
.texture_descriptor
|
||||
.size
|
||||
.height
|
||||
.min(previous.size.height),
|
||||
depth_or_array_layers: image
|
||||
.texture_descriptor
|
||||
.size
|
||||
.depth_or_array_layers
|
||||
.min(previous.size.depth_or_array_layers),
|
||||
};
|
||||
|
||||
command_encoder.copy_texture_to_texture(
|
||||
previous.texture.as_image_copy(),
|
||||
new_texture.as_image_copy(),
|
||||
copy_size,
|
||||
);
|
||||
render_queue.submit([command_encoder.finish()]);
|
||||
} else {
|
||||
warn!("No previous asset to copy from for image: {:?}", image);
|
||||
}
|
||||
}
|
||||
new_texture
|
||||
};
|
||||
|
||||
let texture_view = texture.create_view(
|
||||
image
|
||||
.texture_view_descriptor
|
||||
.as_ref()
|
||||
.unwrap_or(&TextureViewDescriptor::default()),
|
||||
);
|
||||
let sampler = match image.sampler {
|
||||
ImageSampler::Default => (***default_sampler).clone(),
|
||||
ImageSampler::Descriptor(descriptor) => {
|
||||
render_device.create_sampler(&descriptor.as_wgpu())
|
||||
}
|
||||
};
|
||||
|
||||
Ok(GpuImage {
|
||||
texture,
|
||||
texture_view,
|
||||
texture_format: image.texture_descriptor.format,
|
||||
texture_view_format: image.texture_view_descriptor.and_then(|v| v.format),
|
||||
sampler,
|
||||
size: image.texture_descriptor.size,
|
||||
mip_level_count: image.texture_descriptor.mip_level_count,
|
||||
had_data,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl GpuImage {
|
||||
/// Returns the aspect ratio (width / height) of a 2D image.
|
||||
#[inline]
|
||||
pub fn aspect_ratio(&self) -> AspectRatio {
|
||||
AspectRatio::try_from_pixels(self.size.width, self.size.height).expect(
|
||||
"Failed to calculate aspect ratio: Image dimensions must be positive, non-zero values",
|
||||
)
|
||||
}
|
||||
|
||||
/// Returns the size of a 2D image.
|
||||
#[inline]
|
||||
pub fn size_2d(&self) -> UVec2 {
|
||||
UVec2::new(self.size.width, self.size.height)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
use bevy_camera::ManualTextureViewHandle;
|
||||
use bevy_ecs::{prelude::Component, resource::Resource};
|
||||
use bevy_image::BevyDefault;
|
||||
use bevy_math::UVec2;
|
||||
use bevy_platform::collections::HashMap;
|
||||
use bevy_render_macros::ExtractResource;
|
||||
use wgpu::TextureFormat;
|
||||
|
||||
use crate::render_resource::TextureView;
|
||||
|
||||
/// A manually managed [`TextureView`] for use as a [`bevy_camera::RenderTarget`].
|
||||
#[derive(Debug, Clone, Component)]
|
||||
pub struct ManualTextureView {
|
||||
pub texture_view: TextureView,
|
||||
pub size: UVec2,
|
||||
pub view_format: TextureFormat,
|
||||
}
|
||||
|
||||
impl ManualTextureView {
|
||||
pub fn with_default_format(texture_view: TextureView, size: UVec2) -> Self {
|
||||
Self {
|
||||
texture_view,
|
||||
size,
|
||||
view_format: TextureFormat::bevy_default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Resource that stores manually managed [`ManualTextureView`]s for use as a [`RenderTarget`](bevy_camera::RenderTarget).
|
||||
/// This type dereferences to a `HashMap<ManualTextureViewHandle, ManualTextureView>`.
|
||||
/// To add a new texture view, pick a new [`ManualTextureViewHandle`] and insert it into the map.
|
||||
/// Then, to render to the view, set a [`Camera`](bevy_camera::Camera)s `target` to `RenderTarget::TextureView(handle)`.
|
||||
/// ```ignore
|
||||
/// # use bevy_ecs::prelude::*;
|
||||
/// # let mut world = World::default();
|
||||
/// # world.insert_resource(ManualTextureViews::default());
|
||||
/// # let texture_view = todo!();
|
||||
/// let manual_views = world.resource_mut::<ManualTextureViews>();
|
||||
/// let manual_view = ManualTextureView::with_default_format(texture_view, UVec2::new(1024, 1024));
|
||||
///
|
||||
/// // Choose an unused handle value; it's likely only you are inserting manual views.
|
||||
/// const MANUAL_VIEW_HANDLE: ManualTextureViewHandle = ManualTextureViewHandle::new(42);
|
||||
/// manual_views.insert(MANUAL_VIEW_HANDLE, manual_view);
|
||||
///
|
||||
/// // Now you can spawn a Camera that renders to the manual view:
|
||||
/// # use bevy_camera::{Camera, RenderTarget};
|
||||
/// world.spawn(Camera {
|
||||
/// target: RenderTarget::TextureView(MANUAL_VIEW_HANDLE),
|
||||
/// ..Default::default()
|
||||
/// });
|
||||
/// ```
|
||||
/// Bevy will then use the `ManualTextureViews` resource to find your texture view and render to it.
|
||||
#[derive(Default, Clone, Resource, ExtractResource)]
|
||||
pub struct ManualTextureViews(HashMap<ManualTextureViewHandle, ManualTextureView>);
|
||||
|
||||
impl core::ops::Deref for ManualTextureViews {
|
||||
type Target = HashMap<ManualTextureViewHandle, ManualTextureView>;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl core::ops::DerefMut for ManualTextureViews {
|
||||
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||
&mut self.0
|
||||
}
|
||||
}
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
mod fallback_image;
|
||||
mod gpu_image;
|
||||
mod manual_texture_view;
|
||||
mod texture_attachment;
|
||||
mod texture_cache;
|
||||
|
||||
pub use crate::render_resource::DefaultImageSampler;
|
||||
use bevy_image::{CompressedImageFormatSupport, CompressedImageFormats, ImageLoader, ImagePlugin};
|
||||
pub use fallback_image::*;
|
||||
pub use gpu_image::*;
|
||||
pub use manual_texture_view::*;
|
||||
pub use texture_attachment::*;
|
||||
pub use texture_cache::*;
|
||||
|
||||
use crate::{
|
||||
extract_resource::ExtractResourcePlugin, render_asset::RenderAssetPlugin,
|
||||
renderer::RenderDevice, Render, RenderApp, RenderSystems,
|
||||
};
|
||||
use bevy_app::{App, Plugin};
|
||||
use bevy_asset::AssetApp;
|
||||
use bevy_ecs::prelude::*;
|
||||
use tracing::warn;
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct TexturePlugin;
|
||||
|
||||
impl Plugin for TexturePlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.add_plugins((
|
||||
RenderAssetPlugin::<GpuImage>::default(),
|
||||
ExtractResourcePlugin::<ManualTextureViews>::default(),
|
||||
))
|
||||
.init_resource::<ManualTextureViews>();
|
||||
if let Some(render_app) = app.get_sub_app_mut(RenderApp) {
|
||||
render_app.init_resource::<TextureCache>().add_systems(
|
||||
Render,
|
||||
update_texture_cache_system.in_set(RenderSystems::Cleanup),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn finish(&self, app: &mut App) {
|
||||
if !ImageLoader::SUPPORTED_FORMATS.is_empty() {
|
||||
let supported_compressed_formats = if let Some(resource) =
|
||||
app.world().get_resource::<CompressedImageFormatSupport>()
|
||||
{
|
||||
resource.0
|
||||
} else {
|
||||
warn!("CompressedImageFormatSupport resource not found. It should either be initialized in finish() of \
|
||||
RenderPlugin, or manually if not using the RenderPlugin or the WGPU backend.");
|
||||
CompressedImageFormats::NONE
|
||||
};
|
||||
|
||||
app.register_asset_loader(ImageLoader::new(supported_compressed_formats));
|
||||
}
|
||||
let default_sampler = app.get_added_plugins::<ImagePlugin>()[0]
|
||||
.default_sampler
|
||||
.clone();
|
||||
|
||||
if let Some(render_app) = app.get_sub_app_mut(RenderApp) {
|
||||
let default_sampler = {
|
||||
let device = render_app.world().resource::<RenderDevice>();
|
||||
device.create_sampler(&default_sampler.as_wgpu())
|
||||
};
|
||||
render_app
|
||||
.insert_resource(DefaultImageSampler(default_sampler))
|
||||
.init_resource::<FallbackImage>()
|
||||
.init_resource::<FallbackImageZero>()
|
||||
.init_resource::<FallbackImageCubemap>()
|
||||
.init_resource::<FallbackImageFormatMsaaCache>();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
use super::CachedTexture;
|
||||
use crate::render_resource::{TextureFormat, TextureView};
|
||||
use alloc::sync::Arc;
|
||||
use bevy_color::LinearRgba;
|
||||
use core::sync::atomic::{AtomicBool, Ordering};
|
||||
use wgpu::{
|
||||
LoadOp, Operations, RenderPassColorAttachment, RenderPassDepthStencilAttachment, StoreOp,
|
||||
};
|
||||
|
||||
/// A wrapper for a [`CachedTexture`] that is used as a [`RenderPassColorAttachment`].
|
||||
#[derive(Clone)]
|
||||
pub struct ColorAttachment {
|
||||
pub texture: CachedTexture,
|
||||
pub resolve_target: Option<CachedTexture>,
|
||||
pub previous_frame_texture: Option<CachedTexture>,
|
||||
clear_color: Option<LinearRgba>,
|
||||
is_first_call: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
impl ColorAttachment {
|
||||
pub fn new(
|
||||
texture: CachedTexture,
|
||||
resolve_target: Option<CachedTexture>,
|
||||
previous_frame_texture: Option<CachedTexture>,
|
||||
clear_color: Option<LinearRgba>,
|
||||
) -> Self {
|
||||
Self {
|
||||
texture,
|
||||
resolve_target,
|
||||
previous_frame_texture,
|
||||
clear_color,
|
||||
is_first_call: Arc::new(AtomicBool::new(true)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Get this texture view as an attachment. The attachment will be cleared with a value of
|
||||
/// `clear_color` if this is the first time calling this function, otherwise it will be loaded.
|
||||
///
|
||||
/// The returned attachment will always have writing enabled (`store: StoreOp::Load`).
|
||||
pub fn get_attachment(&self) -> RenderPassColorAttachment<'_> {
|
||||
if let Some(resolve_target) = self.resolve_target.as_ref() {
|
||||
let first_call = self.is_first_call.fetch_and(false, Ordering::SeqCst);
|
||||
|
||||
RenderPassColorAttachment {
|
||||
view: &resolve_target.default_view,
|
||||
depth_slice: None,
|
||||
resolve_target: Some(&self.texture.default_view),
|
||||
ops: Operations {
|
||||
load: match (self.clear_color, first_call) {
|
||||
(Some(clear_color), true) => LoadOp::Clear(clear_color.into()),
|
||||
(None, _) | (Some(_), false) => LoadOp::Load,
|
||||
},
|
||||
store: StoreOp::Store,
|
||||
},
|
||||
}
|
||||
} else {
|
||||
self.get_unsampled_attachment()
|
||||
}
|
||||
}
|
||||
|
||||
/// Get this texture view as an attachment, without the resolve target. The attachment will be cleared with
|
||||
/// a value of `clear_color` if this is the first time calling this function, otherwise it will be loaded.
|
||||
///
|
||||
/// The returned attachment will always have writing enabled (`store: StoreOp::Load`).
|
||||
pub fn get_unsampled_attachment(&self) -> RenderPassColorAttachment<'_> {
|
||||
let first_call = self.is_first_call.fetch_and(false, Ordering::SeqCst);
|
||||
|
||||
RenderPassColorAttachment {
|
||||
view: &self.texture.default_view,
|
||||
depth_slice: None,
|
||||
resolve_target: None,
|
||||
ops: Operations {
|
||||
load: match (self.clear_color, first_call) {
|
||||
(Some(clear_color), true) => LoadOp::Clear(clear_color.into()),
|
||||
(None, _) | (Some(_), false) => LoadOp::Load,
|
||||
},
|
||||
store: StoreOp::Store,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn mark_as_cleared(&self) {
|
||||
self.is_first_call.store(false, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
|
||||
/// A wrapper for a [`TextureView`] that is used as a depth-only [`RenderPassDepthStencilAttachment`].
|
||||
#[derive(Clone)]
|
||||
pub struct DepthAttachment {
|
||||
pub view: TextureView,
|
||||
clear_value: Option<f32>,
|
||||
is_first_call: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
impl DepthAttachment {
|
||||
pub fn new(view: TextureView, clear_value: Option<f32>) -> Self {
|
||||
Self {
|
||||
view,
|
||||
clear_value,
|
||||
is_first_call: Arc::new(AtomicBool::new(clear_value.is_some())),
|
||||
}
|
||||
}
|
||||
|
||||
/// Get this texture view as an attachment. The attachment will be cleared with a value of
|
||||
/// `clear_value` if this is the first time calling this function with `store` == [`StoreOp::Store`],
|
||||
/// and a clear value was provided, otherwise it will be loaded.
|
||||
pub fn get_attachment(&self, store: StoreOp) -> RenderPassDepthStencilAttachment<'_> {
|
||||
let first_call = self
|
||||
.is_first_call
|
||||
.fetch_and(store != StoreOp::Store, Ordering::SeqCst);
|
||||
|
||||
RenderPassDepthStencilAttachment {
|
||||
view: &self.view,
|
||||
depth_ops: Some(Operations {
|
||||
load: if first_call {
|
||||
// If first_call is true, then a clear value will always have been provided in the constructor
|
||||
LoadOp::Clear(self.clear_value.unwrap())
|
||||
} else {
|
||||
LoadOp::Load
|
||||
},
|
||||
store,
|
||||
}),
|
||||
stencil_ops: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A wrapper for a [`TextureView`] that is used as a [`RenderPassColorAttachment`] for a view
|
||||
/// target's final output texture.
|
||||
#[derive(Clone)]
|
||||
pub struct OutputColorAttachment {
|
||||
pub view: TextureView,
|
||||
pub view_format: TextureFormat,
|
||||
is_first_call: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
impl OutputColorAttachment {
|
||||
pub fn new(view: TextureView, view_format: TextureFormat) -> Self {
|
||||
Self {
|
||||
view,
|
||||
view_format,
|
||||
is_first_call: Arc::new(AtomicBool::new(true)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Get this texture view as an attachment. The attachment will be cleared with a value of
|
||||
/// the provided `clear_color` if this is the first time calling this function, otherwise it
|
||||
/// will be loaded.
|
||||
pub fn get_attachment(&self, clear_color: Option<LinearRgba>) -> RenderPassColorAttachment<'_> {
|
||||
let first_call = self.is_first_call.fetch_and(false, Ordering::SeqCst);
|
||||
|
||||
RenderPassColorAttachment {
|
||||
view: &self.view,
|
||||
depth_slice: None,
|
||||
resolve_target: None,
|
||||
ops: Operations {
|
||||
load: match (clear_color, first_call) {
|
||||
(Some(clear_color), true) => LoadOp::Clear(clear_color.into()),
|
||||
(None, _) | (Some(_), false) => LoadOp::Load,
|
||||
},
|
||||
store: StoreOp::Store,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns `true` if this attachment has been written to by a render pass.
|
||||
// we re-use is_first_call atomic to track usage, which assumes that calls to get_attachment
|
||||
// are always consumed by a render pass that writes to the attachment
|
||||
pub fn needs_present(&self) -> bool {
|
||||
!self.is_first_call.load(Ordering::SeqCst)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
use crate::{
|
||||
render_resource::{Texture, TextureView},
|
||||
renderer::RenderDevice,
|
||||
};
|
||||
use bevy_ecs::{prelude::ResMut, resource::Resource};
|
||||
use bevy_platform::collections::{hash_map::Entry, HashMap};
|
||||
use wgpu::{TextureDescriptor, TextureViewDescriptor};
|
||||
|
||||
/// The internal representation of a [`CachedTexture`] used to track whether it was recently used
|
||||
/// and is currently taken.
|
||||
struct CachedTextureMeta {
|
||||
texture: Texture,
|
||||
default_view: TextureView,
|
||||
taken: bool,
|
||||
frames_since_last_use: usize,
|
||||
}
|
||||
|
||||
/// A cached GPU [`Texture`] with corresponding [`TextureView`].
|
||||
///
|
||||
/// This is useful for textures that are created repeatedly (each frame) in the rendering process
|
||||
/// to reduce the amount of GPU memory allocations.
|
||||
#[derive(Clone)]
|
||||
pub struct CachedTexture {
|
||||
pub texture: Texture,
|
||||
pub default_view: TextureView,
|
||||
}
|
||||
|
||||
/// This resource caches textures that are created repeatedly in the rendering process and
|
||||
/// are only required for one frame.
|
||||
#[derive(Resource, Default)]
|
||||
pub struct TextureCache {
|
||||
textures: HashMap<TextureDescriptor<'static>, Vec<CachedTextureMeta>>,
|
||||
}
|
||||
|
||||
impl TextureCache {
|
||||
/// Retrieves a texture that matches the `descriptor`. If no matching one is found a new
|
||||
/// [`CachedTexture`] is created.
|
||||
pub fn get(
|
||||
&mut self,
|
||||
render_device: &RenderDevice,
|
||||
descriptor: TextureDescriptor<'static>,
|
||||
) -> CachedTexture {
|
||||
match self.textures.entry(descriptor) {
|
||||
Entry::Occupied(mut entry) => {
|
||||
for texture in entry.get_mut().iter_mut() {
|
||||
if !texture.taken {
|
||||
texture.frames_since_last_use = 0;
|
||||
texture.taken = true;
|
||||
return CachedTexture {
|
||||
texture: texture.texture.clone(),
|
||||
default_view: texture.default_view.clone(),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
let texture = render_device.create_texture(&entry.key().clone());
|
||||
let default_view = texture.create_view(&TextureViewDescriptor::default());
|
||||
entry.get_mut().push(CachedTextureMeta {
|
||||
texture: texture.clone(),
|
||||
default_view: default_view.clone(),
|
||||
frames_since_last_use: 0,
|
||||
taken: true,
|
||||
});
|
||||
CachedTexture {
|
||||
texture,
|
||||
default_view,
|
||||
}
|
||||
}
|
||||
Entry::Vacant(entry) => {
|
||||
let texture = render_device.create_texture(entry.key());
|
||||
let default_view = texture.create_view(&TextureViewDescriptor::default());
|
||||
entry.insert(vec![CachedTextureMeta {
|
||||
texture: texture.clone(),
|
||||
default_view: default_view.clone(),
|
||||
taken: true,
|
||||
frames_since_last_use: 0,
|
||||
}]);
|
||||
CachedTexture {
|
||||
texture,
|
||||
default_view,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns `true` if the texture cache contains no textures.
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.textures.is_empty()
|
||||
}
|
||||
|
||||
/// Updates the cache and only retains recently used textures.
|
||||
pub fn update(&mut self) {
|
||||
self.textures.retain(|_, textures| {
|
||||
for texture in textures.iter_mut() {
|
||||
texture.frames_since_last_use += 1;
|
||||
texture.taken = false;
|
||||
}
|
||||
|
||||
textures.retain(|texture| texture.frames_since_last_use < 3);
|
||||
!textures.is_empty()
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Updates the [`TextureCache`] to only retains recently used textures.
|
||||
pub fn update_texture_cache_system(mut texture_cache: ResMut<TextureCache>) {
|
||||
texture_cache.update();
|
||||
}
|
||||
Reference in new issue
Block a user