From b3135dfaa22f092981cd66c2cec1e42445f03f17 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 25 Nov 2026 21:37:35 +0100 Subject: [PATCH] Add a warp tool bar to the top bar While the selected fill projects through a warp, the top tool bar shows warp controls in place of the tool's own: transform tool settings (manipulator size, grid and angle steps), warp mode list, gizmo modes (move, rotate, scale, place on surface), object or world space, mirrors and resets. The frame gizmo shows only the handles of the chosen mode and snaps moves and turns to the steps while Ctrl is held. Reset frame takes keepCorners to restore the frame alone. --- crates/engine/src/warp_cmds.rs | 34 +- crates/engine/tests/it/fill_projections.rs | 24 ++ crates/ui-egui/src/frame_gizmo.rs | 152 +++++--- crates/ui-egui/src/frame_gizmo/frame_grab.rs | 16 + .../frame_gizmo/warp_toolbar/gizmo_mode.rs | 11 + .../frame_gizmo/warp_toolbar/gizmo_space.rs | 9 + .../src/frame_gizmo/warp_toolbar/mod.rs | 339 ++++++++++++++++++ .../src/frame_gizmo/warp_toolbar/snap.rs | 24 ++ .../frame_gizmo/warp_toolbar/warp_target.rs | 35 ++ .../warp_toolbar/warp_toolbar_settings.rs | 63 ++++ crates/ui-egui/src/projection_gizmo.rs | 2 +- crates/ui-egui/src/projection_gizmo/gizmo.rs | 5 + crates/ui-egui/src/state.rs | 4 + crates/ui-egui/src/toolbar.rs | 18 +- 14 files changed, 672 insertions(+), 64 deletions(-) create mode 100644 crates/ui-egui/src/frame_gizmo/warp_toolbar/gizmo_mode.rs create mode 100644 crates/ui-egui/src/frame_gizmo/warp_toolbar/gizmo_space.rs create mode 100644 crates/ui-egui/src/frame_gizmo/warp_toolbar/mod.rs create mode 100644 crates/ui-egui/src/frame_gizmo/warp_toolbar/snap.rs create mode 100644 crates/ui-egui/src/frame_gizmo/warp_toolbar/warp_target.rs create mode 100644 crates/ui-egui/src/frame_gizmo/warp_toolbar/warp_toolbar_settings.rs diff --git a/crates/engine/src/warp_cmds.rs b/crates/engine/src/warp_cmds.rs index 1669c2e0..452e41dc 100644 --- a/crates/engine/src/warp_cmds.rs +++ b/crates/engine/src/warp_cmds.rs @@ -4,8 +4,8 @@ use serde_json::Value; use texturecraft_core::{Decal, Projection}; use texturecraft_geom::Mesh; -use crate::commands::{CommandSpec, bad, has_layer}; -use crate::layer_cmds::{fill_target, placement_mut}; +use crate::commands::{CommandSpec, bad, boolp, has_layer}; +use crate::layer_cmds::{FillTarget, fill_target, placement_mut}; use crate::{Result, Session, cmd}; /// Reset frame's command id, the prefix of its errors @@ -17,7 +17,7 @@ pub fn specs() -> Vec { "Reset frame", [], None, - "{layer? | effect?: content or mask fill effect id} — a warp projection's frame back around the mesh, seen from the front, with its corners unpulled (Projection Depth and the other settings stay)", + "{layer? | effect?: content or mask fill effect id, keepCorners?: true keeps the corners where they are} — a warp projection's frame back around the mesh, seen from the front, with its corners unpulled unless `keepCorners` (Projection Depth and the other settings stay)", has_layer, reset_frame )] @@ -44,25 +44,33 @@ pub(crate) fn fitted_frame(mesh: &Mesh) -> Decal { /// A fitted frame's smallest side, relative to the mesh diagonal (a flat mesh still gets a frame) const SMALLEST_SIDE: f32 = 1e-3; +/// The frame and corners of the warp projection at `target`; `command` names it in the error of any other projection +fn warp_mut<'a>(s: &'a mut Session, target: FillTarget, command: &str) -> Result<(&'a mut Decal, &'a mut [[f32; 2]; 4])> { + match placement_mut(s, target)? { + (Projection::Warp { frame, corners, .. }, _) => Ok((frame, corners)), + _ => Err(bad(command, "the fill's projection is not a warp projection")), + } +} + fn reset_frame(s: &mut Session, p: &Value) -> Result { let target = fill_target(s, p, RESET_FRAME)?; + let keep_corners = boolp(p, "keepCorners").unwrap_or(false); let fitted = fitted_frame(&s.mesh); - let (Projection::Warp { frame, corners, .. }, _) = placement_mut(s, target)? else { - return Err(bad(RESET_FRAME, "the fill's projection is not a warp projection")); - }; + let (frame, corners) = warp_mut(s, target, RESET_FRAME)?; - // A frame already fitted with unpulled corners adds no undo step - if *frame == fitted && *corners == Projection::FRAME_CORNERS { + // A frame already fitted, with its corners unpulled or kept, adds no undo step + if *frame == fitted && (keep_corners || *corners == Projection::FRAME_CORNERS) { return Ok(Value::Null); } - s.edit("Reset frame", |s| { - let (Projection::Warp { frame, corners, .. }, _) = placement_mut(s, target)? else { - return Err(bad(RESET_FRAME, "the fill's projection is not a warp projection")); - }; + let label = if keep_corners { "Restore the global transformation" } else { "Reset frame" }; + s.edit(label, |s| { + let (frame, corners) = warp_mut(s, target, RESET_FRAME)?; *frame = fitted; - *corners = Projection::FRAME_CORNERS; + if !keep_corners { + *corners = Projection::FRAME_CORNERS; + } Ok(()) })?; Ok(Value::Null) diff --git a/crates/engine/tests/it/fill_projections.rs b/crates/engine/tests/it/fill_projections.rs index 1a16d2ca..d8a5d1d9 100644 --- a/crates/engine/tests/it/fill_projections.rs +++ b/crates/engine/tests/it/fill_projections.rs @@ -337,6 +337,30 @@ fn warp_projection_bends_to_its_corners_reaches_its_depth_and_resets_its_frame() assert!(execute(&mut s, "layer.fill.resetFrame", &json!({"layer": layer.0})).is_err(), "only a warp has a frame to reset"); } +/// Restore the global transformation refits a warp's frame and keeps its pulled corners, in one undo step, none when the frame is fitted +#[test] +fn a_warps_frame_resets_apart_from_its_corners() { + let mut s = session(); + let layer = checker_fill(&mut s); + set(&mut s, layer, json!({"projection": "warp"})); + let Projection::Warp { frame: fitted, .. } = projection(&s, layer) else { panic!("a warp") }; + let pulled = [[-0.5, 0.5], [0.9, 0.9], [0.5, -0.5], [-0.5, -0.5]]; + set(&mut s, layer, json!({"warpCorners": pulled})); + execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "rotation": 30})).unwrap(); + let steps = s.history_labels().len(); + + execute(&mut s, "layer.fill.resetFrame", &json!({"layer": layer.0, "keepCorners": true})).unwrap(); + let Projection::Warp { frame, corners, .. } = projection(&s, layer) else { panic!("a warp") }; + + assert_eq!(frame, fitted, "the frame goes back around the mesh"); + assert_eq!(corners, pulled, "the pulled corners stay"); + assert_eq!(s.history_labels().len(), steps + 1); + + execute(&mut s, "layer.fill.resetFrame", &json!({"layer": layer.0, "keepCorners": true})).unwrap(); + + assert_eq!(s.history_labels().len(), steps + 1, "a fitted frame adds no undo step"); +} + /// Depth culling keeps planar and warp projections off surfaces hidden behind others from the projector; new ones start with it on, older saves without it #[test] fn depth_culling_keeps_planar_and_warp_projections_off_hidden_surfaces() { diff --git a/crates/ui-egui/src/frame_gizmo.rs b/crates/ui-egui/src/frame_gizmo.rs index 6dd6bd18..93a5f724 100644 --- a/crates/ui-egui/src/frame_gizmo.rs +++ b/crates/ui-egui/src/frame_gizmo.rs @@ -5,8 +5,8 @@ use serde_json::{Value, json}; use texturecraft_engine::compose::axis_frame::{placed_from_axis, placing_moves_pattern}; use texturecraft_engine::compose::frame_placement::folded; use texturecraft_engine::compose::pattern::{decal_axes, decal_corners}; -use texturecraft_engine::core::{Decal, EffectKind, Fill, LayerId, LayerKind, Projection}; -use texturecraft_engine::geom::glam::Vec3; +use texturecraft_engine::core::{Decal, EffectKind, Fill, LayerId, LayerKind, Projection, Source}; +use texturecraft_engine::geom::glam::{Vec2, Vec3}; use crate::TextureCraftApp; use crate::projection_gizmo::{Gizmo, dragging}; @@ -14,8 +14,10 @@ use crate::theme::{AXIS_COLORS, SHAFT_HALO, SHAFT_HALO_EXTRA_WIDTH, SHAFT_WIDTH, use crate::viewport::{project, view_ray}; mod frame_grab; +pub(crate) mod warp_toolbar; pub(crate) use frame_grab::FrameGrab; +use warp_toolbar::{GizmoSpace, WarpToolbarSettings, to_step}; /// The selected fill's frame as the 3D view shows it #[derive(Clone, Copy, Debug)] @@ -35,11 +37,16 @@ pub(crate) struct FrameGizmo { pub arrows: [Option; 3], /// On screen, the turn ring round the centre in the frame's plane (None when it is edge on) pub ring: Option<[Pos2; TURN_RING_POINTS]>, + /// A warp's tool bar settings: which handles show, their size and snapping, and the space the arrows move in + pub tools: Option, /// In the world: the frame's centre, and its across, up and out directions origin: Vec3, axes: [Vec3; 3], /// Screen movement per world unit along each direction at the centre steps: [Option; 3], + /// The directions the arrows move along (the frame's own, or the world's in World space) and their screen movement per world unit + move_axes: [Vec3; 3], + move_steps: [Option; 3], } /// Screen length of the axis arrows, and their heads (points): long enough to grab each one apart from the others @@ -69,32 +76,7 @@ impl FrameGizmo { /// The frame of the selected fill layer, or of the selected mask fill effect, with a planar or warp projection pub(crate) fn of(app: &TextureCraftApp, rect: Rect) -> Option { - use texturecraft_engine::StackTarget; - - if app.ui.mode != crate::state::Mode::Painting { - return None; - } - - let layers = &app.session.doc.project; - let selected = app.session.selected_layer()?; - let (layer, effect, projection, sources) = match app.session.target { - StackTarget::Content => { - let layer = layers.content_layer(selected)?; - let LayerKind::Fill(Fill { projection, sources, .. }) = &layer.kind else { return None }; - - (layer.id, None, projection, sources.values().collect::>()) - } - StackTarget::Effect(effect) => { - // Only the selected layer's effective mask may supply a frame, including an instance's inherited mask - let owner = layers.mask_owner(selected); - let mask = layers.layer(owner).ok()?.mask.as_ref()?; - let mask_effect = mask.effects.iter().find(|candidate| candidate.id == effect)?; - let EffectKind::Fill { projection, source, .. } = &mask_effect.kind else { return None }; - - (owner, Some(effect), projection, vec![source]) - } - StackTarget::Mask => return None, - }; + let (layer, effect, projection, sources) = selected_fill_projection(app)?; // An axis planar reading a pattern keeps its axis (see [`placing_moves_pattern`]): it has no frame to move let unplaced = matches!(projection, Projection::Planar { placed: None, .. }); @@ -126,11 +108,21 @@ impl FrameGizmo { let sides = [0, 1, 2, 3].map(|side| corners[side].lerp(corners[(side + 1) % 4], 0.5)); let center = project(app, rect, origin)?; - // Screen movement per world unit along each direction, and an arrow along each one not pointing at the camera + // A warp follows the tool bar: its size scales the arrows and ring, its space picks the directions the arrows move along + let tools = warp.map(|_| app.ui.warp_toolbar); + let scale = tools.map_or(1.0, |tools| tools.gizmo_scale()); + + // Screen movement per world unit along each direction, and an arrow along each moving one not pointing at the camera let reach = decal.size[0].max(decal.size[1]); let axes = [across, up, out]; - let steps = axes.map(|axis| Some((project(app, rect, origin + axis * reach)? - center) / reach.max(f32::MIN_POSITIVE))); - let arrows = steps.map(|step| step.filter(|step| step.length() * reach > MIN_SCREEN_SPAN).map(|step| center + step.normalized() * ARROW)); + let move_axes = match tools { + Some(tools) if tools.space == GizmoSpace::World => [Vec3::X, Vec3::Y, Vec3::Z], + _ => axes, + }; + let step_along = |axis: Vec3| Some((project(app, rect, origin + axis * reach)? - center) / reach.max(f32::MIN_POSITIVE)); + let steps = axes.map(step_along); + let move_steps = move_axes.map(step_along); + let arrows = move_steps.map(|step| step.filter(|step| step.length() * reach > MIN_SCREEN_SPAN).map(|step| center + step.normalized() * ARROW * scale)); // The turn ring, unless the frame is seen too near edge on to grab it let ring = steps[0] @@ -139,7 +131,7 @@ impl FrameGizmo { across_step.length() > f32::EPSILON && solve(*across_step, *up_step, egui::Vec2::X).is_some() && ring_open(app, rect, center, out) }) .and_then(|(step, _)| { - let radius = TURN_RING / step.length(); + let radius = TURN_RING * scale / step.length(); let last = (TURN_RING_POINTS - 1) as f32; let points = (0..TURN_RING_POINTS).map(|index| { let (sin, cos) = (index as f32 / last * std::f32::consts::TAU).sin_cos(); @@ -148,7 +140,7 @@ impl FrameGizmo { points.collect::>>()?.try_into().ok() }); - Some(FrameGizmo { layer, effect, decal, warp, corners, sides, center, arrows, ring, origin, axes, steps }) + Some(FrameGizmo { layer, effect, decal, warp, corners, sides, center, arrows, ring, tools, origin, axes, steps, move_axes, move_steps }) } /// The frame's offset after sliding it across its plane by screen movement `delta` (None when the frame is edge-on) @@ -157,6 +149,16 @@ impl FrameGizmo { Some(self.slid(across, up)) } + /// The tool bar's grid step and angle step (0: no snapping) while a drag snaps + fn snap_steps(&self, snapping: bool) -> (f32, f32) { + self.tools.filter(|_| snapping).map_or((0.0, 0.0), |tools| (tools.grid_step(), tools.angle_step())) + } + + /// Whether the tool bar's mode offers `grab` (a planar's frame, with no tool bar, offers every handle but Place on surface's) + fn offers(&self, grab: FrameGrab) -> bool { + self.tools.map_or(grab != FrameGrab::Place, |tools| grab.offered_in(tools.mode)) + } + /// Where screen point `p` meets the frame's plane, across and up in frame sizes from its centre fn on_plane(&self, app: &TextureCraftApp, rect: Rect, p: Pos2) -> Option<[f32; 2]> { let ray = view_ray(app, rect, p); @@ -178,6 +180,36 @@ impl FrameGizmo { } } +/// The selected fill layer's (or selected mask fill effect's) projection with the layer, the effect and the sources it reads: none outside painting mode +pub(crate) fn selected_fill_projection(app: &TextureCraftApp) -> Option<(LayerId, Option, &Projection, Vec<&Source>)> { + use texturecraft_engine::StackTarget; + + if app.ui.mode != crate::state::Mode::Painting { + return None; + } + + let layers = &app.session.doc.project; + let selected = app.session.selected_layer()?; + match app.session.target { + StackTarget::Content => { + let layer = layers.content_layer(selected)?; + let LayerKind::Fill(Fill { projection, sources, .. }) = &layer.kind else { return None }; + + Some((layer.id, None, projection, sources.values().collect::>())) + } + StackTarget::Effect(effect) => { + // Only the selected layer's effective mask may supply a frame, including an instance's inherited mask + let owner = layers.mask_owner(selected); + let mask = layers.layer(owner).ok()?.mask.as_ref()?; + let mask_effect = mask.effects.iter().find(|candidate| candidate.id == effect)?; + let EffectKind::Fill { projection, source, .. } = &mask_effect.kind else { return None }; + + Some((owner, Some(effect), projection, vec![source])) + } + StackTarget::Mask => None, + } +} + /// Half a turn in degrees: a ring drag's sweep is kept within one either way const HALF_TURN: f32 = 180.0; @@ -255,7 +287,10 @@ impl Gizmo for FrameGizmo { if let Some(ring) = &self.ring { handles.push((FrameGrab::Turn, ring.windows(2).map(|pair| distance_to_segment(at, pair[0], pair[1])).fold(f32::INFINITY, f32::min))); } - nearest(handles) + + // Place on surface takes any press the handles do not: just within reach, so a nearer corner wins + handles.push((FrameGrab::Place, GRAB)); + nearest(handles.into_iter().filter(|(grab, _)| self.offers(*grab))) } fn same_projection(&self, other: &FrameGizmo) -> bool { @@ -264,17 +299,27 @@ impl Gizmo for FrameGizmo { /// The command and params a drag of `grab` from `from` to `to` runs fn edit(&self, app: &TextureCraftApp, rect: Rect, grab: FrameGrab, from: Pos2, to: Pos2) -> Option<(&'static str, Value)> { + self.edit_with_snap(app, rect, grab, from, to, false) + } + + /// As [`Gizmo::edit`]; with `snapping` a warp's moves and turns jump by the tool bar's grid and angle steps + fn edit_with_snap(&self, app: &TextureCraftApp, rect: Rect, grab: FrameGrab, from: Pos2, to: Pos2, snapping: bool) -> Option<(&'static str, Value)> { let delta = to - from; let center = self.center; + let (grid_step, angle_step) = self.snap_steps(snapping); + let world = self.tools.is_some_and(|tools| tools.space == GizmoSpace::World); let mut params = match grab { - FrameGrab::Slide => json!({"offset": self.slid_on_screen(delta)?}), + FrameGrab::Slide => { + let [across, up] = solve(self.steps[0]?, self.steps[1]?, delta)?; + json!({"offset": self.slid(to_step(across, grid_step), to_step(up, grid_step))}) + } FrameGrab::Axis(axis) => { - let step = (*self.steps.get(axis)?)?; - let distance = delta.dot(step) / step.length_sq().max(f32::MIN_POSITIVE); + let step = (*self.move_steps.get(axis)?)?; + let distance = to_step(delta.dot(step) / step.length_sq().max(f32::MIN_POSITIVE), grid_step); match axis { - 0 => json!({"offset": self.slid(distance, 0.0)}), - 1 => json!({"offset": self.slid(0.0, distance)}), - _ => json!({"position": (self.origin + self.axes[2] * distance).to_array(), "normal": self.axes[2].to_array()}), + 0 if !world => json!({"offset": self.slid(distance, 0.0)}), + 1 if !world => json!({"offset": self.slid(0.0, distance)}), + _ => json!({"position": (self.origin + self.move_axes[axis] * distance).to_array(), "normal": self.axes[2].to_array()}), } } FrameGrab::Scale => { @@ -288,12 +333,18 @@ impl Gizmo for FrameGizmo { size[1 - side % 2] *= stretch; json!({"size": size}) } + FrameGrab::Place => { + // Off the model the frame waits where it last touched it + let on_view = to - rect.min; + let hit = app.session.pick(Vec2::new(on_view.x, on_view.y), app.session.viewport)?; + json!({"position": hit.pos.to_array(), "normal": hit.nrm.to_array()}) + } FrameGrab::Turn => { // Measure the turn in the frame's own plane so a tilted frame follows the pointer let angle = |p: Pos2| self.on_plane(app, rect, p).map(|[across, up]| (up * self.decal.size[1]).atan2(across * self.decal.size[0]).to_degrees()); let swept = angle(to)? - angle(from)?; let swept = (swept + HALF_TURN).rem_euclid(2.0 * HALF_TURN) - HALF_TURN; - json!({"rotation": self.decal.rotation + swept}) + json!({"rotation": self.decal.rotation + to_step(swept, angle_step)}) } FrameGrab::Corner(corner) => { let mut corners = self.warp?; @@ -328,7 +379,7 @@ pub(crate) fn overlay(ui: &Ui, rect: Rect, gizmo: &FrameGizmo) { let mut outline = gizmo.corners.to_vec(); outline.push(gizmo.corners[0]); dashed_outline(&painter, &outline); - if let Some(ring) = &gizmo.ring { + if let Some(ring) = gizmo.ring.as_ref().filter(|_| gizmo.offers(FrameGrab::Turn)) { let color = if lit(FrameGrab::Turn) { tokens.viewport_accent } else { AXIS_COLORS[2] }; painter.add(egui::Shape::line(ring.to_vec(), Stroke::new(SHAFT_WIDTH + SHAFT_HALO_EXTRA_WIDTH, SHAFT_HALO))); painter.add(egui::Shape::line(ring.to_vec(), Stroke::new(SHAFT_WIDTH, color))); @@ -345,12 +396,14 @@ pub(crate) fn overlay(ui: &Ui, rect: Rect, gizmo: &FrameGizmo) { } } } - for (index, side) in gizmo.sides.into_iter().enumerate() { + for (index, side) in gizmo.sides.into_iter().enumerate().filter(|(index, _)| gizmo.offers(FrameGrab::Side(*index))) { handle_dot(&painter, side, SIDE_DOT, dot_fill(FrameGrab::Side(index))); } let arrow_color = |axis: usize| if lit(FrameGrab::Axis(axis)) { tokens.viewport_accent } else { AXIS_COLORS[axis] }; - move_handles(&painter, gizmo.center, gizmo.arrows, arrow_color, dot_fill(FrameGrab::Slide)); + if gizmo.offers(FrameGrab::Slide) { + move_handles(&painter, gizmo.center, gizmo.arrows, arrow_color, dot_fill(FrameGrab::Slide)); + } } /// The centre square (filled `square`) with its X/Y/Z arrows to `arrows`, coloured by `arrow_color`; shafts and heads over a dark halo like the symmetry manipulator's @@ -409,6 +462,7 @@ pub(crate) mod tests { use texturecraft_engine::core::{LayerId, LayerKind, Projection}; use super::*; + use crate::frame_gizmo::warp_toolbar::GizmoMode; /// The test window: big enough that the docked panels leave the 3D view room for the ball with every gizmo handle round it const TEST_WINDOW: egui::Vec2 = vec2(1600.0, 960.0); @@ -423,6 +477,12 @@ pub(crate) mod tests { harness } + /// A warp's gizmo in `mode`, as the tool bar's buttons set it (a planar's has no modes) + pub(crate) fn show_handles(harness: &mut egui_kittest::Harness<'_, TextureCraftApp>, mode: GizmoMode) { + harness.state_mut().ui.warp_toolbar.mode = mode; + harness.run_steps(2); + } + /// The ball with a selected fill layer projecting `projection` pub(crate) fn fill_app(projection: &str) -> (egui_kittest::Harness<'static, TextureCraftApp>, LayerId) { fill_app_with(json!({"projection": projection})) @@ -519,7 +579,7 @@ pub(crate) mod tests { ["X", "Y", "Z"].map(|tag| harness.get_by_label(&format!("{row} {tag}")).accesskit_node().numeric_value().unwrap() as f32) } - fn gizmo(harness: &egui_kittest::Harness<'_, TextureCraftApp>) -> FrameGizmo { + pub(crate) fn gizmo(harness: &egui_kittest::Harness<'_, TextureCraftApp>) -> FrameGizmo { FrameGizmo::of(harness.state(), harness.state().viewport_rect).unwrap() } @@ -645,6 +705,7 @@ pub(crate) mod tests { let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); for kind in ["warp", "planar"] { let (mut harness, _) = fill_app(kind); + show_handles(&mut harness, GizmoMode::Rotate); let start = gizmo(&harness); let ring = start.ring.unwrap_or_else(|| panic!("{kind}: a frame facing the camera shows its ring")); let on_ring = *ring @@ -667,6 +728,7 @@ pub(crate) mod tests { } let (mut harness, layer) = fill_app("warp"); + show_handles(&mut harness, GizmoMode::Scale); let warp = gizmo(&harness); assert_eq!(warp.grab(warp.sides[1]), Some(FrameGrab::Side(1))); diff --git a/crates/ui-egui/src/frame_gizmo/frame_grab.rs b/crates/ui-egui/src/frame_gizmo/frame_grab.rs index a0733168..2d31d18d 100644 --- a/crates/ui-egui/src/frame_gizmo/frame_grab.rs +++ b/crates/ui-egui/src/frame_gizmo/frame_grab.rs @@ -1,3 +1,5 @@ +use super::warp_toolbar::GizmoMode; + /// What a drag on the frame does #[derive(Clone, Copy, Debug, PartialEq)] pub(crate) enum FrameGrab { @@ -13,15 +15,29 @@ pub(crate) enum FrameGrab { Corner(usize), /// The ring: turn it round its normal Turn, + /// Place on surface: anywhere over the model puts the frame where the pointer touches it + Place, } impl FrameGrab { + /// Whether a warp's gizmo in `mode` offers this handle: its corners stay in every mode + pub(super) fn offered_in(self, mode: GizmoMode) -> bool { + match self { + FrameGrab::Slide | FrameGrab::Axis(_) => mode == GizmoMode::Move, + FrameGrab::Turn => mode == GizmoMode::Rotate, + FrameGrab::Side(_) => mode == GizmoMode::Scale, + FrameGrab::Place => mode == GizmoMode::PlaceOnSurface, + FrameGrab::Scale | FrameGrab::Corner(_) => true, + } + } + pub(super) fn cursor(self, dragging: bool) -> egui::CursorIcon { match self { FrameGrab::Slide if dragging => egui::CursorIcon::Grabbing, FrameGrab::Slide => egui::CursorIcon::Grab, FrameGrab::Axis(_) | FrameGrab::Corner(_) | FrameGrab::Turn => egui::CursorIcon::Move, FrameGrab::Scale => egui::CursorIcon::ResizeNwSe, + FrameGrab::Place => egui::CursorIcon::Crosshair, FrameGrab::Side(side) if side % 2 == 0 => egui::CursorIcon::ResizeVertical, FrameGrab::Side(_) => egui::CursorIcon::ResizeHorizontal, } diff --git a/crates/ui-egui/src/frame_gizmo/warp_toolbar/gizmo_mode.rs b/crates/ui-egui/src/frame_gizmo/warp_toolbar/gizmo_mode.rs new file mode 100644 index 00000000..e7c3b50a --- /dev/null +++ b/crates/ui-egui/src/frame_gizmo/warp_toolbar/gizmo_mode.rs @@ -0,0 +1,11 @@ +use serde::{Deserialize, Serialize}; + +/// What a warp's frame gizmo does: Move shows the arrows and centre square, Rotate the turn ring, Scale the edge dots that size the frame; Place on surface puts the frame where a drag over the model touches it +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum GizmoMode { + #[default] + Move, + Rotate, + Scale, + PlaceOnSurface, +} diff --git a/crates/ui-egui/src/frame_gizmo/warp_toolbar/gizmo_space.rs b/crates/ui-egui/src/frame_gizmo/warp_toolbar/gizmo_space.rs new file mode 100644 index 00000000..a33269d7 --- /dev/null +++ b/crates/ui-egui/src/frame_gizmo/warp_toolbar/gizmo_space.rs @@ -0,0 +1,9 @@ +use serde::{Deserialize, Serialize}; + +/// The directions a warp's move arrows follow: the frame's own, or the world's +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum GizmoSpace { + #[default] + Object, + World, +} diff --git a/crates/ui-egui/src/frame_gizmo/warp_toolbar/mod.rs b/crates/ui-egui/src/frame_gizmo/warp_toolbar/mod.rs new file mode 100644 index 00000000..22987e6b --- /dev/null +++ b/crates/ui-egui/src/frame_gizmo/warp_toolbar/mod.rs @@ -0,0 +1,339 @@ +//! The warp controls of the top tool bar while the selected fill projects through a warp, in place of the tool's own: the transform tool's settings, the warp mode, the gizmo's mode and space, the mirrors and the resets + +mod gizmo_mode; +mod gizmo_space; +mod snap; +mod warp_target; +mod warp_toolbar_settings; + +use egui::Ui; +use egui_phosphor::regular as ic; +use serde_json::json; + +pub use gizmo_mode::GizmoMode; +pub use gizmo_space::GizmoSpace; +pub(crate) use snap::to_step; +pub use warp_toolbar_settings::WarpToolbarSettings; + +use crate::TextureCraftApp; +use crate::i18n::tr; +use crate::widgets::{icon_button, icon_dropdown_button, slider}; +use texturecraft_engine::core::Projection; +use warp_target::WarpTarget; +use warp_toolbar_settings::{ANGLE_STEPS, GRID_STEPS, MANIPULATOR_SIZES}; + +/// The width of the settings popup (points) +const POPUP_WIDTH: f32 = 220.0; + +/// The gizmo mode buttons: mode, icon, label +const MODES: [(GizmoMode, &str, &str); 4] = [ + (GizmoMode::Move, ic::ARROWS_OUT_CARDINAL, "Move"), + (GizmoMode::Rotate, ic::ARROWS_CLOCKWISE, "Rotate"), + (GizmoMode::Scale, ic::CORNERS_OUT, "Scale"), + (GizmoMode::PlaceOnSurface, ic::ARROW_LINE_DOWN, "Place on surface"), +]; + +/// The warp modes the bar lists; only the first works until the warp has a grid of vertices +const WARP_MODES: [&str; 5] = ["Transform warp", "Edit vertices", "Split warp crosswise", "Split warp horizontally", "Split warp vertically"]; + +/// Why the warp modes past the first and the vertex reset are greyed out +const NEEDS_GRID: &str = "Needs the warp grid, which is not available yet"; + +/// Whether the selected fill projects through a warp, so the top tool bar shows the warp controls +pub(crate) fn shown(app: &TextureCraftApp) -> bool { + WarpTarget::of(app).is_some() +} + +/// The warp controls of the top tool bar, left to right +pub(crate) fn controls(app: &mut TextureCraftApp, ui: &mut Ui) { + let Some(target) = WarpTarget::of(app) else { return }; + let size = ui.spacing().interact_size.y; + + // The only tool there is, so it stays on + icon_button(ui, ic::BOUNDING_BOX, tr("Transform tool"), true, size); + manipulator_settings(app, ui, size); + warp_mode(ui); + ui.separator(); + + let current = app.ui.warp_toolbar.mode; + for (mode, icon, label) in MODES { + if icon_button(ui, icon, tr(label), current == mode, size).clicked() { + app.ui.warp_toolbar.mode = mode; + } + } + gizmo_space(app, ui); + ui.separator(); + + for (axis, icon, label, field) in [(0, ic::FLIP_HORIZONTAL, "Mirror horizontally", "flipU"), (1, ic::FLIP_VERTICAL, "Mirror vertically", "flipV")] { + if icon_button(ui, icon, tr(label), target.flip[axis], size).clicked() { + let mut fields = json!({}); + fields[field] = json!(!target.flip[axis]); + app.run("layer.decal.set", target.params(fields)); + } + } + resets(app, ui, &target); +} + +/// The settings popup of the transform tool: the gizmo's size and the steps its drags snap to +fn manipulator_settings(app: &mut TextureCraftApp, ui: &mut Ui, size: f32) { + let popup_id = ui.make_persistent_id("warp_manipulator_settings"); + let open = egui::Popup::is_id_open(ui.ctx(), popup_id); + let response = icon_dropdown_button(ui, ic::GEAR, tr("Manipulator settings"), open, size); + let response = if open { response } else { response.on_hover_text(tr("Manipulator settings")) }; + + // Sliders sit in the popup, so a click inside must not close it + egui::Popup::menu(&response).id(popup_id).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| { + ui.set_width(POPUP_WIDTH); + ui.label(egui::RichText::new(tr("MANIPULATOR SETTINGS")).strong()); + + let settings = &mut app.ui.warp_toolbar; + slider(ui, tr("Manipulator size"), &mut settings.manipulator_size, MANIPULATOR_SIZES, 2); + slider(ui, tr("Grid steps"), &mut settings.grid_steps, GRID_STEPS, 2).on_hover_text(tr("Hold Ctrl while dragging to move in these steps")); + slider(ui, tr("Angle steps"), &mut settings.angle_steps, ANGLE_STEPS, 0).on_hover_text(tr("Hold Ctrl while dragging to turn in these steps")); + }); +} + +/// The warp mode list: Transform warp works; the others wait for the warp grid +fn warp_mode(ui: &mut Ui) { + icon_dropdown(ui, "warp_mode", ic::FRAME_CORNERS, tr(WARP_MODES[0]), |ui| { + for (index, label) in WARP_MODES.into_iter().enumerate() { + let unavailable = (index > 0).then(|| tr(NEEDS_GRID)); + menu_row(ui, tr(label), index == 0, unavailable); + } + }); +} + +/// Object space or World space: the directions the move arrows follow +fn gizmo_space(app: &mut TextureCraftApp, ui: &mut Ui) { + let spaces = [(GizmoSpace::Object, ic::CUBE, "Object space"), (GizmoSpace::World, ic::GLOBE, "World space")]; + let current = app.ui.warp_toolbar.space; + let (_, icon, label) = spaces.iter().find(|(space, ..)| *space == current).unwrap_or(&spaces[0]); + let mut chosen = None; + icon_dropdown(ui, "warp_space", icon, tr(label), |ui| { + for (space, _, label) in spaces { + if menu_row(ui, tr(label), current == space, None) { + chosen = Some(space); + } + } + }); + + if let Some(space) = chosen { + app.ui.warp_toolbar.space = space; + } +} + +/// The reset list: the frame back around the mesh, or the corners back on the frame +fn resets(app: &mut TextureCraftApp, ui: &mut Ui, target: &WarpTarget) { + let mut command = None; + icon_dropdown(ui, "warp_reset", ic::ARROW_COUNTER_CLOCKWISE, tr("Reset"), |ui| { + if menu_row(ui, tr("Restore the global transformation"), false, None) { + command = Some(("layer.fill.resetFrame", json!({"keepCorners": true}))); + } + if menu_row(ui, tr("Reset all vertices"), false, None) { + command = Some(("layer.fill.projection", json!({"warpCorners": Projection::FRAME_CORNERS}))); + } + + // Vertices cannot be selected before the warp has a grid + menu_row(ui, tr("Reset selected vertices"), false, Some(tr(NEEDS_GRID))); + }); + + if let Some((id, fields)) = command { + app.run(id, target.params(fields)); + } +} + +/// An icon button with a caret that opens `menu` below it, highlighted while open +fn icon_dropdown(ui: &mut Ui, id_salt: &str, icon: &str, tooltip: &str, menu: impl FnOnce(&mut Ui)) { + let popup_id = ui.make_persistent_id(id_salt); + let open = egui::Popup::is_id_open(ui.ctx(), popup_id); + let mut response = icon_dropdown_button(ui, icon, tooltip, open, ui.spacing().interact_size.y); + if !open { + response = response.on_hover_text(tooltip); + } + + egui::Popup::menu(&response).id(popup_id).show(menu); +} + +/// One list entry; `unavailable` greys it out and says why on hover. Returns true when clicked +fn menu_row(ui: &mut Ui, label: &str, selected: bool, unavailable: Option<&str>) -> bool { + let response = ui.add_enabled(unavailable.is_none(), egui::Button::new(label).selected(selected)); + if let Some(reason) = unavailable { + response.on_disabled_hover_text(reason); + return false; + } + + response.clicked() +} + +#[cfg(test)] +mod tests { + use egui::{Modifiers, Pos2, vec2}; + use egui_kittest::Harness; + use egui_kittest::kittest::Queryable; + use serde_json::json; + use texturecraft_engine::core::Projection; + use texturecraft_engine::geom::glam::{Vec2, Vec3}; + + use super::*; + use crate::frame_gizmo::FrameGrab; + use crate::frame_gizmo::tests::{drag, fill_app, gizmo, projection}; + use crate::projection_gizmo::Gizmo; + + fn click_label(harness: &mut Harness<'_, TextureCraftApp>, label: &str) { + harness.get_by_label(label).click(); + harness.run_steps(2); + } + + /// The warp's frame and corners + fn warp_parts(harness: &Harness<'_, TextureCraftApp>, layer: texturecraft_engine::core::LayerId) -> (texturecraft_engine::core::Decal, [[f32; 2]; 4]) { + let Projection::Warp { frame, corners, .. } = projection(harness, layer) else { panic!("a warp") }; + (frame, corners) + } + + #[test] + fn the_bar_shows_for_a_warp_fill_only() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = fill_app("warp"); + + assert!(harness.query_by_label("Transform tool").is_some()); + + harness.state_mut().run("layer.fill.projection", json!({"layer": layer.0, "projection": "planar"})); + harness.run_steps(2); + + assert!(harness.query_by_label("Transform tool").is_none(), "a planar frame has no warp tools"); + + let away = harness.state().viewport_rect.left_bottom() + vec2(10.0, -10.0); + assert_eq!(gizmo(&harness).grab(away), None, "a planar frame has no Place on surface"); + } + + #[test] + fn each_mode_offers_only_its_handles() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, _) = fill_app("warp"); + let start = gizmo(&harness); + let ring_point = *start.ring.as_ref().expect("a frame facing the camera shows its ring").iter().max_by(|a, b| a.y.total_cmp(&b.y)).unwrap(); + let handles: [(FrameGrab, Pos2, GizmoMode); 4] = [ + (FrameGrab::Slide, start.center, GizmoMode::Move), + (FrameGrab::Axis(0), start.arrows[0].unwrap(), GizmoMode::Move), + (FrameGrab::Turn, ring_point, GizmoMode::Rotate), + (FrameGrab::Side(1), start.sides[1], GizmoMode::Scale), + ]; + + for (_, _, label) in MODES { + click_label(&mut harness, label); + let shown = gizmo(&harness); + let mode = shown.tools.unwrap().mode; + + for (grab, at, offered_in) in handles { + assert_eq!(shown.grab(at) == Some(grab), mode == offered_in, "{grab:?} in {mode:?}"); + } + + assert_eq!(shown.grab(shown.corners[1]), Some(FrameGrab::Corner(1)), "a warp's corners stay in {mode:?}"); + } + } + + #[test] + fn place_on_surface_puts_the_frame_where_the_pointer_touches_the_model() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = fill_app("warp"); + let rect = harness.state().viewport_rect; + let middle = crate::viewport::project(harness.state(), rect, Vec3::ZERO).unwrap(); + let (from, onto) = (middle + vec2(30.0, 20.0), middle + vec2(-60.0, -40.0)); + let steps = harness.state().session.history_labels().len(); + let (before, corners_before) = warp_parts(&harness, layer); + click_label(&mut harness, "Place on surface"); + + drag(&mut harness, from, onto, Modifiers::NONE); + + let (placed, corners) = warp_parts(&harness, layer); + let on_view = onto - rect.min; + let hit = harness.state().session.pick(Vec2::new(on_view.x, on_view.y), harness.state().session.viewport).expect("the model is under the pointer"); + assert!(Vec3::from(placed.center).distance(hit.pos) < 1e-2, "the frame centre sits at the surface hit: {:?} {:?}", placed.center, hit.pos); + assert!(Vec3::from(placed.normal).dot(hit.nrm) > 0.99, "the frame faces along the surface normal"); + assert_eq!((placed.size, placed.rotation, corners), (before.size, before.rotation, corners_before), "its size, rotation and corners stay"); + assert_eq!(harness.state().session.history_labels().len(), steps + 1, "one undo step per drag"); + + // Past the model's edge the frame waits where it last touched it + drag(&mut harness, onto, rect.left_bottom() + vec2(10.0, -10.0), Modifiers::NONE); + + let (waiting, _) = warp_parts(&harness, layer); + assert!((Vec3::from(waiting.center).length() - 1.0).abs() < 0.05, "still on the ball: {:?}", waiting.center); + } + + #[test] + fn world_space_arrows_ignore_the_frames_turn() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = fill_app("warp"); + let turn = |harness: &mut Harness<'_, TextureCraftApp>| { + harness.state_mut().run("layer.decal.set", json!({"layer": layer.0, "rotation": 30})); + harness.run_steps(2); + }; + let arrow = |harness: &Harness<'_, TextureCraftApp>| { + let shown = gizmo(harness); + (shown.arrows[0].unwrap() - shown.center).normalized() + }; + let frame_arrow = arrow(&harness); + turn(&mut harness); + + assert!(arrow(&harness).dot(frame_arrow) < 0.95, "an object space arrow turns with the frame"); + + harness.state_mut().run("layer.decal.set", json!({"layer": layer.0, "rotation": 0})); + click_label(&mut harness, "Object space"); + click_label(&mut harness, "World space"); + let world_arrow = arrow(&harness); + turn(&mut harness); + + assert!(arrow(&harness).dot(world_arrow) > 0.999, "a world space arrow stays on its world axis"); + } + + #[test] + fn holding_ctrl_moves_in_whole_grid_steps() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = fill_app("warp"); + let grid_step = harness.state().ui.warp_toolbar.grid_step(); + let start = gizmo(&harness); + let tip = start.arrows[0].unwrap(); + let along = (tip - start.center).normalized(); + + drag(&mut harness, tip, tip + along * 37.0, Modifiers::COMMAND); + + let (frame, _) = warp_parts(&harness, layer); + let steps = frame.offset[0] / grid_step; + assert!(frame.offset[0].abs() > 1e-3 && (steps - steps.round()).abs() < 1e-3, "moved by whole steps of {grid_step}: {:?}", frame.offset); + } + + #[test] + fn the_mirror_and_reset_buttons_edit_the_warp_in_one_undo_step_each() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = fill_app("warp"); + + let (fitted, _) = warp_parts(&harness, layer); + let pulled = [[-0.5, 0.5], [0.9, 0.9], [0.5, -0.5], [-0.5, -0.5]]; + harness.state_mut().run("layer.fill.projection", json!({"layer": layer.0, "warpCorners": pulled})); + harness.state_mut().run("layer.decal.set", json!({"layer": layer.0, "rotation": 30})); + harness.run_steps(2); + let steps = harness.state().session.history_labels().len(); + + click_label(&mut harness, "Mirror horizontally"); + + assert_eq!(warp_parts(&harness, layer).0.flip, [true, false]); + + click_label(&mut harness, "Mirror vertically"); + click_label(&mut harness, "Mirror horizontally"); + + assert_eq!(warp_parts(&harness, layer).0.flip, [false, true], "each button toggles its own direction"); + assert_eq!(harness.state().session.history_labels().len(), steps + 3); + + click_label(&mut harness, "Reset"); + click_label(&mut harness, "Restore the global transformation"); + + let (frame, corners) = warp_parts(&harness, layer); + assert_eq!((frame, corners), (fitted, pulled), "the frame goes back and the corners stay"); + + click_label(&mut harness, "Reset"); + click_label(&mut harness, "Reset all vertices"); + + assert_eq!(warp_parts(&harness, layer).1, Projection::FRAME_CORNERS); + assert_eq!(harness.state().session.history_labels().len(), steps + 5); + } +} diff --git a/crates/ui-egui/src/frame_gizmo/warp_toolbar/snap.rs b/crates/ui-egui/src/frame_gizmo/warp_toolbar/snap.rs new file mode 100644 index 00000000..0245e81f --- /dev/null +++ b/crates/ui-egui/src/frame_gizmo/warp_toolbar/snap.rs @@ -0,0 +1,24 @@ +/// `value` rounded to the nearest multiple of `step`; no step (0, negative or not a number) leaves it as it is +pub(crate) fn to_step(value: f32, step: f32) -> f32 { + if step.is_finite() && step > 0.0 { (value / step).round() * step } else { value } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_value_snaps_to_the_nearest_multiple_of_the_step() { + assert!((to_step(0.29, 0.2) - 0.2).abs() < 1e-6); + assert!((to_step(0.31, 0.2) - 0.4).abs() < 1e-6); + assert!((to_step(-0.31, 0.2) + 0.4).abs() < 1e-6, "negative moves snap the same way"); + assert_eq!(to_step(100.0, 45.0), 90.0); + } + + #[test] + fn no_step_leaves_the_value_alone() { + for step in [0.0, -1.0, f32::NAN, f32::INFINITY] { + assert_eq!(to_step(0.37, step), 0.37, "{step}"); + } + } +} diff --git a/crates/ui-egui/src/frame_gizmo/warp_toolbar/warp_target.rs b/crates/ui-egui/src/frame_gizmo/warp_toolbar/warp_target.rs new file mode 100644 index 00000000..571b42c3 --- /dev/null +++ b/crates/ui-egui/src/frame_gizmo/warp_toolbar/warp_target.rs @@ -0,0 +1,35 @@ +use serde_json::{Value, json}; +use texturecraft_engine::core::{LayerId, Projection}; + +use crate::TextureCraftApp; +use crate::frame_gizmo::selected_fill_projection; + +/// The selected fill with a warp projection that the tool bar edits: a fill layer, or a fill effect in its mask +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) struct WarpTarget { + pub layer: LayerId, + pub effect: Option, + /// The image mirrored left to right and top to bottom inside the frame + pub flip: [bool; 2], +} + +impl WarpTarget { + /// The selected fill when it projects through a warp, in the modes where the frame gizmo shows + pub(super) fn of(app: &TextureCraftApp) -> Option { + let (layer, effect, projection, _) = selected_fill_projection(app)?; + let Projection::Warp { frame, .. } = projection else { return None }; + + Some(WarpTarget { layer, effect, flip: frame.flip }) + } + + /// `fields` addressed to this fill, as every command that edits a fill's projection takes it + pub(super) fn params(&self, fields: Value) -> Value { + let mut params = fields; + params["layer"] = json!(self.layer.0); + if let Some(effect) = self.effect { + params["effect"] = json!(effect.0); + } + + params + } +} diff --git a/crates/ui-egui/src/frame_gizmo/warp_toolbar/warp_toolbar_settings.rs b/crates/ui-egui/src/frame_gizmo/warp_toolbar/warp_toolbar_settings.rs new file mode 100644 index 00000000..f6debfb6 --- /dev/null +++ b/crates/ui-egui/src/frame_gizmo/warp_toolbar/warp_toolbar_settings.rs @@ -0,0 +1,63 @@ +use std::ops::RangeInclusive; + +use serde::{Deserialize, Serialize}; + +use super::{GizmoMode, GizmoSpace}; + +/// The manipulator size the gizmo's measurements are given at +pub(super) const DEFAULT_MANIPULATOR_SIZE: f32 = 0.2; +pub(super) const MANIPULATOR_SIZES: RangeInclusive = 0.1..=0.5; + +/// The default and range of the move step (world units) and of the turn step (degrees) +pub(super) const DEFAULT_GRID_STEP: f32 = 0.2; +pub(super) const GRID_STEPS: RangeInclusive = 0.01..=1.0; +pub(super) const DEFAULT_ANGLE_STEP: f32 = 45.0; +pub(super) const ANGLE_STEPS: RangeInclusive = 1.0..=90.0; + +/// The warp tool bar's settings: the gizmo's mode, space and size, and the steps its drags snap to while Ctrl is held +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct WarpToolbarSettings { + pub mode: GizmoMode, + pub space: GizmoSpace, + /// Manipulator size: [`DEFAULT_MANIPULATOR_SIZE`] draws the gizmo at its base size + pub manipulator_size: f32, + /// Move step in world units + pub grid_steps: f32, + /// Turn step in degrees + pub angle_steps: f32, +} + +impl Default for WarpToolbarSettings { + fn default() -> Self { + WarpToolbarSettings { + mode: GizmoMode::default(), + space: GizmoSpace::default(), + manipulator_size: DEFAULT_MANIPULATOR_SIZE, + grid_steps: DEFAULT_GRID_STEP, + angle_steps: DEFAULT_ANGLE_STEP, + } + } +} + +impl WarpToolbarSettings { + /// How many times its base size the gizmo's arrows and ring are drawn + pub(crate) fn gizmo_scale(&self) -> f32 { + within(self.manipulator_size, MANIPULATOR_SIZES, DEFAULT_MANIPULATOR_SIZE) / DEFAULT_MANIPULATOR_SIZE + } + + /// The move step in world units + pub(crate) fn grid_step(&self) -> f32 { + within(self.grid_steps, GRID_STEPS, DEFAULT_GRID_STEP) + } + + /// The turn step in degrees + pub(crate) fn angle_step(&self) -> f32 { + within(self.angle_steps, ANGLE_STEPS, DEFAULT_ANGLE_STEP) + } +} + +/// `value` held to `range`; `fallback` for a saved value that is not a number +fn within(value: f32, range: RangeInclusive, fallback: f32) -> f32 { + if value.is_finite() { value.clamp(*range.start(), *range.end()) } else { fallback } +} diff --git a/crates/ui-egui/src/projection_gizmo.rs b/crates/ui-egui/src/projection_gizmo.rs index edc56a76..774a3cce 100644 --- a/crates/ui-egui/src/projection_gizmo.rs +++ b/crates/ui-egui/src/projection_gizmo.rs @@ -52,7 +52,7 @@ pub(crate) fn input(app: &mut TextureCraftApp, ctx: &egui::Context, re ctx.set_cursor_icon(gizmo.unwrap_or(&drag.start).cursor(drag.grab, true)); if let Some(pointer) = response.interact_pointer_pos().filter(|_| ctx.input(|input| input.pointer.delta() != egui::Vec2::ZERO)) - && let Some((command, params)) = drag.start.edit(app, rect, drag.grab, drag.from, pointer) + && let Some((command, params)) = drag.start.edit_with_snap(app, rect, drag.grab, drag.from, pointer, ctx.input(|input| input.modifiers.command)) { edit_in_one_step(&mut app.session, command, params, &mut drag.edited_revision); diff --git a/crates/ui-egui/src/projection_gizmo/gizmo.rs b/crates/ui-egui/src/projection_gizmo/gizmo.rs index e95c8270..fb3cbbcc 100644 --- a/crates/ui-egui/src/projection_gizmo/gizmo.rs +++ b/crates/ui-egui/src/projection_gizmo/gizmo.rs @@ -20,6 +20,11 @@ pub(crate) trait Gizmo: Clone + Send + Sync + 'static { /// The command and params a drag of `grab` from `from` to `to` runs fn edit(&self, app: &TextureCraftApp, rect: Rect, grab: Self::Grab, from: Pos2, to: Pos2) -> Option<(&'static str, Value)>; + /// As [`Gizmo::edit`], the drag snapping to the tool bar's steps while `snapping` (a gizmo with none ignores it) + fn edit_with_snap(&self, app: &TextureCraftApp, rect: Rect, grab: Self::Grab, from: Pos2, to: Pos2, _snapping: bool) -> Option<(&'static str, Value)> { + self.edit(app, rect, grab, from, to) + } + /// The cursor over `grab`, or dragging it fn cursor(&self, grab: Self::Grab, dragging: bool) -> egui::CursorIcon; } diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 0c767e1b..d3050b3d 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -624,6 +624,9 @@ pub struct UiState { /// How the 3D view shows symmetry #[serde(default)] pub symmetry: crate::symmetry::SymmetryDisplay, + /// The warp tool bar: the gizmo's mode and space, its size, and the steps its drags snap to + #[serde(default)] + pub warp_toolbar: crate::frame_gizmo::warp_toolbar::WarpToolbarSettings, /// The brush, symmetry and other tool settings of the last session, which the next one starts with #[serde(default)] pub tool_settings: texturecraft_engine::ToolSettings, @@ -791,6 +794,7 @@ impl Default for UiState { keymap: Keymap::new(), bake_paint_brush: crate::bake_mode::BakePaintBrush::default(), symmetry: crate::symmetry::SymmetryDisplay::default(), + warp_toolbar: crate::frame_gizmo::warp_toolbar::WarpToolbarSettings::default(), tool_settings: Default::default(), bake_visualization: crate::bake_mode::BakeVisualizationToggles::default(), named_layouts: Vec::new(), diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 27274a1d..05395a3d 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -7,6 +7,7 @@ use texturecraft_engine::Tool; use crate::TextureCraftApp; use crate::drawn_icon::DrawnIcon; +use crate::frame_gizmo::warp_toolbar; use crate::i18n::{tr, trf}; use crate::keymap::{shortcut_of, tip}; use crate::state::{Mode, ViewLayout}; @@ -61,7 +62,7 @@ pub fn paint_bar(app: &mut TextureCraftApp, ui: &mut egui::Ui) { ui.add(egui::Separator::default().spacing(BAR_SEPARATOR_WIDTH)); if !scroll_views { view_buttons(app, ui); - if app.session.tool_usable(app.session.tool.tool) { + if tool_bar_controls_shown(app) { ui.add(egui::Separator::default().spacing(BAR_SEPARATOR_WIDTH)); } } @@ -74,6 +75,11 @@ pub fn paint_bar(app: &mut TextureCraftApp, ui: &mut egui::Ui) { }); } +/// Whether the bar's left side shows controls: a warp fill's, or the selected tool's when it can act on the selection +fn tool_bar_controls_shown(app: &TextureCraftApp) -> bool { + warp_toolbar::shown(app) || app.session.tool_usable(app.session.tool.tool) +} + /// Width of `view_buttons`, so the bar knows when to move them into the scrolling strip fn view_buttons_width(button_size: f32, spacing: f32) -> f32 { // Two icons, three dropdowns, one separator and the five gaps between them @@ -224,13 +230,15 @@ fn scrolling_tool_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: scroll_area.show(ui, |ui| { ui.scroll_with_delta(vec2(scroll_delta, 0.0)); ui.horizontal_centered(|ui| { - // A tool that can't act on the selection leaves the bar, as the shelf greys it - let tool_usable = app.session.tool_usable(app.session.tool.tool); - if tool_usable { + // A warp fill's controls take the tool's place; a tool that can't act on the selection leaves the bar, as the shelf greys it + let controls_shown = tool_bar_controls_shown(app); + if warp_toolbar::shown(app) { + warp_toolbar::controls(app, ui); + } else if controls_shown { tool_controls(app, ui, tokens); } if scroll_views { - if tool_usable { + if controls_shown { ui.add(egui::Separator::default().spacing(BAR_SEPARATOR_WIDTH)); } let size = vec2(view_buttons_width(button_size, ui.spacing().item_spacing.x), ui.available_height());