Initial project import
CI / Format, lint, test, build (push) Waiting to run

This commit is contained in:
Rbanh committed 2026-06-05 21:44:45 -04:00
commit f29712d158
259 files changed
+52069

No files matched your search

+1
View File
@@ -0,0 +1 @@
{"v":1}
+6
View File
@@ -0,0 +1,6 @@
{
"git": {
"sha1": "bdf2fff085eee3570f84fc9c8e49689d35a53a0b"
},
"path_in_vcs": "crates/transform-gizmo-bevy"
}
+6313
View File
File diff suppressed because it is too large. Load diff
+303
View File
@@ -0,0 +1,303 @@
# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
#
# When uploading crates to the registry Cargo will automatically
# "normalize" Cargo.toml files for maximal compatibility
# with all versions of Cargo and also rewrite `path` dependencies
# to registry (e.g., crates.io) dependencies.
#
# If you are reading this file be aware that the original Cargo.toml
# will likely look very different (and much more reasonable).
# See Cargo.toml.orig for the original contents.
[package]
edition = "2024"
name = "transform-gizmo-bevy"
version = "0.9.0"
authors = ["Urho Laukkarinen <urho.laukkarinen@gmail.com>"]
build = false
include = [
"../../LICENSE-APACHE",
"../../LICENSE-MIT",
"**/*.rs",
"**/*.wgsl",
"Cargo.toml",
]
autolib = false
autobins = false
autoexamples = false
autotests = false
autobenches = false
description = "bevy integration for transform-gizmo"
homepage = "https://github.com/urholaukkarinen/transform-gizmo"
readme = "README.md"
keywords = [
"gizmo",
"bevy",
]
categories = [
"gui",
"game-development",
"game-engines",
]
license = "MIT OR Apache-2.0"
repository = "https://github.com/urholaukkarinen/transform-gizmo"
resolver = "2"
[features]
default = [
"gizmo_picking_backend",
"mouse_interaction",
]
gizmo_picking_backend = ["dep:bevy_picking"]
mouse_interaction = []
[lib]
name = "transform_gizmo_bevy"
path = "src/lib.rs"
[[example]]
name = "bevy_minimal"
path = "examples/bevy_minimal.rs"
[[example]]
name = "ui_blocked_gizmo"
path = "examples/ui_blocked_gizmo.rs"
[dependencies.bevy_app]
version = "0.18"
default-features = false
[dependencies.bevy_asset]
version = "0.18"
default-features = false
[dependencies.bevy_camera]
version = "0.18"
default-features = false
[dependencies.bevy_core_pipeline]
version = "0.18"
default-features = false
[dependencies.bevy_derive]
version = "0.18"
default-features = false
[dependencies.bevy_ecs]
version = "0.18"
default-features = false
[dependencies.bevy_image]
version = "0.18"
default-features = false
[dependencies.bevy_input]
version = "0.18"
default-features = false
[dependencies.bevy_log]
version = "0.18"
default-features = false
[dependencies.bevy_math]
version = "0.18"
features = ["mint"]
default-features = false
[dependencies.bevy_mesh]
version = "0.18"
default-features = false
[dependencies.bevy_pbr]
version = "0.18"
default-features = false
[dependencies.bevy_picking]
version = "0.18"
optional = true
default-features = false
[dependencies.bevy_platform]
version = "0.18"
default-features = false
[dependencies.bevy_reflect]
version = "0.18"
default-features = false
[dependencies.bevy_render]
version = "0.18"
default-features = false
[dependencies.bevy_shader]
version = "0.18"
default-features = false
[dependencies.bevy_transform]
version = "0.18"
default-features = false
[dependencies.bevy_utils]
version = "0.18"
default-features = false
[dependencies.bevy_window]
version = "0.18"
default-features = false
[dependencies.bytemuck]
version = "1.23"
[dependencies.transform-gizmo]
version = "0.9.0"
[dependencies.uuid]
version = "1.17"
[dev-dependencies.bevy]
version = "0.18"
[lints.clippy]
as_ptr_cast_mut = "deny"
await_holding_lock = "deny"
bool_to_int_with_if = "deny"
branches_sharing_code = "deny"
char_lit_as_u8 = "deny"
checked_conversions = "deny"
clear_with_drain = "deny"
cloned_instead_of_copied = "deny"
dbg_macro = "deny"
debug_assert_with_mut_call = "deny"
default_union_representation = "deny"
derive_partial_eq_without_eq = "deny"
disallowed_macros = "deny"
disallowed_methods = "deny"
disallowed_names = "deny"
disallowed_script_idents = "deny"
disallowed_types = "deny"
doc_link_with_quotes = "deny"
doc_markdown = "deny"
empty_enum = "deny"
empty_line_after_outer_attr = "deny"
enum_glob_use = "deny"
equatable_if_let = "deny"
exit = "deny"
expl_impl_clone_on_copy = "deny"
explicit_deref_methods = "deny"
explicit_into_iter_loop = "deny"
explicit_iter_loop = "deny"
fallible_impl_from = "deny"
filter_map_next = "deny"
flat_map_option = "deny"
float_cmp_const = "deny"
fn_params_excessive_bools = "deny"
fn_to_numeric_cast_any = "deny"
from_iter_instead_of_collect = "deny"
get_unwrap = "deny"
if_let_mutex = "deny"
implicit_clone = "deny"
imprecise_flops = "deny"
index_refutable_slice = "deny"
inefficient_to_string = "deny"
invalid_upcast_comparisons = "deny"
iter_not_returning_iterator = "deny"
iter_on_empty_collections = "deny"
iter_on_single_items = "deny"
large-types-passed-by-value = "allow"
large_digit_groups = "deny"
large_include_file = "deny"
large_stack_arrays = "deny"
large_stack_frames = "deny"
large_types_passed_by_value = "deny"
let_underscore_untyped = "allow"
let_unit_value = "deny"
linkedlist = "deny"
lossy_float_literal = "deny"
macro_use_imports = "deny"
manual_assert = "deny"
manual_clamp = "deny"
manual_instant_elapsed = "deny"
manual_let_else = "deny"
manual_ok_or = "deny"
manual_string_new = "deny"
map_err_ignore = "deny"
map_flatten = "deny"
map_unwrap_or = "deny"
match_on_vec_items = "deny"
match_same_arms = "deny"
match_wild_err_arm = "deny"
match_wildcard_for_single_variants = "deny"
mem_forget = "deny"
mismatching_type_param_order = "deny"
missing_assert_message = "allow"
missing_enforced_import_renames = "deny"
missing_errors_doc = "allow"
missing_safety_doc = "deny"
mut_mut = "deny"
mutex_integer = "deny"
needless-pass-by-value = "allow"
needless_borrow = "deny"
needless_continue = "deny"
needless_for_each = "deny"
needless_pass_by_value = "deny"
negative_feature_names = "deny"
nonstandard_macro_braces = "deny"
option_option = "deny"
path_buf_push_overwrite = "deny"
print_stdout = "deny"
ptr_as_ptr = "deny"
ptr_cast_constness = "deny"
pub_without_shorthand = "deny"
rc_mutex = "deny"
redundant_type_annotations = "deny"
ref_option_ref = "deny"
rest_pat_in_fully_bound_structs = "deny"
same_functions_in_if_condition = "deny"
semicolon_if_nothing_returned = "deny"
significant_drop_tightening = "deny"
single_match_else = "deny"
str_to_string = "deny"
string_add = "deny"
string_add_assign = "deny"
string_lit_as_bytes = "deny"
string_to_string = "deny"
suspicious_command_arg_space = "deny"
suspicious_xor_used_as_pow = "deny"
todo = "deny"
too_many_lines = "allow"
trailing_empty_array = "deny"
trait_duplication_in_bounds = "deny"
transmute_ptr_to_ptr = "deny"
tuple_array_conversions = "deny"
unchecked_duration_subtraction = "deny"
undocumented_unsafe_blocks = "allow"
unimplemented = "deny"
uninlined_format_args = "allow"
unnecessary_box_returns = "deny"
unnecessary_safety_comment = "deny"
unnecessary_safety_doc = "deny"
unnecessary_self_imports = "deny"
unnecessary_struct_initialization = "deny"
unnecessary_wraps = "deny"
unnested_or_patterns = "deny"
unused_peekable = "deny"
unused_rounding = "deny"
unused_self = "deny"
unwrap_used = "allow"
use_self = "deny"
useless_transmute = "deny"
verbose_file_reads = "deny"
wildcard_dependencies = "deny"
wildcard_imports = "allow"
zero_sized_map_values = "deny"
[lints.rust]
elided_lifetimes_in_paths = "allow"
rust_2021_prelude_collisions = "deny"
semicolon_in_expressions_from_macros = "deny"
trivial_numeric_casts = "deny"
unsafe_code = "deny"
unsafe_op_in_unsafe_fn = "deny"
unused_extern_crates = "deny"
unused_import_braces = "deny"
unused_lifetimes = "deny"
+50
View File
@@ -0,0 +1,50 @@
[package]
name = "transform-gizmo-bevy"
description = "bevy integration for transform-gizmo"
version.workspace = true
edition.workspace = true
license.workspace = true
homepage.workspace = true
repository.workspace = true
authors.workspace = true
categories = ["gui", "game-development", "game-engines"]
keywords = ["gizmo", "bevy"]
readme = "../../README.md"
include = ["../../LICENSE-APACHE", "../../LICENSE-MIT", "**/*.rs", "**/*.wgsl", "Cargo.toml"]
[features]
default = ["gizmo_picking_backend", "mouse_interaction"]
gizmo_picking_backend = ["dep:bevy_picking"]
mouse_interaction = []
[dependencies]
transform-gizmo.workspace = true
bevy_app.workspace = true
bevy_core_pipeline.workspace = true
bevy_reflect.workspace = true
bevy_math.workspace = true
bevy_mesh.workspace = true
bevy_picking = {workspace = true, optional = true}
bevy_camera.workspace = true
bevy_render.workspace = true
bevy_shader.workspace = true
bevy_input.workspace = true
bevy_asset.workspace = true
bevy_utils.workspace = true
bevy_platform.workspace = true
bevy_pbr.workspace = true
bevy_ecs.workspace = true
bevy_log.workspace = true
bevy_window.workspace = true
bevy_transform.workspace = true
bevy_derive.workspace = true
bevy_image.workspace = true
bytemuck.workspace = true
uuid.workspace = true
[dev-dependencies]
bevy = {workspace = true}
[lints]
workspace = true
+13
View File
@@ -0,0 +1,13 @@
# transform-gizmo-bevy 0.9.0 (patched)
Vendored from crates.io 0.9.0 with one render fix:
- `queue_transform_gizmos` sets `MeshPipelineKey::ATMOSPHERE` when the view has
`ExtractedAtmosphere`, matching Bevy 0.18 PBR mesh-view bind groups.
- `update_gizmos` sets `GizmoInteraction.hovered` when the cursor is inside
`GizmoOptions.viewport_rect` (Scene View dock panel / render-to-texture).
Required for WYSIWYG Scene View (`apply_project_camera_fx` with atmosphere) +
`TransformGizmoPlugin` on the editor fly camera.
Upstream: https://github.com/urholaukkarinen/transform-gizmo
+44
View File
@@ -0,0 +1,44 @@
# transform-gizmo
[![Latest version](https://img.shields.io/crates/v/transform-gizmo.svg)](https://crates.io/crates/transform-gizmo)
[![Documentation](https://docs.rs/transform-gizmo/badge.svg)](https://docs.rs/transform-gizmo)
[![MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/urholaukkarinen/transform-gizmo/blob/main/LICENSE-MIT)
[![Apache](https://img.shields.io/badge/license-Apache-blue.svg)](https://github.com/urholaukkarinen/transform-gizmo/blob/main/LICENSE-APACHE)
`transform-gizmo` is a framework-agnostic Rust crate that provides a feature-rich and customizable 3D transformation gizmo for manipulating the position, rotation and scale of 3D entities.
[Try it out in a web demo](https://urholaukkarinen.github.io/transform-gizmo/)
![All modes](media/all_modes.png)
## Usage
### Bevy
[`transform-gizmo-bevy`](https://docs.rs/transform-gizmo-bevy) provides a Plugin for easy integration into the [Bevy Engine](https://bevyengine.org/).
### Egui
[`transform-gizmo-egui`](https://docs.rs/transform-gizmo-egui) enables you to use the Gizmo wherever [Egui](https://github.com/emilk/egui) is used.
### Other
For interacting with the gizmo, all you will need to do is give `Gizmo::update` sufficient
information about user interaction, in the form of `GizmoInteraction`.
For rendering the gizmo, `Gizmo::draw` provides vertices in viewport coordinates that can be easily rendered
with your favorite graphics APIs.
## Other
The gizmo exposes mathematical types as [mint](https://github.com/kvark/mint) types, which means it is easy to use with types from various crates
such as [nalgebra](https://github.com/dimforge/nalgebra), [glam](https://github.com/bitshifter/glam-rs)
and [cgmath](https://github.com/rustgd/cgmath). You may need to enable a `mint` feature, depending on the math library.
## License
This crate is dual licensed under MIT and Apache 2.0.
## Contributing
Contributions are welcome! See [CONTRIBUTING.md](CONTRIBUTING.md)
@@ -0,0 +1,44 @@
//! A very simple example
//! See the project root's `examples` directory for more examples
use bevy::color::palettes::css::LIME;
use bevy::prelude::*;
use transform_gizmo_bevy::*;
fn main() {
App::new()
.add_plugins((DefaultPlugins, TransformGizmoPlugin))
.add_systems(Startup, setup)
.run();
}
fn setup(
mut commands: Commands,
mut materials: ResMut<Assets<StandardMaterial>>,
mut meshes: ResMut<Assets<Mesh>>,
) {
// camera
commands.spawn((
Camera3d::default(),
Transform::from_translation(Vec3::new(1.0, 3.0, -5.0)).looking_at(Vec3::ZERO, Vec3::Y),
Msaa::Sample2,
GizmoCamera,
));
// cube
commands.spawn((
Mesh3d(meshes.add(Cuboid::new(1.0, 1.0, 1.0))),
MeshMaterial3d(materials.add(Color::from(LIME))),
Transform::from_translation(Vec3::new(0.0, 0.0, 0.0)),
GizmoTarget::default(),
));
// light
commands.spawn((
PointLight {
shadows_enabled: true,
..default()
},
Transform::from_xyz(4.0, 8.0, 4.0),
));
}
@@ -0,0 +1,58 @@
//! Gizmo interactions blocked by other picking backends. In this case, UI.
//! See the project root's `examples` directory for more examples
use bevy::color::palettes::css::LIME;
use bevy::prelude::*;
use transform_gizmo_bevy::*;
fn main() {
App::new()
.add_plugins((DefaultPlugins, TransformGizmoPlugin))
.add_systems(Startup, setup)
.add_observer(|trigger: On<Pointer<Over>>| {
info!("Moved over: {}", trigger.entity);
})
.run();
}
fn setup(
mut commands: Commands,
mut materials: ResMut<Assets<StandardMaterial>>,
mut meshes: ResMut<Assets<Mesh>>,
) {
commands.spawn((
Node {
position_type: PositionType::Absolute,
left: Val::Percent(50.0),
top: Val::Percent(50.0),
width: Val::Px(200.0),
height: Val::Px(200.0),
..default()
},
BackgroundColor(Srgba::new(0.4, 0.4, 0.6, 1.0).into()),
));
// camera
commands.spawn((
Camera3d::default(),
Transform::from_translation(Vec3::new(1.0, 3.0, -5.0)).looking_at(Vec3::ZERO, Vec3::Y),
Msaa::Sample2,
GizmoCamera,
));
// cube
commands.spawn((
Mesh3d(meshes.add(Cuboid::new(1.0, 1.0, 1.0))),
MeshMaterial3d(materials.add(Color::from(LIME))),
Transform::from_translation(Vec3::new(0.0, 0.0, 0.0)),
GizmoTarget::default(),
));
// light
commands.spawn((
PointLight {
shadows_enabled: true,
..default()
},
Transform::from_xyz(4.0, 8.0, 4.0),
));
}
+31
View File
@@ -0,0 +1,31 @@
struct VertexInput {
@location(0) position: vec2<f32>,
@location(1) color: vec4<f32>,
};
struct VertexOutput {
@builtin(position) clip_position: vec4<f32>,
@location(0) color: vec4<f32>,
};
@vertex
fn vertex(vertex: VertexInput) -> VertexOutput {
var position = vec4(vertex.position.x, -vertex.position.y, 0.5, 1.0);
var color = vertex.color;
return VertexOutput(position, color);
}
struct FragmentInput {
@location(0) color: vec4<f32>,
};
struct FragmentOutput {
@location(0) color: vec4<f32>,
};
@fragment
fn fragment(in: FragmentInput) -> FragmentOutput {
return FragmentOutput(in.color);
}
+669
View File
@@ -0,0 +1,669 @@
//! A 3D transformation Gizmo for the Bevy game engine.
//!
//! transform-gizmo-bevy provides a feature-rich and configurable 3D transformation
//! gizmo that can be used to manipulate entities' transforms (position, rotation, scale)
//! visually.
//!
//! # Usage
//!
//! Add `TransformGizmoPlugin` to your App.
//!
//! ```ignore
//! use bevy::prelude::*;
//! use transform_gizmo_bevy::prelude::*;
//!
//! App::new()
//! .add_plugins(DefaultPlugins)
//! .add_plugins(TransformGizmoPlugin)
//! .run();
//! ```
//!
//! Add [`GizmoCamera`] component to your Camera entity.
//!
//! Add [`GizmoTarget`] component to any of your entities that you would like to manipulate the [`Transform`] of.
//!
//! # Configuration
//!
//! You can configure the gizmo by modifying the [`GizmoOptions`] resource.
//!
//! You can either set it up with [`App::insert_resource`] when creating your App, or at any point in a system with [`ResMut<GizmoOptions>`].
use bevy_app::prelude::*;
use bevy_asset::{AssetApp, Assets};
use bevy_camera::Camera;
use bevy_ecs::prelude::*;
use bevy_input::prelude::*;
use bevy_math::{DQuat, DVec3, Vec2};
use bevy_picking::hover::HoverMap;
use bevy_platform::collections::HashMap;
use bevy_transform::prelude::*;
use bevy_window::{PrimaryWindow, Window};
use mouse_interact::MouseGizmoInteractionPlugin;
use picking::TransformGizmoPickingPlugin;
use uuid::Uuid;
use render::{DrawDataHandles, TransformGizmoRenderPlugin};
use transform_gizmo::config::{
DEFAULT_SNAP_ANGLE, DEFAULT_SNAP_DISTANCE, DEFAULT_SNAP_SCALE, GizmoModeKind,
TransformPivotPoint,
};
pub use transform_gizmo::{
GizmoConfig,
math::{Pos2, Rect},
*,
};
pub mod mouse_interact;
pub mod picking;
pub mod prelude;
mod render;
const GIZMO_GROUP_UUID: Uuid = Uuid::from_u128(0x_1c90_3d44_0152_45e1_b1c9_889a_0203_e90c);
/// Adds transform gizmos to the App.
///
/// Gizmos are interactive tools that appear in the scene, allowing users to manipulate
/// entities' transforms (position, rotation, scale) visually.
pub struct TransformGizmoPlugin;
impl Plugin for TransformGizmoPlugin {
fn build(&self, app: &mut App) {
app.init_asset::<render::GizmoDrawData>()
.init_resource::<GizmoOptions>()
.init_resource::<GizmoStorage>()
.add_message::<GizmoDragStarted>()
.add_message::<GizmoDragging>()
.add_plugins(TransformGizmoRenderPlugin)
.add_systems(
Last,
(handle_hotkeys, update_gizmos, draw_gizmos, cleanup_old_data).chain(),
);
#[cfg(feature = "gizmo_picking_backend")]
app.add_plugins(TransformGizmoPickingPlugin);
#[cfg(feature = "mouse_interaction")]
app.add_plugins(MouseGizmoInteractionPlugin);
}
}
/// Various options for configuring the transform gizmos.
#[derive(Resource, Copy, Clone, Debug)]
pub struct GizmoOptions {
/// Modes to use in the gizmos.
pub gizmo_modes: EnumSet<GizmoMode>,
/// Orientation of the gizmo. This affects the behaviour of transformations.
pub gizmo_orientation: GizmoOrientation,
/// Orientation of the gizmo. This affects the behaviour of transformations.
pub pivot_point: TransformPivotPoint,
/// Look and feel of the gizmo.
pub visuals: GizmoVisuals,
/// Whether snapping is enabled in the gizmo transformations.
/// This may be overwritten with hotkeys ([`GizmoHotkeys::enable_snapping`]).
pub snapping: bool,
/// When snapping is enabled, snap twice as often.
/// This may be overwritten with hotkeys ([`GizmoHotkeys::enable_accurate_mode`]).
pub accurate_mode: bool,
/// Angle increment for snapping rotations, in radians.
pub snap_angle: f32,
/// Distance increment for snapping translations.
pub snap_distance: f32,
/// Scale increment for snapping scalings.
pub snap_scale: f32,
/// If `true`, all [`GizmoTarget`]s are transformed
/// using a single gizmo. If `false`, each target
/// has its own gizmo.
pub group_targets: bool,
/// If set, this mode is forced active and other modes are disabled.
/// This may be overwritten with hotkeys.
pub mode_override: Option<GizmoMode>,
/// Hotkeys for easier interaction with the gizmo.
pub hotkeys: Option<GizmoHotkeys>,
/// Allows you to provide a custom viewport rect, which will be used to
/// scale the cursor position. By default, this is set to `None` which means
/// the full window size is used as the viewport.
pub viewport_rect: Option<bevy_math::Rect>,
}
impl Default for GizmoOptions {
fn default() -> Self {
Self {
gizmo_modes: GizmoMode::all(),
gizmo_orientation: GizmoOrientation::default(),
pivot_point: TransformPivotPoint::default(),
visuals: Default::default(),
snapping: false,
accurate_mode: false,
snap_angle: DEFAULT_SNAP_ANGLE,
snap_distance: DEFAULT_SNAP_DISTANCE,
snap_scale: DEFAULT_SNAP_SCALE,
group_targets: true,
mode_override: None,
hotkeys: None,
viewport_rect: None,
}
}
}
/// Hotkeys for easier interaction with the gizmo.
#[derive(Debug, Copy, Clone)]
pub struct GizmoHotkeys {
/// When pressed, transformations snap to according to snap values
/// specified in [`GizmoOptions`].
pub enable_snapping: Option<KeyCode>,
/// When pressed, snapping is twice as accurate.
pub enable_accurate_mode: Option<KeyCode>,
/// Toggles gizmo to rotate-only mode.
pub toggle_rotate: Option<KeyCode>,
/// Toggles gizmo to translate-only mode.
pub toggle_translate: Option<KeyCode>,
/// Toggles gizmo to scale-only mode.
pub toggle_scale: Option<KeyCode>,
/// Limits overridden gizmo mode to X axis only.
pub toggle_x: Option<KeyCode>,
/// Limits overridden gizmo mode to Y axis only.
pub toggle_y: Option<KeyCode>,
/// Limits overridden gizmo mode to Z axis only.
pub toggle_z: Option<KeyCode>,
/// When pressed, deactivates the gizmo if it
/// was active.
pub deactivate_gizmo: Option<KeyCode>,
/// If true, a mouse click deactivates the gizmo if it
/// was active.
pub mouse_click_deactivates: bool,
}
impl Default for GizmoHotkeys {
fn default() -> Self {
Self {
enable_snapping: Some(KeyCode::ControlLeft),
enable_accurate_mode: Some(KeyCode::ShiftLeft),
toggle_rotate: Some(KeyCode::KeyR),
toggle_translate: Some(KeyCode::KeyG),
toggle_scale: Some(KeyCode::KeyS),
toggle_x: Some(KeyCode::KeyX),
toggle_y: Some(KeyCode::KeyY),
toggle_z: Some(KeyCode::KeyZ),
deactivate_gizmo: Some(KeyCode::Escape),
mouse_click_deactivates: true,
}
}
}
/// Marks an entity as a gizmo target.
///
/// When an entity has this component and a [`Transform`],
/// a gizmo is shown, which can be used to manipulate the
/// transform component.
///
/// If target grouping is enabled in [`GizmoOptions`],
/// a single gizmo is used for all targets. Otherwise
/// a separate gizmo is used for each target entity.
#[derive(Component, Copy, Clone, Debug, Default)]
pub struct GizmoTarget {
/// Whether any part of the gizmo is currently focused.
pub(crate) is_focused: bool,
/// Whether the gizmo is currently being interacted with.
pub(crate) is_active: bool,
/// This gets replaced with the result of the most recent
/// gizmo interaction that affected this entity.
pub(crate) latest_result: Option<GizmoResult>,
}
impl GizmoTarget {
/// Whether any part of the gizmo is currently focused.
pub fn is_focused(&self) -> bool {
self.is_focused
}
/// Whether the gizmo is currently being interacted with.
pub fn is_active(&self) -> bool {
self.is_active
}
/// This gets replaced with the result of the most recent
/// gizmo interaction that affected this entity.
pub fn latest_result(&self) -> Option<GizmoResult> {
self.latest_result
}
}
/// Marker used to specify which camera to use for gizmos.
#[derive(Component)]
pub struct GizmoCamera;
#[derive(Resource, Default)]
struct GizmoStorage {
target_entities: Vec<Entity>,
entity_gizmo_map: HashMap<Entity, Uuid>,
gizmos: HashMap<Uuid, Gizmo>,
}
fn handle_hotkeys(
mut gizmo_options: ResMut<GizmoOptions>,
keyboard_input: Res<ButtonInput<KeyCode>>,
mouse_input: Res<ButtonInput<MouseButton>>,
mut axes: Local<EnumSet<GizmoDirection>>,
) {
let Some(hotkeys) = gizmo_options.hotkeys else {
// Hotkeys are disabled.
return;
};
if let Some(snapping_key) = hotkeys.enable_snapping {
gizmo_options.snapping = keyboard_input.pressed(snapping_key);
}
if let Some(accurate_mode_key) = hotkeys.enable_accurate_mode {
gizmo_options.accurate_mode = keyboard_input.pressed(accurate_mode_key);
}
// Modifier for inverting the mode axis selection.
// For example, X would force X axis, but Shift-X would force Y and Z axes.
let invert_modifier = keyboard_input.pressed(KeyCode::ShiftLeft);
let x_hotkey_pressed = hotkeys
.toggle_x
.is_some_and(|key| keyboard_input.just_pressed(key));
let y_hotkey_pressed = hotkeys
.toggle_y
.is_some_and(|key| keyboard_input.just_pressed(key));
let z_hotkey_pressed = hotkeys
.toggle_z
.is_some_and(|key| keyboard_input.just_pressed(key));
let mut new_axes = EnumSet::empty();
if x_hotkey_pressed {
new_axes = if invert_modifier {
enum_set!(GizmoDirection::Y | GizmoDirection::Z)
} else {
enum_set!(GizmoDirection::X)
};
};
if y_hotkey_pressed {
new_axes = if !invert_modifier {
enum_set!(GizmoDirection::Y)
} else {
enum_set!(GizmoDirection::X | GizmoDirection::Z)
};
};
if z_hotkey_pressed {
new_axes = if !invert_modifier {
enum_set!(GizmoDirection::Z)
} else {
enum_set!(GizmoDirection::X | GizmoDirection::Y)
};
};
// Replace the previously chosen axes, if any
if !new_axes.is_empty() {
if *axes == new_axes {
axes.clear();
} else {
*axes = new_axes;
}
}
// If we do not have any mode overridden at this point, do not force the axes either.
// This means you will have to first choose the mode and only then choose the axes.
if gizmo_options.mode_override.is_none() {
axes.clear();
}
let rotate_hotkey_pressed = hotkeys
.toggle_rotate
.is_some_and(|key| keyboard_input.just_pressed(key));
let translate_hotkey_pressed = hotkeys
.toggle_translate
.is_some_and(|key| keyboard_input.just_pressed(key));
let scale_hotkey_pressed = hotkeys
.toggle_scale
.is_some_and(|key| keyboard_input.just_pressed(key));
// Determine which mode we should switch to based on what is currently chosen
// and which hotkey we just pressed, if any.
let mode_kind = if rotate_hotkey_pressed {
// Rotation hotkey toggles between arcball and normal rotation
if gizmo_options
.mode_override
.filter(GizmoMode::is_rotate)
.is_some()
{
Some(GizmoModeKind::Arcball)
} else {
Some(GizmoModeKind::Rotate)
}
} else if translate_hotkey_pressed {
Some(GizmoModeKind::Translate)
} else if scale_hotkey_pressed {
Some(GizmoModeKind::Scale)
} else {
gizmo_options.mode_override.map(|mode| mode.kind())
};
if let Some(kind) = mode_kind {
gizmo_options.mode_override = GizmoMode::from_kind_and_axes(kind, *axes)
.filter(|mode| gizmo_options.gizmo_modes.contains(*mode))
.or_else(|| {
GizmoMode::all_from_kind(kind)
.iter()
.find(|mode| gizmo_options.gizmo_modes.contains(*mode))
});
} else {
gizmo_options.mode_override = None;
}
// Check if gizmo should be deactivated
if (hotkeys.mouse_click_deactivates
&& mouse_input.any_just_pressed([MouseButton::Left, MouseButton::Right]))
|| hotkeys
.deactivate_gizmo
.is_some_and(|key| keyboard_input.just_pressed(key))
{
gizmo_options.mode_override = None;
}
}
#[derive(Debug, Message, Default)]
pub struct GizmoDragStarted;
#[derive(Debug, Message, Default)]
pub struct GizmoDragging;
#[allow(clippy::too_many_arguments)]
fn update_gizmos(
q_window: Query<&Window, With<PrimaryWindow>>,
q_gizmo_camera: Query<(&Camera, &GlobalTransform), With<GizmoCamera>>,
mut q_targets: Query<(Entity, &mut Transform, &mut GizmoTarget), Without<GizmoCamera>>,
mut drag_started: MessageReader<GizmoDragStarted>,
mut dragging: MessageReader<GizmoDragging>,
gizmo_options: Res<GizmoOptions>,
mut gizmo_storage: ResMut<GizmoStorage>,
mut last_cursor_pos: Local<Vec2>,
mut last_scaled_cursor_pos: Local<Vec2>,
#[cfg(feature = "gizmo_picking_backend")] hover_map: Res<HoverMap>,
) {
let Ok(window) = q_window.single() else {
// No primary window found.
return;
};
let mut cursor_pos = window.cursor_position().unwrap_or_else(|| *last_cursor_pos);
*last_cursor_pos = cursor_pos;
let scale_factor = window.scale_factor();
let (camera, camera_transform) = {
let mut active_camera = None;
for camera in q_gizmo_camera.iter() {
if !camera.0.is_active {
continue;
}
if active_camera.is_some() {
// multiple active cameras found, warn and skip
bevy_log::warn!("Only one camera with a GizmoCamera component is supported.");
return;
}
active_camera = Some(camera);
}
match active_camera {
Some(camera) => camera,
None => return, // no active cameras in the scene
}
};
let Some(viewport) = camera.logical_viewport_rect() else {
return;
};
// scale up the cursor pos from the custom viewport rect, if provided
if let Some(custom_viewport) = gizmo_options.viewport_rect {
let vp_ratio = viewport.size() / custom_viewport.size();
let mut scaled_cursor_pos = (cursor_pos - (custom_viewport.min - viewport.min)) * vp_ratio;
if !viewport.contains(scaled_cursor_pos) {
scaled_cursor_pos = *last_scaled_cursor_pos;
}
*last_scaled_cursor_pos = scaled_cursor_pos;
cursor_pos = scaled_cursor_pos;
};
let viewport = Rect::from_min_max(
Pos2::new(viewport.min.x, viewport.min.y),
Pos2::new(viewport.max.x, viewport.max.y),
);
let projection_matrix = camera.clip_from_view();
let view_matrix = camera_transform.to_matrix().inverse();
let mut snap_angle = gizmo_options.snap_angle;
let mut snap_distance = gizmo_options.snap_distance;
let mut snap_scale = gizmo_options.snap_scale;
if gizmo_options.accurate_mode {
snap_angle /= 2.0;
snap_distance /= 2.0;
snap_scale /= 2.0;
}
let gizmo_config = GizmoConfig {
view_matrix: view_matrix.as_dmat4().into(),
projection_matrix: projection_matrix.as_dmat4().into(),
viewport,
modes: gizmo_options.gizmo_modes,
mode_override: gizmo_options.mode_override,
orientation: gizmo_options.gizmo_orientation,
pivot_point: gizmo_options.pivot_point,
visuals: gizmo_options.visuals,
snapping: gizmo_options.snapping,
snap_angle,
snap_distance,
snap_scale,
pixels_per_point: scale_factor,
};
#[cfg(feature = "gizmo_picking_backend")]
// The gizmo picking backend sends hits to the entity the gizmo is targeting.
// We check for those entities in the hover map to.
let any_gizmo_hovered = q_targets
.iter()
.any(|(entity, ..)| hover_map.iter().any(|(_, map)| map.contains_key(&entity)));
#[cfg(not(feature = "gizmo_picking_backend"))]
let any_gizmo_hovered = true;
// When the 3D view is embedded in a dock panel (custom viewport rect), pointer hits
// from the picking backend are still in window space — treat the panel as hoverable.
let cursor_in_custom_viewport = gizmo_options
.viewport_rect
.is_some_and(|custom| custom.contains(cursor_pos));
let hovered = any_gizmo_hovered
|| gizmo_options.mode_override.is_some()
|| cursor_in_custom_viewport;
let gizmo_interaction = GizmoInteraction {
cursor_pos: (cursor_pos.x, cursor_pos.y),
hovered,
drag_started: drag_started.read().len() > 0,
dragging: dragging.read().len() > 0,
};
let mut target_entities: Vec<Entity> = vec![];
let mut target_transforms: Vec<Transform> = vec![];
for (entity, mut target_transform, mut gizmo_target) in &mut q_targets {
target_entities.push(entity);
target_transforms.push(*target_transform);
if gizmo_options.group_targets {
gizmo_storage
.entity_gizmo_map
.insert(entity, GIZMO_GROUP_UUID);
continue;
}
let mut gizmo_uuid = *gizmo_storage
.entity_gizmo_map
.entry(entity)
.or_insert_with(Uuid::new_v4);
// Group gizmo was used previously
if gizmo_uuid == GIZMO_GROUP_UUID {
gizmo_uuid = Uuid::new_v4();
gizmo_storage.entity_gizmo_map.insert(entity, gizmo_uuid);
}
let gizmo = gizmo_storage.gizmos.entry(gizmo_uuid).or_default();
gizmo.update_config(gizmo_config);
let gizmo_result = gizmo.update(
gizmo_interaction,
&[math::Transform {
translation: target_transform.translation.as_dvec3().into(),
rotation: target_transform.rotation.as_dquat().into(),
scale: target_transform.scale.as_dvec3().into(),
}],
);
let is_focused = gizmo.is_focused();
gizmo_target.is_active = gizmo_result.is_some();
gizmo_target.is_focused = is_focused;
if let Some((_, updated_targets)) = &gizmo_result {
let Some(result_transform) = updated_targets.first() else {
bevy_log::warn!("No transform found in GizmoResult!");
continue;
};
target_transform.translation = DVec3::from(result_transform.translation).as_vec3();
target_transform.rotation = DQuat::from(result_transform.rotation).as_quat();
target_transform.scale = DVec3::from(result_transform.scale).as_vec3();
}
gizmo_target.latest_result = gizmo_result.map(|(result, _)| result);
}
if gizmo_options.group_targets {
let gizmo = gizmo_storage.gizmos.entry(GIZMO_GROUP_UUID).or_default();
gizmo.update_config(gizmo_config);
let gizmo_result = gizmo.update(
gizmo_interaction,
target_transforms
.iter()
.map(|transform| transform_gizmo::math::Transform {
translation: transform.translation.as_dvec3().into(),
rotation: transform.rotation.as_dquat().into(),
scale: transform.scale.as_dvec3().into(),
})
.collect::<Vec<_>>()
.as_slice(),
);
let is_focused = gizmo.is_focused();
for (i, (_, mut target_transform, mut gizmo_target)) in q_targets.iter_mut().enumerate() {
gizmo_target.is_active = gizmo_result.is_some();
gizmo_target.is_focused = is_focused;
if let Some((_, updated_targets)) = &gizmo_result {
let Some(result_transform) = updated_targets.get(i) else {
bevy_log::warn!("No transform {i} found in GizmoResult!");
continue;
};
target_transform.translation = DVec3::from(result_transform.translation).as_vec3();
target_transform.rotation = DQuat::from(result_transform.rotation).as_quat();
target_transform.scale = DVec3::from(result_transform.scale).as_vec3();
}
gizmo_target.latest_result = gizmo_result.as_ref().map(|(result, _)| *result);
}
}
gizmo_storage.target_entities = target_entities;
}
fn draw_gizmos(
gizmo_storage: Res<GizmoStorage>,
mut draw_data_assets: ResMut<Assets<render::GizmoDrawData>>,
mut draw_data_handles: ResMut<DrawDataHandles>,
) {
for (gizmo_uuid, gizmo) in &gizmo_storage.gizmos {
let draw_data = gizmo.draw();
let mut bevy_draw_data = render::GizmoDrawData::default();
let (asset, is_new_asset) = if let Some(handle) = draw_data_handles.handles.get(gizmo_uuid)
{
(draw_data_assets.get_mut(handle).unwrap(), false)
} else {
(&mut bevy_draw_data, true)
};
let viewport = &gizmo.config().viewport;
asset.0.vertices.clear();
asset
.0
.vertices
.extend(draw_data.vertices.into_iter().map(|vert| {
[
((vert[0] - viewport.left()) / viewport.width()) * 2.0 - 1.0,
((vert[1] - viewport.top()) / viewport.height()) * 2.0 - 1.0,
]
}));
asset.0.colors = draw_data.colors;
asset.0.indices = draw_data.indices;
if is_new_asset {
let asset = draw_data_assets.add(bevy_draw_data);
draw_data_handles
.handles
.insert(*gizmo_uuid, asset.clone().into());
}
}
}
fn cleanup_old_data(
gizmo_options: Res<GizmoOptions>,
mut gizmo_storage: ResMut<GizmoStorage>,
mut draw_data_handles: ResMut<DrawDataHandles>,
) {
let target_entities = std::mem::take(&mut gizmo_storage.target_entities);
let mut gizmos_to_keep = vec![];
if gizmo_options.group_targets && !target_entities.is_empty() {
gizmos_to_keep.push(GIZMO_GROUP_UUID);
}
gizmo_storage.entity_gizmo_map.retain(|entity, uuid| {
if !target_entities.contains(entity) {
false
} else {
gizmos_to_keep.push(*uuid);
true
}
});
gizmo_storage
.gizmos
.retain(|uuid, _| gizmos_to_keep.contains(uuid));
draw_data_handles
.handles
.retain(|uuid, _| gizmos_to_keep.contains(uuid));
}
+26
View File
@@ -0,0 +1,26 @@
use bevy_app::{App, Plugin, Update};
use bevy_ecs::{message::MessageWriter, system::Res};
use bevy_input::{ButtonInput, mouse::MouseButton};
use crate::{GizmoDragStarted, GizmoDragging};
pub struct MouseGizmoInteractionPlugin;
impl Plugin for MouseGizmoInteractionPlugin {
fn build(&self, app: &mut App) {
app.add_systems(Update, mouse_interact_gizmo);
}
}
fn mouse_interact_gizmo(
mouse: Res<ButtonInput<MouseButton>>,
mut drag_started: MessageWriter<GizmoDragStarted>,
mut dragging: MessageWriter<GizmoDragging>,
) {
if mouse.just_pressed(MouseButton::Left) {
drag_started.write_default();
}
if mouse.pressed(MouseButton::Left) {
dragging.write_default();
}
}
+48
View File
@@ -0,0 +1,48 @@
use bevy_app::{Plugin, PreUpdate};
use bevy_ecs::{
message::MessageWriter,
schedule::IntoScheduleConfigs,
system::{Query, Res},
};
use bevy_picking::{
PickingSystems,
backend::{HitData, PointerHits},
pointer::{PointerId, PointerLocation},
};
use crate::GizmoStorage;
pub struct TransformGizmoPickingPlugin;
impl Plugin for TransformGizmoPickingPlugin {
fn build(&self, app: &mut bevy_app::App) {
app.add_systems(PreUpdate, update_hits.in_set(PickingSystems::Backend));
}
}
fn update_hits(
storage: Res<GizmoStorage>,
mut output: MessageWriter<PointerHits>,
pointers: Query<(&PointerId, &PointerLocation)>,
) {
let gizmos = storage
.entity_gizmo_map
.iter()
.filter_map(|(entity, uuid)| storage.gizmos.get(uuid).map(|gizmo| (*entity, gizmo)))
.collect::<Vec<_>>();
for (pointer_id, pointer_location) in &pointers {
let Some(location) = &pointer_location.location else {
continue;
};
let hits = gizmos
.iter()
.filter(|(_entity, gizmo)| {
gizmo.pick_preview((location.position.x, location.position.y))
})
.map(|(entity, _gizmo)| (*entity, HitData::new(*entity, 0.0, None, None)))
.collect::<Vec<_>>();
output.write(PointerHits::new(*pointer_id, hits, 0.0));
}
}
+3
View File
@@ -0,0 +1,3 @@
pub use transform_gizmo::prelude::*;
pub use crate::{GizmoCamera, GizmoOptions, GizmoTarget, TransformGizmoPlugin};
+420
View File
@@ -0,0 +1,420 @@
use bevy_app::{App, Plugin};
use bevy_asset::{Asset, AssetId, Handle, RenderAssetUsages, load_internal_asset, uuid_handle};
use bevy_camera::visibility::RenderLayers;
use bevy_core_pipeline::core_3d::{CORE_3D_DEPTH_FORMAT, Transparent3d};
use bevy_core_pipeline::prepass::{
DeferredPrepass, DepthPrepass, MotionVectorPrepass, NormalPrepass,
};
use bevy_derive::{Deref, DerefMut};
use bevy_ecs::prelude::*;
use bevy_ecs::query::ROQueryItem;
use bevy_ecs::system::SystemParamItem;
use bevy_ecs::system::lifetimeless::{Read, SRes};
use bevy_image::BevyDefault as _;
use bevy_mesh::{PrimitiveTopology, VertexBufferLayout};
use bevy_pbr::{ExtractedAtmosphere, MeshPipeline, MeshPipelineKey, SetMeshViewBindGroup};
use bevy_platform::collections::{HashMap, HashSet};
use bevy_reflect::{Reflect, TypePath};
use bevy_render::extract_component::ExtractComponent;
use bevy_render::prelude::*;
use bevy_render::render_asset::{
PrepareAssetError, RenderAsset, RenderAssetPlugin, RenderAssets, prepare_assets,
};
use bevy_render::render_phase::{
AddRenderCommand, DrawFunctions, PhaseItem, PhaseItemExtraIndex, RenderCommand,
RenderCommandResult, SetItemPipeline, TrackedRenderPass, ViewSortedRenderPhases,
};
use bevy_render::render_resource::{
BlendState, Buffer, BufferInitDescriptor, BufferUsages, ColorTargetState, ColorWrites,
CompareFunction, DepthBiasState, DepthStencilState, FragmentState, IndexFormat,
MultisampleState, PipelineCache, PrimitiveState, RenderPipelineDescriptor,
SpecializedRenderPipeline, SpecializedRenderPipelines, StencilState, TextureFormat,
VertexAttribute, VertexFormat, VertexState, VertexStepMode,
};
use bevy_render::renderer::RenderDevice;
use bevy_render::sync_world::TemporaryRenderEntity;
use bevy_render::view::{ExtractedView, ViewTarget};
use bevy_render::{Extract, Render, RenderApp, RenderSystems};
use bevy_shader::Shader;
use bytemuck::cast_slice;
use uuid::Uuid;
use crate::GizmoCamera;
const GIZMO_SHADER_HANDLE: Handle<Shader> = uuid_handle!("e44be110-cb2b-4a8d-9c0c-965424e6a633");
pub(crate) struct TransformGizmoRenderPlugin;
impl Plugin for TransformGizmoRenderPlugin {
fn build(&self, app: &mut App) {
load_internal_asset!(app, GIZMO_SHADER_HANDLE, "gizmo.wgsl", Shader::from_wgsl);
app.register_type::<DrawDataHandles>()
.init_resource::<DrawDataHandles>()
.add_plugins(RenderAssetPlugin::<GizmoBuffers>::default());
let Some(render_app) = app.get_sub_app_mut(RenderApp) else {
return;
};
render_app
.add_render_command::<Transparent3d, DrawGizmo>()
.init_resource::<SpecializedRenderPipelines<TransformGizmoPipeline>>()
.add_systems(
Render,
queue_transform_gizmos
.in_set(RenderSystems::Queue)
.after(prepare_assets::<GizmoBuffers>),
);
}
fn finish(&self, app: &mut App) {
let Some(render_app) = app.get_sub_app_mut(RenderApp) else {
return;
};
render_app
.add_systems(ExtractSchedule, extract_gizmo_data)
.init_resource::<TransformGizmoPipeline>();
}
}
#[derive(Resource, Default, Reflect)]
#[reflect(Resource)]
pub(crate) struct DrawDataHandles {
pub(crate) handles: HashMap<Uuid, GizmoDrawDataHandle>,
}
#[derive(
Component,
Default,
Clone,
Debug,
Deref,
DerefMut,
Reflect,
PartialEq,
Eq,
ExtractComponent,
Hash,
)]
#[reflect(Component)]
pub(crate) struct GizmoDrawDataHandle(pub(crate) Handle<GizmoDrawData>);
impl From<Handle<GizmoDrawData>> for GizmoDrawDataHandle {
fn from(handle: Handle<GizmoDrawData>) -> Self {
Self(handle)
}
}
impl From<GizmoDrawDataHandle> for AssetId<GizmoDrawData> {
fn from(handle: GizmoDrawDataHandle) -> Self {
handle.0.id()
}
}
impl From<&GizmoDrawDataHandle> for AssetId<GizmoDrawData> {
fn from(handle: &GizmoDrawDataHandle) -> Self {
handle.0.id()
}
}
fn extract_gizmo_data(mut commands: Commands, handles: Extract<Res<DrawDataHandles>>) {
let handle_refs = handles.handles.values().cloned().collect::<HashSet<_>>();
for handle in handle_refs {
commands.spawn((handle, TemporaryRenderEntity));
}
}
#[derive(Asset, Debug, Default, Clone, TypePath)]
pub(crate) struct GizmoDrawData(pub(crate) transform_gizmo::GizmoDrawData);
#[derive(Debug, Clone)]
pub(crate) struct GizmoBuffers {
position_buffer: Buffer,
index_buffer: Buffer,
color_buffer: Buffer,
index_count: u32,
}
impl RenderAsset for GizmoBuffers {
type SourceAsset = GizmoDrawData;
type Param = SRes<RenderDevice>;
fn asset_usage(_source_asset: &Self::SourceAsset) -> RenderAssetUsages {
RenderAssetUsages::all()
}
fn prepare_asset(
source_asset: Self::SourceAsset,
_: AssetId<Self::SourceAsset>,
render_device: &mut SystemParamItem<Self::Param>,
_: Option<&Self>,
) -> std::result::Result<Self, PrepareAssetError<Self::SourceAsset>> {
let position_buffer_data = cast_slice(&source_asset.0.vertices);
let position_buffer = render_device.create_buffer_with_data(&BufferInitDescriptor {
usage: BufferUsages::VERTEX,
label: Some("TransformGizmo Position Buffer"),
contents: position_buffer_data,
});
let index_buffer_data = cast_slice(&source_asset.0.indices);
let index_buffer = render_device.create_buffer_with_data(&BufferInitDescriptor {
usage: BufferUsages::INDEX,
label: Some("TransformGizmo Index Buffer"),
contents: index_buffer_data,
});
let color_buffer_data = cast_slice(&source_asset.0.colors);
let color_buffer = render_device.create_buffer_with_data(&BufferInitDescriptor {
usage: BufferUsages::VERTEX,
label: Some("TransformGizmo Color Buffer"),
contents: color_buffer_data,
});
Ok(Self {
index_buffer,
position_buffer,
color_buffer,
index_count: source_asset.0.indices.len() as u32,
})
}
}
struct DrawTransformGizmo;
impl<P: PhaseItem> RenderCommand<P> for DrawTransformGizmo {
type ViewQuery = ();
type ItemQuery = Read<GizmoDrawDataHandle>;
type Param = SRes<RenderAssets<GizmoBuffers>>;
#[inline]
fn render<'w>(
_item: &P,
_view: ROQueryItem<'w, '_, Self::ViewQuery>,
handle: Option<ROQueryItem<'w, '_, Self::ItemQuery>>,
gizmos: SystemParamItem<'w, '_, Self::Param>,
pass: &mut TrackedRenderPass<'w>,
) -> RenderCommandResult {
let Some(handle) = handle else {
return RenderCommandResult::Failure("No GizmoDrawDataHandle component found");
};
let Some(gizmo) = gizmos.into_inner().get(handle) else {
return RenderCommandResult::Failure("No GizmoDrawDataHandle inner found");
};
if gizmo.index_buffer.size() > 0 {
pass.set_index_buffer(gizmo.index_buffer.slice(..), IndexFormat::Uint32);
pass.set_vertex_buffer(0, gizmo.position_buffer.slice(..));
pass.set_vertex_buffer(1, gizmo.color_buffer.slice(..));
pass.draw_indexed(0..gizmo.index_count, 0, 0..1);
}
RenderCommandResult::Success
}
}
#[derive(Clone, Resource)]
struct TransformGizmoPipeline {
mesh_pipeline: MeshPipeline,
}
impl FromWorld for TransformGizmoPipeline {
fn from_world(render_world: &mut World) -> Self {
Self {
mesh_pipeline: render_world.resource::<MeshPipeline>().clone(),
}
}
}
#[derive(PartialEq, Eq, Hash, Clone)]
struct TransformGizmoPipelineKey {
view_key: MeshPipelineKey,
perspective: bool,
}
impl SpecializedRenderPipeline for TransformGizmoPipeline {
type Key = TransformGizmoPipelineKey;
fn specialize(&self, key: Self::Key) -> RenderPipelineDescriptor {
let mut shader_defs = vec![
// TODO: When is this flag actually used?
// #[cfg(feature = "webgl")]
// "SIXTEEN_BYTE_ALIGNMENT".into(),
];
if key.perspective {
shader_defs.push("PERSPECTIVE".into());
}
let format = if key.view_key.contains(MeshPipelineKey::HDR) {
ViewTarget::TEXTURE_FORMAT_HDR
} else {
TextureFormat::bevy_default()
};
let view_layout = self
.mesh_pipeline
.get_view_layout(key.view_key.into())
.clone();
let layout = vec![view_layout.main_layout.clone()];
RenderPipelineDescriptor {
label: Some("TransformGizmo Pipeline".into()),
zero_initialize_workgroup_memory: true, // ?
vertex: VertexState {
shader: GIZMO_SHADER_HANDLE,
entry_point: Some("vertex".into()),
shader_defs: shader_defs.clone(),
buffers: vec![
VertexBufferLayout {
array_stride: VertexFormat::Float32x2.size(),
step_mode: VertexStepMode::Vertex,
attributes: vec![VertexAttribute {
format: VertexFormat::Float32x2,
offset: 0,
shader_location: 0,
}],
},
VertexBufferLayout {
array_stride: VertexFormat::Float32x4.size(),
step_mode: VertexStepMode::Vertex,
attributes: vec![VertexAttribute {
format: VertexFormat::Float32x4,
offset: 0,
shader_location: 1,
}],
},
],
},
fragment: Some(FragmentState {
shader: GIZMO_SHADER_HANDLE,
shader_defs,
entry_point: Some("fragment".into()),
targets: vec![Some(ColorTargetState {
format,
blend: Some(BlendState::PREMULTIPLIED_ALPHA_BLENDING),
write_mask: ColorWrites::ALL,
})],
}),
layout,
primitive: PrimitiveState {
topology: PrimitiveTopology::TriangleList,
cull_mode: None,
..PrimitiveState::default()
},
depth_stencil: Some(DepthStencilState {
format: CORE_3D_DEPTH_FORMAT,
depth_write_enabled: true,
depth_compare: CompareFunction::Always,
stencil: StencilState::default(),
bias: DepthBiasState::default(),
}),
multisample: MultisampleState {
count: key.view_key.msaa_samples(),
mask: !0,
alpha_to_coverage_enabled: false,
},
push_constant_ranges: vec![],
}
}
}
type DrawGizmo = (SetItemPipeline, SetMeshViewBindGroup<0>, DrawTransformGizmo);
#[allow(clippy::too_many_arguments, clippy::type_complexity)]
fn queue_transform_gizmos(
draw_functions: Res<DrawFunctions<Transparent3d>>,
pipeline: Res<TransformGizmoPipeline>,
mut pipelines: ResMut<SpecializedRenderPipelines<TransformGizmoPipeline>>,
pipeline_cache: Res<PipelineCache>,
msaa_q: Query<Option<&Msaa>, With<GizmoCamera>>,
transform_gizmos: Query<(Entity, &GizmoDrawDataHandle)>,
transform_gizmo_assets: Res<RenderAssets<GizmoBuffers>>,
mut views: Query<(
Entity,
&ExtractedView,
Option<&Msaa>,
Option<&RenderLayers>,
(
Has<NormalPrepass>,
Has<DepthPrepass>,
Has<MotionVectorPrepass>,
Has<DeferredPrepass>,
Has<ExtractedAtmosphere>,
),
)>,
mut transparent_render_phases: ResMut<ViewSortedRenderPhases<Transparent3d>>,
) {
let draw_function = draw_functions.read().get_id::<DrawGizmo>().unwrap();
let camera_msaa = msaa_q.single().ok().flatten();
for (
view_entity,
view,
entity_msaa,
_render_layers,
(normal_prepass, depth_prepass, motion_vector_prepass, deferred_prepass, atmosphere),
) in &mut views
{
let Some(transparent_phase) = transparent_render_phases.get_mut(&view.retained_view_entity)
else {
continue;
};
// entity_msaa > camera_msaa > default
let msaa_sample_count = entity_msaa.map_or(
camera_msaa.unwrap_or(&Msaa::default()).samples(),
Msaa::samples,
);
let mut view_key = MeshPipelineKey::from_msaa_samples(msaa_sample_count)
| MeshPipelineKey::from_hdr(view.hdr);
if normal_prepass {
view_key |= MeshPipelineKey::NORMAL_PREPASS;
}
if depth_prepass {
view_key |= MeshPipelineKey::DEPTH_PREPASS;
}
if motion_vector_prepass {
view_key |= MeshPipelineKey::MOTION_VECTOR_PREPASS;
}
if deferred_prepass {
view_key |= MeshPipelineKey::DEFERRED_PREPASS;
}
if atmosphere {
view_key |= MeshPipelineKey::ATMOSPHERE;
}
for (entity, handle) in &transform_gizmos {
let Some(_) = transform_gizmo_assets.get(handle.0.id()) else {
continue;
};
let pipeline = pipelines.specialize(
&pipeline_cache,
&pipeline,
TransformGizmoPipelineKey {
view_key,
perspective: true,
},
);
transparent_phase.add(Transparent3d {
entity: (entity, view_entity.into()),
draw_function,
pipeline,
distance: 0.,
batch_range: 0..1,
extra_index: PhaseItemExtraIndex::None,
indexed: false,
});
}
}
}