Suppress the `clippy::type_complexity` lint (#8313)
# Objective
The clippy lint `type_complexity` is known not to play well with bevy.
It frequently triggers when writing complex queries, and taking the
lint's advice of using a type alias almost always just obfuscates the
code with no benefit. Because of this, this lint is currently ignored in
CI, but unfortunately it still shows up when viewing bevy code in an
IDE.
As someone who's made a fair amount of pull requests to this repo, I
will say that this issue has been a consistent thorn in my side. Since
bevy code is filled with spurious, ignorable warnings, it can be very
difficult to spot the *real* warnings that must be fixed -- most of the
time I just ignore all warnings, only to later find out that one of them
was real after I'm done when CI runs.
## Solution
Suppress this lint in all bevy crates. This was previously attempted in
#7050, but the review process ended up making it more complicated than
it needs to be and landed on a subpar solution.
The discussion in https://github.com/rust-lang/rust-clippy/pull/10571
explores some better long-term solutions to this problem. Since there is
no timeline on when these solutions may land, we should resolve this
issue in the meantime by locally suppressing these lints.
### Unresolved issues
Currently, these lints are not suppressed in our examples, since that
would require suppressing the lint in every single source file. They are
still ignored in CI.
2023-04-06 21:27:36 +00:00
|
|
|
#![allow(clippy::type_complexity)]
|
2023-03-28 20:58:02 +00:00
|
|
|
#![warn(missing_docs)]
|
|
|
|
|
|
|
|
//! This crate adds an immediate mode drawing api to Bevy for visual debugging.
|
|
|
|
//!
|
|
|
|
//! # Example
|
|
|
|
//! ```
|
|
|
|
//! # use bevy_gizmos::prelude::*;
|
|
|
|
//! # use bevy_render::prelude::*;
|
|
|
|
//! # use bevy_math::prelude::*;
|
|
|
|
//! fn system(mut gizmos: Gizmos) {
|
|
|
|
//! gizmos.line(Vec3::ZERO, Vec3::X, Color::GREEN);
|
|
|
|
//! }
|
|
|
|
//! # bevy_ecs::system::assert_is_system(system);
|
|
|
|
//! ```
|
|
|
|
//!
|
|
|
|
//! See the documentation on [`Gizmos`](crate::gizmos::Gizmos) for more examples.
|
|
|
|
|
2023-03-20 20:57:54 +00:00
|
|
|
use std::mem;
|
|
|
|
|
2023-07-23 01:01:45 +00:00
|
|
|
use bevy_app::{Last, Plugin, PostUpdate};
|
2023-06-13 06:49:47 +00:00
|
|
|
use bevy_asset::{load_internal_asset, AddAsset, Assets, Handle, HandleUntyped};
|
|
|
|
use bevy_core::cast_slice;
|
2023-03-20 20:57:54 +00:00
|
|
|
use bevy_ecs::{
|
2023-04-24 15:23:06 +00:00
|
|
|
change_detection::DetectChanges,
|
|
|
|
component::Component,
|
|
|
|
entity::Entity,
|
2023-06-13 06:49:47 +00:00
|
|
|
query::{ROQueryItem, Without},
|
2023-04-24 15:23:06 +00:00
|
|
|
reflect::ReflectComponent,
|
2023-03-20 20:57:54 +00:00
|
|
|
schedule::IntoSystemConfigs,
|
2023-06-13 06:49:47 +00:00
|
|
|
system::{
|
|
|
|
lifetimeless::{Read, SRes},
|
|
|
|
Commands, Query, Res, ResMut, Resource, SystemParamItem,
|
|
|
|
},
|
2023-03-20 20:57:54 +00:00
|
|
|
};
|
bevy_reflect: `FromReflect` Ergonomics Implementation (#6056)
# Objective
**This implementation is based on
https://github.com/bevyengine/rfcs/pull/59.**
---
Resolves #4597
Full details and motivation can be found in the RFC, but here's a brief
summary.
`FromReflect` is a very powerful and important trait within the
reflection API. It allows Dynamic types (e.g., `DynamicList`, etc.) to
be formed into Real ones (e.g., `Vec<i32>`, etc.).
This mainly comes into play concerning deserialization, where the
reflection deserializers both return a `Box<dyn Reflect>` that almost
always contain one of these Dynamic representations of a Real type. To
convert this to our Real type, we need to use `FromReflect`.
It also sneaks up in other ways. For example, it's a required bound for
`T` in `Vec<T>` so that `Vec<T>` as a whole can be made `FromReflect`.
It's also required by all fields of an enum as it's used as part of the
`Reflect::apply` implementation.
So in other words, much like `GetTypeRegistration` and `Typed`, it is
very much a core reflection trait.
The problem is that it is not currently treated like a core trait and is
not automatically derived alongside `Reflect`. This makes using it a bit
cumbersome and easy to forget.
## Solution
Automatically derive `FromReflect` when deriving `Reflect`.
Users can then choose to opt-out if needed using the
`#[reflect(from_reflect = false)]` attribute.
```rust
#[derive(Reflect)]
struct Foo;
#[derive(Reflect)]
#[reflect(from_reflect = false)]
struct Bar;
fn test<T: FromReflect>(value: T) {}
test(Foo); // <-- OK
test(Bar); // <-- Panic! Bar does not implement trait `FromReflect`
```
#### `ReflectFromReflect`
This PR also automatically adds the `ReflectFromReflect` (introduced in
#6245) registration to the derived `GetTypeRegistration` impl— if the
type hasn't opted out of `FromReflect` of course.
<details>
<summary><h4>Improved Deserialization</h4></summary>
> **Warning**
> This section includes changes that have since been descoped from this
PR. They will likely be implemented again in a followup PR. I am mainly
leaving these details in for archival purposes, as well as for reference
when implementing this logic again.
And since we can do all the above, we might as well improve
deserialization. We can now choose to deserialize into a Dynamic type or
automatically convert it using `FromReflect` under the hood.
`[Un]TypedReflectDeserializer::new` will now perform the conversion and
return the `Box`'d Real type.
`[Un]TypedReflectDeserializer::new_dynamic` will work like what we have
now and simply return the `Box`'d Dynamic type.
```rust
// Returns the Real type
let reflect_deserializer = UntypedReflectDeserializer::new(®istry);
let mut deserializer = ron::de::Deserializer::from_str(input)?;
let output: SomeStruct = reflect_deserializer.deserialize(&mut deserializer)?.take()?;
// Returns the Dynamic type
let reflect_deserializer = UntypedReflectDeserializer::new_dynamic(®istry);
let mut deserializer = ron::de::Deserializer::from_str(input)?;
let output: DynamicStruct = reflect_deserializer.deserialize(&mut deserializer)?.take()?;
```
</details>
---
## Changelog
* `FromReflect` is now automatically derived within the `Reflect` derive
macro
* This includes auto-registering `ReflectFromReflect` in the derived
`GetTypeRegistration` impl
* ~~Renamed `TypedReflectDeserializer::new` and
`UntypedReflectDeserializer::new` to
`TypedReflectDeserializer::new_dynamic` and
`UntypedReflectDeserializer::new_dynamic`, respectively~~ **Descoped**
* ~~Changed `TypedReflectDeserializer::new` and
`UntypedReflectDeserializer::new` to automatically convert the
deserialized output using `FromReflect`~~ **Descoped**
## Migration Guide
* `FromReflect` is now automatically derived within the `Reflect` derive
macro. Items with both derives will need to remove the `FromReflect`
one.
```rust
// OLD
#[derive(Reflect, FromReflect)]
struct Foo;
// NEW
#[derive(Reflect)]
struct Foo;
```
If using a manual implementation of `FromReflect` and the `Reflect`
derive, users will need to opt-out of the automatic implementation.
```rust
// OLD
#[derive(Reflect)]
struct Foo;
impl FromReflect for Foo {/* ... */}
// NEW
#[derive(Reflect)]
#[reflect(from_reflect = false)]
struct Foo;
impl FromReflect for Foo {/* ... */}
```
<details>
<summary><h4>Removed Migrations</h4></summary>
> **Warning**
> This section includes changes that have since been descoped from this
PR. They will likely be implemented again in a followup PR. I am mainly
leaving these details in for archival purposes, as well as for reference
when implementing this logic again.
* The reflect deserializers now perform a `FromReflect` conversion
internally. The expected output of `TypedReflectDeserializer::new` and
`UntypedReflectDeserializer::new` is no longer a Dynamic (e.g.,
`DynamicList`), but its Real counterpart (e.g., `Vec<i32>`).
```rust
let reflect_deserializer =
UntypedReflectDeserializer::new_dynamic(®istry);
let mut deserializer = ron::de::Deserializer::from_str(input)?;
// OLD
let output: DynamicStruct = reflect_deserializer.deserialize(&mut
deserializer)?.take()?;
// NEW
let output: SomeStruct = reflect_deserializer.deserialize(&mut
deserializer)?.take()?;
```
Alternatively, if this behavior isn't desired, use the
`TypedReflectDeserializer::new_dynamic` and
`UntypedReflectDeserializer::new_dynamic` methods instead:
```rust
// OLD
let reflect_deserializer = UntypedReflectDeserializer::new(®istry);
// NEW
let reflect_deserializer =
UntypedReflectDeserializer::new_dynamic(®istry);
```
</details>
---------
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2023-06-29 01:31:34 +00:00
|
|
|
use bevy_reflect::{std_traits::ReflectDefault, Reflect, TypePath, TypeUuid};
|
2023-03-20 20:57:54 +00:00
|
|
|
use bevy_render::{
|
2023-04-24 15:23:06 +00:00
|
|
|
color::Color,
|
2023-06-13 06:49:47 +00:00
|
|
|
extract_component::{ComponentUniforms, DynamicUniformIndex, UniformComponentPlugin},
|
2023-04-24 15:23:06 +00:00
|
|
|
primitives::Aabb,
|
2023-06-13 06:49:47 +00:00
|
|
|
render_asset::{PrepareAssetError, RenderAsset, RenderAssetPlugin, RenderAssets},
|
|
|
|
render_phase::{PhaseItem, RenderCommand, RenderCommandResult, TrackedRenderPass},
|
|
|
|
render_resource::{
|
|
|
|
BindGroup, BindGroupDescriptor, BindGroupEntry, BindGroupLayout, BindGroupLayoutDescriptor,
|
|
|
|
BindGroupLayoutEntry, BindingType, Buffer, BufferBindingType, BufferInitDescriptor,
|
|
|
|
BufferUsages, Shader, ShaderStages, ShaderType, VertexAttribute, VertexBufferLayout,
|
|
|
|
VertexFormat, VertexStepMode,
|
|
|
|
},
|
|
|
|
renderer::RenderDevice,
|
2023-06-29 00:56:31 +00:00
|
|
|
view::RenderLayers,
|
2023-03-20 20:57:54 +00:00
|
|
|
Extract, ExtractSchedule, Render, RenderApp, RenderSet,
|
|
|
|
};
|
2023-07-23 01:01:45 +00:00
|
|
|
use bevy_transform::{
|
|
|
|
components::{GlobalTransform, Transform},
|
|
|
|
TransformSystem,
|
|
|
|
};
|
2023-03-20 20:57:54 +00:00
|
|
|
|
|
|
|
pub mod gizmos;
|
|
|
|
|
|
|
|
#[cfg(feature = "bevy_sprite")]
|
|
|
|
mod pipeline_2d;
|
|
|
|
#[cfg(feature = "bevy_pbr")]
|
|
|
|
mod pipeline_3d;
|
|
|
|
|
2023-04-24 15:23:06 +00:00
|
|
|
use gizmos::{GizmoStorage, Gizmos};
|
2023-03-20 20:57:54 +00:00
|
|
|
|
|
|
|
/// The `bevy_gizmos` prelude.
|
|
|
|
pub mod prelude {
|
|
|
|
#[doc(hidden)]
|
2023-04-24 15:23:06 +00:00
|
|
|
pub use crate::{gizmos::Gizmos, AabbGizmo, AabbGizmoConfig, GizmoConfig};
|
2023-03-20 20:57:54 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
const LINE_SHADER_HANDLE: HandleUntyped =
|
|
|
|
HandleUntyped::weak_from_u64(Shader::TYPE_UUID, 7414812689238026784);
|
|
|
|
|
2023-03-28 20:58:02 +00:00
|
|
|
/// A [`Plugin`] that provides an immediate mode drawing api for visual debugging.
|
2023-03-20 20:57:54 +00:00
|
|
|
pub struct GizmoPlugin;
|
|
|
|
|
|
|
|
impl Plugin for GizmoPlugin {
|
|
|
|
fn build(&self, app: &mut bevy_app::App) {
|
|
|
|
load_internal_asset!(app, LINE_SHADER_HANDLE, "lines.wgsl", Shader::from_wgsl);
|
|
|
|
|
2023-06-21 20:51:03 +00:00
|
|
|
app.add_plugins(UniformComponentPlugin::<LineGizmoUniform>::default())
|
2023-06-13 06:49:47 +00:00
|
|
|
.add_asset::<LineGizmo>()
|
2023-06-21 20:51:03 +00:00
|
|
|
.add_plugins(RenderAssetPlugin::<LineGizmo>::default())
|
2023-06-13 06:49:47 +00:00
|
|
|
.init_resource::<LineGizmoHandles>()
|
2023-03-20 20:57:54 +00:00
|
|
|
.init_resource::<GizmoConfig>()
|
|
|
|
.init_resource::<GizmoStorage>()
|
2023-04-24 15:23:06 +00:00
|
|
|
.add_systems(Last, update_gizmo_meshes)
|
|
|
|
.add_systems(
|
2023-07-23 01:01:45 +00:00
|
|
|
PostUpdate,
|
2023-04-24 15:23:06 +00:00
|
|
|
(
|
|
|
|
draw_aabbs,
|
|
|
|
draw_all_aabbs.run_if(|config: Res<GizmoConfig>| config.aabb.draw_all),
|
2023-07-23 01:01:45 +00:00
|
|
|
)
|
|
|
|
.after(TransformSystem::TransformPropagate),
|
2023-04-24 15:23:06 +00:00
|
|
|
);
|
2023-03-20 20:57:54 +00:00
|
|
|
|
|
|
|
let Ok(render_app) = app.get_sub_app_mut(RenderApp) else { return; };
|
|
|
|
|
2023-06-13 06:49:47 +00:00
|
|
|
render_app
|
|
|
|
.add_systems(ExtractSchedule, extract_gizmo_data)
|
|
|
|
.add_systems(Render, queue_line_gizmo_bind_group.in_set(RenderSet::Queue));
|
2023-03-20 20:57:54 +00:00
|
|
|
|
|
|
|
#[cfg(feature = "bevy_sprite")]
|
2023-06-21 20:51:03 +00:00
|
|
|
app.add_plugins(pipeline_2d::LineGizmo2dPlugin);
|
2023-03-20 20:57:54 +00:00
|
|
|
#[cfg(feature = "bevy_pbr")]
|
2023-06-21 20:51:03 +00:00
|
|
|
app.add_plugins(pipeline_3d::LineGizmo3dPlugin);
|
2023-03-20 20:57:54 +00:00
|
|
|
}
|
Webgpu support (#8336)
# Objective
- Support WebGPU
- alternative to #5027 that doesn't need any async / await
- fixes #8315
- Surprise fix #7318
## Solution
### For async renderer initialisation
- Update the plugin lifecycle:
- app builds the plugin
- calls `plugin.build`
- registers the plugin
- app starts the event loop
- event loop waits for `ready` of all registered plugins in the same
order
- returns `true` by default
- then call all `finish` then all `cleanup` in the same order as
registered
- then execute the schedule
In the case of the renderer, to avoid anything async:
- building the renderer plugin creates a detached task that will send
back the initialised renderer through a mutex in a resource
- `ready` will wait for the renderer to be present in the resource
- `finish` will take that renderer and place it in the expected
resources by other plugins
- other plugins (that expect the renderer to be available) `finish` are
called and they are able to set up their pipelines
- `cleanup` is called, only custom one is still for pipeline rendering
### For WebGPU support
- update the `build-wasm-example` script to support passing `--api
webgpu` that will build the example with WebGPU support
- feature for webgl2 was always enabled when building for wasm. it's now
in the default feature list and enabled on all platforms, so check for
this feature must also check that the target_arch is `wasm32`
---
## Migration Guide
- `Plugin::setup` has been renamed `Plugin::cleanup`
- `Plugin::finish` has been added, and plugins adding pipelines should
do it in this function instead of `Plugin::build`
```rust
// Before
impl Plugin for MyPlugin {
fn build(&self, app: &mut App) {
app.insert_resource::<MyResource>
.add_systems(Update, my_system);
let render_app = match app.get_sub_app_mut(RenderApp) {
Ok(render_app) => render_app,
Err(_) => return,
};
render_app
.init_resource::<RenderResourceNeedingDevice>()
.init_resource::<OtherRenderResource>();
}
}
// After
impl Plugin for MyPlugin {
fn build(&self, app: &mut App) {
app.insert_resource::<MyResource>
.add_systems(Update, my_system);
let render_app = match app.get_sub_app_mut(RenderApp) {
Ok(render_app) => render_app,
Err(_) => return,
};
render_app
.init_resource::<OtherRenderResource>();
}
fn finish(&self, app: &mut App) {
let render_app = match app.get_sub_app_mut(RenderApp) {
Ok(render_app) => render_app,
Err(_) => return,
};
render_app
.init_resource::<RenderResourceNeedingDevice>();
}
}
```
2023-05-04 22:07:57 +00:00
|
|
|
|
|
|
|
fn finish(&self, app: &mut bevy_app::App) {
|
|
|
|
let Ok(render_app) = app.get_sub_app_mut(RenderApp) else { return; };
|
|
|
|
|
2023-06-13 06:49:47 +00:00
|
|
|
let render_device = render_app.world.resource::<RenderDevice>();
|
|
|
|
let layout = render_device.create_bind_group_layout(&BindGroupLayoutDescriptor {
|
|
|
|
entries: &[BindGroupLayoutEntry {
|
|
|
|
binding: 0,
|
|
|
|
visibility: ShaderStages::VERTEX,
|
|
|
|
ty: BindingType::Buffer {
|
|
|
|
ty: BufferBindingType::Uniform,
|
|
|
|
has_dynamic_offset: true,
|
|
|
|
min_binding_size: Some(LineGizmoUniform::min_size()),
|
|
|
|
},
|
|
|
|
count: None,
|
|
|
|
}],
|
|
|
|
label: Some("LineGizmoUniform layout"),
|
|
|
|
});
|
|
|
|
|
|
|
|
render_app.insert_resource(LineGizmoUniformBindgroupLayout { layout });
|
Webgpu support (#8336)
# Objective
- Support WebGPU
- alternative to #5027 that doesn't need any async / await
- fixes #8315
- Surprise fix #7318
## Solution
### For async renderer initialisation
- Update the plugin lifecycle:
- app builds the plugin
- calls `plugin.build`
- registers the plugin
- app starts the event loop
- event loop waits for `ready` of all registered plugins in the same
order
- returns `true` by default
- then call all `finish` then all `cleanup` in the same order as
registered
- then execute the schedule
In the case of the renderer, to avoid anything async:
- building the renderer plugin creates a detached task that will send
back the initialised renderer through a mutex in a resource
- `ready` will wait for the renderer to be present in the resource
- `finish` will take that renderer and place it in the expected
resources by other plugins
- other plugins (that expect the renderer to be available) `finish` are
called and they are able to set up their pipelines
- `cleanup` is called, only custom one is still for pipeline rendering
### For WebGPU support
- update the `build-wasm-example` script to support passing `--api
webgpu` that will build the example with WebGPU support
- feature for webgl2 was always enabled when building for wasm. it's now
in the default feature list and enabled on all platforms, so check for
this feature must also check that the target_arch is `wasm32`
---
## Migration Guide
- `Plugin::setup` has been renamed `Plugin::cleanup`
- `Plugin::finish` has been added, and plugins adding pipelines should
do it in this function instead of `Plugin::build`
```rust
// Before
impl Plugin for MyPlugin {
fn build(&self, app: &mut App) {
app.insert_resource::<MyResource>
.add_systems(Update, my_system);
let render_app = match app.get_sub_app_mut(RenderApp) {
Ok(render_app) => render_app,
Err(_) => return,
};
render_app
.init_resource::<RenderResourceNeedingDevice>()
.init_resource::<OtherRenderResource>();
}
}
// After
impl Plugin for MyPlugin {
fn build(&self, app: &mut App) {
app.insert_resource::<MyResource>
.add_systems(Update, my_system);
let render_app = match app.get_sub_app_mut(RenderApp) {
Ok(render_app) => render_app,
Err(_) => return,
};
render_app
.init_resource::<OtherRenderResource>();
}
fn finish(&self, app: &mut App) {
let render_app = match app.get_sub_app_mut(RenderApp) {
Ok(render_app) => render_app,
Err(_) => return,
};
render_app
.init_resource::<RenderResourceNeedingDevice>();
}
}
```
2023-05-04 22:07:57 +00:00
|
|
|
}
|
2023-03-20 20:57:54 +00:00
|
|
|
}
|
|
|
|
|
2023-03-28 20:58:02 +00:00
|
|
|
/// A [`Resource`] that stores configuration for gizmos.
|
2023-04-24 15:23:06 +00:00
|
|
|
#[derive(Resource, Clone)]
|
2023-03-20 20:57:54 +00:00
|
|
|
pub struct GizmoConfig {
|
|
|
|
/// Set to `false` to stop drawing gizmos.
|
|
|
|
///
|
|
|
|
/// Defaults to `true`.
|
|
|
|
pub enabled: bool,
|
2023-06-13 06:49:47 +00:00
|
|
|
/// Line width specified in pixels.
|
|
|
|
///
|
|
|
|
/// If `line_perspective` is `true` then this is the size in pixels at the camera's near plane.
|
2023-03-20 20:57:54 +00:00
|
|
|
///
|
2023-06-13 06:49:47 +00:00
|
|
|
/// Defaults to `2.0`.
|
|
|
|
pub line_width: f32,
|
|
|
|
/// Apply perspective to gizmo lines.
|
|
|
|
///
|
|
|
|
/// This setting only affects 3D, non-orhographic cameras.
|
2023-03-20 20:57:54 +00:00
|
|
|
///
|
|
|
|
/// Defaults to `false`.
|
2023-06-13 06:49:47 +00:00
|
|
|
pub line_perspective: bool,
|
|
|
|
/// How closer to the camera than real geometry the line should be.
|
|
|
|
///
|
|
|
|
/// Value between -1 and 1 (inclusive).
|
|
|
|
/// * 0 means that there is no change to the line position when rendering
|
|
|
|
/// * 1 means it is furthest away from camera as possible
|
|
|
|
/// * -1 means that it will always render in front of other things.
|
|
|
|
///
|
|
|
|
/// This is typically useful if you are drawing wireframes on top of polygons
|
|
|
|
/// and your wireframe is z-fighting (flickering on/off) with your main model.
|
|
|
|
/// You would set this value to a negative number close to 0.0.
|
|
|
|
pub depth_bias: f32,
|
2023-04-24 15:23:06 +00:00
|
|
|
/// Configuration for the [`AabbGizmo`].
|
|
|
|
pub aabb: AabbGizmoConfig,
|
2023-06-29 00:56:31 +00:00
|
|
|
/// Describes which rendering layers gizmos will be rendered to.
|
|
|
|
///
|
|
|
|
/// Gizmos will only be rendered to cameras with intersecting layers.
|
|
|
|
pub render_layers: RenderLayers,
|
2023-03-20 20:57:54 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl Default for GizmoConfig {
|
|
|
|
fn default() -> Self {
|
|
|
|
Self {
|
|
|
|
enabled: true,
|
2023-06-13 06:49:47 +00:00
|
|
|
line_width: 2.,
|
|
|
|
line_perspective: false,
|
|
|
|
depth_bias: 0.,
|
2023-04-24 15:23:06 +00:00
|
|
|
aabb: Default::default(),
|
2023-06-29 00:56:31 +00:00
|
|
|
render_layers: Default::default(),
|
2023-03-20 20:57:54 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-04-24 15:23:06 +00:00
|
|
|
/// Configuration for drawing the [`Aabb`] component on entities.
|
|
|
|
#[derive(Clone, Default)]
|
|
|
|
pub struct AabbGizmoConfig {
|
|
|
|
/// Draws all bounding boxes in the scene when set to `true`.
|
|
|
|
///
|
|
|
|
/// To draw a specific entity's bounding box, you can add the [`AabbGizmo`] component.
|
|
|
|
///
|
|
|
|
/// Defaults to `false`.
|
|
|
|
pub draw_all: bool,
|
|
|
|
/// The default color for bounding box gizmos.
|
|
|
|
///
|
|
|
|
/// A random color is chosen per box if `None`.
|
|
|
|
///
|
|
|
|
/// Defaults to `None`.
|
|
|
|
pub default_color: Option<Color>,
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Add this [`Component`] to an entity to draw its [`Aabb`] component.
|
bevy_reflect: `FromReflect` Ergonomics Implementation (#6056)
# Objective
**This implementation is based on
https://github.com/bevyengine/rfcs/pull/59.**
---
Resolves #4597
Full details and motivation can be found in the RFC, but here's a brief
summary.
`FromReflect` is a very powerful and important trait within the
reflection API. It allows Dynamic types (e.g., `DynamicList`, etc.) to
be formed into Real ones (e.g., `Vec<i32>`, etc.).
This mainly comes into play concerning deserialization, where the
reflection deserializers both return a `Box<dyn Reflect>` that almost
always contain one of these Dynamic representations of a Real type. To
convert this to our Real type, we need to use `FromReflect`.
It also sneaks up in other ways. For example, it's a required bound for
`T` in `Vec<T>` so that `Vec<T>` as a whole can be made `FromReflect`.
It's also required by all fields of an enum as it's used as part of the
`Reflect::apply` implementation.
So in other words, much like `GetTypeRegistration` and `Typed`, it is
very much a core reflection trait.
The problem is that it is not currently treated like a core trait and is
not automatically derived alongside `Reflect`. This makes using it a bit
cumbersome and easy to forget.
## Solution
Automatically derive `FromReflect` when deriving `Reflect`.
Users can then choose to opt-out if needed using the
`#[reflect(from_reflect = false)]` attribute.
```rust
#[derive(Reflect)]
struct Foo;
#[derive(Reflect)]
#[reflect(from_reflect = false)]
struct Bar;
fn test<T: FromReflect>(value: T) {}
test(Foo); // <-- OK
test(Bar); // <-- Panic! Bar does not implement trait `FromReflect`
```
#### `ReflectFromReflect`
This PR also automatically adds the `ReflectFromReflect` (introduced in
#6245) registration to the derived `GetTypeRegistration` impl— if the
type hasn't opted out of `FromReflect` of course.
<details>
<summary><h4>Improved Deserialization</h4></summary>
> **Warning**
> This section includes changes that have since been descoped from this
PR. They will likely be implemented again in a followup PR. I am mainly
leaving these details in for archival purposes, as well as for reference
when implementing this logic again.
And since we can do all the above, we might as well improve
deserialization. We can now choose to deserialize into a Dynamic type or
automatically convert it using `FromReflect` under the hood.
`[Un]TypedReflectDeserializer::new` will now perform the conversion and
return the `Box`'d Real type.
`[Un]TypedReflectDeserializer::new_dynamic` will work like what we have
now and simply return the `Box`'d Dynamic type.
```rust
// Returns the Real type
let reflect_deserializer = UntypedReflectDeserializer::new(®istry);
let mut deserializer = ron::de::Deserializer::from_str(input)?;
let output: SomeStruct = reflect_deserializer.deserialize(&mut deserializer)?.take()?;
// Returns the Dynamic type
let reflect_deserializer = UntypedReflectDeserializer::new_dynamic(®istry);
let mut deserializer = ron::de::Deserializer::from_str(input)?;
let output: DynamicStruct = reflect_deserializer.deserialize(&mut deserializer)?.take()?;
```
</details>
---
## Changelog
* `FromReflect` is now automatically derived within the `Reflect` derive
macro
* This includes auto-registering `ReflectFromReflect` in the derived
`GetTypeRegistration` impl
* ~~Renamed `TypedReflectDeserializer::new` and
`UntypedReflectDeserializer::new` to
`TypedReflectDeserializer::new_dynamic` and
`UntypedReflectDeserializer::new_dynamic`, respectively~~ **Descoped**
* ~~Changed `TypedReflectDeserializer::new` and
`UntypedReflectDeserializer::new` to automatically convert the
deserialized output using `FromReflect`~~ **Descoped**
## Migration Guide
* `FromReflect` is now automatically derived within the `Reflect` derive
macro. Items with both derives will need to remove the `FromReflect`
one.
```rust
// OLD
#[derive(Reflect, FromReflect)]
struct Foo;
// NEW
#[derive(Reflect)]
struct Foo;
```
If using a manual implementation of `FromReflect` and the `Reflect`
derive, users will need to opt-out of the automatic implementation.
```rust
// OLD
#[derive(Reflect)]
struct Foo;
impl FromReflect for Foo {/* ... */}
// NEW
#[derive(Reflect)]
#[reflect(from_reflect = false)]
struct Foo;
impl FromReflect for Foo {/* ... */}
```
<details>
<summary><h4>Removed Migrations</h4></summary>
> **Warning**
> This section includes changes that have since been descoped from this
PR. They will likely be implemented again in a followup PR. I am mainly
leaving these details in for archival purposes, as well as for reference
when implementing this logic again.
* The reflect deserializers now perform a `FromReflect` conversion
internally. The expected output of `TypedReflectDeserializer::new` and
`UntypedReflectDeserializer::new` is no longer a Dynamic (e.g.,
`DynamicList`), but its Real counterpart (e.g., `Vec<i32>`).
```rust
let reflect_deserializer =
UntypedReflectDeserializer::new_dynamic(®istry);
let mut deserializer = ron::de::Deserializer::from_str(input)?;
// OLD
let output: DynamicStruct = reflect_deserializer.deserialize(&mut
deserializer)?.take()?;
// NEW
let output: SomeStruct = reflect_deserializer.deserialize(&mut
deserializer)?.take()?;
```
Alternatively, if this behavior isn't desired, use the
`TypedReflectDeserializer::new_dynamic` and
`UntypedReflectDeserializer::new_dynamic` methods instead:
```rust
// OLD
let reflect_deserializer = UntypedReflectDeserializer::new(®istry);
// NEW
let reflect_deserializer =
UntypedReflectDeserializer::new_dynamic(®istry);
```
</details>
---------
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2023-06-29 01:31:34 +00:00
|
|
|
#[derive(Component, Reflect, Default, Debug)]
|
|
|
|
#[reflect(Component, Default)]
|
2023-04-24 15:23:06 +00:00
|
|
|
pub struct AabbGizmo {
|
|
|
|
/// The color of the box.
|
|
|
|
///
|
|
|
|
/// The default color from the [`GizmoConfig`] resource is used if `None`,
|
|
|
|
pub color: Option<Color>,
|
|
|
|
}
|
|
|
|
|
|
|
|
fn draw_aabbs(
|
|
|
|
query: Query<(Entity, &Aabb, &GlobalTransform, &AabbGizmo)>,
|
|
|
|
config: Res<GizmoConfig>,
|
|
|
|
mut gizmos: Gizmos,
|
|
|
|
) {
|
|
|
|
for (entity, &aabb, &transform, gizmo) in &query {
|
|
|
|
let color = gizmo
|
|
|
|
.color
|
|
|
|
.or(config.aabb.default_color)
|
|
|
|
.unwrap_or_else(|| color_from_entity(entity));
|
|
|
|
gizmos.cuboid(aabb_transform(aabb, transform), color);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn draw_all_aabbs(
|
|
|
|
query: Query<(Entity, &Aabb, &GlobalTransform), Without<AabbGizmo>>,
|
|
|
|
config: Res<GizmoConfig>,
|
|
|
|
mut gizmos: Gizmos,
|
|
|
|
) {
|
|
|
|
for (entity, &aabb, &transform) in &query {
|
|
|
|
let color = config
|
|
|
|
.aabb
|
|
|
|
.default_color
|
|
|
|
.unwrap_or_else(|| color_from_entity(entity));
|
|
|
|
gizmos.cuboid(aabb_transform(aabb, transform), color);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn color_from_entity(entity: Entity) -> Color {
|
Replace AHash with a good sequence for entity AABB colors (#9175)
# Objective
- #8960 isn't optimal for very distinct AABB colors, it can be improved
## Solution
We want a function that maps sequential values (entities concurrently
living in a scene _usually_ have ids that are sequential) into very
different colors (the hue component of the color, to be specific)
What we are looking for is a [so-called "low discrepancy"
sequence](https://en.wikipedia.org/wiki/Low-discrepancy_sequence). ie: a
function `f` such as for integers in a given range (eg: 101, 102, 103…),
`f(i)` returns a rational number in the [0..1] range, such as `|f(i) -
f(i±1)| ≈ 0.5` (maximum difference of images for neighboring preimages)
AHash is a good random hasher, but it has relatively high discrepancy,
so we need something else.
Known good low discrepancy sequences are:
#### The [Van Der Corput
sequence](https://en.wikipedia.org/wiki/Van_der_Corput_sequence)
<details><summary>Rust implementation</summary>
```rust
fn van_der_corput(bits: u64) -> f32 {
let leading_zeros = if bits == 0 { 0 } else { bits.leading_zeros() };
let nominator = bits.reverse_bits() >> leading_zeros;
let denominator = bits.next_power_of_two();
nominator as f32 / denominator as f32
}
```
</details>
#### The [Gold Kronecker
sequence](https://extremelearning.com.au/unreasonable-effectiveness-of-quasirandom-sequences/)
<details><summary>Rust implementation</summary>
Note that the implementation suggested in the linked post assumes
floats, we have integers
```rust
fn gold_kronecker(bits: u64) -> f32 {
const U64_MAX_F: f32 = u64::MAX as f32;
// (u64::MAX / Φ) rounded down
const FRAC_U64MAX_GOLDEN_RATIO: u64 = 11400714819323198485;
bits.wrapping_mul(FRAC_U64MAX_GOLDEN_RATIO) as f32 / U64_MAX_F
}
```
</details>
### Comparison of the sequences
So they are both pretty good. Both only have a single (!) division and
two `u32 as f32` conversions.
- Kronecker is resilient to regular sequence (eg: 100, 102, 104, 106)
while this kills Van Der Corput (consider that potentially one entity
out of two spawned might be a mesh)
I made a small app to compare the two sequences, available at:
https://gist.github.com/nicopap/5dd9bd6700c6a9a9cf90c9199941883e
At the top, we have Van Der Corput, at the bottom we have the Gold
Kronecker. In the video, we spawn a vertical line at the position on
screen where the x coordinate is the image of the sequence. The
preimages are 1,2,3,4,… The ideal algorithm would always have the
largest possible gap between each line (imagine the screen x coordinate
as the color hue):
https://github.com/bevyengine/bevy/assets/26321040/349aa8f8-f669-43ba-9842-f9a46945e25c
Here, we repeat the experiment, but with with `entity.to_bits()` instead
of a sequence:
https://github.com/bevyengine/bevy/assets/26321040/516cea27-7135-4daa-a4e7-edfd1781d119
Notice how Van Der Corput tend to bunch the lines on a single side of
the screen. This is because we always skip odd-numbered entities.
Gold Kronecker seems always worse than Van Der Corput, but it is
resilient to finicky stuff like entity indices being multiples of a
number rather than purely sequential, so I prefer it over Van Der
Corput, since we can't really predict how distributed the entity indices
will be.
### Chosen implementation
You'll notice this PR's implementation is not the Golden ratio-based
Kronecker sequence as described in
[tueoqs](https://extremelearning.com.au/unreasonable-effectiveness-of-quasirandom-sequences/).
Why?
tueoqs R function multiplies a rational/float and takes the fractional
part of the result `(x/Φ) % 1`. We start with an integer `u32`. So
instead of converting into float and dividing by Φ (mod 1) we directly
divide by Φ as integer (mod 2³²) both operations are equivalent, the
integer division (which is actually a multiplication by `u32::MAX / Φ`)
is probably faster.
## Acknowledgements
- `inspi` on discord linked me to
https://extremelearning.com.au/unreasonable-effectiveness-of-quasirandom-sequences/
and the wikipedia article.
- [this blog
post](https://probablydance.com/2018/06/16/fibonacci-hashing-the-optimization-that-the-world-forgot-or-a-better-alternative-to-integer-modulo/)
for the idea of multiplying the `u32` rather than the `f32`.
- `nakedible` for suggesting the `index()` over `to_bits()` which
considerably reduces generated code (goes from 50 to 11 instructions)
2023-07-21 20:12:38 +00:00
|
|
|
let index = entity.index();
|
|
|
|
|
|
|
|
// from https://extremelearning.com.au/unreasonable-effectiveness-of-quasirandom-sequences/
|
|
|
|
//
|
|
|
|
// See https://en.wikipedia.org/wiki/Low-discrepancy_sequence
|
|
|
|
// Map a sequence of integers (eg: 154, 155, 156, 157, 158) into the [0.0..1.0] range,
|
|
|
|
// so that the closer the numbers are, the larger the difference of their image.
|
|
|
|
const FRAC_U32MAX_GOLDEN_RATIO: u32 = 2654435769; // (u32::MAX / Φ) rounded up
|
|
|
|
const RATIO_360: f32 = 360.0 / u32::MAX as f32;
|
|
|
|
let hue = index.wrapping_mul(FRAC_U32MAX_GOLDEN_RATIO) as f32 * RATIO_360;
|
2023-06-26 16:38:31 +00:00
|
|
|
|
2023-04-24 15:23:06 +00:00
|
|
|
Color::hsl(hue, 1., 0.5)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn aabb_transform(aabb: Aabb, transform: GlobalTransform) -> GlobalTransform {
|
|
|
|
transform
|
|
|
|
* GlobalTransform::from(
|
|
|
|
Transform::from_translation(aabb.center.into())
|
|
|
|
.with_scale((aabb.half_extents * 2.).into()),
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
2023-06-13 06:49:47 +00:00
|
|
|
#[derive(Resource, Default)]
|
|
|
|
struct LineGizmoHandles {
|
|
|
|
list: Option<Handle<LineGizmo>>,
|
|
|
|
strip: Option<Handle<LineGizmo>>,
|
2023-03-20 20:57:54 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
fn update_gizmo_meshes(
|
2023-06-13 06:49:47 +00:00
|
|
|
mut line_gizmos: ResMut<Assets<LineGizmo>>,
|
|
|
|
mut handles: ResMut<LineGizmoHandles>,
|
2023-03-20 20:57:54 +00:00
|
|
|
mut storage: ResMut<GizmoStorage>,
|
|
|
|
) {
|
2023-04-18 16:31:55 +00:00
|
|
|
if storage.list_positions.is_empty() {
|
|
|
|
handles.list = None;
|
|
|
|
} else if let Some(handle) = handles.list.as_ref() {
|
2023-06-13 06:49:47 +00:00
|
|
|
let list = line_gizmos.get_mut(handle).unwrap();
|
2023-03-20 20:57:54 +00:00
|
|
|
|
2023-06-13 06:49:47 +00:00
|
|
|
list.positions = mem::take(&mut storage.list_positions);
|
|
|
|
list.colors = mem::take(&mut storage.list_colors);
|
2023-04-18 16:31:55 +00:00
|
|
|
} else {
|
2023-06-13 06:49:47 +00:00
|
|
|
let mut list = LineGizmo {
|
|
|
|
strip: false,
|
|
|
|
..Default::default()
|
|
|
|
};
|
2023-03-20 20:57:54 +00:00
|
|
|
|
2023-06-13 06:49:47 +00:00
|
|
|
list.positions = mem::take(&mut storage.list_positions);
|
|
|
|
list.colors = mem::take(&mut storage.list_colors);
|
2023-03-20 20:57:54 +00:00
|
|
|
|
2023-06-13 06:49:47 +00:00
|
|
|
handles.list = Some(line_gizmos.add(list));
|
2023-04-17 21:20:29 +00:00
|
|
|
}
|
|
|
|
|
2023-04-18 16:31:55 +00:00
|
|
|
if storage.strip_positions.is_empty() {
|
|
|
|
handles.strip = None;
|
|
|
|
} else if let Some(handle) = handles.strip.as_ref() {
|
2023-06-13 06:49:47 +00:00
|
|
|
let strip = line_gizmos.get_mut(handle).unwrap();
|
2023-04-18 16:31:55 +00:00
|
|
|
|
2023-06-13 06:49:47 +00:00
|
|
|
strip.positions = mem::take(&mut storage.strip_positions);
|
|
|
|
strip.colors = mem::take(&mut storage.strip_colors);
|
2023-04-18 16:31:55 +00:00
|
|
|
} else {
|
2023-06-13 06:49:47 +00:00
|
|
|
let mut strip = LineGizmo {
|
|
|
|
strip: true,
|
|
|
|
..Default::default()
|
|
|
|
};
|
2023-03-20 20:57:54 +00:00
|
|
|
|
2023-06-13 06:49:47 +00:00
|
|
|
strip.positions = mem::take(&mut storage.strip_positions);
|
|
|
|
strip.colors = mem::take(&mut storage.strip_colors);
|
2023-04-17 21:20:29 +00:00
|
|
|
|
2023-06-13 06:49:47 +00:00
|
|
|
handles.strip = Some(line_gizmos.add(strip));
|
2023-04-17 21:20:29 +00:00
|
|
|
}
|
2023-03-20 20:57:54 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
fn extract_gizmo_data(
|
|
|
|
mut commands: Commands,
|
2023-06-13 06:49:47 +00:00
|
|
|
handles: Extract<Res<LineGizmoHandles>>,
|
2023-03-20 20:57:54 +00:00
|
|
|
config: Extract<Res<GizmoConfig>>,
|
|
|
|
) {
|
|
|
|
if config.is_changed() {
|
2023-04-24 15:23:06 +00:00
|
|
|
commands.insert_resource(config.clone());
|
2023-03-20 20:57:54 +00:00
|
|
|
}
|
|
|
|
|
2023-04-18 16:31:55 +00:00
|
|
|
if !config.enabled {
|
2023-03-20 20:57:54 +00:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2023-06-13 06:49:47 +00:00
|
|
|
for handle in [&handles.list, &handles.strip].into_iter().flatten() {
|
|
|
|
commands.spawn((
|
|
|
|
LineGizmoUniform {
|
|
|
|
line_width: config.line_width,
|
|
|
|
depth_bias: config.depth_bias,
|
|
|
|
#[cfg(feature = "webgl")]
|
|
|
|
_padding: Default::default(),
|
|
|
|
},
|
|
|
|
handle.clone_weak(),
|
|
|
|
));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Component, ShaderType, Clone, Copy)]
|
|
|
|
struct LineGizmoUniform {
|
|
|
|
line_width: f32,
|
|
|
|
depth_bias: f32,
|
|
|
|
/// WebGL2 structs must be 16 byte aligned.
|
|
|
|
#[cfg(feature = "webgl")]
|
|
|
|
_padding: bevy_math::Vec2,
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Debug, Default, Clone, TypeUuid, TypePath)]
|
|
|
|
#[uuid = "02b99cbf-bb26-4713-829a-aee8e08dedc0"]
|
|
|
|
struct LineGizmo {
|
|
|
|
positions: Vec<[f32; 3]>,
|
|
|
|
colors: Vec<[f32; 4]>,
|
|
|
|
/// Whether this gizmo's topology is a line-strip or line-list
|
|
|
|
strip: bool,
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Debug, Clone)]
|
|
|
|
struct GpuLineGizmo {
|
|
|
|
position_buffer: Buffer,
|
|
|
|
color_buffer: Buffer,
|
|
|
|
vertex_count: u32,
|
|
|
|
strip: bool,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl RenderAsset for LineGizmo {
|
|
|
|
type ExtractedAsset = LineGizmo;
|
|
|
|
|
|
|
|
type PreparedAsset = GpuLineGizmo;
|
|
|
|
|
|
|
|
type Param = SRes<RenderDevice>;
|
|
|
|
|
|
|
|
fn extract_asset(&self) -> Self::ExtractedAsset {
|
|
|
|
self.clone()
|
|
|
|
}
|
|
|
|
|
|
|
|
fn prepare_asset(
|
|
|
|
line_gizmo: Self::ExtractedAsset,
|
|
|
|
render_device: &mut SystemParamItem<Self::Param>,
|
|
|
|
) -> Result<Self::PreparedAsset, PrepareAssetError<Self::ExtractedAsset>> {
|
|
|
|
let position_buffer_data = cast_slice(&line_gizmo.positions);
|
|
|
|
let position_buffer = render_device.create_buffer_with_data(&BufferInitDescriptor {
|
|
|
|
usage: BufferUsages::VERTEX,
|
|
|
|
label: Some("LineGizmo Position Buffer"),
|
|
|
|
contents: position_buffer_data,
|
|
|
|
});
|
|
|
|
|
|
|
|
let color_buffer_data = cast_slice(&line_gizmo.colors);
|
|
|
|
let color_buffer = render_device.create_buffer_with_data(&BufferInitDescriptor {
|
|
|
|
usage: BufferUsages::VERTEX,
|
|
|
|
label: Some("LineGizmo Color Buffer"),
|
|
|
|
contents: color_buffer_data,
|
|
|
|
});
|
|
|
|
|
|
|
|
Ok(GpuLineGizmo {
|
|
|
|
position_buffer,
|
|
|
|
color_buffer,
|
|
|
|
vertex_count: line_gizmo.positions.len() as u32,
|
|
|
|
strip: line_gizmo.strip,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Resource)]
|
|
|
|
struct LineGizmoUniformBindgroupLayout {
|
|
|
|
layout: BindGroupLayout,
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Resource)]
|
|
|
|
struct LineGizmoUniformBindgroup {
|
|
|
|
bindgroup: BindGroup,
|
|
|
|
}
|
|
|
|
|
|
|
|
fn queue_line_gizmo_bind_group(
|
|
|
|
mut commands: Commands,
|
|
|
|
line_gizmo_uniform_layout: Res<LineGizmoUniformBindgroupLayout>,
|
|
|
|
render_device: Res<RenderDevice>,
|
|
|
|
line_gizmo_uniforms: Res<ComponentUniforms<LineGizmoUniform>>,
|
|
|
|
) {
|
|
|
|
if let Some(binding) = line_gizmo_uniforms.uniforms().binding() {
|
|
|
|
commands.insert_resource(LineGizmoUniformBindgroup {
|
|
|
|
bindgroup: render_device.create_bind_group(&BindGroupDescriptor {
|
|
|
|
entries: &[BindGroupEntry {
|
|
|
|
binding: 0,
|
|
|
|
resource: binding,
|
|
|
|
}],
|
|
|
|
label: Some("LineGizmoUniform bindgroup"),
|
|
|
|
layout: &line_gizmo_uniform_layout.layout,
|
2023-04-18 16:31:55 +00:00
|
|
|
}),
|
2023-06-13 06:49:47 +00:00
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
struct SetLineGizmoBindGroup<const I: usize>;
|
|
|
|
impl<const I: usize, P: PhaseItem> RenderCommand<P> for SetLineGizmoBindGroup<I> {
|
|
|
|
type ViewWorldQuery = ();
|
|
|
|
type ItemWorldQuery = Read<DynamicUniformIndex<LineGizmoUniform>>;
|
|
|
|
type Param = SRes<LineGizmoUniformBindgroup>;
|
|
|
|
|
|
|
|
#[inline]
|
|
|
|
fn render<'w>(
|
|
|
|
_item: &P,
|
|
|
|
_view: ROQueryItem<'w, Self::ViewWorldQuery>,
|
|
|
|
uniform_index: ROQueryItem<'w, Self::ItemWorldQuery>,
|
|
|
|
bind_group: SystemParamItem<'w, '_, Self::Param>,
|
|
|
|
pass: &mut TrackedRenderPass<'w>,
|
|
|
|
) -> RenderCommandResult {
|
|
|
|
pass.set_bind_group(
|
|
|
|
I,
|
|
|
|
&bind_group.into_inner().bindgroup,
|
|
|
|
&[uniform_index.index()],
|
|
|
|
);
|
|
|
|
RenderCommandResult::Success
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
struct DrawLineGizmo;
|
|
|
|
impl<P: PhaseItem> RenderCommand<P> for DrawLineGizmo {
|
|
|
|
type ViewWorldQuery = ();
|
|
|
|
type ItemWorldQuery = Read<Handle<LineGizmo>>;
|
|
|
|
type Param = SRes<RenderAssets<LineGizmo>>;
|
|
|
|
|
|
|
|
#[inline]
|
|
|
|
fn render<'w>(
|
|
|
|
_item: &P,
|
|
|
|
_view: ROQueryItem<'w, Self::ViewWorldQuery>,
|
|
|
|
handle: ROQueryItem<'w, Self::ItemWorldQuery>,
|
|
|
|
line_gizmos: SystemParamItem<'w, '_, Self::Param>,
|
|
|
|
pass: &mut TrackedRenderPass<'w>,
|
|
|
|
) -> RenderCommandResult {
|
|
|
|
let Some(line_gizmo) = line_gizmos.into_inner().get(handle) else {
|
|
|
|
return RenderCommandResult::Failure;
|
|
|
|
};
|
|
|
|
|
|
|
|
let instances = if line_gizmo.strip {
|
2023-06-22 03:01:24 +00:00
|
|
|
let item_size = VertexFormat::Float32x3.size();
|
|
|
|
let buffer_size = line_gizmo.position_buffer.size() - item_size;
|
|
|
|
pass.set_vertex_buffer(0, line_gizmo.position_buffer.slice(..buffer_size));
|
|
|
|
pass.set_vertex_buffer(1, line_gizmo.position_buffer.slice(item_size..));
|
|
|
|
|
|
|
|
let item_size = VertexFormat::Float32x4.size();
|
|
|
|
let buffer_size = line_gizmo.color_buffer.size() - item_size;
|
|
|
|
pass.set_vertex_buffer(2, line_gizmo.color_buffer.slice(..buffer_size));
|
|
|
|
pass.set_vertex_buffer(3, line_gizmo.color_buffer.slice(item_size..));
|
|
|
|
|
2023-06-13 06:49:47 +00:00
|
|
|
u32::max(line_gizmo.vertex_count, 1) - 1
|
|
|
|
} else {
|
2023-06-22 03:01:24 +00:00
|
|
|
pass.set_vertex_buffer(0, line_gizmo.position_buffer.slice(..));
|
|
|
|
pass.set_vertex_buffer(1, line_gizmo.color_buffer.slice(..));
|
|
|
|
|
2023-06-13 06:49:47 +00:00
|
|
|
line_gizmo.vertex_count / 2
|
|
|
|
};
|
|
|
|
|
|
|
|
pass.draw(0..6, 0..instances);
|
|
|
|
|
|
|
|
RenderCommandResult::Success
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn line_gizmo_vertex_buffer_layouts(strip: bool) -> Vec<VertexBufferLayout> {
|
|
|
|
use VertexFormat::*;
|
2023-06-22 03:01:24 +00:00
|
|
|
let mut position_layout = VertexBufferLayout {
|
|
|
|
array_stride: Float32x3.size(),
|
|
|
|
step_mode: VertexStepMode::Instance,
|
|
|
|
attributes: vec![VertexAttribute {
|
|
|
|
format: Float32x3,
|
|
|
|
offset: 0,
|
|
|
|
shader_location: 0,
|
|
|
|
}],
|
|
|
|
};
|
|
|
|
|
|
|
|
let mut color_layout = VertexBufferLayout {
|
|
|
|
array_stride: Float32x4.size(),
|
|
|
|
step_mode: VertexStepMode::Instance,
|
|
|
|
attributes: vec![VertexAttribute {
|
|
|
|
format: Float32x4,
|
|
|
|
offset: 0,
|
|
|
|
shader_location: 2,
|
|
|
|
}],
|
|
|
|
};
|
|
|
|
|
|
|
|
if strip {
|
|
|
|
vec![
|
|
|
|
position_layout.clone(),
|
|
|
|
{
|
|
|
|
position_layout.attributes[0].shader_location = 1;
|
|
|
|
position_layout
|
|
|
|
},
|
|
|
|
color_layout.clone(),
|
|
|
|
{
|
|
|
|
color_layout.attributes[0].shader_location = 3;
|
|
|
|
color_layout
|
|
|
|
},
|
|
|
|
]
|
|
|
|
} else {
|
|
|
|
position_layout.array_stride *= 2;
|
|
|
|
position_layout.attributes.push(VertexAttribute {
|
|
|
|
format: Float32x3,
|
|
|
|
offset: Float32x3.size(),
|
|
|
|
shader_location: 1,
|
|
|
|
});
|
|
|
|
|
|
|
|
color_layout.array_stride *= 2;
|
|
|
|
color_layout.attributes.push(VertexAttribute {
|
|
|
|
format: Float32x4,
|
|
|
|
offset: Float32x4.size(),
|
|
|
|
shader_location: 3,
|
|
|
|
});
|
|
|
|
|
|
|
|
vec![position_layout, color_layout]
|
|
|
|
}
|
2023-03-20 20:57:54 +00:00
|
|
|
}
|