2022-03-15 22:26:46 +00:00
|
|
|
#[cfg(feature = "basis-universal")]
|
|
|
|
use super::basis::*;
|
|
|
|
#[cfg(feature = "dds")]
|
|
|
|
use super::dds::*;
|
|
|
|
#[cfg(feature = "ktx2")]
|
|
|
|
use super::ktx2::*;
|
|
|
|
|
2021-06-25 03:04:28 +00:00
|
|
|
use crate::{
|
Modular Rendering (#2831)
This changes how render logic is composed to make it much more modular. Previously, all extraction logic was centralized for a given "type" of rendered thing. For example, we extracted meshes into a vector of ExtractedMesh, which contained the mesh and material asset handles, the transform, etc. We looked up bindings for "drawn things" using their index in the `Vec<ExtractedMesh>`. This worked fine for built in rendering, but made it hard to reuse logic for "custom" rendering. It also prevented us from reusing things like "extracted transforms" across contexts.
To make rendering more modular, I made a number of changes:
* Entities now drive rendering:
* We extract "render components" from "app components" and store them _on_ entities. No more centralized uber lists! We now have true "ECS-driven rendering"
* To make this perform well, I implemented #2673 in upstream Bevy for fast batch insertions into specific entities. This was merged into the `pipelined-rendering` branch here: #2815
* Reworked the `Draw` abstraction:
* Generic `PhaseItems`: each draw phase can define its own type of "rendered thing", which can define its own "sort key"
* Ported the 2d, 3d, and shadow phases to the new PhaseItem impl (currently Transparent2d, Transparent3d, and Shadow PhaseItems)
* `Draw` trait and and `DrawFunctions` are now generic on PhaseItem
* Modular / Ergonomic `DrawFunctions` via `RenderCommands`
* RenderCommand is a trait that runs an ECS query and produces one or more RenderPass calls. Types implementing this trait can be composed to create a final DrawFunction. For example the DrawPbr DrawFunction is created from the following DrawCommand tuple. Const generics are used to set specific bind group locations:
```rust
pub type DrawPbr = (
SetPbrPipeline,
SetMeshViewBindGroup<0>,
SetStandardMaterialBindGroup<1>,
SetTransformBindGroup<2>,
DrawMesh,
);
```
* The new `custom_shader_pipelined` example illustrates how the commands above can be reused to create a custom draw function:
```rust
type DrawCustom = (
SetCustomMaterialPipeline,
SetMeshViewBindGroup<0>,
SetTransformBindGroup<2>,
DrawMesh,
);
```
* ExtractComponentPlugin and UniformComponentPlugin:
* Simple, standardized ways to easily extract individual components and write them to GPU buffers
* Ported PBR and Sprite rendering to the new primitives above.
* Removed staging buffer from UniformVec in favor of direct Queue usage
* Makes UniformVec much easier to use and more ergonomic. Completely removes the need for custom render graph nodes in these contexts (see the PbrNode and view Node removals and the much simpler call patterns in the relevant Prepare systems).
* Added a many_cubes_pipelined example to benchmark baseline 3d rendering performance and ensure there were no major regressions during this port. Avoiding regressions was challenging given that the old approach of extracting into centralized vectors is basically the "optimal" approach. However thanks to a various ECS optimizations and render logic rephrasing, we pretty much break even on this benchmark!
* Lifetimeless SystemParams: this will be a bit divisive, but as we continue to embrace "trait driven systems" (ex: ExtractComponentPlugin, UniformComponentPlugin, DrawCommand), the ergonomics of `(Query<'static, 'static, (&'static A, &'static B, &'static)>, Res<'static, C>)` were getting very hard to bear. As a compromise, I added "static type aliases" for the relevant SystemParams. The previous example can now be expressed like this: `(SQuery<(Read<A>, Read<B>)>, SRes<C>)`. If anyone has better ideas / conflicting opinions, please let me know!
* RunSystem trait: a way to define Systems via a trait with a SystemParam associated type. This is used to implement the various plugins mentioned above. I also added SystemParamItem and QueryItem type aliases to make "trait stye" ecs interactions nicer on the eyes (and fingers).
* RenderAsset retrying: ensures that render assets are only created when they are "ready" and allows us to create bind groups directly inside render assets (which significantly simplified the StandardMaterial code). I think ultimately we should swap this out on "asset dependency" events to wait for dependencies to load, but this will require significant asset system changes.
* Updated some built in shaders to account for missing MeshUniform fields
2021-09-23 06:16:11 +00:00
|
|
|
render_asset::{PrepareAssetError, RenderAsset},
|
2021-06-25 03:04:28 +00:00
|
|
|
render_resource::{Sampler, Texture, TextureView},
|
|
|
|
renderer::{RenderDevice, RenderQueue},
|
2021-09-16 22:50:21 +00:00
|
|
|
texture::BevyDefault,
|
2021-06-25 03:04:28 +00:00
|
|
|
};
|
2021-12-07 01:13:55 +00:00
|
|
|
use bevy_asset::HandleUntyped;
|
2022-06-11 09:13:37 +00:00
|
|
|
use bevy_derive::{Deref, DerefMut};
|
Make `Resource` trait opt-in, requiring `#[derive(Resource)]` V2 (#5577)
*This PR description is an edited copy of #5007, written by @alice-i-cecile.*
# Objective
Follow-up to https://github.com/bevyengine/bevy/pull/2254. The `Resource` trait currently has a blanket implementation for all types that meet its bounds.
While ergonomic, this results in several drawbacks:
* it is possible to make confusing, silent mistakes such as inserting a function pointer (Foo) rather than a value (Foo::Bar) as a resource
* it is challenging to discover if a type is intended to be used as a resource
* we cannot later add customization options (see the [RFC](https://github.com/bevyengine/rfcs/blob/main/rfcs/27-derive-component.md) for the equivalent choice for Component).
* dependencies can use the same Rust type as a resource in invisibly conflicting ways
* raw Rust types used as resources cannot preserve privacy appropriately, as anyone able to access that type can read and write to internal values
* we cannot capture a definitive list of possible resources to display to users in an editor
## Notes to reviewers
* Review this commit-by-commit; there's effectively no back-tracking and there's a lot of churn in some of these commits.
*ira: My commits are not as well organized :')*
* I've relaxed the bound on Local to Send + Sync + 'static: I don't think these concerns apply there, so this can keep things simple. Storing e.g. a u32 in a Local is fine, because there's a variable name attached explaining what it does.
* I think this is a bad place for the Resource trait to live, but I've left it in place to make reviewing easier. IMO that's best tackled with https://github.com/bevyengine/bevy/issues/4981.
## Changelog
`Resource` is no longer automatically implemented for all matching types. Instead, use the new `#[derive(Resource)]` macro.
## Migration Guide
Add `#[derive(Resource)]` to all types you are using as a resource.
If you are using a third party type as a resource, wrap it in a tuple struct to bypass orphan rules. Consider deriving `Deref` and `DerefMut` to improve ergonomics.
`ClearColor` no longer implements `Component`. Using `ClearColor` as a component in 0.8 did nothing.
Use the `ClearColorConfig` in the `Camera3d` and `Camera2d` components instead.
Co-authored-by: Alice <alice.i.cecile@gmail.com>
Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
Co-authored-by: devil-ira <justthecooldude@gmail.com>
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2022-08-08 21:36:35 +00:00
|
|
|
use bevy_ecs::system::{lifetimeless::SRes, Resource, SystemParamItem};
|
2022-04-25 13:54:46 +00:00
|
|
|
use bevy_math::Vec2;
|
add `ReflectAsset` and `ReflectHandle` (#5923)
# Objective
![image](https://user-images.githubusercontent.com/22177966/189350194-639a0211-e984-4f73-ae62-0ede44891eb9.png)
^ enable this
Concretely, I need to
- list all handle ids for an asset type
- fetch the asset as `dyn Reflect`, given a `HandleUntyped`
- when encountering a `Handle<T>`, find out what asset type that handle refers to (`T`'s type id) and turn the handle into a `HandleUntyped`
## Solution
- add `ReflectAsset` type containing function pointers for working with assets
```rust
pub struct ReflectAsset {
type_uuid: Uuid,
assets_resource_type_id: TypeId, // TypeId of the `Assets<T>` resource
get: fn(&World, HandleUntyped) -> Option<&dyn Reflect>,
get_mut: fn(&mut World, HandleUntyped) -> Option<&mut dyn Reflect>,
get_unchecked_mut: unsafe fn(&World, HandleUntyped) -> Option<&mut dyn Reflect>,
add: fn(&mut World, &dyn Reflect) -> HandleUntyped,
set: fn(&mut World, HandleUntyped, &dyn Reflect) -> HandleUntyped,
len: fn(&World) -> usize,
ids: for<'w> fn(&'w World) -> Box<dyn Iterator<Item = HandleId> + 'w>,
remove: fn(&mut World, HandleUntyped) -> Option<Box<dyn Reflect>>,
}
```
- add `ReflectHandle` type relating the handle back to the asset type and providing a way to create a `HandleUntyped`
```rust
pub struct ReflectHandle {
type_uuid: Uuid,
asset_type_id: TypeId,
downcast_handle_untyped: fn(&dyn Any) -> Option<HandleUntyped>,
}
```
- add the corresponding `FromType` impls
- add a function `app.register_asset_reflect` which is supposed to be called after `.add_asset` and registers `ReflectAsset` and `ReflectHandle` in the type registry
---
## Changelog
- add `ReflectAsset` and `ReflectHandle` types, which allow code to use reflection to manipulate arbitrary assets without knowing their types at compile time
2022-10-28 20:42:33 +00:00
|
|
|
use bevy_reflect::{FromReflect, Reflect, TypeUuid};
|
2023-02-19 20:38:13 +00:00
|
|
|
|
2022-06-11 09:13:37 +00:00
|
|
|
use std::hash::Hash;
|
2021-04-11 20:13:07 +00:00
|
|
|
use thiserror::Error;
|
2022-12-05 23:39:42 +00:00
|
|
|
use wgpu::{Extent3d, TextureDimension, TextureFormat, TextureViewDescriptor};
|
2021-04-11 20:13:07 +00:00
|
|
|
|
|
|
|
pub const TEXTURE_ASSET_INDEX: u64 = 0;
|
|
|
|
pub const SAMPLER_ASSET_INDEX: u64 = 1;
|
2021-12-07 01:13:55 +00:00
|
|
|
pub const DEFAULT_IMAGE_HANDLE: HandleUntyped =
|
|
|
|
HandleUntyped::weak_from_u64(Image::TYPE_UUID, 13148262314052771789);
|
2021-04-11 20:13:07 +00:00
|
|
|
|
2022-03-15 22:26:46 +00:00
|
|
|
#[derive(Debug)]
|
|
|
|
pub enum ImageFormat {
|
|
|
|
Avif,
|
|
|
|
Basis,
|
|
|
|
Bmp,
|
|
|
|
Dds,
|
|
|
|
Farbfeld,
|
|
|
|
Gif,
|
2023-02-19 20:38:13 +00:00
|
|
|
OpenExr,
|
2022-03-15 22:26:46 +00:00
|
|
|
Hdr,
|
|
|
|
Ico,
|
|
|
|
Jpeg,
|
|
|
|
Ktx2,
|
|
|
|
Png,
|
|
|
|
Pnm,
|
|
|
|
Tga,
|
|
|
|
Tiff,
|
|
|
|
WebP,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl ImageFormat {
|
|
|
|
pub fn from_mime_type(mime_type: &str) -> Option<Self> {
|
|
|
|
Some(match mime_type.to_ascii_lowercase().as_str() {
|
2022-05-31 01:38:07 +00:00
|
|
|
"image/bmp" | "image/x-bmp" => ImageFormat::Bmp,
|
2022-03-15 22:26:46 +00:00
|
|
|
"image/vnd-ms.dds" => ImageFormat::Dds,
|
|
|
|
"image/jpeg" => ImageFormat::Jpeg,
|
|
|
|
"image/ktx2" => ImageFormat::Ktx2,
|
|
|
|
"image/png" => ImageFormat::Png,
|
2023-02-19 20:38:13 +00:00
|
|
|
"image/x-exr" => ImageFormat::OpenExr,
|
2022-05-31 01:38:07 +00:00
|
|
|
"image/x-targa" | "image/x-tga" => ImageFormat::Tga,
|
2022-03-15 22:26:46 +00:00
|
|
|
_ => return None,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn from_extension(extension: &str) -> Option<Self> {
|
|
|
|
Some(match extension.to_ascii_lowercase().as_str() {
|
|
|
|
"avif" => ImageFormat::Avif,
|
|
|
|
"basis" => ImageFormat::Basis,
|
|
|
|
"bmp" => ImageFormat::Bmp,
|
|
|
|
"dds" => ImageFormat::Dds,
|
|
|
|
"ff" | "farbfeld" => ImageFormat::Farbfeld,
|
|
|
|
"gif" => ImageFormat::Gif,
|
2023-02-19 20:38:13 +00:00
|
|
|
"exr" => ImageFormat::OpenExr,
|
2022-03-15 22:26:46 +00:00
|
|
|
"hdr" => ImageFormat::Hdr,
|
|
|
|
"ico" => ImageFormat::Ico,
|
|
|
|
"jpg" | "jpeg" => ImageFormat::Jpeg,
|
|
|
|
"ktx2" => ImageFormat::Ktx2,
|
|
|
|
"pbm" | "pam" | "ppm" | "pgm" => ImageFormat::Pnm,
|
|
|
|
"png" => ImageFormat::Png,
|
|
|
|
"tga" => ImageFormat::Tga,
|
|
|
|
"tif" | "tiff" => ImageFormat::Tiff,
|
|
|
|
"webp" => ImageFormat::WebP,
|
|
|
|
_ => return None,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn as_image_crate_format(&self) -> Option<image::ImageFormat> {
|
|
|
|
Some(match self {
|
|
|
|
ImageFormat::Avif => image::ImageFormat::Avif,
|
|
|
|
ImageFormat::Bmp => image::ImageFormat::Bmp,
|
|
|
|
ImageFormat::Dds => image::ImageFormat::Dds,
|
|
|
|
ImageFormat::Farbfeld => image::ImageFormat::Farbfeld,
|
|
|
|
ImageFormat::Gif => image::ImageFormat::Gif,
|
2023-02-19 20:38:13 +00:00
|
|
|
ImageFormat::OpenExr => image::ImageFormat::OpenExr,
|
2022-03-15 22:26:46 +00:00
|
|
|
ImageFormat::Hdr => image::ImageFormat::Hdr,
|
|
|
|
ImageFormat::Ico => image::ImageFormat::Ico,
|
|
|
|
ImageFormat::Jpeg => image::ImageFormat::Jpeg,
|
|
|
|
ImageFormat::Png => image::ImageFormat::Png,
|
|
|
|
ImageFormat::Pnm => image::ImageFormat::Pnm,
|
|
|
|
ImageFormat::Tga => image::ImageFormat::Tga,
|
|
|
|
ImageFormat::Tiff => image::ImageFormat::Tiff,
|
|
|
|
ImageFormat::WebP => image::ImageFormat::WebP,
|
2022-05-31 01:38:07 +00:00
|
|
|
ImageFormat::Basis | ImageFormat::Ktx2 => return None,
|
2022-03-15 22:26:46 +00:00
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
add `ReflectAsset` and `ReflectHandle` (#5923)
# Objective
![image](https://user-images.githubusercontent.com/22177966/189350194-639a0211-e984-4f73-ae62-0ede44891eb9.png)
^ enable this
Concretely, I need to
- list all handle ids for an asset type
- fetch the asset as `dyn Reflect`, given a `HandleUntyped`
- when encountering a `Handle<T>`, find out what asset type that handle refers to (`T`'s type id) and turn the handle into a `HandleUntyped`
## Solution
- add `ReflectAsset` type containing function pointers for working with assets
```rust
pub struct ReflectAsset {
type_uuid: Uuid,
assets_resource_type_id: TypeId, // TypeId of the `Assets<T>` resource
get: fn(&World, HandleUntyped) -> Option<&dyn Reflect>,
get_mut: fn(&mut World, HandleUntyped) -> Option<&mut dyn Reflect>,
get_unchecked_mut: unsafe fn(&World, HandleUntyped) -> Option<&mut dyn Reflect>,
add: fn(&mut World, &dyn Reflect) -> HandleUntyped,
set: fn(&mut World, HandleUntyped, &dyn Reflect) -> HandleUntyped,
len: fn(&World) -> usize,
ids: for<'w> fn(&'w World) -> Box<dyn Iterator<Item = HandleId> + 'w>,
remove: fn(&mut World, HandleUntyped) -> Option<Box<dyn Reflect>>,
}
```
- add `ReflectHandle` type relating the handle back to the asset type and providing a way to create a `HandleUntyped`
```rust
pub struct ReflectHandle {
type_uuid: Uuid,
asset_type_id: TypeId,
downcast_handle_untyped: fn(&dyn Any) -> Option<HandleUntyped>,
}
```
- add the corresponding `FromType` impls
- add a function `app.register_asset_reflect` which is supposed to be called after `.add_asset` and registers `ReflectAsset` and `ReflectHandle` in the type registry
---
## Changelog
- add `ReflectAsset` and `ReflectHandle` types, which allow code to use reflection to manipulate arbitrary assets without knowing their types at compile time
2022-10-28 20:42:33 +00:00
|
|
|
#[derive(Reflect, FromReflect, Debug, Clone, TypeUuid)]
|
2021-04-11 20:13:07 +00:00
|
|
|
#[uuid = "6ea26da6-6cf8-4ea2-9986-1d7bf6c17d6f"]
|
add `ReflectAsset` and `ReflectHandle` (#5923)
# Objective
![image](https://user-images.githubusercontent.com/22177966/189350194-639a0211-e984-4f73-ae62-0ede44891eb9.png)
^ enable this
Concretely, I need to
- list all handle ids for an asset type
- fetch the asset as `dyn Reflect`, given a `HandleUntyped`
- when encountering a `Handle<T>`, find out what asset type that handle refers to (`T`'s type id) and turn the handle into a `HandleUntyped`
## Solution
- add `ReflectAsset` type containing function pointers for working with assets
```rust
pub struct ReflectAsset {
type_uuid: Uuid,
assets_resource_type_id: TypeId, // TypeId of the `Assets<T>` resource
get: fn(&World, HandleUntyped) -> Option<&dyn Reflect>,
get_mut: fn(&mut World, HandleUntyped) -> Option<&mut dyn Reflect>,
get_unchecked_mut: unsafe fn(&World, HandleUntyped) -> Option<&mut dyn Reflect>,
add: fn(&mut World, &dyn Reflect) -> HandleUntyped,
set: fn(&mut World, HandleUntyped, &dyn Reflect) -> HandleUntyped,
len: fn(&World) -> usize,
ids: for<'w> fn(&'w World) -> Box<dyn Iterator<Item = HandleId> + 'w>,
remove: fn(&mut World, HandleUntyped) -> Option<Box<dyn Reflect>>,
}
```
- add `ReflectHandle` type relating the handle back to the asset type and providing a way to create a `HandleUntyped`
```rust
pub struct ReflectHandle {
type_uuid: Uuid,
asset_type_id: TypeId,
downcast_handle_untyped: fn(&dyn Any) -> Option<HandleUntyped>,
}
```
- add the corresponding `FromType` impls
- add a function `app.register_asset_reflect` which is supposed to be called after `.add_asset` and registers `ReflectAsset` and `ReflectHandle` in the type registry
---
## Changelog
- add `ReflectAsset` and `ReflectHandle` types, which allow code to use reflection to manipulate arbitrary assets without knowing their types at compile time
2022-10-28 20:42:33 +00:00
|
|
|
#[reflect_value]
|
2021-06-21 23:28:52 +00:00
|
|
|
pub struct Image {
|
2021-04-11 20:13:07 +00:00
|
|
|
pub data: Vec<u8>,
|
2021-06-21 23:28:52 +00:00
|
|
|
// TODO: this nesting makes accessing Image metadata verbose. Either flatten out descriptor or add accessors
|
|
|
|
pub texture_descriptor: wgpu::TextureDescriptor<'static>,
|
2022-06-26 02:26:29 +00:00
|
|
|
/// The [`ImageSampler`] to use during rendering.
|
2022-06-11 09:13:37 +00:00
|
|
|
pub sampler_descriptor: ImageSampler,
|
Support array / cubemap / cubemap array textures in KTX2 (#5325)
# Objective
- Fix / support KTX2 array / cubemap / cubemap array textures
- Fixes #4495 . Supersedes #4514 .
## Solution
- Add `Option<TextureViewDescriptor>` to `Image` to enable configuration of the `TextureViewDimension` of a texture.
- This allows users to set `D2Array`, `D3`, `Cube`, `CubeArray` or whatever they need
- Automatically configure this when loading KTX2
- Transcode all layers and faces instead of just one
- Use the UASTC block size of 128 bits, and the number of blocks in x/y for a given mip level in order to determine the offset of the layer and face within the KTX2 mip level data
- `wgpu` wants data ordered as layer 0 mip 0..n, layer 1 mip 0..n, etc. See https://docs.rs/wgpu/latest/wgpu/util/trait.DeviceExt.html#tymethod.create_texture_with_data
- Reorder the data KTX2 mip X layer Y face Z to `wgpu` layer Y face Z mip X order
- Add a `skybox` example to demonstrate / test loading cubemaps from PNG and KTX2, including ASTC 4x4, BC7, and ETC2 compression for support everywhere. Note that you need to enable the `ktx2,zstd` features to be able to load the compressed textures.
---
## Changelog
- Fixed: KTX2 array / cubemap / cubemap array textures
- Fixes: Validation failure for compressed textures stored in KTX2 where the width/height are not a multiple of the block dimensions.
- Added: `Image` now has an `Option<TextureViewDescriptor>` field to enable configuration of the texture view. This is useful for configuring the `TextureViewDimension` when it is not just a plain 2D texture and the loader could/did not identify what it should be.
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2022-07-30 07:02:58 +00:00
|
|
|
pub texture_view_descriptor: Option<wgpu::TextureViewDescriptor<'static>>,
|
2021-04-11 20:13:07 +00:00
|
|
|
}
|
|
|
|
|
2022-06-26 02:26:29 +00:00
|
|
|
/// Used in [`Image`], this determines what image sampler to use when rendering. The default setting,
|
Use plugin setup for resource only used at setup time (#6360)
# Objective
- Build on #6336 for more plugin configurations
## Solution
- `LogSettings`, `ImageSettings` and `DefaultTaskPoolOptions` are now plugins settings rather than resources
---
## Changelog
- `LogSettings` plugin settings have been move to `LogPlugin`, `ImageSettings` to `ImagePlugin` and `DefaultTaskPoolOptions` to `CorePlugin`
## Migration Guide
The `LogSettings` settings have been moved from a resource to `LogPlugin` configuration:
```rust
// Old (Bevy 0.8)
app
.insert_resource(LogSettings {
level: Level::DEBUG,
filter: "wgpu=error,bevy_render=info,bevy_ecs=trace".to_string(),
})
.add_plugins(DefaultPlugins)
// New (Bevy 0.9)
app.add_plugins(DefaultPlugins.set(LogPlugin {
level: Level::DEBUG,
filter: "wgpu=error,bevy_render=info,bevy_ecs=trace".to_string(),
}))
```
The `ImageSettings` settings have been moved from a resource to `ImagePlugin` configuration:
```rust
// Old (Bevy 0.8)
app
.insert_resource(ImageSettings::default_nearest())
.add_plugins(DefaultPlugins)
// New (Bevy 0.9)
app.add_plugins(DefaultPlugins.set(ImagePlugin::default_nearest()))
```
The `DefaultTaskPoolOptions` settings have been moved from a resource to `CorePlugin::task_pool_options`:
```rust
// Old (Bevy 0.8)
app
.insert_resource(DefaultTaskPoolOptions::with_num_threads(4))
.add_plugins(DefaultPlugins)
// New (Bevy 0.9)
app.add_plugins(DefaultPlugins.set(CorePlugin {
task_pool_options: TaskPoolOptions::with_num_threads(4),
}))
```
2022-10-25 22:19:34 +00:00
|
|
|
/// [`ImageSampler::Default`], will read the sampler from the [`ImagePlugin`](super::ImagePlugin) at setup.
|
2022-06-26 02:26:29 +00:00
|
|
|
/// Setting this to [`ImageSampler::Descriptor`] will override the global default descriptor for this [`Image`].
|
2022-07-01 03:42:15 +00:00
|
|
|
#[derive(Debug, Default, Clone)]
|
2022-06-11 09:13:37 +00:00
|
|
|
pub enum ImageSampler {
|
Use plugin setup for resource only used at setup time (#6360)
# Objective
- Build on #6336 for more plugin configurations
## Solution
- `LogSettings`, `ImageSettings` and `DefaultTaskPoolOptions` are now plugins settings rather than resources
---
## Changelog
- `LogSettings` plugin settings have been move to `LogPlugin`, `ImageSettings` to `ImagePlugin` and `DefaultTaskPoolOptions` to `CorePlugin`
## Migration Guide
The `LogSettings` settings have been moved from a resource to `LogPlugin` configuration:
```rust
// Old (Bevy 0.8)
app
.insert_resource(LogSettings {
level: Level::DEBUG,
filter: "wgpu=error,bevy_render=info,bevy_ecs=trace".to_string(),
})
.add_plugins(DefaultPlugins)
// New (Bevy 0.9)
app.add_plugins(DefaultPlugins.set(LogPlugin {
level: Level::DEBUG,
filter: "wgpu=error,bevy_render=info,bevy_ecs=trace".to_string(),
}))
```
The `ImageSettings` settings have been moved from a resource to `ImagePlugin` configuration:
```rust
// Old (Bevy 0.8)
app
.insert_resource(ImageSettings::default_nearest())
.add_plugins(DefaultPlugins)
// New (Bevy 0.9)
app.add_plugins(DefaultPlugins.set(ImagePlugin::default_nearest()))
```
The `DefaultTaskPoolOptions` settings have been moved from a resource to `CorePlugin::task_pool_options`:
```rust
// Old (Bevy 0.8)
app
.insert_resource(DefaultTaskPoolOptions::with_num_threads(4))
.add_plugins(DefaultPlugins)
// New (Bevy 0.9)
app.add_plugins(DefaultPlugins.set(CorePlugin {
task_pool_options: TaskPoolOptions::with_num_threads(4),
}))
```
2022-10-25 22:19:34 +00:00
|
|
|
/// Default image sampler, derived from the [`ImagePlugin`](super::ImagePlugin) setup.
|
2022-07-01 03:42:15 +00:00
|
|
|
#[default]
|
2022-06-11 09:13:37 +00:00
|
|
|
Default,
|
2022-06-26 02:26:29 +00:00
|
|
|
/// Custom sampler for this image which will override global default.
|
2022-06-11 09:13:37 +00:00
|
|
|
Descriptor(wgpu::SamplerDescriptor<'static>),
|
|
|
|
}
|
|
|
|
|
|
|
|
impl ImageSampler {
|
2023-04-23 17:28:36 +00:00
|
|
|
/// Returns an image sampler with [`Linear`](crate::render_resource::FilterMode::Linear) min and mag filters
|
2022-07-27 06:49:37 +00:00
|
|
|
#[inline]
|
|
|
|
pub fn linear() -> ImageSampler {
|
|
|
|
ImageSampler::Descriptor(Self::linear_descriptor())
|
|
|
|
}
|
|
|
|
|
2023-04-23 17:28:36 +00:00
|
|
|
/// Returns an image sampler with [`Nearest`](crate::render_resource::FilterMode::Nearest) min and mag filters
|
2022-07-27 06:49:37 +00:00
|
|
|
#[inline]
|
|
|
|
pub fn nearest() -> ImageSampler {
|
|
|
|
ImageSampler::Descriptor(Self::nearest_descriptor())
|
|
|
|
}
|
|
|
|
|
2023-04-23 17:28:36 +00:00
|
|
|
/// Returns a sampler descriptor with [`Linear`](crate::render_resource::FilterMode::Linear) min and mag filters
|
2022-07-27 06:49:37 +00:00
|
|
|
#[inline]
|
2022-06-11 09:13:37 +00:00
|
|
|
pub fn linear_descriptor() -> wgpu::SamplerDescriptor<'static> {
|
|
|
|
wgpu::SamplerDescriptor {
|
|
|
|
mag_filter: wgpu::FilterMode::Linear,
|
|
|
|
min_filter: wgpu::FilterMode::Linear,
|
2022-11-03 15:33:41 +00:00
|
|
|
mipmap_filter: wgpu::FilterMode::Linear,
|
2022-06-11 09:13:37 +00:00
|
|
|
..Default::default()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-04-23 17:28:36 +00:00
|
|
|
/// Returns a sampler descriptor with [`Nearest`](crate::render_resource::FilterMode::Nearest) min and mag filters
|
2022-07-27 06:49:37 +00:00
|
|
|
#[inline]
|
2022-06-11 09:13:37 +00:00
|
|
|
pub fn nearest_descriptor() -> wgpu::SamplerDescriptor<'static> {
|
|
|
|
wgpu::SamplerDescriptor {
|
|
|
|
mag_filter: wgpu::FilterMode::Nearest,
|
|
|
|
min_filter: wgpu::FilterMode::Nearest,
|
2022-11-03 15:33:41 +00:00
|
|
|
mipmap_filter: wgpu::FilterMode::Nearest,
|
2022-06-11 09:13:37 +00:00
|
|
|
..Default::default()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-06-26 02:26:29 +00:00
|
|
|
/// A rendering resource for the default image sampler which is set during renderer
|
2022-07-21 20:46:54 +00:00
|
|
|
/// initialization.
|
2022-06-26 02:26:29 +00:00
|
|
|
///
|
Use plugin setup for resource only used at setup time (#6360)
# Objective
- Build on #6336 for more plugin configurations
## Solution
- `LogSettings`, `ImageSettings` and `DefaultTaskPoolOptions` are now plugins settings rather than resources
---
## Changelog
- `LogSettings` plugin settings have been move to `LogPlugin`, `ImageSettings` to `ImagePlugin` and `DefaultTaskPoolOptions` to `CorePlugin`
## Migration Guide
The `LogSettings` settings have been moved from a resource to `LogPlugin` configuration:
```rust
// Old (Bevy 0.8)
app
.insert_resource(LogSettings {
level: Level::DEBUG,
filter: "wgpu=error,bevy_render=info,bevy_ecs=trace".to_string(),
})
.add_plugins(DefaultPlugins)
// New (Bevy 0.9)
app.add_plugins(DefaultPlugins.set(LogPlugin {
level: Level::DEBUG,
filter: "wgpu=error,bevy_render=info,bevy_ecs=trace".to_string(),
}))
```
The `ImageSettings` settings have been moved from a resource to `ImagePlugin` configuration:
```rust
// Old (Bevy 0.8)
app
.insert_resource(ImageSettings::default_nearest())
.add_plugins(DefaultPlugins)
// New (Bevy 0.9)
app.add_plugins(DefaultPlugins.set(ImagePlugin::default_nearest()))
```
The `DefaultTaskPoolOptions` settings have been moved from a resource to `CorePlugin::task_pool_options`:
```rust
// Old (Bevy 0.8)
app
.insert_resource(DefaultTaskPoolOptions::with_num_threads(4))
.add_plugins(DefaultPlugins)
// New (Bevy 0.9)
app.add_plugins(DefaultPlugins.set(CorePlugin {
task_pool_options: TaskPoolOptions::with_num_threads(4),
}))
```
2022-10-25 22:19:34 +00:00
|
|
|
/// The [`ImagePlugin`](super::ImagePlugin) can be set during app initialization to change the default
|
2022-06-26 02:26:29 +00:00
|
|
|
/// image sampler.
|
Make `Resource` trait opt-in, requiring `#[derive(Resource)]` V2 (#5577)
*This PR description is an edited copy of #5007, written by @alice-i-cecile.*
# Objective
Follow-up to https://github.com/bevyengine/bevy/pull/2254. The `Resource` trait currently has a blanket implementation for all types that meet its bounds.
While ergonomic, this results in several drawbacks:
* it is possible to make confusing, silent mistakes such as inserting a function pointer (Foo) rather than a value (Foo::Bar) as a resource
* it is challenging to discover if a type is intended to be used as a resource
* we cannot later add customization options (see the [RFC](https://github.com/bevyengine/rfcs/blob/main/rfcs/27-derive-component.md) for the equivalent choice for Component).
* dependencies can use the same Rust type as a resource in invisibly conflicting ways
* raw Rust types used as resources cannot preserve privacy appropriately, as anyone able to access that type can read and write to internal values
* we cannot capture a definitive list of possible resources to display to users in an editor
## Notes to reviewers
* Review this commit-by-commit; there's effectively no back-tracking and there's a lot of churn in some of these commits.
*ira: My commits are not as well organized :')*
* I've relaxed the bound on Local to Send + Sync + 'static: I don't think these concerns apply there, so this can keep things simple. Storing e.g. a u32 in a Local is fine, because there's a variable name attached explaining what it does.
* I think this is a bad place for the Resource trait to live, but I've left it in place to make reviewing easier. IMO that's best tackled with https://github.com/bevyengine/bevy/issues/4981.
## Changelog
`Resource` is no longer automatically implemented for all matching types. Instead, use the new `#[derive(Resource)]` macro.
## Migration Guide
Add `#[derive(Resource)]` to all types you are using as a resource.
If you are using a third party type as a resource, wrap it in a tuple struct to bypass orphan rules. Consider deriving `Deref` and `DerefMut` to improve ergonomics.
`ClearColor` no longer implements `Component`. Using `ClearColor` as a component in 0.8 did nothing.
Use the `ClearColorConfig` in the `Camera3d` and `Camera2d` components instead.
Co-authored-by: Alice <alice.i.cecile@gmail.com>
Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
Co-authored-by: devil-ira <justthecooldude@gmail.com>
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2022-08-08 21:36:35 +00:00
|
|
|
#[derive(Resource, Debug, Clone, Deref, DerefMut)]
|
2022-06-11 09:13:37 +00:00
|
|
|
pub struct DefaultImageSampler(pub(crate) Sampler);
|
|
|
|
|
2021-06-21 23:28:52 +00:00
|
|
|
impl Default for Image {
|
2023-03-04 12:29:10 +00:00
|
|
|
/// default is a 1x1x1 all '1.0' texture
|
2021-04-11 20:13:07 +00:00
|
|
|
fn default() -> Self {
|
2021-09-16 22:50:21 +00:00
|
|
|
let format = wgpu::TextureFormat::bevy_default();
|
2022-10-28 21:03:01 +00:00
|
|
|
let data = vec![255; format.pixel_size()];
|
2021-06-21 23:28:52 +00:00
|
|
|
Image {
|
2021-09-16 22:50:21 +00:00
|
|
|
data,
|
2021-06-21 23:28:52 +00:00
|
|
|
texture_descriptor: wgpu::TextureDescriptor {
|
|
|
|
size: wgpu::Extent3d {
|
|
|
|
width: 1,
|
|
|
|
height: 1,
|
|
|
|
depth_or_array_layers: 1,
|
|
|
|
},
|
2021-09-16 22:50:21 +00:00
|
|
|
format,
|
2021-06-21 23:28:52 +00:00
|
|
|
dimension: wgpu::TextureDimension::D2,
|
|
|
|
label: None,
|
|
|
|
mip_level_count: 1,
|
|
|
|
sample_count: 1,
|
2021-10-08 19:55:24 +00:00
|
|
|
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
|
Wgpu 0.15 (#7356)
# Objective
Update Bevy to wgpu 0.15.
## Changelog
- Update to wgpu 0.15, wgpu-hal 0.15.1, and naga 0.11
- Users can now use the [DirectX Shader Compiler](https://github.com/microsoft/DirectXShaderCompiler) (DXC) on Windows with DX12 for faster shader compilation and ShaderModel 6.0+ support (requires `dxcompiler.dll` and `dxil.dll`, which are included in DXC downloads from [here](https://github.com/microsoft/DirectXShaderCompiler/releases/latest))
## Migration Guide
### WGSL Top-Level `let` is now `const`
All top level constants are now declared with `const`, catching up with the wgsl spec.
`let` is no longer allowed at the global scope, only within functions.
```diff
-let SOME_CONSTANT = 12.0;
+const SOME_CONSTANT = 12.0;
```
#### `TextureDescriptor` and `SurfaceConfiguration` now requires a `view_formats` field
The new `view_formats` field in the `TextureDescriptor` is used to specify a list of formats the texture can be re-interpreted to in a texture view. Currently only changing srgb-ness is allowed (ex. `Rgba8Unorm` <=> `Rgba8UnormSrgb`). You should set `view_formats` to `&[]` (empty) unless you have a specific reason not to.
#### The DirectX Shader Compiler (DXC) is now supported on DX12
DXC is now the default shader compiler when using the DX12 backend. DXC is Microsoft's replacement for their legacy FXC compiler, and is faster, less buggy, and allows for modern shader features to be used (ShaderModel 6.0+). DXC requires `dxcompiler.dll` and `dxil.dll` to be available, otherwise it will log a warning and fall back to FXC.
You can get `dxcompiler.dll` and `dxil.dll` by downloading the latest release from [Microsoft's DirectXShaderCompiler github repo](https://github.com/microsoft/DirectXShaderCompiler/releases/latest) and copying them into your project's root directory. These must be included when you distribute your Bevy game/app/etc if you plan on supporting the DX12 backend and are using DXC.
`WgpuSettings` now has a `dx12_shader_compiler` field which can be used to choose between either FXC or DXC (if you pass None for the paths for DXC, it will check for the .dlls in the working directory).
2023-01-29 20:27:30 +00:00
|
|
|
view_formats: &[],
|
2021-04-11 20:13:07 +00:00
|
|
|
},
|
2022-06-11 09:13:37 +00:00
|
|
|
sampler_descriptor: ImageSampler::Default,
|
Support array / cubemap / cubemap array textures in KTX2 (#5325)
# Objective
- Fix / support KTX2 array / cubemap / cubemap array textures
- Fixes #4495 . Supersedes #4514 .
## Solution
- Add `Option<TextureViewDescriptor>` to `Image` to enable configuration of the `TextureViewDimension` of a texture.
- This allows users to set `D2Array`, `D3`, `Cube`, `CubeArray` or whatever they need
- Automatically configure this when loading KTX2
- Transcode all layers and faces instead of just one
- Use the UASTC block size of 128 bits, and the number of blocks in x/y for a given mip level in order to determine the offset of the layer and face within the KTX2 mip level data
- `wgpu` wants data ordered as layer 0 mip 0..n, layer 1 mip 0..n, etc. See https://docs.rs/wgpu/latest/wgpu/util/trait.DeviceExt.html#tymethod.create_texture_with_data
- Reorder the data KTX2 mip X layer Y face Z to `wgpu` layer Y face Z mip X order
- Add a `skybox` example to demonstrate / test loading cubemaps from PNG and KTX2, including ASTC 4x4, BC7, and ETC2 compression for support everywhere. Note that you need to enable the `ktx2,zstd` features to be able to load the compressed textures.
---
## Changelog
- Fixed: KTX2 array / cubemap / cubemap array textures
- Fixes: Validation failure for compressed textures stored in KTX2 where the width/height are not a multiple of the block dimensions.
- Added: `Image` now has an `Option<TextureViewDescriptor>` field to enable configuration of the texture view. This is useful for configuring the `TextureViewDimension` when it is not just a plain 2D texture and the loader could/did not identify what it should be.
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2022-07-30 07:02:58 +00:00
|
|
|
texture_view_descriptor: None,
|
2021-04-11 20:13:07 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-06-21 23:28:52 +00:00
|
|
|
impl Image {
|
2021-11-16 03:37:48 +00:00
|
|
|
/// Creates a new image from raw binary data and the corresponding metadata.
|
|
|
|
///
|
|
|
|
/// # Panics
|
|
|
|
/// Panics if the length of the `data`, volume of the `size` and the size of the `format`
|
|
|
|
/// do not match.
|
2021-04-11 20:13:07 +00:00
|
|
|
pub fn new(
|
|
|
|
size: Extent3d,
|
|
|
|
dimension: TextureDimension,
|
|
|
|
data: Vec<u8>,
|
|
|
|
format: TextureFormat,
|
|
|
|
) -> Self {
|
|
|
|
debug_assert_eq!(
|
|
|
|
size.volume() * format.pixel_size(),
|
|
|
|
data.len(),
|
|
|
|
"Pixel data, size and format have to match",
|
|
|
|
);
|
2021-07-02 01:05:20 +00:00
|
|
|
let mut image = Self {
|
|
|
|
data,
|
|
|
|
..Default::default()
|
|
|
|
};
|
2021-06-21 23:28:52 +00:00
|
|
|
image.texture_descriptor.dimension = dimension;
|
|
|
|
image.texture_descriptor.size = size;
|
|
|
|
image.texture_descriptor.format = format;
|
|
|
|
image
|
2021-04-11 20:13:07 +00:00
|
|
|
}
|
|
|
|
|
2021-11-16 03:37:48 +00:00
|
|
|
/// Creates a new image from raw binary data and the corresponding metadata, by filling
|
|
|
|
/// the image data with the `pixel` data repeated multiple times.
|
|
|
|
///
|
|
|
|
/// # Panics
|
|
|
|
/// Panics if the size of the `format` is not a multiple of the length of the `pixel` data.
|
2021-04-11 20:13:07 +00:00
|
|
|
pub fn new_fill(
|
|
|
|
size: Extent3d,
|
|
|
|
dimension: TextureDimension,
|
|
|
|
pixel: &[u8],
|
|
|
|
format: TextureFormat,
|
|
|
|
) -> Self {
|
2021-06-21 23:28:52 +00:00
|
|
|
let mut value = Image::default();
|
|
|
|
value.texture_descriptor.format = format;
|
|
|
|
value.texture_descriptor.dimension = dimension;
|
2021-04-11 20:13:07 +00:00
|
|
|
value.resize(size);
|
|
|
|
|
|
|
|
debug_assert_eq!(
|
|
|
|
pixel.len() % format.pixel_size(),
|
|
|
|
0,
|
|
|
|
"Must not have incomplete pixel data."
|
|
|
|
);
|
|
|
|
debug_assert!(
|
|
|
|
pixel.len() <= value.data.len(),
|
|
|
|
"Fill data must fit within pixel buffer."
|
|
|
|
);
|
|
|
|
|
|
|
|
for current_pixel in value.data.chunks_exact_mut(pixel.len()) {
|
2021-07-30 03:17:27 +00:00
|
|
|
current_pixel.copy_from_slice(pixel);
|
2021-04-11 20:13:07 +00:00
|
|
|
}
|
|
|
|
value
|
|
|
|
}
|
|
|
|
|
2021-11-16 03:37:48 +00:00
|
|
|
/// Returns the aspect ratio (height/width) of a 2D image.
|
2021-04-11 20:13:07 +00:00
|
|
|
pub fn aspect_2d(&self) -> f32 {
|
2021-06-21 23:28:52 +00:00
|
|
|
self.texture_descriptor.size.height as f32 / self.texture_descriptor.size.width as f32
|
2021-04-11 20:13:07 +00:00
|
|
|
}
|
|
|
|
|
2022-02-04 03:21:33 +00:00
|
|
|
/// Returns the size of a 2D image.
|
|
|
|
pub fn size(&self) -> Vec2 {
|
|
|
|
Vec2::new(
|
|
|
|
self.texture_descriptor.size.width as f32,
|
|
|
|
self.texture_descriptor.size.height as f32,
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
2021-11-16 03:37:48 +00:00
|
|
|
/// Resizes the image to the new size, by removing information or appending 0 to the `data`.
|
|
|
|
/// Does not properly resize the contents of the image, but only its internal `data` buffer.
|
2021-04-11 20:13:07 +00:00
|
|
|
pub fn resize(&mut self, size: Extent3d) {
|
2021-06-21 23:28:52 +00:00
|
|
|
self.texture_descriptor.size = size;
|
|
|
|
self.data.resize(
|
|
|
|
size.volume() * self.texture_descriptor.format.pixel_size(),
|
|
|
|
0,
|
|
|
|
);
|
2021-04-11 20:13:07 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Changes the `size`, asserting that the total number of data elements (pixels) remains the
|
|
|
|
/// same.
|
2021-11-16 03:37:48 +00:00
|
|
|
///
|
|
|
|
/// # Panics
|
|
|
|
/// Panics if the `new_size` does not have the same volume as to old one.
|
2021-04-11 20:13:07 +00:00
|
|
|
pub fn reinterpret_size(&mut self, new_size: Extent3d) {
|
|
|
|
assert!(
|
2021-06-21 23:28:52 +00:00
|
|
|
new_size.volume() == self.texture_descriptor.size.volume(),
|
2021-04-11 20:13:07 +00:00
|
|
|
"Incompatible sizes: old = {:?} new = {:?}",
|
2021-06-21 23:28:52 +00:00
|
|
|
self.texture_descriptor.size,
|
2021-04-11 20:13:07 +00:00
|
|
|
new_size
|
|
|
|
);
|
|
|
|
|
2021-06-21 23:28:52 +00:00
|
|
|
self.texture_descriptor.size = new_size;
|
2021-04-11 20:13:07 +00:00
|
|
|
}
|
|
|
|
|
2021-11-16 03:37:48 +00:00
|
|
|
/// Takes a 2D image containing vertically stacked images of the same size, and reinterprets
|
2021-04-11 20:13:07 +00:00
|
|
|
/// it as a 2D array texture, where each of the stacked images becomes one layer of the
|
|
|
|
/// array. This is primarily for use with the `texture2DArray` shader uniform type.
|
2021-11-16 03:37:48 +00:00
|
|
|
///
|
|
|
|
/// # Panics
|
|
|
|
/// Panics if the texture is not 2D, has more than one layers or is not evenly dividable into
|
|
|
|
/// the `layers`.
|
2021-04-11 20:13:07 +00:00
|
|
|
pub fn reinterpret_stacked_2d_as_array(&mut self, layers: u32) {
|
|
|
|
// Must be a stacked image, and the height must be divisible by layers.
|
2021-06-21 23:28:52 +00:00
|
|
|
assert!(self.texture_descriptor.dimension == TextureDimension::D2);
|
|
|
|
assert!(self.texture_descriptor.size.depth_or_array_layers == 1);
|
|
|
|
assert_eq!(self.texture_descriptor.size.height % layers, 0);
|
2021-04-11 20:13:07 +00:00
|
|
|
|
|
|
|
self.reinterpret_size(Extent3d {
|
2021-06-21 23:28:52 +00:00
|
|
|
width: self.texture_descriptor.size.width,
|
|
|
|
height: self.texture_descriptor.size.height / layers,
|
2021-04-11 20:13:07 +00:00
|
|
|
depth_or_array_layers: layers,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2022-09-03 17:47:38 +00:00
|
|
|
/// Convert a texture from a format to another. Only a few formats are
|
|
|
|
/// supported as input and output:
|
2021-04-11 20:13:07 +00:00
|
|
|
/// - `TextureFormat::R8Unorm`
|
|
|
|
/// - `TextureFormat::Rg8Unorm`
|
|
|
|
/// - `TextureFormat::Rgba8UnormSrgb`
|
2022-09-03 17:47:38 +00:00
|
|
|
///
|
|
|
|
/// To get [`Image`] as a [`image::DynamicImage`] see:
|
|
|
|
/// [`Image::try_into_dynamic`].
|
2021-04-11 20:13:07 +00:00
|
|
|
pub fn convert(&self, new_format: TextureFormat) -> Option<Self> {
|
2022-09-03 17:47:38 +00:00
|
|
|
self.clone()
|
|
|
|
.try_into_dynamic()
|
|
|
|
.ok()
|
2021-04-11 20:13:07 +00:00
|
|
|
.and_then(|img| match new_format {
|
2022-03-15 22:26:46 +00:00
|
|
|
TextureFormat::R8Unorm => {
|
|
|
|
Some((image::DynamicImage::ImageLuma8(img.into_luma8()), false))
|
2021-04-11 20:13:07 +00:00
|
|
|
}
|
2022-03-15 22:26:46 +00:00
|
|
|
TextureFormat::Rg8Unorm => Some((
|
|
|
|
image::DynamicImage::ImageLumaA8(img.into_luma_alpha8()),
|
|
|
|
false,
|
|
|
|
)),
|
2021-04-11 20:13:07 +00:00
|
|
|
TextureFormat::Rgba8UnormSrgb => {
|
2022-03-15 22:26:46 +00:00
|
|
|
Some((image::DynamicImage::ImageRgba8(img.into_rgba8()), true))
|
2021-04-11 20:13:07 +00:00
|
|
|
}
|
|
|
|
_ => None,
|
|
|
|
})
|
2022-09-03 17:47:38 +00:00
|
|
|
.map(|(dyn_img, is_srgb)| Self::from_dynamic(dyn_img, is_srgb))
|
2021-04-11 20:13:07 +00:00
|
|
|
}
|
|
|
|
|
2022-01-18 01:28:09 +00:00
|
|
|
/// Load a bytes buffer in a [`Image`], according to type `image_type`, using the `image`
|
2022-01-09 11:09:46 +00:00
|
|
|
/// crate
|
2022-03-15 22:26:46 +00:00
|
|
|
pub fn from_buffer(
|
|
|
|
buffer: &[u8],
|
|
|
|
image_type: ImageType,
|
|
|
|
#[allow(unused_variables)] supported_compressed_formats: CompressedImageFormats,
|
|
|
|
is_srgb: bool,
|
|
|
|
) -> Result<Image, TextureError> {
|
|
|
|
let format = image_type.to_image_format()?;
|
2021-04-11 20:13:07 +00:00
|
|
|
|
|
|
|
// Load the image in the expected format.
|
|
|
|
// Some formats like PNG allow for R or RG textures too, so the texture
|
|
|
|
// format needs to be determined. For RGB textures an alpha channel
|
|
|
|
// needs to be added, so the image data needs to be converted in those
|
|
|
|
// cases.
|
|
|
|
|
2022-03-15 22:26:46 +00:00
|
|
|
match format {
|
|
|
|
#[cfg(feature = "basis-universal")]
|
|
|
|
ImageFormat::Basis => {
|
|
|
|
basis_buffer_to_image(buffer, supported_compressed_formats, is_srgb)
|
|
|
|
}
|
|
|
|
#[cfg(feature = "dds")]
|
|
|
|
ImageFormat::Dds => dds_buffer_to_image(buffer, supported_compressed_formats, is_srgb),
|
|
|
|
#[cfg(feature = "ktx2")]
|
|
|
|
ImageFormat::Ktx2 => {
|
|
|
|
ktx2_buffer_to_image(buffer, supported_compressed_formats, is_srgb)
|
|
|
|
}
|
|
|
|
_ => {
|
2022-10-28 21:03:01 +00:00
|
|
|
let image_crate_format = format
|
|
|
|
.as_image_crate_format()
|
|
|
|
.ok_or_else(|| TextureError::UnsupportedTextureFormat(format!("{format:?}")))?;
|
2022-07-13 11:31:18 +00:00
|
|
|
let mut reader = image::io::Reader::new(std::io::Cursor::new(buffer));
|
|
|
|
reader.set_format(image_crate_format);
|
|
|
|
reader.no_limits();
|
|
|
|
let dyn_img = reader.decode()?;
|
2022-09-03 17:47:38 +00:00
|
|
|
Ok(Self::from_dynamic(dyn_img, is_srgb))
|
2022-03-15 22:26:46 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Whether the texture format is compressed or uncompressed
|
|
|
|
pub fn is_compressed(&self) -> bool {
|
2023-04-26 15:34:23 +00:00
|
|
|
let format_description = self.texture_descriptor.format;
|
2022-03-15 22:26:46 +00:00
|
|
|
format_description
|
2023-04-26 15:34:23 +00:00
|
|
|
.required_features()
|
|
|
|
.contains(wgpu::Features::TEXTURE_COMPRESSION_ASTC)
|
2022-03-15 22:26:46 +00:00
|
|
|
|| format_description
|
2023-04-26 15:34:23 +00:00
|
|
|
.required_features()
|
2022-03-15 22:26:46 +00:00
|
|
|
.contains(wgpu::Features::TEXTURE_COMPRESSION_BC)
|
|
|
|
|| format_description
|
2023-04-26 15:34:23 +00:00
|
|
|
.required_features()
|
2022-03-15 22:26:46 +00:00
|
|
|
.contains(wgpu::Features::TEXTURE_COMPRESSION_ETC2)
|
2021-04-11 20:13:07 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-03-15 22:26:46 +00:00
|
|
|
#[derive(Clone, Copy, Debug)]
|
|
|
|
pub enum DataFormat {
|
2022-06-17 00:14:02 +00:00
|
|
|
Rgb,
|
|
|
|
Rgba,
|
|
|
|
Rrr,
|
|
|
|
Rrrg,
|
|
|
|
Rg,
|
2022-03-15 22:26:46 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Clone, Copy, Debug)]
|
|
|
|
pub enum TranscodeFormat {
|
|
|
|
Etc1s,
|
Fix KTX2 R8_SRGB, R8_UNORM, R8G8_SRGB, R8G8_UNORM, R8G8B8_SRGB, R8G8B8_UNORM support (#4594)
# Objective
- Fixes #4592
## Solution
- Implement `SrgbColorSpace` for `u8` via `f32`
- Convert KTX2 R8 and R8G8 non-linear sRGB to wgpu `R8Unorm` and `Rg8Unorm` as non-linear sRGB are not supported by wgpu for these formats
- Convert KTX2 R8G8B8 formats to `Rgba8Unorm` and `Rgba8UnormSrgb` by adding an alpha channel as the Rgb variants don't exist in wgpu
---
## Changelog
- Added: Support for KTX2 `R8_SRGB`, `R8_UNORM`, `R8G8_SRGB`, `R8G8_UNORM`, `R8G8B8_SRGB`, `R8G8B8_UNORM` formats by converting to supported wgpu formats as appropriate
2023-01-30 09:04:08 +00:00
|
|
|
Uastc(DataFormat),
|
|
|
|
// Has to be transcoded to R8Unorm for use with `wgpu`
|
|
|
|
R8UnormSrgb,
|
|
|
|
// Has to be transcoded to R8G8Unorm for use with `wgpu`
|
|
|
|
Rg8UnormSrgb,
|
2022-03-15 22:26:46 +00:00
|
|
|
// Has to be transcoded to Rgba8 for use with `wgpu`
|
|
|
|
Rgb8,
|
|
|
|
}
|
|
|
|
|
2021-04-11 20:13:07 +00:00
|
|
|
/// An error that occurs when loading a texture
|
|
|
|
#[derive(Error, Debug)]
|
|
|
|
pub enum TextureError {
|
2022-03-15 22:26:46 +00:00
|
|
|
#[error("invalid image mime type: {0}")]
|
2021-04-11 20:13:07 +00:00
|
|
|
InvalidImageMimeType(String),
|
2022-03-15 22:26:46 +00:00
|
|
|
#[error("invalid image extension: {0}")]
|
2021-04-11 20:13:07 +00:00
|
|
|
InvalidImageExtension(String),
|
|
|
|
#[error("failed to load an image: {0}")]
|
|
|
|
ImageError(#[from] image::ImageError),
|
2022-03-15 22:26:46 +00:00
|
|
|
#[error("unsupported texture format: {0}")]
|
|
|
|
UnsupportedTextureFormat(String),
|
|
|
|
#[error("supercompression not supported: {0}")]
|
|
|
|
SuperCompressionNotSupported(String),
|
|
|
|
#[error("failed to load an image: {0}")]
|
|
|
|
SuperDecompressionError(String),
|
|
|
|
#[error("invalid data: {0}")]
|
|
|
|
InvalidData(String),
|
|
|
|
#[error("transcode error: {0}")]
|
|
|
|
TranscodeError(String),
|
|
|
|
#[error("format requires transcoding: {0:?}")]
|
|
|
|
FormatRequiresTranscodingError(TranscodeFormat),
|
2021-04-11 20:13:07 +00:00
|
|
|
}
|
|
|
|
|
2021-11-16 03:37:48 +00:00
|
|
|
/// The type of a raw image buffer.
|
2021-04-11 20:13:07 +00:00
|
|
|
pub enum ImageType<'a> {
|
2021-11-16 03:37:48 +00:00
|
|
|
/// The mime type of an image, for example `"image/png"`.
|
2021-04-11 20:13:07 +00:00
|
|
|
MimeType(&'a str),
|
2021-11-16 03:37:48 +00:00
|
|
|
/// The extension of an image file, for example `"png"`.
|
2021-04-11 20:13:07 +00:00
|
|
|
Extension(&'a str),
|
|
|
|
}
|
2021-06-21 23:28:52 +00:00
|
|
|
|
2022-03-15 22:26:46 +00:00
|
|
|
impl<'a> ImageType<'a> {
|
|
|
|
pub fn to_image_format(&self) -> Result<ImageFormat, TextureError> {
|
|
|
|
match self {
|
|
|
|
ImageType::MimeType(mime_type) => ImageFormat::from_mime_type(mime_type)
|
|
|
|
.ok_or_else(|| TextureError::InvalidImageMimeType(mime_type.to_string())),
|
|
|
|
ImageType::Extension(extension) => ImageFormat::from_extension(extension)
|
|
|
|
.ok_or_else(|| TextureError::InvalidImageExtension(extension.to_string())),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-11-16 03:37:48 +00:00
|
|
|
/// Used to calculate the volume of an item.
|
2021-06-21 23:28:52 +00:00
|
|
|
pub trait Volume {
|
|
|
|
fn volume(&self) -> usize;
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Volume for Extent3d {
|
2021-12-18 00:09:23 +00:00
|
|
|
/// Calculates the volume of the [`Extent3d`].
|
2021-06-21 23:28:52 +00:00
|
|
|
fn volume(&self) -> usize {
|
|
|
|
(self.width * self.height * self.depth_or_array_layers) as usize
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-11-16 03:37:48 +00:00
|
|
|
/// Extends the wgpu [`TextureFormat`] with information about the pixel.
|
2021-06-21 23:28:52 +00:00
|
|
|
pub trait TextureFormatPixelInfo {
|
2022-12-11 18:22:07 +00:00
|
|
|
/// Returns the size of a pixel in bytes of the format.
|
|
|
|
fn pixel_size(&self) -> usize;
|
2021-06-21 23:28:52 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl TextureFormatPixelInfo for TextureFormat {
|
2022-12-11 18:22:07 +00:00
|
|
|
fn pixel_size(&self) -> usize {
|
2023-04-26 15:34:23 +00:00
|
|
|
let info = self;
|
|
|
|
match info.block_dimensions() {
|
|
|
|
(1, 1) => info.block_size(None).unwrap() as usize,
|
2022-12-11 18:22:07 +00:00
|
|
|
_ => panic!("Using pixel_size for compressed textures is invalid"),
|
2021-06-21 23:28:52 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2021-06-25 03:04:28 +00:00
|
|
|
|
2021-11-16 03:37:48 +00:00
|
|
|
/// The GPU-representation of an [`Image`].
|
2022-04-25 13:54:46 +00:00
|
|
|
/// Consists of the [`Texture`], its [`TextureView`] and the corresponding [`Sampler`], and the texture's size.
|
2021-06-25 03:04:28 +00:00
|
|
|
#[derive(Debug, Clone)]
|
|
|
|
pub struct GpuImage {
|
|
|
|
pub texture: Texture,
|
|
|
|
pub texture_view: TextureView,
|
2022-03-15 22:26:46 +00:00
|
|
|
pub texture_format: TextureFormat,
|
2021-06-25 03:04:28 +00:00
|
|
|
pub sampler: Sampler,
|
2022-04-25 13:54:46 +00:00
|
|
|
pub size: Vec2,
|
2023-02-20 00:02:40 +00:00
|
|
|
pub mip_level_count: u32,
|
2021-06-25 03:04:28 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl RenderAsset for Image {
|
|
|
|
type ExtractedAsset = Image;
|
|
|
|
type PreparedAsset = GpuImage;
|
2022-06-11 09:13:37 +00:00
|
|
|
type Param = (
|
|
|
|
SRes<RenderDevice>,
|
|
|
|
SRes<RenderQueue>,
|
|
|
|
SRes<DefaultImageSampler>,
|
|
|
|
);
|
2021-06-25 03:04:28 +00:00
|
|
|
|
2021-11-16 03:37:48 +00:00
|
|
|
/// Clones the Image.
|
2021-06-25 03:04:28 +00:00
|
|
|
fn extract_asset(&self) -> Self::ExtractedAsset {
|
|
|
|
self.clone()
|
|
|
|
}
|
|
|
|
|
2021-11-16 03:37:48 +00:00
|
|
|
/// Converts the extracted image into a [`GpuImage`].
|
2021-06-25 03:04:28 +00:00
|
|
|
fn prepare_asset(
|
|
|
|
image: Self::ExtractedAsset,
|
2022-06-11 09:13:37 +00:00
|
|
|
(render_device, render_queue, default_sampler): &mut SystemParamItem<Self::Param>,
|
Modular Rendering (#2831)
This changes how render logic is composed to make it much more modular. Previously, all extraction logic was centralized for a given "type" of rendered thing. For example, we extracted meshes into a vector of ExtractedMesh, which contained the mesh and material asset handles, the transform, etc. We looked up bindings for "drawn things" using their index in the `Vec<ExtractedMesh>`. This worked fine for built in rendering, but made it hard to reuse logic for "custom" rendering. It also prevented us from reusing things like "extracted transforms" across contexts.
To make rendering more modular, I made a number of changes:
* Entities now drive rendering:
* We extract "render components" from "app components" and store them _on_ entities. No more centralized uber lists! We now have true "ECS-driven rendering"
* To make this perform well, I implemented #2673 in upstream Bevy for fast batch insertions into specific entities. This was merged into the `pipelined-rendering` branch here: #2815
* Reworked the `Draw` abstraction:
* Generic `PhaseItems`: each draw phase can define its own type of "rendered thing", which can define its own "sort key"
* Ported the 2d, 3d, and shadow phases to the new PhaseItem impl (currently Transparent2d, Transparent3d, and Shadow PhaseItems)
* `Draw` trait and and `DrawFunctions` are now generic on PhaseItem
* Modular / Ergonomic `DrawFunctions` via `RenderCommands`
* RenderCommand is a trait that runs an ECS query and produces one or more RenderPass calls. Types implementing this trait can be composed to create a final DrawFunction. For example the DrawPbr DrawFunction is created from the following DrawCommand tuple. Const generics are used to set specific bind group locations:
```rust
pub type DrawPbr = (
SetPbrPipeline,
SetMeshViewBindGroup<0>,
SetStandardMaterialBindGroup<1>,
SetTransformBindGroup<2>,
DrawMesh,
);
```
* The new `custom_shader_pipelined` example illustrates how the commands above can be reused to create a custom draw function:
```rust
type DrawCustom = (
SetCustomMaterialPipeline,
SetMeshViewBindGroup<0>,
SetTransformBindGroup<2>,
DrawMesh,
);
```
* ExtractComponentPlugin and UniformComponentPlugin:
* Simple, standardized ways to easily extract individual components and write them to GPU buffers
* Ported PBR and Sprite rendering to the new primitives above.
* Removed staging buffer from UniformVec in favor of direct Queue usage
* Makes UniformVec much easier to use and more ergonomic. Completely removes the need for custom render graph nodes in these contexts (see the PbrNode and view Node removals and the much simpler call patterns in the relevant Prepare systems).
* Added a many_cubes_pipelined example to benchmark baseline 3d rendering performance and ensure there were no major regressions during this port. Avoiding regressions was challenging given that the old approach of extracting into centralized vectors is basically the "optimal" approach. However thanks to a various ECS optimizations and render logic rephrasing, we pretty much break even on this benchmark!
* Lifetimeless SystemParams: this will be a bit divisive, but as we continue to embrace "trait driven systems" (ex: ExtractComponentPlugin, UniformComponentPlugin, DrawCommand), the ergonomics of `(Query<'static, 'static, (&'static A, &'static B, &'static)>, Res<'static, C>)` were getting very hard to bear. As a compromise, I added "static type aliases" for the relevant SystemParams. The previous example can now be expressed like this: `(SQuery<(Read<A>, Read<B>)>, SRes<C>)`. If anyone has better ideas / conflicting opinions, please let me know!
* RunSystem trait: a way to define Systems via a trait with a SystemParam associated type. This is used to implement the various plugins mentioned above. I also added SystemParamItem and QueryItem type aliases to make "trait stye" ecs interactions nicer on the eyes (and fingers).
* RenderAsset retrying: ensures that render assets are only created when they are "ready" and allows us to create bind groups directly inside render assets (which significantly simplified the StandardMaterial code). I think ultimately we should swap this out on "asset dependency" events to wait for dependencies to load, but this will require significant asset system changes.
* Updated some built in shaders to account for missing MeshUniform fields
2021-09-23 06:16:11 +00:00
|
|
|
) -> Result<Self::PreparedAsset, PrepareAssetError<Self::ExtractedAsset>> {
|
2022-12-05 23:39:42 +00:00
|
|
|
let texture = render_device.create_texture_with_data(
|
|
|
|
render_queue,
|
|
|
|
&image.texture_descriptor,
|
|
|
|
&image.data,
|
|
|
|
);
|
2021-06-25 03:04:28 +00:00
|
|
|
|
Support array / cubemap / cubemap array textures in KTX2 (#5325)
# Objective
- Fix / support KTX2 array / cubemap / cubemap array textures
- Fixes #4495 . Supersedes #4514 .
## Solution
- Add `Option<TextureViewDescriptor>` to `Image` to enable configuration of the `TextureViewDimension` of a texture.
- This allows users to set `D2Array`, `D3`, `Cube`, `CubeArray` or whatever they need
- Automatically configure this when loading KTX2
- Transcode all layers and faces instead of just one
- Use the UASTC block size of 128 bits, and the number of blocks in x/y for a given mip level in order to determine the offset of the layer and face within the KTX2 mip level data
- `wgpu` wants data ordered as layer 0 mip 0..n, layer 1 mip 0..n, etc. See https://docs.rs/wgpu/latest/wgpu/util/trait.DeviceExt.html#tymethod.create_texture_with_data
- Reorder the data KTX2 mip X layer Y face Z to `wgpu` layer Y face Z mip X order
- Add a `skybox` example to demonstrate / test loading cubemaps from PNG and KTX2, including ASTC 4x4, BC7, and ETC2 compression for support everywhere. Note that you need to enable the `ktx2,zstd` features to be able to load the compressed textures.
---
## Changelog
- Fixed: KTX2 array / cubemap / cubemap array textures
- Fixes: Validation failure for compressed textures stored in KTX2 where the width/height are not a multiple of the block dimensions.
- Added: `Image` now has an `Option<TextureViewDescriptor>` field to enable configuration of the texture view. This is useful for configuring the `TextureViewDimension` when it is not just a plain 2D texture and the loader could/did not identify what it should be.
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2022-07-30 07:02:58 +00:00
|
|
|
let texture_view = texture.create_view(
|
|
|
|
image
|
|
|
|
.texture_view_descriptor
|
|
|
|
.or_else(|| Some(TextureViewDescriptor::default()))
|
|
|
|
.as_ref()
|
|
|
|
.unwrap(),
|
|
|
|
);
|
2022-04-25 13:54:46 +00:00
|
|
|
let size = Vec2::new(
|
Add 2d meshes and materials (#3460)
# Objective
The current 2d rendering is specialized to render sprites, we need a generic way to render 2d items, using meshes and materials like we have for 3d.
## Solution
I cloned a good part of `bevy_pbr` into `bevy_sprite/src/mesh2d`, removed lighting and pbr itself, adapted it to 2d rendering, added a `ColorMaterial`, and modified the sprite rendering to break batches around 2d meshes.
~~The PR is a bit crude; I tried to change as little as I could in both the parts copied from 3d and the current sprite rendering to make reviewing easier. In the future, I expect we could make the sprite rendering a normal 2d material, cleanly integrated with the rest.~~ _edit: see <https://github.com/bevyengine/bevy/pull/3460#issuecomment-1003605194>_
## Remaining work
- ~~don't require mesh normals~~ _out of scope_
- ~~add an example~~ _done_
- support 2d meshes & materials in the UI?
- bikeshed names (I didn't think hard about naming, please check if it's fine)
## Remaining questions
- ~~should we add a depth buffer to 2d now that there are 2d meshes?~~ _let's revisit that when we have an opaque render phase_
- ~~should we add MSAA support to the sprites, or remove it from the 2d meshes?~~ _I added MSAA to sprites since it's really needed for 2d meshes_
- ~~how to customize vertex attributes?~~ _#3120_
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2022-01-08 01:29:08 +00:00
|
|
|
image.texture_descriptor.size.width as f32,
|
|
|
|
image.texture_descriptor.size.height as f32,
|
|
|
|
);
|
2022-06-11 09:13:37 +00:00
|
|
|
let sampler = match image.sampler_descriptor {
|
|
|
|
ImageSampler::Default => (***default_sampler).clone(),
|
|
|
|
ImageSampler::Descriptor(descriptor) => render_device.create_sampler(&descriptor),
|
|
|
|
};
|
|
|
|
|
Modular Rendering (#2831)
This changes how render logic is composed to make it much more modular. Previously, all extraction logic was centralized for a given "type" of rendered thing. For example, we extracted meshes into a vector of ExtractedMesh, which contained the mesh and material asset handles, the transform, etc. We looked up bindings for "drawn things" using their index in the `Vec<ExtractedMesh>`. This worked fine for built in rendering, but made it hard to reuse logic for "custom" rendering. It also prevented us from reusing things like "extracted transforms" across contexts.
To make rendering more modular, I made a number of changes:
* Entities now drive rendering:
* We extract "render components" from "app components" and store them _on_ entities. No more centralized uber lists! We now have true "ECS-driven rendering"
* To make this perform well, I implemented #2673 in upstream Bevy for fast batch insertions into specific entities. This was merged into the `pipelined-rendering` branch here: #2815
* Reworked the `Draw` abstraction:
* Generic `PhaseItems`: each draw phase can define its own type of "rendered thing", which can define its own "sort key"
* Ported the 2d, 3d, and shadow phases to the new PhaseItem impl (currently Transparent2d, Transparent3d, and Shadow PhaseItems)
* `Draw` trait and and `DrawFunctions` are now generic on PhaseItem
* Modular / Ergonomic `DrawFunctions` via `RenderCommands`
* RenderCommand is a trait that runs an ECS query and produces one or more RenderPass calls. Types implementing this trait can be composed to create a final DrawFunction. For example the DrawPbr DrawFunction is created from the following DrawCommand tuple. Const generics are used to set specific bind group locations:
```rust
pub type DrawPbr = (
SetPbrPipeline,
SetMeshViewBindGroup<0>,
SetStandardMaterialBindGroup<1>,
SetTransformBindGroup<2>,
DrawMesh,
);
```
* The new `custom_shader_pipelined` example illustrates how the commands above can be reused to create a custom draw function:
```rust
type DrawCustom = (
SetCustomMaterialPipeline,
SetMeshViewBindGroup<0>,
SetTransformBindGroup<2>,
DrawMesh,
);
```
* ExtractComponentPlugin and UniformComponentPlugin:
* Simple, standardized ways to easily extract individual components and write them to GPU buffers
* Ported PBR and Sprite rendering to the new primitives above.
* Removed staging buffer from UniformVec in favor of direct Queue usage
* Makes UniformVec much easier to use and more ergonomic. Completely removes the need for custom render graph nodes in these contexts (see the PbrNode and view Node removals and the much simpler call patterns in the relevant Prepare systems).
* Added a many_cubes_pipelined example to benchmark baseline 3d rendering performance and ensure there were no major regressions during this port. Avoiding regressions was challenging given that the old approach of extracting into centralized vectors is basically the "optimal" approach. However thanks to a various ECS optimizations and render logic rephrasing, we pretty much break even on this benchmark!
* Lifetimeless SystemParams: this will be a bit divisive, but as we continue to embrace "trait driven systems" (ex: ExtractComponentPlugin, UniformComponentPlugin, DrawCommand), the ergonomics of `(Query<'static, 'static, (&'static A, &'static B, &'static)>, Res<'static, C>)` were getting very hard to bear. As a compromise, I added "static type aliases" for the relevant SystemParams. The previous example can now be expressed like this: `(SQuery<(Read<A>, Read<B>)>, SRes<C>)`. If anyone has better ideas / conflicting opinions, please let me know!
* RunSystem trait: a way to define Systems via a trait with a SystemParam associated type. This is used to implement the various plugins mentioned above. I also added SystemParamItem and QueryItem type aliases to make "trait stye" ecs interactions nicer on the eyes (and fingers).
* RenderAsset retrying: ensures that render assets are only created when they are "ready" and allows us to create bind groups directly inside render assets (which significantly simplified the StandardMaterial code). I think ultimately we should swap this out on "asset dependency" events to wait for dependencies to load, but this will require significant asset system changes.
* Updated some built in shaders to account for missing MeshUniform fields
2021-09-23 06:16:11 +00:00
|
|
|
Ok(GpuImage {
|
2021-06-25 03:04:28 +00:00
|
|
|
texture,
|
|
|
|
texture_view,
|
2022-03-15 22:26:46 +00:00
|
|
|
texture_format: image.texture_descriptor.format,
|
2021-06-25 03:04:28 +00:00
|
|
|
sampler,
|
Add 2d meshes and materials (#3460)
# Objective
The current 2d rendering is specialized to render sprites, we need a generic way to render 2d items, using meshes and materials like we have for 3d.
## Solution
I cloned a good part of `bevy_pbr` into `bevy_sprite/src/mesh2d`, removed lighting and pbr itself, adapted it to 2d rendering, added a `ColorMaterial`, and modified the sprite rendering to break batches around 2d meshes.
~~The PR is a bit crude; I tried to change as little as I could in both the parts copied from 3d and the current sprite rendering to make reviewing easier. In the future, I expect we could make the sprite rendering a normal 2d material, cleanly integrated with the rest.~~ _edit: see <https://github.com/bevyengine/bevy/pull/3460#issuecomment-1003605194>_
## Remaining work
- ~~don't require mesh normals~~ _out of scope_
- ~~add an example~~ _done_
- support 2d meshes & materials in the UI?
- bikeshed names (I didn't think hard about naming, please check if it's fine)
## Remaining questions
- ~~should we add a depth buffer to 2d now that there are 2d meshes?~~ _let's revisit that when we have an opaque render phase_
- ~~should we add MSAA support to the sprites, or remove it from the 2d meshes?~~ _I added MSAA to sprites since it's really needed for 2d meshes_
- ~~how to customize vertex attributes?~~ _#3120_
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2022-01-08 01:29:08 +00:00
|
|
|
size,
|
2023-02-20 00:02:40 +00:00
|
|
|
mip_level_count: image.texture_descriptor.mip_level_count,
|
Modular Rendering (#2831)
This changes how render logic is composed to make it much more modular. Previously, all extraction logic was centralized for a given "type" of rendered thing. For example, we extracted meshes into a vector of ExtractedMesh, which contained the mesh and material asset handles, the transform, etc. We looked up bindings for "drawn things" using their index in the `Vec<ExtractedMesh>`. This worked fine for built in rendering, but made it hard to reuse logic for "custom" rendering. It also prevented us from reusing things like "extracted transforms" across contexts.
To make rendering more modular, I made a number of changes:
* Entities now drive rendering:
* We extract "render components" from "app components" and store them _on_ entities. No more centralized uber lists! We now have true "ECS-driven rendering"
* To make this perform well, I implemented #2673 in upstream Bevy for fast batch insertions into specific entities. This was merged into the `pipelined-rendering` branch here: #2815
* Reworked the `Draw` abstraction:
* Generic `PhaseItems`: each draw phase can define its own type of "rendered thing", which can define its own "sort key"
* Ported the 2d, 3d, and shadow phases to the new PhaseItem impl (currently Transparent2d, Transparent3d, and Shadow PhaseItems)
* `Draw` trait and and `DrawFunctions` are now generic on PhaseItem
* Modular / Ergonomic `DrawFunctions` via `RenderCommands`
* RenderCommand is a trait that runs an ECS query and produces one or more RenderPass calls. Types implementing this trait can be composed to create a final DrawFunction. For example the DrawPbr DrawFunction is created from the following DrawCommand tuple. Const generics are used to set specific bind group locations:
```rust
pub type DrawPbr = (
SetPbrPipeline,
SetMeshViewBindGroup<0>,
SetStandardMaterialBindGroup<1>,
SetTransformBindGroup<2>,
DrawMesh,
);
```
* The new `custom_shader_pipelined` example illustrates how the commands above can be reused to create a custom draw function:
```rust
type DrawCustom = (
SetCustomMaterialPipeline,
SetMeshViewBindGroup<0>,
SetTransformBindGroup<2>,
DrawMesh,
);
```
* ExtractComponentPlugin and UniformComponentPlugin:
* Simple, standardized ways to easily extract individual components and write them to GPU buffers
* Ported PBR and Sprite rendering to the new primitives above.
* Removed staging buffer from UniformVec in favor of direct Queue usage
* Makes UniformVec much easier to use and more ergonomic. Completely removes the need for custom render graph nodes in these contexts (see the PbrNode and view Node removals and the much simpler call patterns in the relevant Prepare systems).
* Added a many_cubes_pipelined example to benchmark baseline 3d rendering performance and ensure there were no major regressions during this port. Avoiding regressions was challenging given that the old approach of extracting into centralized vectors is basically the "optimal" approach. However thanks to a various ECS optimizations and render logic rephrasing, we pretty much break even on this benchmark!
* Lifetimeless SystemParams: this will be a bit divisive, but as we continue to embrace "trait driven systems" (ex: ExtractComponentPlugin, UniformComponentPlugin, DrawCommand), the ergonomics of `(Query<'static, 'static, (&'static A, &'static B, &'static)>, Res<'static, C>)` were getting very hard to bear. As a compromise, I added "static type aliases" for the relevant SystemParams. The previous example can now be expressed like this: `(SQuery<(Read<A>, Read<B>)>, SRes<C>)`. If anyone has better ideas / conflicting opinions, please let me know!
* RunSystem trait: a way to define Systems via a trait with a SystemParam associated type. This is used to implement the various plugins mentioned above. I also added SystemParamItem and QueryItem type aliases to make "trait stye" ecs interactions nicer on the eyes (and fingers).
* RenderAsset retrying: ensures that render assets are only created when they are "ready" and allows us to create bind groups directly inside render assets (which significantly simplified the StandardMaterial code). I think ultimately we should swap this out on "asset dependency" events to wait for dependencies to load, but this will require significant asset system changes.
* Updated some built in shaders to account for missing MeshUniform fields
2021-09-23 06:16:11 +00:00
|
|
|
})
|
2021-06-25 03:04:28 +00:00
|
|
|
}
|
|
|
|
}
|
2022-02-04 03:21:33 +00:00
|
|
|
|
2022-03-15 22:26:46 +00:00
|
|
|
bitflags::bitflags! {
|
|
|
|
#[derive(Default)]
|
|
|
|
#[repr(transparent)]
|
|
|
|
pub struct CompressedImageFormats: u32 {
|
|
|
|
const NONE = 0;
|
|
|
|
const ASTC_LDR = (1 << 0);
|
|
|
|
const BC = (1 << 1);
|
|
|
|
const ETC2 = (1 << 2);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl CompressedImageFormats {
|
|
|
|
pub fn from_features(features: wgpu::Features) -> Self {
|
|
|
|
let mut supported_compressed_formats = Self::default();
|
2023-04-26 15:34:23 +00:00
|
|
|
if features.contains(wgpu::Features::TEXTURE_COMPRESSION_ASTC) {
|
2022-03-15 22:26:46 +00:00
|
|
|
supported_compressed_formats |= Self::ASTC_LDR;
|
|
|
|
}
|
|
|
|
if features.contains(wgpu::Features::TEXTURE_COMPRESSION_BC) {
|
|
|
|
supported_compressed_formats |= Self::BC;
|
|
|
|
}
|
|
|
|
if features.contains(wgpu::Features::TEXTURE_COMPRESSION_ETC2) {
|
|
|
|
supported_compressed_formats |= Self::ETC2;
|
|
|
|
}
|
|
|
|
supported_compressed_formats
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn supports(&self, format: TextureFormat) -> bool {
|
|
|
|
match format {
|
2022-05-31 01:38:07 +00:00
|
|
|
TextureFormat::Bc1RgbaUnorm
|
|
|
|
| TextureFormat::Bc1RgbaUnormSrgb
|
|
|
|
| TextureFormat::Bc2RgbaUnorm
|
|
|
|
| TextureFormat::Bc2RgbaUnormSrgb
|
|
|
|
| TextureFormat::Bc3RgbaUnorm
|
|
|
|
| TextureFormat::Bc3RgbaUnormSrgb
|
|
|
|
| TextureFormat::Bc4RUnorm
|
|
|
|
| TextureFormat::Bc4RSnorm
|
|
|
|
| TextureFormat::Bc5RgUnorm
|
|
|
|
| TextureFormat::Bc5RgSnorm
|
|
|
|
| TextureFormat::Bc6hRgbUfloat
|
2023-04-26 15:34:23 +00:00
|
|
|
| TextureFormat::Bc6hRgbFloat
|
2022-05-31 01:38:07 +00:00
|
|
|
| TextureFormat::Bc7RgbaUnorm
|
|
|
|
| TextureFormat::Bc7RgbaUnormSrgb => self.contains(CompressedImageFormats::BC),
|
|
|
|
TextureFormat::Etc2Rgb8Unorm
|
|
|
|
| TextureFormat::Etc2Rgb8UnormSrgb
|
|
|
|
| TextureFormat::Etc2Rgb8A1Unorm
|
|
|
|
| TextureFormat::Etc2Rgb8A1UnormSrgb
|
|
|
|
| TextureFormat::Etc2Rgba8Unorm
|
|
|
|
| TextureFormat::Etc2Rgba8UnormSrgb
|
|
|
|
| TextureFormat::EacR11Unorm
|
|
|
|
| TextureFormat::EacR11Snorm
|
|
|
|
| TextureFormat::EacRg11Unorm
|
|
|
|
| TextureFormat::EacRg11Snorm => self.contains(CompressedImageFormats::ETC2),
|
2022-07-14 21:17:16 +00:00
|
|
|
TextureFormat::Astc { .. } => self.contains(CompressedImageFormats::ASTC_LDR),
|
2022-03-15 22:26:46 +00:00
|
|
|
_ => true,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-02-04 03:21:33 +00:00
|
|
|
#[cfg(test)]
|
|
|
|
mod test {
|
|
|
|
|
|
|
|
use super::*;
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn image_size() {
|
|
|
|
let size = Extent3d {
|
|
|
|
width: 200,
|
|
|
|
height: 100,
|
|
|
|
depth_or_array_layers: 1,
|
|
|
|
};
|
|
|
|
let image = Image::new_fill(
|
|
|
|
size,
|
|
|
|
TextureDimension::D2,
|
|
|
|
&[0, 0, 0, 255],
|
|
|
|
TextureFormat::Rgba8Unorm,
|
|
|
|
);
|
|
|
|
assert_eq!(
|
|
|
|
Vec2::new(size.width as f32, size.height as f32),
|
|
|
|
image.size()
|
|
|
|
);
|
|
|
|
}
|
|
|
|
#[test]
|
|
|
|
fn image_default_size() {
|
|
|
|
let image = Image::default();
|
2022-07-03 19:55:33 +00:00
|
|
|
assert_eq!(Vec2::ONE, image.size());
|
2022-02-04 03:21:33 +00:00
|
|
|
}
|
|
|
|
}
|