Skip to main content

bevy_yoleck/
vpeol_3d.rs

1//! # Viewport Editing Overlay for 3D games.
2//!
3//! Use this module to implement simple 3D editing for 3D games.
4//!
5//! To use add the egui and Yoleck plugins to the Bevy app, as well as the plugin of this module:
6//!
7//! ```no_run
8//! # use bevy::prelude::*;
9//! # use bevy_yoleck::bevy_egui::EguiPlugin;
10//! # use bevy_yoleck::prelude::*;
11//! # use bevy_yoleck::vpeol::prelude::*;
12//! # let mut app = App::new();
13//! app.add_plugins(EguiPlugin::default());
14//! app.add_plugins(YoleckPluginForEditor);
15//! // - Use `Vpeol3dPluginForGame` instead when setting up for game.
16//! // - Use topdown is for games that utilize the XZ plane. There is also
17//! //   `Vpeol3dPluginForEditor::sidescroller` for games that mainly need the XY plane.
18//! app.add_plugins(Vpeol3dPluginForEditor::topdown());
19//! ```
20//!
21//! Add the following components to the camera entity:
22//! * [`VpeolCameraState`] in order to select and drag entities.
23//! * [`Vpeol3dCameraControl`] in order to control the camera with the mouse. This one can be
24//!   skipped if there are other means to control the camera inside the editor, or if no camera
25//!   control inside the editor is desired.
26//!
27//! ```no_run
28//! # use bevy::prelude::*;
29//! # use bevy_yoleck::vpeol::prelude::*;
30//! # let commands: Commands = panic!();
31//! commands
32//!     .spawn(Camera3d::default())
33//!     .insert(VpeolCameraState::default())
34//!     // Use a variant of the camera controls that fit the choice of editor plugin.
35//!     .insert(Vpeol3dCameraControl::topdown());
36//! ```
37//!
38//! ## Custom Camera Modes
39//!
40//! You can customize available camera modes using [`YoleckCameraChoices`]:
41//!
42//! ```no_run
43//! # use bevy::prelude::*;
44//! # use bevy_yoleck::vpeol::prelude::*;
45//! # let mut app = App::new();
46//! app.insert_resource(
47//!     YoleckCameraChoices::default()
48//!         .choice_with_transform(
49//!             "Custom Camera",
50//!             {
51//!                 let mut control = Vpeol3dCameraControl::fps();
52//!                 control.mode = Vpeol3dCameraMode::Custom(0);
53//!                 control
54//!             },
55//!             Vec3::new(10.0, 10.0, 10.0),
56//!             Vec3::ZERO,
57//!             Vec3::Y,
58//!         )
59//! );
60//!
61//! // Implement custom camera movement
62//! app.add_systems(PostUpdate, custom_camera_movement);
63//!
64//! fn custom_camera_movement(
65//!     mut cameras: Query<(&mut Transform, &Vpeol3dCameraControl)>,
66//! ) {
67//!     for (mut transform, control) in cameras.iter_mut() {
68//!         if control.mode == Vpeol3dCameraMode::Custom(0) {
69//!             // Your custom camera logic here
70//!         }
71//!     }
72//! }
73//! ```
74//!
75//! Entity selection by clicking on it is supported by just adding the plugin. To implement
76//! dragging, there are two options:
77//!
78//! 1. Add the [`Vpeol3dPosition`] Yoleck component and use it as the source of position. Gizmo
79//!    with axis knobs (X, Y, Z) are automatically added to all entities with `Vpeol3dPosition`.
80//!    Configure them using the [`Vpeol3dTranslationGizmoConfig`] resource. Optionally add
81//!    [`Vpeol3dRotation`] (edited with Euler angles) and [`Vpeol3dScale`] (edited with X, Y, Z
82//!    values) for rotation and scale support.
83//!     ```no_run
84//!     # use bevy::prelude::*;
85//!     # use bevy_yoleck::prelude::*;
86//!     # use bevy_yoleck::vpeol::prelude::*;
87//!     # use serde::{Deserialize, Serialize};
88//!     # #[derive(Clone, PartialEq, Serialize, Deserialize, Component, Default, YoleckComponent)]
89//!     # struct Example;
90//!     # let mut app = App::new();
91//!     app.add_yoleck_entity_type({
92//!         YoleckEntityType::new("Example")
93//!             .with::<Vpeol3dPosition>() // vpeol_3d dragging with axis knobs
94//!             .with::<Vpeol3dRotation>() // optional: rotation with egui (Euler angles)
95//!             .with::<Vpeol3dScale>() // optional: scale with egui
96//!             .with::<Example>() // entity's specific data and systems
97//!     });
98//!     ```
99//! 2. Use data passing. vpeol_3d will pass a `Vec3` to the entity being dragged:
100//!     ```no_run
101//!     # use bevy::prelude::*;
102//!     # use bevy_yoleck::prelude::*;
103//!     # use serde::{Deserialize, Serialize};
104//!     # #[derive(Clone, PartialEq, Serialize, Deserialize, Component, Default, YoleckComponent)]
105//!     # struct Example {
106//!     #     position: Vec3,
107//!     # }
108//!     # let mut app = App::new();
109//!     fn edit_example(mut edit: YoleckEdit<(Entity, &mut Example)>, passed_data: Res<YoleckPassedData>) {
110//!         let Ok((entity, mut example)) = edit.single_mut() else { return };
111//!         if let Some(pos) = passed_data.get::<Vec3>(entity) {
112//!             example.position = *pos;
113//!         }
114//!     }
115//!
116//!     fn populate_example(
117//!         mut populate: YoleckPopulate<&Example>,
118//!         asset_server: Res<AssetServer>
119//!     ) {
120//!         populate.populate(|_ctx, mut cmd, example| {
121//!             cmd.insert(Transform::from_translation(example.position));
122//!             cmd.insert(WorldAssetRoot(asset_server.load("scene.glb#Scene0")));
123//!         });
124//!     }
125//!     ```
126
127use std::any::TypeId;
128
129use crate::bevy_egui::egui;
130use crate::editor_panels::YoleckPanelUi;
131use crate::exclusive_systems::{
132    YoleckEntityCreationExclusiveSystems, YoleckExclusiveSystemDirective,
133};
134use crate::vpeol::{
135    VpeolBasePlugin, VpeolCameraState, VpeolClicksOnObjectsState, VpeolDragPlane,
136    VpeolOverrideDragPlane, VpeolRepositionLevel, VpeolRootResolver, VpeolSystems,
137    handle_clickable_children_system, ray_intersection_with_mesh,
138};
139use crate::{
140    YoleckBelongsToLevel, YoleckDirective, YoleckEditorTopPanelSections, YoleckSchedule, prelude::*,
141};
142use bevy::camera::visibility::VisibleEntities;
143use bevy::color::palettes::css;
144use bevy::input::mouse::{MouseMotion, MouseWheel};
145use bevy::math::DVec3;
146use bevy::prelude::*;
147use bevy::window::{CursorGrabMode, CursorOptions, PrimaryWindow};
148use bevy_egui::EguiContexts;
149use serde::{Deserialize, Serialize};
150
151/// Add the systems required for loading levels that use vpeol_3d components
152pub struct Vpeol3dPluginForGame;
153
154impl Plugin for Vpeol3dPluginForGame {
155    fn build(&self, app: &mut App) {
156        app.add_systems(
157            YoleckSchedule::OverrideCommonComponents,
158            vpeol_3d_populate_transform,
159        );
160        #[cfg(feature = "bevy_reflect")]
161        register_reflect_types(app);
162    }
163}
164
165#[cfg(feature = "bevy_reflect")]
166fn register_reflect_types(app: &mut App) {
167    app.register_type::<Vpeol3dPosition>();
168    app.register_type::<Vpeol3dRotation>();
169    app.register_type::<Vpeol3dScale>();
170    app.register_type::<Vpeol3dCameraControl>();
171}
172
173/// Add the systems required for 3D editing.
174///
175/// * 3D camera control (for cameras with [`Vpeol3dCameraControl`])
176/// * Entity selection.
177/// * Entity dragging.
178/// * Connecting nested entities.
179pub struct Vpeol3dPluginForEditor {
180    /// The plane to configure the global [`VpeolDragPlane`] resource with.
181    ///
182    /// Indiviual entities can override this with their own [`VpeolDragPlane`] component.
183    ///
184    /// It is a good idea to match this to [`Vpeol3dCameraControl::plane`].
185    pub drag_plane: InfinitePlane3d,
186}
187
188impl Vpeol3dPluginForEditor {
189    /// For sidescroller games - drag entities along the XY plane.
190    ///
191    /// Indiviual entities can override this with a [`VpeolDragPlane`] component.
192    ///
193    /// This combines well with [`Vpeol3dCameraControl::sidescroller`].
194    pub fn sidescroller() -> Self {
195        Self {
196            drag_plane: InfinitePlane3d { normal: Dir3::Z },
197        }
198    }
199
200    /// For games that are not sidescrollers - drag entities along the XZ plane.
201    ///
202    /// Indiviual entities can override this with a [`VpeolDragPlane`] component.
203    ///
204    /// This combines well with [`Vpeol3dCameraControl::topdown`].
205    pub fn topdown() -> Self {
206        Self {
207            drag_plane: InfinitePlane3d { normal: Dir3::Y },
208        }
209    }
210}
211
212impl Plugin for Vpeol3dPluginForEditor {
213    fn build(&self, app: &mut App) {
214        app.add_plugins(VpeolBasePlugin);
215        app.add_plugins(Vpeol3dPluginForGame);
216        app.insert_resource(VpeolDragPlane(self.drag_plane));
217        app.init_resource::<Vpeol3dTranslationGizmoConfig>();
218        app.init_resource::<YoleckCameraChoices>();
219
220        let camera_mode_selector = app.register_system(vpeol_3d_camera_mode_selector);
221        app.world_mut()
222            .resource_mut::<YoleckEditorTopPanelSections>()
223            .0
224            .push(camera_mode_selector);
225        let translation_gizmo_mode_selector =
226            app.register_system(vpeol_3d_translation_gizmo_mode_selector);
227        app.world_mut()
228            .resource_mut::<YoleckEditorTopPanelSections>()
229            .0
230            .push(translation_gizmo_mode_selector);
231
232        app.add_systems(
233            Update,
234            (update_camera_status_for_models,).in_set(VpeolSystems::UpdateCameraState),
235        );
236        app.add_systems(
237            PostUpdate,
238            (
239                camera_3d_wasd_movement,
240                camera_3d_move_along_plane_normal,
241                camera_3d_rotate,
242            )
243                .run_if(in_state(YoleckEditorState::EditorActive)),
244        );
245        app.add_systems(
246            Update,
247            draw_scene_gizmo.run_if(in_state(YoleckEditorState::EditorActive)),
248        );
249        app.add_systems(
250            Update,
251            (
252                ApplyDeferred,
253                handle_clickable_children_system::<With<Mesh3d>, ()>,
254                ApplyDeferred,
255            )
256                .chain()
257                .run_if(in_state(YoleckEditorState::EditorActive)),
258        );
259        app.add_yoleck_edit_system(vpeol_3d_edit_transform_group);
260        app.world_mut()
261            .resource_mut::<YoleckEntityCreationExclusiveSystems>()
262            .on_entity_creation(|queue| queue.push_back(vpeol_3d_init_position));
263        app.add_yoleck_edit_system(vpeol_3d_edit_axis_knobs);
264    }
265}
266
267fn update_camera_status_for_models(
268    mut cameras_query: Query<(&mut VpeolCameraState, &VisibleEntities)>,
269    entities_query: Query<(Entity, &GlobalTransform, &Mesh3d)>,
270    mesh_assets: Res<Assets<Mesh>>,
271    root_resolver: VpeolRootResolver,
272) {
273    for (mut camera_state, visible_entities) in cameras_query.iter_mut() {
274        let Some(cursor_ray) = camera_state.cursor_ray else {
275            continue;
276        };
277        for (entity, global_transform, mesh) in entities_query
278            .iter_many(visible_entities.iter(TypeId::of::<Mesh3d>()))
279            .matched()
280        {
281            let Some(mesh) = mesh_assets.get(&mesh.0) else {
282                continue;
283            };
284
285            let inverse_transform = global_transform.to_matrix().inverse();
286
287            // Note: the transform may change the ray's length, which Bevy no longer supports
288            // (since version 0.13), so we keep the ray length separately and apply it later to the
289            // distance.
290            let ray_origin = inverse_transform.transform_point3(cursor_ray.origin);
291            let ray_vector = inverse_transform.transform_vector3(*cursor_ray.direction);
292            let Ok((ray_direction, ray_length_factor)) = Dir3::new_and_length(ray_vector) else {
293                continue;
294            };
295
296            let ray_in_object_coords = Ray3d {
297                origin: ray_origin,
298                direction: ray_direction,
299            };
300
301            let Some(distance) = ray_intersection_with_mesh(ray_in_object_coords, mesh) else {
302                continue;
303            };
304
305            let distance = distance / ray_length_factor;
306
307            let Some(root_entity) = root_resolver.resolve_root(entity) else {
308                continue;
309            };
310            camera_state.consider(root_entity, -distance, || cursor_ray.get_point(distance));
311        }
312    }
313}
314
315/// A single camera mode choice with its control settings and optional initial transform.
316///
317/// The `control` field contains the camera settings that will be applied when this mode is selected.
318/// The `initial_transform` field, if present, will reposition the camera when switching to this mode.
319pub struct YoleckCameraChoice {
320    /// Display name shown in the camera mode selector UI.
321    pub name: String,
322    /// Camera control settings for this mode.
323    pub control: Vpeol3dCameraControl,
324    /// Optional initial transform (position, look_at, up) to apply when switching to this mode.
325    pub initial_transform: Option<(Vec3, Vec3, Vec3)>,
326}
327
328/// Resource that defines available camera modes in the editor.
329///
330/// This allows users to customize which camera modes are available and add custom modes.
331///
332/// # Example
333///
334/// ```no_run
335/// # use bevy::prelude::*;
336/// # use bevy_yoleck::vpeol::prelude::*;
337/// # let mut app = App::new();
338/// app.insert_resource(
339///     YoleckCameraChoices::default()
340///         .choice_with_transform(
341///             "Isometric",
342///             {
343///                 let mut control = Vpeol3dCameraControl::fps();
344///                 control.mode = Vpeol3dCameraMode::Custom(2);
345///                 control.allow_rotation_while_maintaining_up = None;
346///                 control
347///             },
348///             Vec3::new(10.0, 10.0, 10.0),
349///             Vec3::ZERO,
350///             Vec3::Y,
351///         )
352/// );
353/// ```
354#[derive(Resource)]
355pub struct YoleckCameraChoices {
356    pub choices: Vec<YoleckCameraChoice>,
357}
358
359impl YoleckCameraChoices {
360    pub fn new() -> Self {
361        Self {
362            choices: Vec::new(),
363        }
364    }
365
366    /// Add a camera mode choice without initial transform.
367    ///
368    /// The camera will keep its current position when switching to this mode.
369    pub fn choice(mut self, name: impl Into<String>, control: Vpeol3dCameraControl) -> Self {
370        self.choices.push(YoleckCameraChoice {
371            name: name.into(),
372            control,
373            initial_transform: None,
374        });
375        self
376    }
377
378    /// Add a camera mode choice with initial transform.
379    ///
380    /// When switching to this mode, the camera will be repositioned according to
381    /// the provided `position`, `look_at`, and `up` parameters.
382    pub fn choice_with_transform(
383        mut self,
384        name: impl Into<String>,
385        control: Vpeol3dCameraControl,
386        position: Vec3,
387        look_at: Vec3,
388        up: Vec3,
389    ) -> Self {
390        self.choices.push(YoleckCameraChoice {
391            name: name.into(),
392            control,
393            initial_transform: Some((position, look_at, up)),
394        });
395        self
396    }
397}
398
399impl Default for YoleckCameraChoices {
400    fn default() -> Self {
401        Self::new()
402            .choice_with_transform(
403                "FPS",
404                Vpeol3dCameraControl::fps(),
405                Vec3::ZERO,
406                Vec3::NEG_Z,
407                Vec3::Y,
408            )
409            .choice_with_transform(
410                "Sidescroller",
411                Vpeol3dCameraControl::sidescroller(),
412                Vec3::new(0.0, 0.0, 10.0),
413                Vec3::ZERO,
414                Vec3::Y,
415            )
416            .choice_with_transform(
417                "Topdown",
418                Vpeol3dCameraControl::topdown(),
419                Vec3::new(0.0, 10.0, 0.0),
420                Vec3::ZERO,
421                Vec3::NEG_Z,
422            )
423    }
424}
425
426/// Camera mode identifier for type-safe camera mode comparisons.
427///
428/// Use this enum to identify which camera mode is currently active, instead of string comparisons.
429/// The built-in modes (`Fps`, `Sidescroller`, `Topdown`) are provided by default.
430/// Use `Custom(u32)` for user-defined camera modes with unique identifiers.
431#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
432#[cfg_attr(feature = "bevy_reflect", derive(bevy::reflect::Reflect))]
433pub enum Vpeol3dCameraMode {
434    /// FPS-style camera with full rotation freedom.
435    #[default]
436    Fps,
437    /// Fixed camera for sidescroller games (XY plane).
438    Sidescroller,
439    /// Top-down camera for games using XZ plane.
440    Topdown,
441    /// Custom camera mode with a unique identifier.
442    Custom(u32),
443}
444
445/// Move and rotate a camera entity with the mouse while inside the editor.
446#[derive(Component, Default, Clone)]
447#[cfg_attr(feature = "bevy_reflect", derive(bevy::reflect::Reflect))]
448pub struct Vpeol3dCameraControl {
449    /// Camera mode identifier for type-safe mode comparisons.
450    ///
451    /// Use this to identify which camera mode is active in custom camera systems.
452    pub mode: Vpeol3dCameraMode,
453    /// Defines the plane normal for mouse wheel zoom movement.
454    pub plane: InfinitePlane3d,
455    /// If `Some`, enable mouse rotation. The up direction of the camera will be the specific
456    /// direction.
457    ///
458    /// It is a good idea to match this to [`Vpeol3dPluginForEditor::drag_plane`].
459    pub allow_rotation_while_maintaining_up: Option<Dir3>,
460    /// How much to change the proximity to the plane when receiving scroll event in
461    /// `MouseScrollUnit::Line` units.
462    pub proximity_per_scroll_line: f32,
463    /// How much to change the proximity to the plane when receiving scroll event in
464    /// `MouseScrollUnit::Pixel` units.
465    pub proximity_per_scroll_pixel: f32,
466    /// Movement speed for WASD controls (units per second).
467    pub wasd_movement_speed: f32,
468    /// Mouse sensitivity for camera rotation.
469    pub mouse_sensitivity: f32,
470}
471
472impl Vpeol3dCameraControl {
473    /// Preset for FPS-style camera control with full rotation freedom.
474    ///
475    /// This mode allows complete free-look rotation with mouse and WASD movement.
476    pub fn fps() -> Self {
477        Self {
478            mode: Vpeol3dCameraMode::Fps,
479            plane: InfinitePlane3d { normal: Dir3::Y },
480            allow_rotation_while_maintaining_up: Some(Dir3::Y),
481            proximity_per_scroll_line: 2.0,
482            proximity_per_scroll_pixel: 0.01,
483            wasd_movement_speed: 10.0,
484            mouse_sensitivity: 0.003,
485        }
486    }
487
488    /// Preset for sidescroller games, where the the game world is on the XY plane.
489    ///
490    /// With this preset, the camera stays fixed looking at the scene from the side.
491    ///
492    /// This combines well with [`Vpeol3dPluginForEditor::sidescroller`].
493    pub fn sidescroller() -> Self {
494        Self {
495            mode: Vpeol3dCameraMode::Sidescroller,
496            plane: InfinitePlane3d {
497                normal: Dir3::NEG_Z,
498            },
499            allow_rotation_while_maintaining_up: None,
500            proximity_per_scroll_line: 2.0,
501            proximity_per_scroll_pixel: 0.01,
502            wasd_movement_speed: 10.0,
503            mouse_sensitivity: 0.003,
504        }
505    }
506
507    /// Preset for games where the the game world is mainly on the XZ plane (though there can still
508    /// be verticality)
509    ///
510    /// This combines well with [`Vpeol3dPluginForEditor::topdown`].
511    pub fn topdown() -> Self {
512        Self {
513            mode: Vpeol3dCameraMode::Topdown,
514            plane: InfinitePlane3d {
515                normal: Dir3::NEG_Y,
516            },
517            allow_rotation_while_maintaining_up: None,
518            proximity_per_scroll_line: 2.0,
519            proximity_per_scroll_pixel: 0.01,
520            wasd_movement_speed: 10.0,
521            mouse_sensitivity: 0.003,
522        }
523    }
524}
525
526fn camera_3d_wasd_movement(
527    mut egui_context: EguiContexts,
528    keyboard_input: Res<ButtonInput<KeyCode>>,
529    time: Res<Time>,
530    mut cameras_query: Query<(&mut Transform, &Vpeol3dCameraControl)>,
531) -> Result {
532    if egui_context.ctx_mut()?.egui_wants_keyboard_input() {
533        return Ok(());
534    }
535
536    let mut direction = Vec3::ZERO;
537
538    if keyboard_input.pressed(KeyCode::KeyW) {
539        direction += Vec3::NEG_Z;
540    }
541    if keyboard_input.pressed(KeyCode::KeyS) {
542        direction += Vec3::Z;
543    }
544    if keyboard_input.pressed(KeyCode::KeyA) {
545        direction += Vec3::NEG_X;
546    }
547    if keyboard_input.pressed(KeyCode::KeyD) {
548        direction += Vec3::X;
549    }
550    if keyboard_input.pressed(KeyCode::KeyE) {
551        direction += Vec3::Y;
552    }
553    if keyboard_input.pressed(KeyCode::KeyQ) {
554        direction += Vec3::NEG_Y;
555    }
556
557    if direction == Vec3::ZERO {
558        return Ok(());
559    }
560
561    direction = direction.normalize_or_zero();
562
563    let speed_multiplier = if keyboard_input.pressed(KeyCode::ShiftLeft) {
564        2.0
565    } else {
566        1.0
567    };
568
569    for (mut camera_transform, camera_control) in cameras_query.iter_mut() {
570        let movement = match camera_control.mode {
571            Vpeol3dCameraMode::Sidescroller => {
572                let mut world_direction = Vec3::ZERO;
573                if keyboard_input.pressed(KeyCode::KeyW) {
574                    world_direction.y += 1.0;
575                }
576                if keyboard_input.pressed(KeyCode::KeyS) {
577                    world_direction.y -= 1.0;
578                }
579                if keyboard_input.pressed(KeyCode::KeyA) {
580                    world_direction.x -= 1.0;
581                }
582                if keyboard_input.pressed(KeyCode::KeyD) {
583                    world_direction.x += 1.0;
584                }
585                world_direction.normalize_or_zero()
586                    * camera_control.wasd_movement_speed
587                    * speed_multiplier
588                    * time.delta_secs()
589            }
590            Vpeol3dCameraMode::Topdown => {
591                let mut world_direction = Vec3::ZERO;
592                if keyboard_input.pressed(KeyCode::KeyW) {
593                    world_direction.z -= 1.0;
594                }
595                if keyboard_input.pressed(KeyCode::KeyS) {
596                    world_direction.z += 1.0;
597                }
598                if keyboard_input.pressed(KeyCode::KeyA) {
599                    world_direction.x -= 1.0;
600                }
601                if keyboard_input.pressed(KeyCode::KeyD) {
602                    world_direction.x += 1.0;
603                }
604                world_direction.normalize_or_zero()
605                    * camera_control.wasd_movement_speed
606                    * speed_multiplier
607                    * time.delta_secs()
608            }
609            _ => {
610                camera_transform.rotation
611                    * direction
612                    * camera_control.wasd_movement_speed
613                    * speed_multiplier
614                    * time.delta_secs()
615            }
616        };
617
618        camera_transform.translation += movement;
619    }
620    Ok(())
621}
622
623fn camera_3d_move_along_plane_normal(
624    mut egui_context: EguiContexts,
625    mut cameras_query: Query<(&mut Transform, &Vpeol3dCameraControl)>,
626    mut wheel_events_reader: MessageReader<MouseWheel>,
627) -> Result {
628    if egui_context.ctx_mut()?.is_pointer_over_egui() {
629        return Ok(());
630    }
631
632    for (mut camera_transform, camera_control) in cameras_query.iter_mut() {
633        let zoom_amount: f32 = wheel_events_reader
634            .read()
635            .map(|wheel_event| match wheel_event.unit {
636                bevy::input::mouse::MouseScrollUnit::Line => {
637                    wheel_event.y * camera_control.proximity_per_scroll_line
638                }
639                bevy::input::mouse::MouseScrollUnit::Pixel => {
640                    wheel_event.y * camera_control.proximity_per_scroll_pixel
641                }
642            })
643            .sum();
644
645        if zoom_amount == 0.0 {
646            continue;
647        }
648
649        camera_transform.translation += zoom_amount * *camera_control.plane.normal;
650    }
651    Ok(())
652}
653
654fn draw_scene_gizmo(
655    mut egui_context: EguiContexts,
656    mut cameras_query: Query<&mut Transform, With<VpeolCameraState>>,
657    mouse_buttons: Res<ButtonInput<MouseButton>>,
658    mut first_frame_skipped: Local<bool>,
659    editor_viewport: Res<crate::editor_window::YoleckEditorViewportRect>,
660) -> Result {
661    if !*first_frame_skipped {
662        *first_frame_skipped = true;
663        return Ok(());
664    }
665
666    let ctx = egui_context.ctx_mut()?;
667
668    if !ctx.egui_is_using_pointer() && ctx.input(|i| i.viewport_rect().width() == 0.0) {
669        return Ok(());
670    }
671
672    let Ok(mut camera_transform) = cameras_query.single_mut() else {
673        return Ok(());
674    };
675
676    let screen_rect = editor_viewport
677        .rect
678        .unwrap_or_else(|| ctx.input(|i| i.viewport_rect()));
679
680    if screen_rect.width() == 0.0 || screen_rect.height() == 0.0 {
681        return Ok(());
682    }
683
684    let gizmo_size = 60.0;
685    let axis_length = 25.0;
686    let margin = 20.0;
687    let click_radius = 10.0;
688
689    let center = egui::Pos2::new(
690        screen_rect.max.x - margin - gizmo_size / 2.0,
691        screen_rect.min.y + margin + gizmo_size / 2.0,
692    );
693
694    let camera_rotation = camera_transform.rotation;
695    let inv_rotation = camera_rotation.inverse();
696
697    let world_x = inv_rotation * Vec3::X;
698    let world_y = inv_rotation * Vec3::Y;
699    let world_z = inv_rotation * Vec3::Z;
700
701    let to_screen = |v: Vec3| -> egui::Pos2 {
702        let perspective_scale = 1.0 / (1.0 - v.z * 0.3);
703        let screen_x = v.x * axis_length * perspective_scale;
704        let screen_y = v.y * axis_length * perspective_scale;
705
706        let len = (screen_x * screen_x + screen_y * screen_y).sqrt();
707        let min_len = 8.0;
708        let (screen_x, screen_y) = if len < min_len && len > 0.001 {
709            let scale = min_len / len;
710            (screen_x * scale, screen_y * scale)
711        } else {
712            (screen_x, screen_y)
713        };
714
715        egui::Pos2::new(center.x + screen_x, center.y - screen_y)
716    };
717
718    let x_pos = to_screen(world_x);
719    let x_neg = to_screen(-world_x);
720    let y_pos = to_screen(world_y);
721    let y_neg = to_screen(-world_y);
722    let z_pos = to_screen(world_z);
723    let z_neg = to_screen(-world_z);
724
725    let cursor_pos = ctx.input(|i| i.pointer.hover_pos());
726    let gizmo_rect = egui::Rect::from_center_size(center, egui::Vec2::splat(gizmo_size));
727
728    if let Some(cursor) = cursor_pos
729        && mouse_buttons.just_pressed(MouseButton::Left)
730        && gizmo_rect.contains(cursor)
731    {
732        let distances = [
733            (cursor.distance(x_pos), Vec3::NEG_X, Vec3::Y),
734            (cursor.distance(x_neg), Vec3::X, Vec3::Y),
735            (cursor.distance(y_pos), Vec3::NEG_Y, Vec3::Z),
736            (cursor.distance(y_neg), Vec3::Y, Vec3::Z),
737            (cursor.distance(z_pos), Vec3::NEG_Z, Vec3::Y),
738            (cursor.distance(z_neg), Vec3::Z, Vec3::Y),
739        ];
740
741        if let Some((_, forward, up)) = distances
742            .iter()
743            .filter(|(d, _, _)| *d < click_radius)
744            .min_by(|a, b| a.0.partial_cmp(&b.0).unwrap())
745        {
746            camera_transform.look_to(*forward, *up);
747        }
748    }
749
750    #[derive(Clone, Copy)]
751    struct AxisData {
752        depth: f32,
753        color_bright: egui::Color32,
754        color_dim: egui::Color32,
755        pos_end: egui::Pos2,
756        neg_end: egui::Pos2,
757        world_dir: Vec3,
758    }
759
760    let mut axes = vec![
761        AxisData {
762            depth: world_x.z.abs(),
763            color_bright: egui::Color32::from_rgb(230, 60, 60),
764            color_dim: egui::Color32::from_rgb(120, 50, 50),
765            pos_end: x_pos,
766            neg_end: x_neg,
767            world_dir: world_x,
768        },
769        AxisData {
770            depth: world_y.z.abs(),
771            color_bright: egui::Color32::from_rgb(60, 230, 60),
772            color_dim: egui::Color32::from_rgb(50, 120, 50),
773            pos_end: y_pos,
774            neg_end: y_neg,
775            world_dir: world_y,
776        },
777        AxisData {
778            depth: world_z.z.abs(),
779            color_bright: egui::Color32::from_rgb(60, 120, 230),
780            color_dim: egui::Color32::from_rgb(50, 70, 120),
781            pos_end: z_pos,
782            neg_end: z_neg,
783            world_dir: world_z,
784        },
785    ];
786    axes.sort_by(|a, b| b.depth.partial_cmp(&a.depth).unwrap());
787
788    let painter = ctx.layer_painter(egui::LayerId::new(
789        egui::Order::Foreground,
790        egui::Id::new("scene_gizmo"),
791    ));
792
793    painter.circle_filled(
794        center,
795        gizmo_size / 2.0,
796        egui::Color32::from_rgba_unmultiplied(40, 40, 40, 200),
797    );
798
799    let stroke_bright = 3.0;
800    let stroke_dim = 2.0;
801    let cone_radius_bright = 5.0;
802    let cone_radius_dim = 3.5;
803    let cone_length = 8.0;
804
805    for axis in &axes {
806        let (front_end, front_color, back_end, back_color) = if axis.world_dir.z >= 0.0 {
807            (
808                axis.pos_end,
809                axis.color_bright,
810                axis.neg_end,
811                axis.color_dim,
812            )
813        } else {
814            (
815                axis.neg_end,
816                axis.color_dim,
817                axis.pos_end,
818                axis.color_bright,
819            )
820        };
821
822        let back_dir = (back_end - center).normalized();
823        let back_line_end = back_end - back_dir * cone_length;
824        painter.line_segment(
825            [center, back_line_end],
826            egui::Stroke::new(stroke_dim, back_color),
827        );
828
829        let back_perp = egui::Vec2::new(-back_dir.y, back_dir.x);
830        let back_cone_base = back_end - back_dir * cone_length;
831        let back_cone = vec![
832            back_end,
833            back_cone_base + back_perp * cone_radius_dim,
834            back_cone_base - back_perp * cone_radius_dim,
835        ];
836        painter.add(egui::Shape::convex_polygon(
837            back_cone,
838            back_color,
839            egui::Stroke::NONE,
840        ));
841
842        let front_dir = (front_end - center).normalized();
843        let front_line_end = front_end - front_dir * cone_length;
844        painter.line_segment(
845            [center, front_line_end],
846            egui::Stroke::new(stroke_bright, front_color),
847        );
848
849        let front_perp = egui::Vec2::new(-front_dir.y, front_dir.x);
850        let front_cone_base = front_end - front_dir * cone_length;
851        let front_cone = vec![
852            front_end,
853            front_cone_base + front_perp * cone_radius_bright,
854            front_cone_base - front_perp * cone_radius_bright,
855        ];
856        painter.add(egui::Shape::convex_polygon(
857            front_cone,
858            front_color,
859            egui::Stroke::NONE,
860        ));
861    }
862
863    let label_offset = 12.0;
864    let font_id = egui::FontId::proportional(12.0);
865
866    let axis_labels = [
867        ("X", x_pos, egui::Color32::from_rgb(230, 60, 60), world_x.z),
868        ("Y", y_pos, egui::Color32::from_rgb(60, 230, 60), world_y.z),
869        ("Z", z_pos, egui::Color32::from_rgb(60, 120, 230), world_z.z),
870    ];
871
872    for (label, pos, color, depth) in axis_labels {
873        let dir = (pos - center).normalized();
874        let label_pos = pos + dir * label_offset;
875        let alpha = if depth >= 0.0 { 255 } else { 120 };
876        let label_color =
877            egui::Color32::from_rgba_unmultiplied(color.r(), color.g(), color.b(), alpha);
878        painter.text(
879            label_pos,
880            egui::Align2::CENTER_CENTER,
881            label,
882            font_id.clone(),
883            label_color,
884        );
885    }
886
887    Ok(())
888}
889
890fn camera_3d_rotate(
891    mut egui_context: EguiContexts,
892    mouse_buttons: Res<ButtonInput<MouseButton>>,
893    mut cameras_query: Query<(&mut Transform, &Vpeol3dCameraControl)>,
894    mut mouse_motion_reader: MessageReader<MouseMotion>,
895    mut cursor_options: Query<&mut CursorOptions, With<PrimaryWindow>>,
896    mut is_rotating: Local<bool>,
897) -> Result {
898    let Ok(mut cursor) = cursor_options.single_mut() else {
899        return Ok(());
900    };
901
902    if mouse_buttons.just_pressed(MouseButton::Right) {
903        if egui_context.ctx_mut()?.is_pointer_over_egui() {
904            return Ok(());
905        }
906
907        let has_rotatable_camera = cameras_query
908            .iter()
909            .any(|(_, control)| control.allow_rotation_while_maintaining_up.is_some());
910
911        if has_rotatable_camera {
912            cursor.grab_mode = CursorGrabMode::Locked;
913            cursor.visible = false;
914            *is_rotating = true;
915        }
916    }
917
918    if mouse_buttons.just_released(MouseButton::Right) {
919        cursor.grab_mode = CursorGrabMode::None;
920        cursor.visible = true;
921        *is_rotating = false;
922    }
923
924    if !*is_rotating {
925        return Ok(());
926    }
927
928    let mut delta = Vec2::ZERO;
929    for motion in mouse_motion_reader.read() {
930        delta += motion.delta;
931    }
932
933    if delta == Vec2::ZERO {
934        return Ok(());
935    }
936
937    for (mut camera_transform, camera_control) in cameras_query.iter_mut() {
938        let Some(maintaining_up) = camera_control.allow_rotation_while_maintaining_up else {
939            continue;
940        };
941
942        let yaw = -delta.x * camera_control.mouse_sensitivity;
943        let pitch = -delta.y * camera_control.mouse_sensitivity;
944
945        let yaw_rotation = Quat::from_axis_angle(*maintaining_up, yaw);
946        camera_transform.rotation = yaw_rotation * camera_transform.rotation;
947
948        let right = camera_transform.right();
949        let pitch_rotation = Quat::from_axis_angle(*right, pitch);
950        camera_transform.rotation = pitch_rotation * camera_transform.rotation;
951
952        let new_forward = camera_transform.forward();
953        camera_transform.look_to(*new_forward, *maintaining_up);
954    }
955    Ok(())
956}
957
958pub fn vpeol_3d_translation_gizmo_mode_selector(
959    mut ui: ResMut<YoleckPanelUi>,
960    mut config: ResMut<Vpeol3dTranslationGizmoConfig>,
961) -> Result {
962    let ui = &mut **ui;
963    ui.add_space(ui.available_width());
964
965    ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
966        ui.radio_value(
967            &mut config.mode,
968            Vpeol3dTranslationGizmoMode::Local,
969            "Local",
970        );
971        ui.radio_value(
972            &mut config.mode,
973            Vpeol3dTranslationGizmoMode::World,
974            "World",
975        );
976        ui.label("Gizmo:");
977    });
978
979    Ok(())
980}
981
982pub fn vpeol_3d_camera_mode_selector(
983    mut ui: ResMut<YoleckPanelUi>,
984    mut query: Query<(&mut Vpeol3dCameraControl, &mut Transform)>,
985    choices: Res<YoleckCameraChoices>,
986) -> Result {
987    if let Ok((mut camera_control, mut camera_transform)) = query.single_mut() {
988        let old_mode = camera_control.mode;
989
990        let current_choice = choices
991            .choices
992            .iter()
993            .find(|c| c.control.mode == camera_control.mode);
994        let selected_text = current_choice.map(|c| c.name.as_str()).unwrap_or("Unknown");
995
996        egui::ComboBox::from_id_salt("camera_mode_selector")
997            .selected_text(selected_text)
998            .show_ui(&mut ui, |ui| {
999                for choice in choices.choices.iter() {
1000                    ui.selectable_value(
1001                        &mut camera_control.mode,
1002                        choice.control.mode,
1003                        &choice.name,
1004                    );
1005                }
1006            });
1007
1008        if old_mode != camera_control.mode
1009            && let Some(choice) = choices
1010                .choices
1011                .iter()
1012                .find(|c| c.control.mode == camera_control.mode)
1013        {
1014            *camera_control = choice.control.clone();
1015
1016            if let Some((position, look_at, up)) = choice.initial_transform {
1017                camera_transform.translation = position;
1018                camera_transform.look_at(look_at, up);
1019            }
1020        }
1021    }
1022
1023    Ok(())
1024}
1025
1026/// A position component that's edited and populated by vpeol_3d.
1027///
1028/// Editing is done with egui, or by dragging the entity on a [`VpeolDragPlane`]  that passes
1029/// through the entity.
1030#[derive(Clone, PartialEq, Serialize, Deserialize, Component, Default, YoleckComponent)]
1031#[serde(transparent)]
1032#[cfg_attr(feature = "bevy_reflect", derive(bevy::reflect::Reflect))]
1033pub struct Vpeol3dPosition(pub Vec3);
1034
1035/// Add this to an entity with [`Vpeol3dPosition`] to force it to be on a specific plane while
1036/// editing.
1037///
1038/// This is useful for 2D games that use 3D graphics but don't want to allow free positioning of
1039/// entities on all axes.
1040///
1041/// Note that this is not a [`YoleckComponent`]. Do not add it with
1042/// [`insert_on_init_during_editor`](YoleckEntityType::with). The best way to add it is by using
1043/// [`insert_on_init_during_editor`](YoleckEntityType::insert_on_init_during_editor) which also
1044/// allows setting the data.
1045#[derive(Component)]
1046pub struct Vpeol3dSnapToPlane {
1047    pub normal: Dir3,
1048    /// Offset of the plane from the origin of axes
1049    pub offset: f32,
1050}
1051
1052#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1053pub enum Vpeol3dTranslationGizmoMode {
1054    World,
1055    Local,
1056}
1057
1058#[derive(Resource)]
1059pub struct Vpeol3dTranslationGizmoConfig {
1060    pub knob_distance: f32,
1061    pub knob_scale: f32,
1062    pub mode: Vpeol3dTranslationGizmoMode,
1063}
1064
1065impl Default for Vpeol3dTranslationGizmoConfig {
1066    fn default() -> Self {
1067        Self {
1068            knob_distance: 2.0,
1069            knob_scale: 0.5,
1070            mode: Vpeol3dTranslationGizmoMode::World,
1071        }
1072    }
1073}
1074
1075/// A rotation component that's edited and populated by vpeol_3d.
1076///
1077/// Editing is done with egui using Euler angles (X, Y, Z in degrees).
1078#[derive(Clone, PartialEq, Serialize, Deserialize, Component, YoleckComponent)]
1079#[serde(transparent)]
1080#[cfg_attr(feature = "bevy_reflect", derive(bevy::reflect::Reflect))]
1081pub struct Vpeol3dRotation(pub Quat);
1082
1083impl Default for Vpeol3dRotation {
1084    fn default() -> Self {
1085        Self(Quat::IDENTITY)
1086    }
1087}
1088
1089/// A scale component that's edited and populated by vpeol_3d.
1090///
1091/// Editing is done with egui using separate drag values for X, Y, Z axes.
1092#[derive(Clone, PartialEq, Serialize, Deserialize, Component, YoleckComponent)]
1093#[serde(transparent)]
1094#[cfg_attr(feature = "bevy_reflect", derive(bevy::reflect::Reflect))]
1095pub struct Vpeol3dScale(pub Vec3);
1096
1097impl Default for Vpeol3dScale {
1098    fn default() -> Self {
1099        Self(Vec3::ONE)
1100    }
1101}
1102
1103enum CommonDragPlane {
1104    NotDecidedYet,
1105    WithNormal(Vec3),
1106    NoSharedPlane,
1107}
1108
1109impl CommonDragPlane {
1110    fn consider(&mut self, normal: Vec3) {
1111        *self = match self {
1112            CommonDragPlane::NotDecidedYet => CommonDragPlane::WithNormal(normal),
1113            CommonDragPlane::WithNormal(current_normal) => {
1114                if *current_normal == normal {
1115                    CommonDragPlane::WithNormal(normal)
1116                } else {
1117                    CommonDragPlane::NoSharedPlane
1118                }
1119            }
1120            CommonDragPlane::NoSharedPlane => CommonDragPlane::NoSharedPlane,
1121        }
1122    }
1123
1124    fn shared_normal(&self) -> Option<Vec3> {
1125        if let CommonDragPlane::WithNormal(normal) = self {
1126            Some(*normal)
1127        } else {
1128            None
1129        }
1130    }
1131}
1132
1133fn vpeol_3d_edit_transform_group(
1134    mut ui: ResMut<YoleckUi>,
1135    position_edit: YoleckEdit<(
1136        Entity,
1137        &mut Vpeol3dPosition,
1138        Option<&VpeolDragPlane>,
1139        Option<&Vpeol3dSnapToPlane>,
1140    )>,
1141    rotation_edit: YoleckEdit<&mut Vpeol3dRotation>,
1142    scale_edit: YoleckEdit<&mut Vpeol3dScale>,
1143    global_drag_plane: Res<VpeolDragPlane>,
1144    passed_data: Res<YoleckPassedData>,
1145) {
1146    let has_any = !position_edit.is_empty() || !rotation_edit.is_empty() || !scale_edit.is_empty();
1147    if !has_any {
1148        return;
1149    }
1150
1151    ui.group(|ui| {
1152        ui.label(egui::RichText::new("Transform").strong());
1153        ui.separator();
1154
1155        vpeol_3d_edit_position_impl(ui, position_edit, &global_drag_plane, &passed_data);
1156        vpeol_3d_edit_rotation_impl(ui, rotation_edit);
1157        vpeol_3d_edit_scale_impl(ui, scale_edit);
1158    });
1159}
1160
1161fn vpeol_3d_edit_position_impl(
1162    ui: &mut egui::Ui,
1163    mut edit: YoleckEdit<(
1164        Entity,
1165        &mut Vpeol3dPosition,
1166        Option<&VpeolDragPlane>,
1167        Option<&Vpeol3dSnapToPlane>,
1168    )>,
1169    global_drag_plane: &VpeolDragPlane,
1170    passed_data: &YoleckPassedData,
1171) {
1172    if edit.is_empty() || edit.has_nonmatching() {
1173        return;
1174    }
1175    let mut average = DVec3::ZERO;
1176    let mut num_entities = 0;
1177    let mut transition = Vec3::ZERO;
1178
1179    let mut common_drag_plane = CommonDragPlane::NotDecidedYet;
1180
1181    for (entity, position, drag_plane, _) in edit.iter_matching() {
1182        let VpeolDragPlane(drag_plane) = drag_plane.unwrap_or(global_drag_plane);
1183        common_drag_plane.consider(*drag_plane.normal);
1184
1185        if let Some(pos) = passed_data.get::<Vec3>(entity) {
1186            transition = *pos - position.0;
1187        }
1188        average += position.0.as_dvec3();
1189        num_entities += 1;
1190    }
1191    average /= num_entities as f64;
1192
1193    if common_drag_plane.shared_normal().is_none() {
1194        transition = Vec3::ZERO;
1195        ui.label(
1196            egui::RichText::new("Drag plane differs - cannot drag together")
1197                .color(egui::Color32::RED),
1198        );
1199    }
1200    ui.horizontal(|ui| {
1201        let mut new_average = average;
1202
1203        ui.add(egui::Label::new("Position"));
1204        ui.add(egui::DragValue::new(&mut new_average.x).prefix("X:"));
1205        ui.add(egui::DragValue::new(&mut new_average.y).prefix("Y:"));
1206        ui.add(egui::DragValue::new(&mut new_average.z).prefix("Z:"));
1207
1208        transition += (new_average - average).as_vec3();
1209    });
1210
1211    if transition.is_finite() && transition != Vec3::ZERO {
1212        for (_, mut position, _, snap) in edit.iter_matching_mut() {
1213            position.0 += transition;
1214            if let Some(snap) = snap {
1215                let displacement = position.0.project_onto(*snap.normal);
1216                position.0 += snap.offset * snap.normal - displacement;
1217            }
1218        }
1219    }
1220}
1221
1222fn vpeol_3d_edit_rotation_impl(ui: &mut egui::Ui, mut edit: YoleckEdit<&mut Vpeol3dRotation>) {
1223    if edit.is_empty() || edit.has_nonmatching() {
1224        return;
1225    }
1226
1227    let mut average_euler = Vec3::ZERO;
1228    let mut num_entities = 0;
1229
1230    for rotation in edit.iter_matching() {
1231        let (x, y, z) = rotation.0.to_euler(EulerRot::XYZ);
1232        average_euler += Vec3::new(x, y, z);
1233        num_entities += 1;
1234    }
1235    average_euler /= num_entities as f32;
1236
1237    ui.horizontal(|ui| {
1238        let mut new_euler = average_euler;
1239        let mut x_deg = new_euler.x.to_degrees();
1240        let mut y_deg = new_euler.y.to_degrees();
1241        let mut z_deg = new_euler.z.to_degrees();
1242
1243        ui.add(egui::Label::new("Rotation"));
1244        ui.add(
1245            egui::DragValue::new(&mut x_deg)
1246                .prefix("X:")
1247                .speed(1.0)
1248                .suffix("°"),
1249        );
1250        ui.add(
1251            egui::DragValue::new(&mut y_deg)
1252                .prefix("Y:")
1253                .speed(1.0)
1254                .suffix("°"),
1255        );
1256        ui.add(
1257            egui::DragValue::new(&mut z_deg)
1258                .prefix("Z:")
1259                .speed(1.0)
1260                .suffix("°"),
1261        );
1262
1263        new_euler.x = x_deg.to_radians();
1264        new_euler.y = y_deg.to_radians();
1265        new_euler.z = z_deg.to_radians();
1266
1267        let transition = new_euler - average_euler;
1268
1269        if transition.is_finite() && transition != Vec3::ZERO {
1270            for mut rotation in edit.iter_matching_mut() {
1271                let (x, y, z) = rotation.0.to_euler(EulerRot::XYZ);
1272                rotation.0 = Quat::from_euler(
1273                    EulerRot::XYZ,
1274                    x + transition.x,
1275                    y + transition.y,
1276                    z + transition.z,
1277                )
1278            }
1279        }
1280    });
1281}
1282
1283fn vpeol_3d_edit_scale_impl(ui: &mut egui::Ui, mut edit: YoleckEdit<&mut Vpeol3dScale>) {
1284    if edit.is_empty() || edit.has_nonmatching() {
1285        return;
1286    }
1287    let mut average = DVec3::ZERO;
1288    let mut num_entities = 0;
1289
1290    for scale in edit.iter_matching() {
1291        average += scale.0.as_dvec3();
1292        num_entities += 1;
1293    }
1294    average /= num_entities as f64;
1295
1296    ui.horizontal(|ui| {
1297        let mut new_average = average;
1298
1299        ui.add(egui::Label::new("Scale"));
1300        ui.vertical(|ui| {
1301            ui.centered_and_justified(|ui| {
1302                let axis_average = (average.x + average.y + average.z) / 3.0;
1303                let mut new_axis_average = axis_average;
1304                if ui
1305                    .add(egui::DragValue::new(&mut new_axis_average).speed(0.01))
1306                    .dragged()
1307                {
1308                    // Use difference instead of ration to avoid problems when reaching/crossing
1309                    // the zero.
1310                    let diff = new_axis_average - axis_average;
1311                    new_average.x += diff;
1312                    new_average.y += diff;
1313                    new_average.z += diff;
1314                }
1315            });
1316            ui.horizontal(|ui| {
1317                ui.add(
1318                    egui::DragValue::new(&mut new_average.x)
1319                        .prefix("X:")
1320                        .speed(0.01),
1321                );
1322                ui.add(
1323                    egui::DragValue::new(&mut new_average.y)
1324                        .prefix("Y:")
1325                        .speed(0.01),
1326                );
1327                ui.add(
1328                    egui::DragValue::new(&mut new_average.z)
1329                        .prefix("Z:")
1330                        .speed(0.01),
1331                );
1332            });
1333        });
1334
1335        let transition = (new_average - average).as_vec3();
1336
1337        if transition.is_finite() && transition != Vec3::ZERO {
1338            for mut scale in edit.iter_matching_mut() {
1339                scale.0 += transition;
1340            }
1341        }
1342    });
1343}
1344
1345fn vpeol_3d_init_position(
1346    mut egui_context: EguiContexts,
1347    ui: Res<YoleckUi>,
1348    mut edit: YoleckEdit<(&mut Vpeol3dPosition, Option<&VpeolOverrideDragPlane>)>,
1349    global_drag_plane: Res<VpeolDragPlane>,
1350    cameras_query: Query<&VpeolCameraState>,
1351    mouse_buttons: Res<ButtonInput<MouseButton>>,
1352) -> YoleckExclusiveSystemDirective {
1353    let Ok((mut position, drag_plane)) = edit.single_mut() else {
1354        return YoleckExclusiveSystemDirective::Finished;
1355    };
1356
1357    let Some(cursor_ray) = cameras_query
1358        .iter()
1359        .find_map(|camera_state| camera_state.cursor_ray)
1360    else {
1361        return YoleckExclusiveSystemDirective::Listening;
1362    };
1363
1364    let drag_plane = if let Some(VpeolOverrideDragPlane(drag_plane)) = drag_plane {
1365        drag_plane
1366    } else {
1367        &global_drag_plane.0
1368    };
1369    if let Some(distance_to_plane) =
1370        cursor_ray.intersect_plane(position.0, InfinitePlane3d::new(*drag_plane.normal))
1371    {
1372        position.0 = cursor_ray.get_point(distance_to_plane);
1373    };
1374
1375    if egui_context.ctx_mut().unwrap().is_pointer_over_egui() || ui.ctx().is_pointer_over_egui() {
1376        return YoleckExclusiveSystemDirective::Listening;
1377    }
1378
1379    if mouse_buttons.just_released(MouseButton::Left) {
1380        return YoleckExclusiveSystemDirective::Finished;
1381    }
1382
1383    YoleckExclusiveSystemDirective::Listening
1384}
1385
1386#[derive(Clone, Copy)]
1387struct AxisKnobData {
1388    axis: Vec3,
1389    drag_plane_normal: Dir3,
1390}
1391
1392#[allow(clippy::type_complexity, clippy::too_many_arguments)]
1393fn vpeol_3d_edit_axis_knobs(
1394    mut edit: YoleckEdit<(
1395        Entity,
1396        &GlobalTransform,
1397        &Vpeol3dPosition,
1398        Option<&Vpeol3dRotation>,
1399    )>,
1400    translation_gizmo_config: Res<Vpeol3dTranslationGizmoConfig>,
1401    mut knobs: YoleckKnobs,
1402    mut mesh_assets: ResMut<Assets<Mesh>>,
1403    mut material_assets: ResMut<Assets<StandardMaterial>>,
1404    mut cached_assets: Local<
1405        Option<(
1406            Handle<Mesh>,
1407            Handle<Mesh>,
1408            [Handle<StandardMaterial>; 3],
1409            [Handle<StandardMaterial>; 3],
1410        )>,
1411    >,
1412    mut directives_writer: MessageWriter<YoleckDirective>,
1413    cameras_query: Query<(&GlobalTransform, &VpeolCameraState)>,
1414) {
1415    if edit.is_empty() || edit.has_nonmatching() {
1416        return;
1417    }
1418
1419    let (camera_position, dragged_entity) = cameras_query
1420        .iter()
1421        .next()
1422        .map(|(t, state)| {
1423            let dragged = match &state.clicks_on_objects_state {
1424                VpeolClicksOnObjectsState::BeingDragged { entity, .. } => Some(*entity),
1425                _ => None,
1426            };
1427            (t.translation(), dragged)
1428        })
1429        .unwrap_or((Vec3::ZERO, None));
1430
1431    let (cone_mesh, line_mesh, materials, materials_active) =
1432        cached_assets.get_or_insert_with(|| {
1433            (
1434                mesh_assets.add(Mesh::from(Cone {
1435                    radius: 0.5,
1436                    height: 1.0,
1437                })),
1438                mesh_assets.add(Mesh::from(Cylinder {
1439                    radius: 0.15,
1440                    half_height: 0.5,
1441                })),
1442                [
1443                    material_assets.add(StandardMaterial {
1444                        base_color: Color::from(css::RED),
1445                        unlit: true,
1446                        ..default()
1447                    }),
1448                    material_assets.add(StandardMaterial {
1449                        base_color: Color::from(css::GREEN),
1450                        unlit: true,
1451                        ..default()
1452                    }),
1453                    material_assets.add(StandardMaterial {
1454                        base_color: Color::from(css::BLUE),
1455                        unlit: true,
1456                        ..default()
1457                    }),
1458                ],
1459                [
1460                    material_assets.add(StandardMaterial {
1461                        base_color: Color::linear_rgb(1.0, 0.5, 0.5),
1462                        unlit: true,
1463                        ..default()
1464                    }),
1465                    material_assets.add(StandardMaterial {
1466                        base_color: Color::linear_rgb(0.5, 1.0, 0.5),
1467                        unlit: true,
1468                        ..default()
1469                    }),
1470                    material_assets.add(StandardMaterial {
1471                        base_color: Color::linear_rgb(0.5, 0.5, 1.0),
1472                        unlit: true,
1473                        ..default()
1474                    }),
1475                ],
1476            )
1477        });
1478
1479    let world_axes = [
1480        AxisKnobData {
1481            axis: Vec3::X,
1482            drag_plane_normal: Dir3::Z,
1483        },
1484        AxisKnobData {
1485            axis: Vec3::Y,
1486            drag_plane_normal: Dir3::X,
1487        },
1488        AxisKnobData {
1489            axis: Vec3::Z,
1490            drag_plane_normal: Dir3::Y,
1491        },
1492    ];
1493
1494    for (entity, global_transform, _, rotation) in edit.iter_matching() {
1495        let entity_position = global_transform.translation();
1496        let entity_scale = global_transform.to_scale_rotation_translation().0;
1497        let entity_radius = entity_scale.max_element();
1498
1499        let distance_to_camera = (camera_position - entity_position).length();
1500        let distance_scale = (distance_to_camera / 40.0).max(1.0);
1501
1502        let axes = match translation_gizmo_config.mode {
1503            Vpeol3dTranslationGizmoMode::World => world_axes,
1504            Vpeol3dTranslationGizmoMode::Local => {
1505                let rot = if let Some(Vpeol3dRotation(euler_angles)) = rotation {
1506                    Quat::from_euler(
1507                        EulerRot::XYZ,
1508                        euler_angles.x,
1509                        euler_angles.y,
1510                        euler_angles.z,
1511                    )
1512                } else {
1513                    Quat::IDENTITY
1514                };
1515
1516                let local_x = (rot * Vec3::X).normalize();
1517                let local_y = (rot * Vec3::Y).normalize();
1518                let local_z = (rot * Vec3::Z).normalize();
1519
1520                [
1521                    AxisKnobData {
1522                        axis: local_x,
1523                        drag_plane_normal: Dir3::new_unchecked(local_z),
1524                    },
1525                    AxisKnobData {
1526                        axis: local_y,
1527                        drag_plane_normal: Dir3::new_unchecked(local_x),
1528                    },
1529                    AxisKnobData {
1530                        axis: local_z,
1531                        drag_plane_normal: Dir3::new_unchecked(local_y),
1532                    },
1533                ]
1534            }
1535        };
1536
1537        for (axis_idx, axis_data) in axes.iter().enumerate() {
1538            let knob_name = match axis_idx {
1539                0 => "vpeol-3d-axis-knob-x",
1540                1 => "vpeol-3d-axis-knob-y",
1541                _ => "vpeol-3d-axis-knob-z",
1542            };
1543
1544            let line_name = match axis_idx {
1545                0 => "vpeol-3d-axis-line-x",
1546                1 => "vpeol-3d-axis-line-y",
1547                _ => "vpeol-3d-axis-line-z",
1548            };
1549
1550            let scaled_knob_scale = translation_gizmo_config.knob_scale * distance_scale;
1551            let base_distance = translation_gizmo_config.knob_distance + entity_radius;
1552            let scaled_distance = base_distance * (1.0 + (distance_scale - 1.0) * 0.3);
1553
1554            let knob_offset = scaled_distance * axis_data.axis;
1555            let knob_position = entity_position + knob_offset;
1556            let knob_transform = Transform {
1557                translation: knob_position,
1558                rotation: Quat::from_rotation_arc(Vec3::Y, axis_data.axis),
1559                scale: scaled_knob_scale * Vec3::ONE,
1560            };
1561
1562            let line_length = scaled_distance - scaled_knob_scale * 0.5;
1563            let line_center = entity_position + axis_data.axis * line_length * 0.5;
1564            let line_transform = Transform {
1565                translation: line_center,
1566                rotation: Quat::from_rotation_arc(Vec3::Y, axis_data.axis),
1567                scale: Vec3::new(scaled_knob_scale, line_length, scaled_knob_scale),
1568            };
1569
1570            let line_knob = knobs.knob((entity, line_name));
1571            let line_knob_id = line_knob.cmd.id();
1572            drop(line_knob);
1573
1574            let knob = knobs.knob((entity, knob_name));
1575            let knob_id = knob.cmd.id();
1576            let passed_pos = knob.get_passed_data::<Vec3>().copied();
1577            drop(knob);
1578
1579            let is_active = dragged_entity == Some(line_knob_id) || dragged_entity == Some(knob_id);
1580
1581            let material = if is_active {
1582                &materials_active[axis_idx]
1583            } else {
1584                &materials[axis_idx]
1585            };
1586
1587            let mut line_knob = knobs.knob((entity, line_name));
1588            line_knob.cmd.insert((
1589                Mesh3d(line_mesh.clone()),
1590                MeshMaterial3d(material.clone()),
1591                line_transform,
1592                GlobalTransform::from(line_transform),
1593            ));
1594
1595            let mut knob = knobs.knob((entity, knob_name));
1596            knob.cmd.insert(VpeolOverrideDragPlane(InfinitePlane3d {
1597                normal: axis_data.drag_plane_normal,
1598            }));
1599            knob.cmd.insert((
1600                Mesh3d(cone_mesh.clone()),
1601                MeshMaterial3d(material.clone()),
1602                knob_transform,
1603                GlobalTransform::from(knob_transform),
1604            ));
1605
1606            if let Some(pos) = passed_pos {
1607                let vector_from_entity = pos - knob_offset - entity_position;
1608                let along_axis = vector_from_entity.dot(axis_data.axis);
1609                let new_position = entity_position + along_axis * axis_data.axis;
1610                directives_writer.write(YoleckDirective::pass_to_entity(entity, new_position));
1611            }
1612        }
1613    }
1614}
1615
1616fn vpeol_3d_populate_transform(
1617    mut populate: YoleckPopulate<(
1618        &Vpeol3dPosition,
1619        Option<&Vpeol3dRotation>,
1620        Option<&Vpeol3dScale>,
1621        &YoleckBelongsToLevel,
1622    )>,
1623    levels_query: Query<&VpeolRepositionLevel>,
1624) {
1625    populate.populate(
1626        |_ctx, mut cmd, (position, rotation, scale, belongs_to_level)| {
1627            let mut transform = Transform::from_translation(position.0);
1628            if let Some(Vpeol3dRotation(quat)) = rotation {
1629                transform = transform.with_rotation(*quat);
1630            }
1631            if let Some(Vpeol3dScale(scale)) = scale {
1632                transform = transform.with_scale(*scale);
1633            }
1634
1635            if let Ok(VpeolRepositionLevel(level_transform)) =
1636                levels_query.get(belongs_to_level.level)
1637            {
1638                transform = *level_transform * transform;
1639            }
1640
1641            cmd.insert((transform, GlobalTransform::from(transform)));
1642        },
1643    )
1644}