diff --git a/crates/ui-egui/src/frame_gizmo.rs b/crates/ui-egui/src/frame_gizmo.rs new file mode 100644 index 00000000..6b27767b --- /dev/null +++ b/crates/ui-egui/src/frame_gizmo.rs @@ -0,0 +1,988 @@ +//! The frame of the selected planar or warp projection in the 3D view: the centre square slides it, the axis arrows move it along its across, up and out directions, the ring turns it round its normal, a planar's corners scale it, the edge dots stretch one side, a warp's corners pull freely + +use egui::{Color32, Pos2, Rect, Stroke, Ui, vec2}; +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 crate::TextureCraftApp; +use crate::projection_gizmo::{Gizmo, dragging}; +use crate::theme::{AXIS_COLORS, SHAFT_HALO, SHAFT_HALO_EXTRA_WIDTH, SHAFT_WIDTH, Tokens}; +use crate::viewport::{project, view_ray}; + +mod frame_grab; + +pub(crate) use frame_grab::FrameGrab; + +/// The selected fill's frame as the 3D view shows it +#[derive(Clone, Copy, Debug)] +pub(crate) struct FrameGizmo { + pub layer: LayerId, + /// The selected mask fill effect projecting from the frame, when it is in a mask + pub effect: Option, + /// The frame; an axis planar shows the frame it is placed as on its first drag + pub decal: Decal, + /// A warp's corners, across and up in frame sizes from its centre + pub warp: Option<[[f32; 2]; 4]>, + /// On screen: the corners (a warp's pulled ones), the edge dots and the centre + pub corners: [Pos2; 4], + pub sides: [Pos2; 4], + pub center: Pos2, + /// On screen, the tips of the across, up and out arrows (None when one points at the camera) + 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]>, + /// 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], +} + +/// Screen length of the axis arrows, and their heads (points): long enough to grab each one apart from the others +pub(crate) const ARROW: f32 = 56.0; +const ARROW_HEAD: f32 = 14.0; +/// The centre square's side, the corner and edge dot radii, a warp corner's radius (points) +pub(crate) const CENTER_SQUARE: f32 = 16.0; +const CORNER_DOT: f32 = 6.5; +const SIDE_DOT: f32 = 5.5; +const WARP_DOT: f32 = 8.0; +/// How near a handle or arrow a press grabs it (points) +pub(crate) const GRAB: f32 = 11.0; +/// Screen radius of the turn rings (frames and round projectors alike): past the arrow heads, so a ring is grabbed apart from the arrows +pub(crate) const TURN_RING: f32 = 84.0; +/// Points on a frame's turn ring, the first repeated at the end to close it +pub(crate) const TURN_RING_POINTS: usize = 49; +/// The smallest share of its size a dragged side keeps +const MIN_SIDE_STRETCH: f32 = 0.02; +/// The least distance from the centre a resize drag measures from, so a press on the centre never divides by zero (points) +pub(crate) const MIN_HANDLE_REACH: f32 = 1.0; + +impl FrameGizmo { + /// The frame as the 3D view shows it: none while the Projection row's eye hides the projection gizmos + pub(crate) fn shown(app: &TextureCraftApp, rect: Rect) -> Option { + FrameGizmo::of(app, rect).filter(|_| app.session.doc.project.display.projection_gizmos) + } + + /// 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, + }; + + // 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, .. }); + if unplaced && placing_moves_pattern(sources.into_iter()) { + return None; + } + let placed = placed_from_axis(projection, app.session.mesh.bounds()); + + // Where the projection lands: a projector's own turn and scale moved into the frame, as the panel's 3D projection settings show it + let landed = folded(placed.as_ref().unwrap_or(projection))?; + let decal = *landed.frame()?; + let warp = match projection { + Projection::Warp { corners, .. } => Some(*corners), + _ => None, + }; + let (origin, across, up, out) = decal_axes(&decal)?; + + // The corners on screen: a warp's pulled ones, or the frame's own + let at = |[x, y]: [f32; 2]| project(app, rect, origin + across * x * decal.size[0] + up * y * decal.size[1]); + let corners = match warp { + Some([top_left, top_right, bottom_right, bottom_left]) => [at(top_left)?, at(top_right)?, at(bottom_right)?, at(bottom_left)?], + None => { + let [top_left, top_right, bottom_right, bottom_left] = decal_corners(&decal)?.map(|corner| project(app, rect, corner)); + [top_left?, top_right?, bottom_right?, bottom_left?] + } + }; + + 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 + 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)); + + // The turn ring, unless the frame is seen too near edge on to grab it + let ring = steps[0] + .zip(steps[1]) + .filter(|(across_step, up_step)| { + 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 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(); + project(app, rect, origin + (across * cos + up * sin) * radius) + }); + points.collect::>>()?.try_into().ok() + }); + + Some(FrameGizmo { layer, effect, decal, warp, corners, sides, center, arrows, ring, origin, axes, steps }) + } + + /// The frame's offset after sliding it across its plane by screen movement `delta` (None when the frame is edge-on) + pub(crate) fn slid_on_screen(&self, delta: egui::Vec2) -> Option<[f32; 2]> { + let [across, up] = solve(self.steps[0]?, self.steps[1]?, delta)?; + Some(self.slid(across, up)) + } + + /// 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); + let [across, up, out] = self.axes; + let facing = ray.dir.dot(out); + if facing.abs() < EDGE_ON_FACING { + return None; + } + + let hit = ray.origin + ray.dir * ((self.origin - ray.origin).dot(out) / facing); + let local = [(hit - self.origin).dot(across) / self.decal.size[0], (hit - self.origin).dot(up) / self.decal.size[1]]; + local.iter().all(|value| value.is_finite()).then_some(local) + } + + /// The frame's offset after moving `across` and `up` world units along its turned directions, unturned as `layer.decal.set` stores it + fn slid(&self, across: f32, up: f32) -> [f32; 2] { + let (sin, cos) = self.decal.rotation.to_radians().sin_cos(); + [self.decal.offset[0] + across * cos - up * sin, self.decal.offset[1] + across * sin + up * cos] + } +} + +/// Half a turn in degrees: a ring drag's sweep is kept within one either way +const HALF_TURN: f32 = 180.0; + +/// The smallest determinant of two screen steps (points² per world unit²) that still tells them apart: below it they run parallel on screen +const PARALLEL_DETERMINANT: f32 = 1e-6; + +/// The smallest cosine between a view ray and a plane's normal for the ray to meet the plane: nearer edge on, the hit runs off far away +pub(crate) const EDGE_ON_FACING: f32 = 1e-4; + +/// The smallest length a direction spans on screen to point somewhere (points): shorter, it points at the camera +pub(crate) const MIN_SCREEN_SPAN: f32 = 1.0; + +/// The smallest cosine between the view ray and a turn ring's axis for the ring to show: flatter, its half height on screen is under its drawn line's width, it reads as a line and a drag along it turns half a turn at once across the centre +const MIN_RING_FACING: f32 = (SHAFT_WIDTH + SHAFT_HALO_EXTRA_WIDTH) / TURN_RING; + +/// Whether a turn ring round `axis`, centred on screen at `center`, is seen open enough to show and grab +pub(crate) fn ring_open(app: &TextureCraftApp, rect: Rect, center: Pos2, axis: Vec3) -> bool { + view_ray(app, rect, center).dir.dot(axis).abs() >= MIN_RING_FACING +} + +/// `delta` as a mix of screen steps `across_step` and `up_step` (None when they are parallel on screen) +fn solve(across_step: egui::Vec2, up_step: egui::Vec2, delta: egui::Vec2) -> Option<[f32; 2]> { + let determinant = across_step.x * up_step.y - across_step.y * up_step.x; + if determinant.abs() < PARALLEL_DETERMINANT { + return None; + } + + Some([(delta.x * up_step.y - delta.y * up_step.x) / determinant, (across_step.x * delta.y - across_step.y * delta.x) / determinant]) +} + +/// How far `p` is from the centre square (0 inside it) +pub(crate) fn center_distance(center: Pos2, p: Pos2) -> f32 { + Rect::from_center_size(center, egui::Vec2::splat(CENTER_SQUARE)).distance_to_pos(p) +} + +/// How far `p` is from the arrow from `center` to `tip`, its head included +pub(crate) fn arrow_distance(p: Pos2, center: Pos2, tip: Pos2) -> f32 { + distance_to_segment(p, center, tip + (tip - center).normalized() * ARROW_HEAD) +} + +/// The handle nearest its distance, if one is within `GRAB` (the first listed wins a tie) +pub(crate) fn nearest(handles: impl IntoIterator) -> Option { + let mut best: Option<(T, f32)> = None; + for (handle, distance) in handles { + if distance <= GRAB && best.is_none_or(|(_, nearest)| distance < nearest) { + best = Some((handle, distance)); + } + } + best.map(|(handle, _)| handle) +} + +pub(crate) fn distance_to_segment(p: Pos2, a: Pos2, b: Pos2) -> f32 { + let ab = b - a; + let t = ((p - a).dot(ab) / ab.length_sq().max(f32::MIN_POSITIVE)).clamp(0.0, 1.0); + p.distance(a + ab * t) +} + +impl Gizmo for FrameGizmo { + type Grab = FrameGrab; + + fn drag_id() -> egui::Id { + egui::Id::unique("tc_frame_drag") + } + + /// The handle under screen point `p`: the nearest one within reach, so a small frame's corners stay grabbable beside its arrows + fn grab(&self, at: Pos2) -> Option { + let mut handles = vec![(FrameGrab::Slide, center_distance(self.center, at))]; + handles.extend((0..3).filter_map(|axis| Some((FrameGrab::Axis(axis), arrow_distance(at, self.center, self.arrows[axis]?))))); + let near = |points: [Pos2; 4], grab: fn(usize) -> FrameGrab| (0..4).map(move |index| (grab(index), points[index].distance(at))); + match self.warp { + // A mask effect's warp corners have no command to pull them + Some(_) if self.effect.is_none() => handles.extend(near(self.corners, FrameGrab::Corner)), + Some(_) => {} + None => handles.extend(near(self.corners, |_| FrameGrab::Scale)), + } + handles.extend(near(self.sides, FrameGrab::Side)); + 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) + } + + fn same_projection(&self, other: &FrameGizmo) -> bool { + self.layer == other.layer && self.effect == other.effect + } + + /// 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)> { + let delta = to - from; + let center = self.center; + let mut params = match grab { + FrameGrab::Slide => json!({"offset": self.slid_on_screen(delta)?}), + FrameGrab::Axis(axis) => { + let step = (*self.steps.get(axis)?)?; + let distance = delta.dot(step) / step.length_sq().max(f32::MIN_POSITIVE); + 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()}), + } + } + FrameGrab::Scale => { + let scale = (to - center).length() / (from - center).length().max(MIN_HANDLE_REACH); + json!({"size": [self.decal.size[0] * scale, self.decal.size[1] * scale]}) + } + FrameGrab::Side(side) => { + let direction = (*self.sides.get(side)? - center).normalized(); + let stretch = ((to - center).dot(direction) / (from - center).dot(direction).max(MIN_HANDLE_REACH)).max(MIN_SIDE_STRETCH); + let mut size = self.decal.size; + size[1 - side % 2] *= stretch; + json!({"size": size}) + } + FrameGrab::Turn => { + // The sweep round the centre on the frame's own plane (across turning towards up is a positive turn), so a tilted or off-centre frame follows the pointer too + 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}) + } + FrameGrab::Corner(corner) => { + let mut corners = self.warp?; + *corners.get_mut(corner)? = self.on_plane(app, rect, to)?; + return Some(("layer.fill.projection", json!({"layer": self.layer.0, "warpCorners": corners}))); + } + }; + params["layer"] = json!(self.layer.0); + if let Some(effect) = self.effect { + params["effect"] = json!(effect.0); + } + Some(("layer.decal.set", params)) + } + + fn cursor(&self, grab: FrameGrab, dragging: bool) -> egui::CursorIcon { + grab.cursor(dragging) + } +} + +/// The selected frame over the 3D view: dashed outline, corner and edge dots, and the centre square with its axis arrows +pub(crate) fn overlay(ui: &Ui, rect: Rect, gizmo: &FrameGizmo) { + let tokens = Tokens::get(ui.ctx()); + let painter = ui.painter_at(rect); + let active = dragging::(ui.ctx()).map(|drag| drag.grab); + let hovered = ui.ctx().pointer_hover_pos().filter(|hover| rect.contains(*hover)).and_then(|hover| gizmo.grab(hover)); + let lit = |grab: FrameGrab| active == Some(grab) || (active.is_none() && hovered == Some(grab)); + let dot_fill = |grab: FrameGrab| if lit(grab) { tokens.viewport_accent } else { Color32::WHITE }; + + let mut outline = gizmo.corners.to_vec(); + outline.push(gizmo.corners[0]); + dashed_outline(&painter, &outline); + if let Some(ring) = &gizmo.ring { + 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))); + } + match gizmo.warp { + Some(_) => { + for (index, corner) in gizmo.corners.into_iter().enumerate() { + handle_dot(&painter, corner, WARP_DOT, dot_fill(FrameGrab::Corner(index))); + } + } + None => { + for corner in gizmo.corners { + handle_dot(&painter, corner, CORNER_DOT, dot_fill(FrameGrab::Scale)); + } + } + } + for (index, side) in gizmo.sides.into_iter().enumerate() { + 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)); +} + +/// 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 +pub(crate) fn move_handles(painter: &egui::Painter, center: Pos2, arrows: [Option; 3], arrow_color: impl Fn(usize) -> Color32, square: Color32) { + for (axis, tip) in arrows.into_iter().enumerate() { + let Some(tip) = tip else { continue }; + + let color = arrow_color(axis); + let direction = (tip - center).normalized(); + let side = direction.rot90() * ARROW_HEAD * ARROW_HEAD_HALF_WIDTH; + let start = center + direction * CENTER_SQUARE * 0.5; + painter.line_segment([start, tip], Stroke::new(SHAFT_WIDTH + SHAFT_HALO_EXTRA_WIDTH, SHAFT_HALO)); + painter.line_segment([start, tip], Stroke::new(SHAFT_WIDTH, color)); + painter.add(egui::Shape::convex_polygon(vec![tip + direction * ARROW_HEAD, tip + side, tip - side], color, HANDLE_EDGE)); + } + let square_rect = Rect::from_center_size(center, vec2(CENTER_SQUARE, CENTER_SQUARE)); + painter.rect(square_rect, CENTER_SQUARE_CORNER_RADIUS, square, HANDLE_EDGE, egui::StrokeKind::Middle); +} + +/// The dashed outline: the dark shadow's width and colour, the light dashes' width and colour over it (white at 230 alpha, premultiplied), the dash and gap lengths +const OUTLINE_SHADOW_WIDTH: f32 = 3.0; +const OUTLINE_SHADOW: Color32 = Color32::from_black_alpha(140); +const OUTLINE_WIDTH: f32 = 1.2; +const OUTLINE_COLOR: Color32 = Color32::from_rgba_premultiplied(230, 230, 230, 230); +const OUTLINE_DASH: f32 = 6.0; +const OUTLINE_GAP: f32 = 4.0; + +/// A gizmo's dashed outline through `points`, light over a dark shadow so it reads on any model +pub(crate) fn dashed_outline(painter: &egui::Painter, points: &[Pos2]) { + for stroke in [Stroke::new(OUTLINE_SHADOW_WIDTH, OUTLINE_SHADOW), Stroke::new(OUTLINE_WIDTH, OUTLINE_COLOR)] { + painter.add(egui::Shape::dashed_line(points, stroke, OUTLINE_DASH, OUTLINE_GAP)); + } +} + +/// An arrow head's half width, as a share of its length +const ARROW_HEAD_HALF_WIDTH: f32 = 0.45; + +/// The dark rim around a handle dot +const DOT_RIM: f32 = 1.5; +/// The thin dark edge round handle dots, arrow heads and the centre square +pub(crate) const HANDLE_EDGE: Stroke = Stroke { width: 1.0, color: Color32::from_black_alpha(200) }; +/// The centre square's corner radius (points) +const CENTER_SQUARE_CORNER_RADIUS: f32 = 2.0; + +/// A handle dot of `radius`: `fill` over a dark rim, so it reads on a light or dark model +pub(crate) fn handle_dot(painter: &egui::Painter, at: Pos2, radius: f32, fill: Color32) { + painter.circle_filled(at, radius + DOT_RIM, SHAFT_HALO); + painter.circle(at, radius, fill, HANDLE_EDGE); +} + +#[cfg(test)] +pub(crate) mod tests { + use egui::{Modifiers, PointerButton, Pos2, vec2}; + use egui_kittest::kittest::Queryable; + use serde_json::json; + use texturecraft_engine::Session; + use texturecraft_engine::core::{LayerId, LayerKind, Projection}; + + use super::*; + + /// 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); + + /// The ball in a new project, its first frames run; with `render` the views render through wgpu + pub(crate) fn ball_app(render: bool) -> egui_kittest::Harness<'static, TextureCraftApp> { + let session = Session::new_project("Gizmo", texturecraft_engine::geom::primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 128).unwrap(); + let builder = egui_kittest::Harness::builder().with_size(TEST_WINDOW); + let builder = if render { builder.wgpu() } else { builder }; + let mut harness = builder.build_eframe(|context| TextureCraftApp::new(context, session)); + harness.run_steps(4); + harness + } + + /// 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})) + } + + /// The ball with a selected fill layer set up by `fields` of layer.fill.projection + pub(crate) fn fill_app_with(fields: serde_json::Value) -> (egui_kittest::Harness<'static, TextureCraftApp>, LayerId) { + fill_app_rendered(fields, false) + } + + /// As [`fill_app_with`]; with `render` the views render through wgpu + pub(crate) fn fill_app_rendered(mut fields: serde_json::Value, render: bool) -> (egui_kittest::Harness<'static, TextureCraftApp>, LayerId) { + let mut harness = ball_app(render); + let layer = harness.state_mut().run("layer.add.fill", json!({})).unwrap()["layer"].as_u64().unwrap(); + fields["layer"] = json!(layer); + harness.state_mut().run("layer.fill.projection", fields).unwrap(); + harness.run_steps(2); + (harness, LayerId(layer)) + } + + pub(crate) fn projection(harness: &egui_kittest::Harness<'_, TextureCraftApp>, layer: LayerId) -> Projection { + match &harness.state().session.doc.project.layer(layer).unwrap().kind { + LayerKind::Fill(fill) => fill.projection.clone(), + _ => panic!("a fill layer"), + } + } + + /// A primary-button drag from `from` to `to` over a few frames, with `modifiers` held + pub(crate) fn drag(harness: &mut egui_kittest::Harness<'_, TextureCraftApp>, from: Pos2, to: Pos2, modifiers: Modifiers) { + press_and_move(harness, from, to, modifiers); + harness.event_modifiers(egui::Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers }, modifiers); + harness.run_steps(2); + } + + /// The press and moves of [`drag`], the button still down at `to` + pub(crate) fn press_and_move(harness: &mut egui_kittest::Harness<'_, TextureCraftApp>, from: Pos2, to: Pos2, modifiers: Modifiers) { + harness.event_modifiers(egui::Event::PointerMoved(from), modifiers); + harness.event_modifiers(egui::Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers }, modifiers); + harness.run_steps(2); + for step in 1..=4 { + harness.event_modifiers(egui::Event::PointerMoved(from.lerp(to, step as f32 / 4.0)), modifiers); + harness.run_steps(1); + } + } + + /// Whether a frame drag is under way + fn frame_dragging(harness: &egui_kittest::Harness<'_, TextureCraftApp>) -> bool { + crate::projection_gizmo::dragging::(&harness.ctx).is_some() + } + + /// A drag as a mouse sends it, one small move per frame; after each frame `check` looks at the app and (with `preview`) the 3D preview square must have re-rendered + #[track_caller] + pub(crate) fn drag_frames( + harness: &mut egui_kittest::Harness<'_, TextureCraftApp>, + layer: LayerId, + from: Pos2, + to: Pos2, + modifiers: Modifiers, + preview: bool, + mut check: impl FnMut(&egui_kittest::Harness<'_, TextureCraftApp>), + ) { + harness.event_modifiers(egui::Event::PointerMoved(from), modifiers); + harness.event_modifiers(egui::Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers }, modifiers); + harness.run_steps(2); + let mut shown = crate::projection_preview::shown_key(&harness.ctx); + let mut was = projection(harness, layer); + let mut moved = 0; + for step in 1..=6 { + harness.event_modifiers(egui::Event::PointerMoved(from.lerp(to, step as f32 / 6.0)), modifiers); + harness.step(); + let now = projection(harness, layer); + + // Until the pointer passes the drag threshold nothing moves + if now == was { + assert_eq!(moved, 0, "frame {step}: once started, every frame of the drag moves it"); + continue; + } + + moved += 1; + check(harness); + let key = crate::projection_preview::shown_key(&harness.ctx); + assert!(!preview || (key.is_some() && key != shown), "frame {step}: the preview square re-rendered for the new values"); + (shown, was) = (key, now); + } + assert!(moved >= 4, "the drag moved it on {moved} frames"); + harness.event_modifiers(egui::Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers }, modifiers); + harness.run_steps(2); + check(harness); + } + + /// The panel's X, Y and Z fields of a 3D projection settings row + pub(crate) fn panel_xyz(harness: &egui_kittest::Harness<'_, TextureCraftApp>, row: &str) -> [f32; 3] { + use egui_kittest::kittest::NodeT; + ["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 { + FrameGizmo::of(harness.state(), harness.state().viewport_rect).unwrap() + } + + #[test] + fn an_axis_planar_is_placed_on_its_first_drag_and_its_handles_move_size_and_stretch_it() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + + // Repeating three times across the mesh, the frame is smaller than the ball + let (mut harness, layer) = fill_app_with(json!({"projection": "planar", "scale": 3})); + let axis = gizmo(&harness); + assert!(matches!(projection(&harness, layer), Projection::Planar { placed: None, .. }), "a new planar projects along its axis"); + assert!(axis.warp.is_none() && axis.arrows.iter().all(Option::is_some), "a planar frame with its three arrows: {axis:?}"); + + drag(&mut harness, axis.center, axis.center + vec2(30.0, 0.0), Modifiers::NONE); + let Projection::Planar { placed: Some(slid), .. } = projection(&harness, layer) else { panic!("placed on the first drag") }; + assert!(slid.offset[0] > 0.0 && slid.offset[1].abs() < slid.offset[0] * 0.2, "the centre square slides it right: {slid:?}"); + assert_eq!(slid.size, axis.decal.size, "sliding keeps its size"); + assert_eq!(harness.state().session.history_labels().last().map(String::as_str), Some("Edit decal")); + let steps = harness.state().session.history_labels().len(); + + let placed = gizmo(&harness); + drag(&mut harness, placed.sides[1], placed.center + (placed.sides[1] - placed.center) * 0.5, Modifiers::NONE); + let Projection::Planar { placed: Some(stretched), .. } = projection(&harness, layer) else { panic!("still placed") }; + assert!(stretched.size[0] < slid.size[0] * 0.75 && stretched.size[1] == slid.size[1], "the right edge dot narrows it only: {stretched:?}"); + + let narrowed = gizmo(&harness); + drag(&mut harness, narrowed.corners[2], narrowed.center + (narrowed.corners[2] - narrowed.center) * 1.5, Modifiers::NONE); + let Projection::Planar { placed: Some(scaled), .. } = projection(&harness, layer) else { panic!("still placed") }; + assert!(scaled.size[1] > stretched.size[1] * 1.2, "a corner scales it: {scaled:?}"); + assert_eq!(harness.state().session.history_labels().len(), steps + 2, "one undo step per drag"); + } + + #[test] + fn a_warp_corner_follows_the_pointer_on_the_frame_plane() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = fill_app("warp"); + let warp = gizmo(&harness); + assert_eq!(warp.warp, Some(Projection::FRAME_CORNERS)); + let to = warp.corners[1] + vec2(-40.0, 30.0); + drag(&mut harness, warp.corners[1], to, Modifiers::NONE); + let Projection::Warp { corners, frame, .. } = projection(&harness, layer) else { panic!("still a warp") }; + assert_eq!((frame, corners[0], corners[2], corners[3]), (warp.decal, [-0.5, 0.5], [0.5, -0.5], [-0.5, -0.5]), "only that corner moves"); + assert!(corners[1][0] < 0.45 && corners[1][1] < 0.45, "top right pulled in: {corners:?}"); + assert!(gizmo(&harness).corners[1].distance(to) < 1.5, "the corner sits under the pointer"); + } + + /// A move that arrives in the same frame as the release still moves the corner: it ends under the pointer, not one step short + #[test] + fn a_move_in_the_release_frame_still_moves_the_corner() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, _) = fill_app("warp"); + let warp = gizmo(&harness); + let to = warp.corners[1] + vec2(-40.0, 30.0); + press_and_move(&mut harness, warp.corners[1], warp.corners[1].lerp(to, 0.5), Modifiers::NONE); + + // Straight into the next frame's input: the harness's queued events would each get a frame of their own + let release = egui::Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }; + harness.input_mut().events.extend([egui::Event::PointerMoved(to), release]); + harness.run_steps(2); + + assert!(crate::projection_gizmo::dragging::(&harness.ctx).is_none(), "the release ends the drag"); + assert!(gizmo(&harness).corners[1].distance(to) < 1.5, "the corner sits under the release point: {:?} {to:?}", gizmo(&harness).corners[1]); + } + + /// The across and up arrows slide a frame on its own plane and the out arrow moves it along its normal, each following the pointer; one undo step per drag + #[test] + fn the_arrows_move_a_frame_along_its_directions() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = fill_app("warp"); + let steps = harness.state().session.history_labels().len(); + let frame = |harness: &egui_kittest::Harness<'_, TextureCraftApp>| match projection(harness, layer) { + Projection::Warp { frame, .. } => frame, + other => panic!("still a warp: {other:?}"), + }; + + for axis in 0..3 { + let start = gizmo(&harness); + let tip = start.arrows[axis].unwrap_or_else(|| panic!("arrow {axis} shows")); + let along = (tip - start.center).normalized(); + let before = frame(&harness); + drag(&mut harness, tip, tip + along * 25.0, Modifiers::NONE); + + let moved = gizmo(&harness); + assert!( + (moved.center - start.center).dot(along) > 15.0, + "arrow {axis}: the centre follows the pointer along it: {:?} -> {:?}", + start.center, + moved.center + ); + assert_eq!(frame(&harness).normal, before.normal, "arrow {axis}: moving never turns the frame"); + + // Across and up slide it on its own plane, out moves it along its normal + let shift = moved.origin - start.origin; + assert!(shift.normalize().dot(start.axes[axis]) > 0.99, "arrow {axis} moves it along its own direction: {shift:?}"); + assert_eq!(harness.state().session.history_labels().len(), steps + axis + 1, "arrow {axis}: one undo step per drag"); + } + } + + /// The panel's Rotation turns a frame and its Scale sizes it, so the gizmo does both: the ring turns a planar or warp frame round its normal, following the pointer round the centre; a warp's edge dots size its frame as a planar's do + #[test] + fn the_ring_turns_a_frame_and_a_warps_edge_dots_size_it() { + 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); + 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 + .iter() + .filter(|at| start.grab(**at) == Some(FrameGrab::Turn)) + .max_by(|a, b| a.y.total_cmp(&b.y)) + .expect("a ring point clear of the other handles"); + let steps = harness.state().session.history_labels().len(); + let quarter = start.center + (on_ring - start.center).rot90(); + drag(&mut harness, on_ring, quarter, Modifiers::NONE); + let turned = gizmo(&harness); + let sweep = |from: egui::Vec2, to: egui::Vec2| (to.angle() - from.angle()).to_degrees(); + let pointer = sweep(on_ring - start.center, quarter - start.center); + let corner = sweep(start.corners[1] - start.center, turned.corners[1] - turned.center); + let off = (corner - pointer + 180.0).rem_euclid(360.0) - 180.0; + assert!(off.abs() < 6.0, "{kind}: the frame turns a quarter with the pointer: corner {corner}°, pointer {pointer}°"); + assert!(turned.center.distance(start.center) < 1.0, "{kind}: round its centre"); + assert_eq!(harness.state().session.history_labels().len(), steps + 1, "{kind}: one undo step"); + } + + let (mut harness, layer) = fill_app("warp"); + let warp = gizmo(&harness); + assert_eq!(warp.grab(warp.sides[1]), Some(FrameGrab::Side(1))); + drag(&mut harness, warp.sides[1], warp.center + (warp.sides[1] - warp.center) * 0.5, Modifiers::NONE); + let Projection::Warp { frame, corners, .. } = projection(&harness, layer) else { panic!("still a warp") }; + assert!(frame.size[0] < warp.decal.size[0] * 0.75 && (frame.size[1] - warp.decal.size[1]).abs() < 1e-4, "the right edge dot narrows it: {frame:?}"); + assert_eq!(corners, Projection::FRAME_CORNERS, "its corners stay where they are on the frame"); + } + + /// Losing the focus mid-drag (Alt+Tab) ends a frame drag as a release does: one undo step, and moves after it (egui still has the button down) leave the frame alone + #[test] + fn losing_the_window_focus_ends_a_frame_drag() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = fill_app("planar"); + let steps = harness.state().session.history_labels().len(); + let center = gizmo(&harness).center; + let to = center + vec2(40.0, 0.0); + press_and_move(&mut harness, center, to, Modifiers::NONE); + assert!(frame_dragging(&harness), "the centre square is held"); + + harness.event(egui::Event::WindowFocused(false)); + harness.run_steps(1); + let left = projection(&harness, layer); + assert!(!frame_dragging(&harness), "the focus loss ends the drag"); + assert_eq!(harness.state().session.history_labels().len(), steps + 1, "as one undo step"); + + for step in 1..=3 { + harness.event(egui::Event::PointerMoved(to + vec2(20.0, 10.0) * step as f32)); + harness.run_steps(1); + } + assert_eq!(projection(&harness, layer), left, "moves after it leave the frame where it was"); + harness.event(egui::Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(2); + assert_eq!(harness.state().session.history_labels().len(), steps + 1, "and add no step"); + } + + /// Alt pressed mid-drag hands the pointer to the camera and ends the frame drag where it is: let go of Alt with the button still down, the drag does not resume from where it began; one undo step + #[test] + fn alt_mid_drag_ends_a_frame_drag() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = fill_app("planar"); + let steps = harness.state().session.history_labels().len(); + let center = gizmo(&harness).center; + let to = center + vec2(40.0, 0.0); + press_and_move(&mut harness, center, to, Modifiers::NONE); + let slid = projection(&harness, layer); + let camera = harness.state().session.camera; + + harness.event_modifiers(egui::Event::PointerMoved(to + vec2(20.0, 0.0)), Modifiers::ALT); + harness.run_steps(1); + assert_ne!(harness.state().session.camera, camera, "Alt turns the camera"); + assert!(!frame_dragging(&harness), "and ends the frame drag"); + + for step in 2..=4 { + harness.event(egui::Event::PointerMoved(to + vec2(20.0, 5.0) * step as f32)); + harness.run_steps(1); + } + assert_eq!(projection(&harness, layer), slid, "Alt let go, the frame stays where the drag left it"); + harness.event(egui::Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(2); + assert_eq!(harness.state().session.history_labels().len(), steps + 1, "one undo step"); + } + + /// The rest of a drag held at `from`: moves to `to` over a few frames and lets go there + fn move_and_let_go(harness: &mut egui_kittest::Harness<'_, TextureCraftApp>, from: Pos2, to: Pos2) { + for step in 1..=4 { + harness.event(egui::Event::PointerMoved(from.lerp(to, step as f32 / 4.0))); + harness.run_steps(1); + } + harness.event(egui::Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(2); + } + + /// A drag whose first edit changes nothing (its arrow pulled further past the offset limit) makes no undo step, so its later edits make the drag's own step instead of joining the edit before it + #[test] + fn a_drag_that_first_changes_nothing_keeps_its_own_undo_step() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = fill_app("warp"); + + // The frame waits at its left limit, a mesh diagonal off the ball's centre, clear of the panels on the right; the camera backs off so it shows with its arrows + harness.state_mut().run("layer.decal.set", json!({"layer": layer.0, "offset": [-100.0, 0.0]})).unwrap(); + harness.state_mut().session.camera.distance *= 3.0; + harness.run_steps(2); + let at_limit = projection(&harness, layer); + let steps = harness.state().session.history_labels().len(); + let start = gizmo(&harness); + let tip = start.arrows[0].expect("the across arrow shows"); + let inward = (tip - start.center).normalized(); + + press_and_move(&mut harness, tip, tip - inward * 25.0, Modifiers::NONE); + + assert_eq!(projection(&harness, layer), at_limit, "past the limit the frame stays where it is"); + move_and_let_go(&mut harness, tip - inward * 25.0, tip + inward * 25.0); + + assert_ne!(projection(&harness, layer), at_limit, "back inside the frame moves"); + assert_eq!(harness.state().session.history_labels().len(), steps + 1, "the drag made its own undo step"); + + harness.state_mut().session.undo().unwrap(); + assert_eq!(projection(&harness, layer), at_limit, "undo takes back the drag only"); + } + + /// An axis planar reading a pattern keeps its axis, so it shows no frame to drag; reading an image it shows one + #[test] + fn an_axis_planar_reading_a_pattern_has_no_frame() { + let (mut harness, layer) = fill_app("planar"); + assert!(FrameGizmo::of(harness.state(), harness.state().viewport_rect).is_some(), "a uniform fill places as its frame"); + + harness.state_mut().run("layer.fill.set", json!({"layer": layer.0, "channel": "roughness", "procedural": "Checker"})).unwrap(); + harness.run_steps(2); + assert!(FrameGizmo::of(harness.state(), harness.state().viewport_rect).is_none(), "placing would move the pattern"); + } + + /// An Undo mid-drag takes the drag's step away: the drag's next edits make a step of their own instead of joining the drag before it + #[test] + fn undo_mid_drag_leaves_the_drag_before_its_own_step() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = fill_app("warp"); + let center = gizmo(&harness).center; + drag(&mut harness, center, center + vec2(30.0, 0.0), Modifiers::NONE); + let first = projection(&harness, layer); + let steps = harness.state().session.history_labels().len(); + + let center = gizmo(&harness).center; + press_and_move(&mut harness, center, center + vec2(0.0, 30.0), Modifiers::NONE); + harness.key_press_modifiers(Modifiers::COMMAND, egui::Key::Z); + harness.run_steps(1); + assert_eq!(projection(&harness, layer), first, "Ctrl+Z undid the drag so far"); + move_and_let_go(&mut harness, center + vec2(0.0, 30.0), center + vec2(0.0, 40.0)); + assert_eq!(harness.state().session.history_labels().len(), steps + 1, "the drag's later edits made a step of their own"); + + harness.state_mut().session.undo().unwrap(); + assert_eq!(projection(&harness, layer), first, "undo goes back to where the first drag left the frame"); + } + + /// A click as a mouse sends it: move there, press, release + fn click(harness: &mut egui_kittest::Harness<'_, TextureCraftApp>, at: Pos2) { + harness.event(egui::Event::PointerMoved(at)); + harness.event(egui::Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(1); + harness.event(egui::Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(2); + } + + /// The Projection row's eye hides the gizmo: not drawn, a press on where its handle was moves nothing, and the eye brings it back + #[test] + fn the_projection_rows_eye_hides_and_shows_the_gizmo() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = fill_app_with(json!({"projection": "planar", "scale": 3})); + let shown = gizmo(&harness); + let eye = harness.get_by_label("Hide projection gizmos").rect(); + let projection_row = harness.get_by_label("Planar projection").rect(); + assert!(eye.left() > projection_row.right() && (eye.center().y - projection_row.center().y).abs() < 0.5, "the eye ends the Projection row"); + + click(&mut harness, eye.center()); + assert!(!harness.state().session.doc.project.display.projection_gizmos, "the eye hides the gizmos"); + assert!(FrameGizmo::shown(harness.state(), harness.state().viewport_rect).is_none(), "the 3D view has no frame to draw or grab"); + let before = projection(&harness, layer); + drag(&mut harness, shown.center, shown.center + vec2(30.0, 0.0), Modifiers::NONE); + assert_eq!(projection(&harness, layer), before, "a drag where the centre square was moves nothing"); + + let eye = harness.get_by_label("Show projection gizmos").rect(); + click(&mut harness, eye.center()); + assert!(harness.state().session.doc.project.display.projection_gizmos, "the eye shows them again"); + drag(&mut harness, shown.center, shown.center + vec2(30.0, 0.0), Modifiers::NONE); + assert_ne!(projection(&harness, layer), before, "shown, the centre square slides it again"); + + // A UV projection has no gizmo: its row keeps the whole width for the dropdown + harness.state_mut().run("layer.fill.projection", json!({"layer": layer.0, "projection": "uv"})).unwrap(); + harness.run_steps(2); + assert!(harness.query_by_label("Hide projection gizmos").is_none(), "no eye without a gizmo"); + } + + #[test] + fn round_projections_have_no_frame() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + for projection in ["uv", "triplanar", "spherical", "cylindrical"] { + let (harness, _) = fill_app(projection); + assert!(FrameGizmo::of(harness.state(), harness.state().viewport_rect).is_none(), "{projection}"); + } + } + + /// The planar and warp frames over the ball, a handle hovered, Move on model lit, and the round projectors + #[test] + #[ignore = "requires an offscreen GPU adapter and TC_UI_SNAPSHOTS"] + fn frame_gizmo_snapshots() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let Some(directory) = std::env::var_os("TC_UI_SNAPSHOTS").map(std::path::PathBuf::from) else { return }; + + std::fs::create_dir_all(&directory).unwrap(); + let checker = |harness: &mut egui_kittest::Harness<'_, TextureCraftApp>, layer: LayerId| { + let fields = + json!({"layer": layer.0, "channel": "baseColor", "procedural": "Checker", "scale": 4, "low": [0.2, 0.2, 0.2], "high": [0.6, 0.6, 0.6]}); + harness.state_mut().run("layer.fill.set", fields).unwrap(); + harness.state_mut().run("layer.fill.projection", json!({"layer": layer.0, "shapeCrop": "cropped"})).unwrap(); + }; + let (mut harness, layer) = fill_app_rendered(json!({"projection": "planar", "scale": 3}), true); + checker(&mut harness, layer); + harness.run_steps(4); + let planar = gizmo(&harness); + harness.hover_at(planar.sides[1]); + harness.run_steps(4); + harness.render().unwrap().save(directory.join("move-planar-side-hover.png")).unwrap(); + + // Move on model held down and dragged into the 3D view: the button stays lit and the frame follows + let button = harness.get_by_label("Move on model").rect().center(); + harness.event(egui::Event::PointerMoved(button)); + harness.event(egui::Event::PointerButton { pos: button, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(2); + for step in 1..=6 { + harness.event(egui::Event::PointerMoved(button + vec2(-40.0, 10.0) * step as f32)); + harness.run_steps(1); + } + harness.run_steps(3); + harness.render().unwrap().save(directory.join("move-planar-held.png")).unwrap(); + harness.event(egui::Event::PointerButton { + pos: button + vec2(-240.0, 60.0), + button: PointerButton::Primary, + pressed: false, + modifiers: Modifiers::NONE, + }); + harness.run_steps(2); + + let (mut harness, layer) = fill_app_rendered(json!({"projection": "warp"}), true); + checker(&mut harness, layer); + let pulled = json!([[-0.35, 0.3], [0.4, 0.42], [0.42, -0.4], [-0.3, -0.32]]); + harness.state_mut().run("layer.fill.projection", json!({"layer": layer.0, "warpCorners": pulled, "projectionDepth": 1})).unwrap(); + harness.run_steps(4); + harness.hover_at(gizmo(&harness).corners[1]); + harness.run_steps(4); + harness.render().unwrap().save(directory.join("move-warp-corner-hover.png")).unwrap(); + + // Mid drag: the panel's 3D projection settings and the preview square hold the frame the gizmo is dragging + let (mut harness, layer) = fill_app_rendered(json!({"projection": "planar", "scale": 3}), true); + checker(&mut harness, layer); + harness.run_steps(4); + let held = gizmo(&harness); + let (from, to) = (held.sides[0], held.center + (held.sides[0] - held.center) * 0.6 + vec2(30.0, 0.0)); + harness.event(egui::Event::PointerMoved(from)); + harness.event(egui::Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(2); + for step in 1..=6 { + harness.event(egui::Event::PointerMoved(from.lerp(to, step as f32 / 6.0))); + harness.run_steps(1); + } + harness.run_steps(3); + harness.render().unwrap().save(directory.join("sync-planar-mid-drag.png")).unwrap(); + harness.event(egui::Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(2); + + let (mut harness, layer) = fill_app_rendered(json!({"projection": "spherical"}), true); + checker(&mut harness, layer); + harness.run_steps(4); + let round = crate::round_gizmo::RoundGizmo::of(harness.state(), harness.state().viewport_rect).unwrap(); + let dot = round.sizes.iter().find(|size| size.axes == [true; 3]).expect("the even-scale dot").at; + let to = round.center + (dot - round.center) * 0.6; + harness.event(egui::Event::PointerMoved(dot)); + harness.event(egui::Event::PointerButton { pos: dot, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(2); + for step in 1..=6 { + harness.event(egui::Event::PointerMoved(dot.lerp(to, step as f32 / 6.0))); + harness.run_steps(1); + } + harness.run_steps(3); + harness.render().unwrap().save(directory.join("sync-sphere-mid-drag.png")).unwrap(); + + // The round projections with their fill selected: the shape round it, a ring hovered (a sphere: its one dot; a cylinder: its height arrow) + for kind in ["triplanar", "spherical", "cylindrical"] { + let (mut harness, layer) = fill_app_rendered(json!({"projection": kind}), true); + checker(&mut harness, layer); + harness.run_steps(4); + let round = crate::round_gizmo::RoundGizmo::of(harness.state(), harness.state().viewport_rect).unwrap(); + let size_at = |axes: [bool; 3]| round.sizes.iter().find(|size| size.axes == axes).expect("the size handle").at; + let hover = match kind { + "triplanar" => round.rings[2][crate::round_gizmo::CIRCLE_POINTS / 8], + "spherical" => size_at([true; 3]), + _ => size_at([false, true, false]), + }; + harness.hover_at(hover); + harness.run_steps(4); + harness.render().unwrap().save(directory.join(format!("move-{kind}.png"))).unwrap(); + } + } + + /// The panel's 3D projection settings show the frame the gizmo drags (its centre, turn and size), and the preview square follows, every frame of every drag: resize, stretch, slide, turn, a warp's slide and corners; one undo step per drag + #[test] + fn the_panel_and_its_preview_follow_every_frame_of_a_frame_drag() { + // Dolly exponent stepping the camera back before the corner drag + const CORNER_ZOOM_OUT: f32 = 0.4; + + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + use texturecraft_engine::compose::frame_placement::placement; + + let check = |layer: LayerId| { + move |harness: &egui_kittest::Harness<'_, TextureCraftApp>| { + let Some(shown) = placement(&projection(harness, layer), harness.state().session.mesh.bounds()) else { panic!("placed on its first drag") }; + for (row, value) in [("Offset", shown.offset), ("Rotation", shown.rotation), ("Scale", shown.scale)] { + let field = panel_xyz(harness, row); + for axis in 0..3 { + assert!((field[axis] - value[axis]).abs() < 1e-3, "the panel's {row} shows the frame's {value:?}, not {field:?}"); + } + } + } + }; + + let (mut harness, layer) = fill_app("planar"); + let steps = harness.state().session.history_labels().len(); + let center = gizmo(&harness).center; + drag_frames(&mut harness, layer, center, center + vec2(30.0, -10.0), Modifiers::NONE, true, check(layer)); + let slid = placement(&projection(&harness, layer), harness.state().session.mesh.bounds()).unwrap(); + + // The top edge dot and a corner inside the view (the frame starts bigger than the model) + let side = gizmo(&harness); + drag_frames(&mut harness, layer, side.sides[0], side.center + (side.sides[0] - side.center) * 0.5, Modifiers::NONE, true, check(layer)); + let narrowed = placement(&projection(&harness, layer), harness.state().session.mesh.bounds()).unwrap(); + assert!(narrowed.scale[1] < slid.scale[1] * 0.75 && (narrowed.scale[0] - slid.scale[0]).abs() < 1e-4, "{slid:?} -> {narrowed:?}"); + + // The view steps back so a corner shows beside the panels + harness.state_mut().session.camera.zoom(-CORNER_ZOOM_OUT); + harness.run_steps(2); + let corner = gizmo(&harness); + let view = harness.state().viewport_rect.shrink(10.0); + let inside = *corner.corners.iter().find(|at| view.contains(**at)).expect("a corner in the view"); + drag_frames(&mut harness, layer, inside, corner.center + (inside - corner.center) * 0.6, Modifiers::NONE, true, check(layer)); + let scaled = placement(&projection(&harness, layer), harness.state().session.mesh.bounds()).unwrap(); + assert!(scaled.scale[1] < narrowed.scale[1] * 0.8 && scaled.scale[0] < narrowed.scale[0] * 0.8, "a corner scales it: {scaled:?}"); + + // Move on model held with Shift turns the frame round its normal + let before = placement(&projection(&harness, layer), harness.state().session.mesh.bounds()).unwrap(); + let button = harness.get_by_label("Move on model").rect().center(); + drag_frames(&mut harness, layer, button, button + vec2(-60.0, 0.0), Modifiers::SHIFT, true, check(layer)); + let turned = placement(&projection(&harness, layer), harness.state().session.mesh.bounds()).unwrap(); + assert!((turned.rotation[2] - before.rotation[2]).abs() > 10.0, "turned: {before:?} -> {turned:?}"); + assert_eq!(harness.state().session.history_labels().len(), steps + 4, "one undo step per drag"); + + let (mut harness, layer) = fill_app("warp"); + let warp = gizmo(&harness); + drag_frames(&mut harness, layer, warp.center, warp.center + vec2(30.0, 25.0), Modifiers::NONE, false, check(layer)); + let warp = gizmo(&harness); + drag_frames(&mut harness, layer, warp.corners[0], warp.corners[0] + vec2(-25.0, -15.0), Modifiers::NONE, false, check(layer)); + let Projection::Warp { corners, .. } = projection(&harness, layer) else { panic!("a warp") }; + assert_ne!(corners[0], Projection::FRAME_CORNERS[0], "the corner was pulled"); + } +} diff --git a/crates/ui-egui/src/frame_gizmo/frame_grab.rs b/crates/ui-egui/src/frame_gizmo/frame_grab.rs new file mode 100644 index 00000000..a0733168 --- /dev/null +++ b/crates/ui-egui/src/frame_gizmo/frame_grab.rs @@ -0,0 +1,29 @@ +/// What a drag on the frame does +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) enum FrameGrab { + /// The centre square: slide the frame across its own plane + Slide, + /// Along the frame's across (0), up (1) or out (2) direction + Axis(usize), + /// A planar's corner: scale it about its centre + Scale, + /// A planar's edge dot (top, right, bottom, left): stretch that side + Side(usize), + /// A warp's corner (top left, top right, bottom right, bottom left): pull it + Corner(usize), + /// The ring: turn it round its normal + Turn, +} + +impl FrameGrab { + 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::Side(side) if side % 2 == 0 => egui::CursorIcon::ResizeVertical, + FrameGrab::Side(_) => egui::CursorIcon::ResizeHorizontal, + } + } +} diff --git a/crates/ui-egui/src/projection_gizmo.rs b/crates/ui-egui/src/projection_gizmo.rs new file mode 100644 index 00000000..06b1c199 --- /dev/null +++ b/crates/ui-egui/src/projection_gizmo.rs @@ -0,0 +1,77 @@ +//! A drag on a handle of the selected fill's projection gizmo, a planar or warp frame or a round projector: one undo step per drag, the projection updating live + +mod gizmo; +mod gizmo_drag; +mod shown_gizmo; + +use egui::{PointerButton, Rect}; +use serde_json::{Value, json}; +use texturecraft_engine::Session; + +use crate::TextureCraftApp; +use crate::viewport::focus_lost; + +pub(crate) use gizmo::Gizmo; +pub(crate) use gizmo_drag::GizmoDrag; +pub(crate) use shown_gizmo::ShownGizmo; + +/// The drag under way on a handle of a `G` gizmo +pub(crate) fn dragging(ctx: &egui::Context) -> Option> { + ctx.data(|data| data.get_temp::>(G::drag_id())) +} + +/// Ends a drag under way on a `G` gizmo where it is: its undo step stays one step +pub(crate) fn let_go(ctx: &egui::Context) { + ctx.data_mut(|data| data.remove::>(G::drag_id())); +} + +/// Drags on `gizmo`'s handles (one undo step per drag, the projection updates live); returns whether a drag owns the pointer. The cursor shows what the handle under it, or the one dragged, does (only while the gizmo takes input: an Alt orbit or a held Move on model keeps its own) +pub(crate) fn input(app: &mut TextureCraftApp, ctx: &egui::Context, response: &egui::Response, rect: Rect, gizmo: Option<&G>) -> bool { + let mut drag = dragging::(ctx).filter(|drag| gizmo.is_some_and(|gizmo| gizmo.same_projection(&drag.start))); + if response.drag_started_by(PointerButton::Primary) + && let (Some(gizmo), Some(from)) = (gizmo, ctx.input(|input| input.pointer.press_origin())) + && let Some(grab) = gizmo.grab(from) + { + drag = Some(GizmoDrag { grab, from, start: gizmo.clone(), edited_revision: None }); + } + + // A window that lost the focus gets no release: the drag ends there. A release still applies a move that came in the same frame + let released = response.drag_stopped_by(PointerButton::Primary); + let pressed = response.dragged_by(PointerButton::Primary) || response.drag_started_by(PointerButton::Primary) || released; + let Some(mut drag) = drag.filter(|_| pressed && !focus_lost(ctx)) else { + let_go::(ctx); + if let Some((gizmo, grab)) = gizmo.and_then(|gizmo| Some((gizmo, gizmo.grab(response.hover_pos()?)?))) { + ctx.set_cursor_icon(gizmo.cursor(grab, false)); + } + return false; + }; + + // A drag lives only while its gizmo shows, so the gizmo drawn this frame names the cursor + 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) + { + edit_in_one_step(&mut app.session, command, params, &mut drag.edited_revision); + + // The panel drew before this edit: one more frame shows its fields and preview where the projection is now + ctx.request_repaint(); + } + if released { + let_go::(ctx); + } else { + ctx.data_mut(|data| data.insert_temp(G::drag_id(), drag)); + } + true +} + +/// Runs one edit of a drag or hold, joining the undo step its last edit (at `edited_revision`) made while the history is still where that edit left it: an edit that changed nothing made no step to join, and an Undo took the step away +pub(crate) fn edit_in_one_step(session: &mut Session, command: &str, mut params: Value, edited_revision: &mut Option) { + params["merge"] = json!(*edited_revision == Some(session.revision)); + let before = session.revision; + + // Off the plane or past the size limits: the projection waits where it is + if texturecraft_engine::execute(session, command, ¶ms).is_ok() && session.revision != before { + *edited_revision = Some(session.revision); + } +} diff --git a/crates/ui-egui/src/projection_gizmo/gizmo.rs b/crates/ui-egui/src/projection_gizmo/gizmo.rs new file mode 100644 index 00000000..e95c8270 --- /dev/null +++ b/crates/ui-egui/src/projection_gizmo/gizmo.rs @@ -0,0 +1,25 @@ +use egui::{Pos2, Rect}; +use serde_json::Value; + +use crate::TextureCraftApp; + +/// A projection gizmo whose handles a drag edits +pub(crate) trait Gizmo: Clone + Send + Sync + 'static { + /// What a drag on one of its handles does + type Grab: Copy + PartialEq + Send + Sync + 'static; + + /// Where a drag on it is kept in egui's memory + fn drag_id() -> egui::Id; + + /// The handle under screen point `at` + fn grab(&self, at: Pos2) -> Option; + + /// Whether `other` shows the same projection: a drag goes on only while the projection it began on shows + fn same_projection(&self, other: &Self) -> bool; + + /// 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)>; + + /// The cursor over `grab`, or dragging it + fn cursor(&self, grab: Self::Grab, dragging: bool) -> egui::CursorIcon; +} diff --git a/crates/ui-egui/src/projection_gizmo/gizmo_drag.rs b/crates/ui-egui/src/projection_gizmo/gizmo_drag.rs new file mode 100644 index 00000000..bf8221b5 --- /dev/null +++ b/crates/ui-egui/src/projection_gizmo/gizmo_drag.rs @@ -0,0 +1,14 @@ +use egui::Pos2; + +use super::Gizmo; + +/// A handle of a projection gizmo being dragged (kept in egui's memory between frames) +#[derive(Clone, Debug)] +pub(crate) struct GizmoDrag { + pub(crate) grab: G::Grab, + /// Where the drag started and the gizmo then + pub(crate) from: Pos2, + pub(crate) start: G, + /// The session revision the drag's last edit left: later updates merge into its undo step while the history is still there + pub(crate) edited_revision: Option, +} diff --git a/crates/ui-egui/src/projection_gizmo/shown_gizmo.rs b/crates/ui-egui/src/projection_gizmo/shown_gizmo.rs new file mode 100644 index 00000000..cd2a7e26 --- /dev/null +++ b/crates/ui-egui/src/projection_gizmo/shown_gizmo.rs @@ -0,0 +1,73 @@ +use egui::{Pos2, Rect, Ui}; + +use super::{Gizmo, dragging, let_go}; +use crate::TextureCraftApp; +use crate::frame_gizmo::FrameGizmo; +use crate::round_gizmo::RoundGizmo; + +/// The selected fill's projection gizmo the 3D view shows, built once a frame: a planar or warp frame, or a round projector +pub(crate) enum ShownGizmo { + // Both boxed: each gizmo is hundreds of bytes and of a different size + Frame(Box), + Round(Box), +} + +impl ShownGizmo { + /// The gizmo of the selected fill's projection: none while the Projection row's eye hides it + pub(crate) fn of(app: &TextureCraftApp, rect: Rect) -> Option { + FrameGizmo::shown(app, rect) + .map(|frame| ShownGizmo::Frame(Box::new(frame))) + .or_else(|| RoundGizmo::shown(app, rect).map(|round| ShownGizmo::Round(Box::new(round)))) + } + + fn frame(gizmo: Option<&ShownGizmo>) -> Option<&FrameGizmo> { + match gizmo? { + ShownGizmo::Frame(frame) => Some(frame), + ShownGizmo::Round(_) => None, + } + } + + fn round(gizmo: Option<&ShownGizmo>) -> Option<&RoundGizmo> { + match gizmo? { + ShownGizmo::Round(round) => Some(round), + ShownGizmo::Frame(_) => None, + } + } + + /// Drags on `gizmo`'s handles; returns whether a drag owns the pointer + pub(crate) fn input(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response, rect: Rect, gizmo: Option<&ShownGizmo>) -> bool { + let ctx = ui.ctx(); + super::input(app, ctx, response, rect, ShownGizmo::frame(gizmo)) || super::input(app, ctx, response, rect, ShownGizmo::round(gizmo)) + } + + /// Ends a drag under way on either gizmo where it is + pub(crate) fn let_go(ctx: &egui::Context) { + let_go::(ctx); + let_go::(ctx); + } + + /// Whether screen point `at` is on one of its handles + pub(crate) fn on_handle(&self, rect: Rect, at: Pos2) -> bool { + rect.contains(at) + && match self { + ShownGizmo::Frame(frame) => frame.grab(at).is_some(), + ShownGizmo::Round(round) => round.grab(at).is_some(), + } + } + + /// Whether the pointer is over one of `gizmo`'s handles or dragging one (the brush cursor hides there) + pub(crate) fn hovered(ui: &Ui, rect: Rect, gizmo: Option<&ShownGizmo>) -> bool { + let ctx = ui.ctx(); + dragging::(ctx).is_some() + || dragging::(ctx).is_some() + || ctx.pointer_hover_pos().is_some_and(|hover| gizmo.is_some_and(|gizmo| gizmo.on_handle(rect, hover))) + } + + /// The gizmo over the 3D view + pub(crate) fn overlay(&self, app: &TextureCraftApp, ui: &Ui, rect: Rect) { + match self { + ShownGizmo::Frame(frame) => crate::frame_gizmo::overlay(ui, rect, frame), + ShownGizmo::Round(round) => crate::round_gizmo::overlay(app, ui, rect, round), + } + } +} diff --git a/crates/ui-egui/src/projector_outline.rs b/crates/ui-egui/src/projector_outline.rs new file mode 100644 index 00000000..ddd40e64 --- /dev/null +++ b/crates/ui-egui/src/projector_outline.rs @@ -0,0 +1,159 @@ +//! The projector a 3D projection's preview square draws round its object, as the 3D view's gizmo shows it round the model: a planar's frame with the dot its image travels to, a sphere's rim, equator and meridian, a tri-planar box or a cylinder + +use texturecraft_engine::compose::axis_frame::axis_frame; +use texturecraft_engine::compose::pattern::{cylinder_axis_index, decal_axes}; +use texturecraft_engine::core::Projection; +use texturecraft_engine::geom::glam::{Vec2, Vec3}; + +use crate::round_gizmo::{BOX_REACH, CIRCLE_POINTS, CYLINDER_HEIGHT, CYLINDER_REACH, SPHERE_REACH, box_corner, box_edges}; + +mod place; + +use place::Place; + +/// How far in front of the object a planar's frame stands (preview units) +const FRAME_GAP: f32 = 0.15; + +/// How far a planar's direction line reaches back from its frame (preview units) +const DIRECTION_LENGTH: f32 = 0.35; + +/// The projector's outline in the preview's coordinates (the compositor's: the mesh's centre at the origin, its half diagonal 1) +#[derive(Clone, Debug, Default, PartialEq)] +pub(crate) struct ProjectorOutline { + /// Polylines; a closed one repeats its first point at its end + pub lines: Vec>, + /// Where a planar's image travels to from its frame: the direction dot + pub tip: Option, + /// The projector's centre: a frame's middle, a round projector's centre + pub center: Vec3, +} + +impl ProjectorOutline { + /// The outline of `projection`'s projector round an object with half sizes `object` (None for projections without one: UV, warp, placed planars, which the preview shows as axis planars) + pub(crate) fn of(projection: &Projection, object: Vec3) -> Option { + let outline = match projection { + Projection::Planar { scale, axis, offset, projector, placed: None, .. } => { + // The compositor's coordinates as a mesh: centred, half diagonal 1, so each corner sits 1/√3 out along every axis + let corner = Vec3::splat(1.0 / 3f32.sqrt()); + let frame = axis_frame(*scale, *axis, Vec3::from(*offset), projector, (-corner, corner))?; + planar(frame.size, decal_axes(&frame)?, object) + } + Projection::Triplanar { scale, offset, projector, .. } => { + let place = Place::new(projector.rotation, projector.scale, Vec3::from(*offset), *scale); + let size = object * BOX_REACH; + let corner = |index: usize| place.world(place.local + size * box_corner(index)); + let lines = box_edges().map(|(first, second)| vec![corner(first), corner(second)]).collect(); + + ProjectorOutline { lines, tip: None, center: place.world(place.local) } + } + Projection::Spherical { offset, projector, .. } => { + let place = Place::new(projector.rotation, projector.scale, Vec3::from(*offset), 1.0); + let radius = object.max_element() * SPHERE_REACH; + let (u, v) = place.facing().any_orthonormal_pair(); + let ring = |a: Vec3, b: Vec3| circle(|t| place.world(place.local + (a * t.x + b * t.y) * radius)); + ProjectorOutline { lines: vec![ring(u, v), ring(Vec3::X, Vec3::Z), ring(Vec3::Y, Vec3::Z)], tip: None, center: place.world(place.local) } + } + Projection::Cylindrical { axis, offset, projector, .. } => { + let place = Place::new(projector.rotation, projector.scale, Vec3::from(*offset), 1.0); + let axis = cylinder_axis_index(*axis); + let along = Vec3::AXES[axis]; + let (u, v) = (Vec3::AXES[(axis + 1) % Vec3::AXES.len()], Vec3::AXES[(axis + 2) % Vec3::AXES.len()]); + let radius = (object * (Vec3::ONE - along)).max_element() * CYLINDER_REACH; + let half_height = object[axis] * CYLINDER_HEIGHT; + let cap = |height: f32| circle(|t| place.world(place.local + along * height + (u * t.x + v * t.y) * radius)); + let mut lines = vec![cap(half_height), cap(-half_height)]; + + // The two side lines, where the round side turns away from the camera + let facing = place.facing(); + if let Some(side) = along.cross(facing - along * facing.dot(along)).try_normalize() { + for edge in [side, -side] { + lines.push(vec![ + place.world(place.local + edge * radius + along * half_height), + place.world(place.local + edge * radius - along * half_height), + ]); + } + } + ProjectorOutline { lines, tip: None, center: place.world(place.local) } + } + Projection::Planar { placed: Some(_), .. } | Projection::Warp { .. } | Projection::Uv { .. } | Projection::UvTile => return None, + }; + let finite = outline.points().all(|point| point.is_finite()) && outline.center.is_finite(); + finite.then_some(outline) + } + + /// Every point the outline draws, the direction dot included + pub(crate) fn points(&self) -> impl Iterator + '_ { + self.lines.iter().flatten().copied().chain(self.tip) + } +} + +/// A planar's frame, `size` across and up on the frame `axes` (origin, across, up, out), stood just in front of the object on the side its image reads from, and the line its image travels along into the object +fn planar(size: [f32; 2], (origin, across, up, out): (Vec3, Vec3, Vec3, Vec3), object: Vec3) -> ProjectorOutline { + let center = origin + out * (object.max_element() + FRAME_GAP - origin.dot(out)); + let (across, up) = (across * size[0] / 2.0, up * size[1] / 2.0); + let corners = [center - across - up, center + across - up, center + across + up, center - across + up, center - across - up]; + let tip = center - out * DIRECTION_LENGTH; + ProjectorOutline { lines: vec![corners.to_vec(), vec![center, tip]], tip: Some(tip), center } +} + +/// A closed circle through `at` of the unit circle's points +fn circle(at: impl Fn(Vec2) -> Vec3) -> Vec { + (0..=CIRCLE_POINTS) + .map(|index| { + let angle = index as f32 / CIRCLE_POINTS as f32 * std::f32::consts::TAU; + at(Vec2::new(angle.cos(), angle.sin())) + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + use texturecraft_engine::core::{Projector, UvTransform}; + + const BALL: Vec3 = Vec3::splat(0.85); + + fn spherical(projector: Projector, offset: [f32; 3]) -> Projection { + Projection::Spherical { scale: 1.0, uv: UvTransform::default(), offset, projector } + } + + #[test] + fn every_3d_projection_has_its_projector_outline() { + let planar = Projection::Planar { scale: 1.0, axis: 2, offset: [0.0; 3], uv: UvTransform::default(), projector: Projector::default(), placed: None }; + let outline = ProjectorOutline::of(&planar, BALL).unwrap(); + assert_eq!(outline.lines.len(), 2, "a frame and its direction line"); + let tip = outline.tip.unwrap(); + assert!(tip.z < BALL.z + FRAME_GAP && outline.lines[0][0].z > BALL.z, "the frame stands in front of the ball, the dot points into it"); + + assert_eq!(ProjectorOutline::of(&spherical(Projector::default(), [0.0; 3]), BALL).unwrap().lines.len(), 3, "rim, equator, meridian"); + let cylinder = + Projection::Cylindrical { scale: 1.0, axis: 1, uv: UvTransform::default(), offset: [0.0; 3], projector: Projector::default(), angle: 360.0 }; + assert_eq!(ProjectorOutline::of(&cylinder, Vec3::new(0.55, 0.7, 0.55)).unwrap().lines.len(), 4, "two caps, two side lines"); + let triplanar = Projection::triplanar(); + assert_eq!(ProjectorOutline::of(&triplanar, Vec3::splat(0.55)).unwrap().lines.len(), 12, "a box's edges"); + assert!(ProjectorOutline::of(&Projection::UvTile, BALL).is_none()); + } + + #[test] + fn a_cylinder_axis_past_z_wraps_round_y_as_the_compositor_reads_it() { + let cylinder = |axis: u8| Projection::Cylindrical { + scale: 1.0, + axis, + uv: UvTransform::default(), + offset: [0.0; 3], + projector: Projector::default(), + angle: 360.0, + }; + let object = Vec3::new(0.55, 0.7, 0.4); + assert_eq!(ProjectorOutline::of(&cylinder(3), object), ProjectorOutline::of(&cylinder(1), object)); + } + + #[test] + fn the_outline_follows_the_projectors_size_and_centre() { + let reach = |projection: &Projection| ProjectorOutline::of(projection, BALL).unwrap().points().map(Vec3::length).fold(0.0, f32::max); + let plain = reach(&spherical(Projector::default(), [0.0; 3])); + assert!((plain - 0.85 * SPHERE_REACH).abs() < 1e-4, "{plain}"); + assert!((reach(&spherical(Projector { scale: [3.0; 3], ..Projector::default() }, [0.0; 3])) - 3.0 * plain).abs() < 1e-3, "x3 is three times as far"); + assert!(reach(&spherical(Projector::default(), [0.5, 0.0, 0.0])) > plain + 0.4, "an offset moves it"); + } +} diff --git a/crates/ui-egui/src/projector_outline/place.rs b/crates/ui-egui/src/projector_outline/place.rs new file mode 100644 index 00000000..9cf1d79a --- /dev/null +++ b/crates/ui-egui/src/projector_outline/place.rs @@ -0,0 +1,27 @@ +use texturecraft_engine::compose::pattern::nonzero_stretch; +use texturecraft_engine::geom::glam::{EulerRot, Mat3, Vec3}; + +/// A round projector's turn, stretch and centre: a point in its own units lands at `turn × (stretch × point)` (the gizmo's placement) +pub(super) struct Place { + pub(super) turn: Mat3, + pub(super) stretch: Vec3, + /// Its centre in its own units + pub(super) local: Vec3, +} + +impl Place { + /// `offset` moves the centre by `-offset / per_local` of its own units + pub(super) fn new(rotation: [f32; 3], scale: [f32; 3], offset: Vec3, per_local: f32) -> Place { + let [x, y, z] = rotation.map(f32::to_radians); + Place { turn: Mat3::from_euler(EulerRot::ZYX, z, y, x), stretch: Vec3::from(scale).map(nonzero_stretch), local: -offset / nonzero_stretch(per_local) } + } + + pub(super) fn world(&self, local: Vec3) -> Vec3 { + self.turn * (self.stretch * local) + } + + /// The preview camera's view direction in the projector's own units: the rim is the circle across it + pub(super) fn facing(&self) -> Vec3 { + (self.turn.transpose() * crate::projection_preview::view_direction() / self.stretch).try_normalize().unwrap_or(Vec3::Z) + } +} diff --git a/crates/ui-egui/src/round_gizmo.rs b/crates/ui-egui/src/round_gizmo.rs new file mode 100644 index 00000000..146cd50f --- /dev/null +++ b/crates/ui-egui/src/round_gizmo.rs @@ -0,0 +1,885 @@ +//! The selected tri-planar, spherical or cylindrical fill shows its projector round the whole model: a dashed box, sphere or cylinder with the centre square, X/Y/Z arrows and turn rings, and size handles: a dot scales it evenly (or a cylinder across its axis), a double arrow stretches it along one direction. Only a press on one of those handles moves it: any other drag paints or turns the camera + +use egui::{Color32, Pos2, Rect, Stroke, Ui}; +use serde_json::{Value, json}; +use texturecraft_engine::compose::pattern::{cylinder_axis_index, mesh_frame, nonzero_stretch, projector_stretch}; +use texturecraft_engine::core::Projection; +use texturecraft_engine::geom::glam::{EulerRot, Mat3, Quat, Vec2, Vec3}; +use texturecraft_engine::layer_cmds::signed_scale; + +use crate::TextureCraftApp; +use crate::frame_gizmo::{ + ARROW, EDGE_ON_FACING, HANDLE_EDGE, MIN_HANDLE_REACH, MIN_SCREEN_SPAN, TURN_RING, arrow_distance, center_distance, dashed_outline, distance_to_segment, + handle_dot, move_handles, nearest, ring_open, +}; +use crate::move_on_model::MoveOnModel; +use crate::projection_gizmo::{Gizmo, dragging}; +use crate::theme::{AXIS_COLORS, SHAFT_HALO, SHAFT_HALO_EXTRA_WIDTH, SHAFT_WIDTH, Tokens}; +use crate::viewport::{project, view_ray}; + +mod round_grab; +mod shape; +mod size_handle; + +pub(crate) use round_grab::RoundGrab; +use shape::Shape; +pub(crate) use size_handle::SizeHandle; + +/// The projector of the fill Move on model moves, as the 3D view shows it +#[derive(Clone, Debug)] +pub(crate) struct RoundGizmo { + pub(crate) target: MoveOnModel, + /// Mesh centre and radius: the projector reads positions around it in radii + mesh_center: Vec3, + radius: f32, + /// The projector's turn and per-axis scale (a mirrored axis keeps its sign, as the projection reads it) + turn: Mat3, + stretch: Vec3, + /// The projection's centre in the projector's units, and what offset puts it there (offset = -local × this) + local: Vec3, + offset_per_local: f32, + /// On screen: the centre, the arrow tips, the turn rings, the dashed outline and the size handles + pub center: Pos2, + pub arrows: [Option; 3], + pub rings: [Vec; 3], + outline: Vec>, + pub sizes: Vec, + /// Screen movement per world unit along each projector direction at the centre + steps: [Option; 3], +} + +/// How far round the model each shape reaches, in the mesh's half sizes: the box, the sphere, the cylinder's radius and half height +pub(crate) const BOX_REACH: f32 = 1.08; +pub(crate) const SPHERE_REACH: f32 = 1.2; +pub(crate) const CYLINDER_REACH: f32 = 1.1; +pub(crate) const CYLINDER_HEIGHT: f32 = 1.15; +/// The size dots' radius (points) +const SIZE_DOT: f32 = 7.0; +/// A size double arrow's half length, tip to middle, and its heads' length and half width (points) +const SIZE_ARROW: f32 = 12.0; +const SIZE_ARROW_HEAD: f32 = 7.0; +const SIZE_ARROW_HEAD_HALF_WIDTH: f32 = 5.0; +/// How far from the centre a box face's double arrow must land on screen to show: nearer, the face is seen head on and its arrow would sit on the centre square +const FACE_CLEARANCE: f32 = 40.0; +/// Points on a drawn circle +pub(crate) const CIRCLE_POINTS: usize = 48; +/// A box's corners, and the bit of a corner's index that flips it along each axis +const BOX_CORNERS: usize = 8; +const BOX_AXIS_BITS: [usize; 3] = [1, 2, 4]; +/// How far along each direction its screen step is measured, in mesh radii: half way out, inside the model, where perspective bends it little +const STEP_PROBE_RADII: f32 = 0.5; + +impl RoundGizmo { + /// The projector as the 3D view shows it: none while the Projection row's eye hides the projection gizmos + pub(crate) fn shown(app: &TextureCraftApp, rect: Rect) -> Option { + RoundGizmo::of(app, rect).filter(|_| app.session.doc.project.display.projection_gizmos) + } + + /// The projector of the selected tri-planar, spherical or cylindrical fill + pub(crate) fn of(app: &TextureCraftApp, rect: Rect) -> Option { + if app.ui.mode != crate::state::Mode::Painting { + return None; + } + + let target = MoveOnModel::selected(app)?; + let (shape, offset, projector, offset_per_local) = match target.projection(app)? { + Projection::Triplanar { scale, offset, projector, .. } => (Shape::Box, offset, projector, scale), + Projection::Spherical { offset, projector, .. } => (Shape::Sphere, offset, projector, 1.0), + Projection::Cylindrical { axis, offset, projector, .. } => (Shape::Cylinder(cylinder_axis_index(axis)), offset, projector, 1.0), + _ => return None, + }; + + let (lower, upper) = app.session.mesh.bounds(); + let (mesh_center, radius) = mesh_frame((lower, upper)); + let [x, y, z] = projector.rotation.map(f32::to_radians); + let turn = Mat3::from_euler(EulerRot::ZYX, z, y, x); + let stretch = projector_stretch(&projector); + let offset_per_local = nonzero_stretch(offset_per_local); + let local = -Vec3::from(offset) / offset_per_local; + let mut gizmo = RoundGizmo { + target, + mesh_center, + radius, + turn, + stretch, + local, + offset_per_local, + center: Pos2::ZERO, + arrows: [None; 3], + rings: Default::default(), + outline: Vec::new(), + sizes: Vec::new(), + steps: [None; 3], + }; + let origin = gizmo.world(local); + if !origin.is_finite() { + return None; + } + + gizmo.center = project(app, rect, origin)?; + gizmo.move_and_turn_handles(app, rect, origin)?; + + // The shape, sized round the mesh in the projector's units; a size handle past the view's edge waits at the edge, where it can be grabbed + let at = |point: Vec3| project(app, rect, mesh_center + turn * (stretch * point) * radius); + let view = rect.shrink(SIZE_ARROW); + let half = (upper - lower) * 0.5 / radius; + let forward = app.session.camera.forward(); + + // The view direction in the projector's units: what faces the camera there + let facing = (turn.transpose() * forward / stretch).try_normalize().unwrap_or(Vec3::Z); + match shape { + Shape::Box => gizmo.box_handles(at, half * BOX_REACH, forward, view), + Shape::Sphere => gizmo.sphere_handles(at, half.max_element() * SPHERE_REACH, facing, view), + Shape::Cylinder(axis) => gizmo.cylinder_handles(at, axis, half, facing, view), + } + Some(gizmo) + } + + /// The arrows along the projector's turned directions and the rings that turn round them, each ring seen too near edge on left out (empty: neither drawn nor grabbed) + fn move_and_turn_handles(&mut self, app: &TextureCraftApp, rect: Rect, origin: Vec3) -> Option<()> { + let center = self.center; + let directions = self.directions(); + let reach = self.radius * STEP_PROBE_RADII; + self.steps = directions.map(|direction| Some((project(app, rect, origin + direction * reach)? - center) / reach)); + self.arrows = self.steps.map(|step| step.filter(|step| step.length() * reach > MIN_SCREEN_SPAN).map(|step| center + step.normalized() * ARROW)); + + let right = app.session.camera.forward().cross(Vec3::Y).try_normalize().unwrap_or(Vec3::X); + let pixels = (project(app, rect, origin + right * reach)? - center).length() / reach; + let ring = TURN_RING / pixels.max(f32::MIN_POSITIVE); + self.rings = directions.map(|direction| { + if !ring_open(app, rect, center, direction) { + return Vec::new(); + } + + let (tangent, bitangent) = direction.any_orthonormal_pair(); + circle(|unit| project(app, rect, origin + (tangent * unit.x + bitangent * unit.y) * ring)) + }); + Some(()) + } + + /// A box of half size `size`: its edges, a dot on the corner up and right on screen that scales it evenly, and a double arrow on each face turned towards the camera that stretches it along that direction + fn box_handles(&mut self, at: impl Fn(Vec3) -> Option, size: Vec3, forward: Vec3, view: Rect) { + let local = self.local; + let corner = |index: usize| local + size * box_corner(index); + for (first_corner, second_corner) in box_edges() { + if let (Some(from), Some(to)) = (at(corner(first_corner)), at(corner(second_corner))) { + self.outline.push(vec![from, to]); + } + } + + let corners = (0..BOX_CORNERS).filter_map(|index| at(corner(index))); + if let Some(top_right) = corners.max_by(|first, second| (first.x - first.y).total_cmp(&(second.x - second.y))) { + self.sizes.push(SizeHandle { at: kept_in(view, top_right), axes: [true; 3], along: None }); + } + for (axis, direction) in self.directions().iter().enumerate() { + // The face toward the camera, on the other side in the projector's units when a mirrored axis flips it + let facing_side = if direction.dot(forward) > 0.0 { -1.0 } else { 1.0 }; + let toward = facing_side * self.stretch[axis].signum(); + let Some(face) = at(local + Vec3::AXES[axis] * size * toward) else { continue }; + let out = face - self.center; + if out.length() >= FACE_CLEARANCE { + self.sizes.push(SizeHandle { at: kept_in(view, face), axes: only_axis(axis), along: Some(out.normalized()) }); + } + } + } + + /// A sphere of `radius`: its silhouette across `facing` and its equator, and one dot on its right side (a sphere only scales evenly) + fn sphere_handles(&mut self, at: impl Fn(Vec3) -> Option, radius: f32, facing: Vec3, view: Rect) { + let local = self.local; + let (tangent, bitangent) = facing.any_orthonormal_pair(); + let silhouette = circle(|unit| at(local + (tangent * unit.x + bitangent * unit.y) * radius)); + if let Some(side) = silhouette.iter().copied().max_by(|first, second| first.x.total_cmp(&second.x)) { + self.sizes.push(SizeHandle { at: kept_in(view, side), axes: [true; 3], along: None }); + } + self.outline.push(silhouette); + self.outline.push(circle(|unit| at(local + Vec3::new(unit.x, 0.0, unit.y) * radius))); + } + + /// A cylinder round `axis` over a mesh of half sizes `half`: its caps and side lines, a double arrow on the top rim that stretches its height (seen end on, a dot) and a dot on its right side that scales it across (seen end on, on the rim's right) + fn cylinder_handles(&mut self, at: impl Fn(Vec3) -> Option, axis: usize, half: Vec3, facing: Vec3, view: Rect) { + let local = self.local; + let along = Vec3::AXES[axis]; + let (tangent, bitangent) = (Vec3::AXES[(axis + 1) % 3], Vec3::AXES[(axis + 2) % 3]); + let radius = (half * (Vec3::ONE - along)).max_element() * CYLINDER_REACH; + let half_height = half[axis] * CYLINDER_HEIGHT; + let cap = |height: f32| circle(|unit| at(local + along * height + (tangent * unit.x + bitangent * unit.y) * radius)); + let top = cap(half_height); + let along_axis = match (at(local + along * half_height), at(local - along * half_height)) { + (Some(top), Some(bottom)) => Some(top - bottom).filter(|span| span.length() > MIN_SCREEN_SPAN).map(egui::Vec2::normalized), + _ => None, + }; + if let Some(rim) = top.iter().copied().min_by(|first, second| first.y.total_cmp(&second.y)) { + self.sizes.push(SizeHandle { at: kept_in(view, rim), axes: only_axis(axis), along: along_axis }); + } + let right_of_rim = top.iter().copied().max_by(|first, second| first.x.total_cmp(&second.x)); + self.outline.extend([top, cap(-half_height)]); + + // The two side lines, where the round side turns away from the camera; seen end on there are none, and the dot sits on the rim's right + let side = along.cross(facing - along * facing.dot(along)).try_normalize(); + let mut sides = Vec::new(); + for edge in side.into_iter().flat_map(|side| [side, -side]) { + if let (Some(top), Some(bottom)) = (at(local + edge * radius + along * half_height), at(local + edge * radius - along * half_height)) { + self.outline.push(vec![top, bottom]); + sides.push(top.lerp(bottom, 0.5)); + } + } + let across_at = match side { + Some(_) => sides.into_iter().max_by(|first, second| first.x.total_cmp(&second.x)), + None => right_of_rim, + }; + if let Some(side) = across_at { + let mut across = [true; 3]; + across[axis] = false; + self.sizes.push(SizeHandle { at: kept_in(view, side), axes: across, along: None }); + } + } + + /// A point in the projector's units, in the world + fn world(&self, local: Vec3) -> Vec3 { + self.mesh_center + self.turn * (self.stretch * local) * self.radius + } + + /// The projector's turned X, Y and Z directions in the world + fn directions(&self) -> [Vec3; 3] { + Vec3::AXES.map(|axis| self.turn * axis) + } + + /// The `layer.fill.projection` params that slide the projector across the view from `from` to `to`, as its centre square does + pub(crate) fn slid(&self, app: &TextureCraftApp, rect: Rect, from: Pos2, to: Pos2) -> Option { + self.params(app, rect, RoundGrab::Slide, from, to) + } + + /// The `layer.fill.projection` params a drag of `grab` from `from` to `to` sets; only a size handle sets the scale, so a mirrored axis keeps its sign through a slide or turn + fn params(&self, app: &TextureCraftApp, rect: Rect, grab: RoundGrab, from: Pos2, to: Pos2) -> Option { + let origin = self.world(self.local); + let (turn, stretch, center) = match grab { + RoundGrab::Slide => { + let forward = app.session.camera.forward(); + let moved = on_view_plane(app, rect, origin, forward, to)? - on_view_plane(app, rect, origin, forward, from)?; + (self.turn, self.stretch, origin + moved) + } + RoundGrab::Axis(axis) => { + let step = (*self.steps.get(axis)?)?; + let distance = (to - from).dot(step) / step.length_sq().max(f32::MIN_POSITIVE); + (self.turn, self.stretch, origin + self.directions()[axis] * distance) + } + RoundGrab::Ring(axis) => { + let angle = (to - self.center).angle() - (from - self.center).angle(); + + // Seen from the side its direction points to, a turn runs the other way round on screen + let facing = self.directions()[axis].dot(app.session.camera.forward()); + let angle = if facing < 0.0 { -angle } else { angle }; + let turn = self.turn * Mat3::from_axis_angle(Vec3::AXES[axis], angle); + (turn, self.stretch, origin) + } + RoundGrab::Size(axes) => { + // How far the pointer went along the line from the centre through where the handle was grabbed (past the centre, none: a drag never flips it); the command keeps each axis's size in its limits on its own side, so does the offset worked out here + let reach = from - self.center; + let factor = ((to - self.center).dot(reach) / reach.length().max(MIN_HANDLE_REACH).powi(2)).max(0.0); + let stretch = Vec3::from(axes.map(|on| if on { factor } else { 1.0 })) * self.stretch; + (self.turn, stretch.map(signed_scale), origin) + } + }; + + // The centre stays where it was put: the offset follows the turn and scale + let local = turn.transpose() * ((center - self.mesh_center) / self.radius) / stretch; + let offset = -local * self.offset_per_local; + let (z, y, x) = Quat::from_mat3(&turn).to_euler(EulerRot::ZYX); + let rotation = [x, y, z].map(f32::to_degrees); + let values = [offset.to_array(), rotation, stretch.to_array()]; + if !values.iter().flatten().all(|value| value.is_finite()) { + return None; + } + + let mut params = self.target.target(); + params["offset"] = json!(offset.to_array()); + params["projectorRotation"] = json!(rotation); + if matches!(grab, RoundGrab::Size(_)) { + params["projectorScale"] = json!(stretch.to_array()); + } + Some(params) + } +} + +impl Gizmo for RoundGizmo { + type Grab = RoundGrab; + + fn drag_id() -> egui::Id { + egui::Id::unique("tc_round_drag") + } + + /// The handle under screen point `p`: the nearest one within reach (where rings cross, the nearest ring) + fn grab(&self, at: Pos2) -> Option { + let mut handles = vec![(RoundGrab::Slide, center_distance(self.center, at))]; + handles.extend((0..3).filter_map(|axis| Some((RoundGrab::Axis(axis), arrow_distance(at, self.center, self.arrows[axis]?))))); + handles.extend(self.sizes.iter().map(|size| (RoundGrab::Size(size.axes), size.distance(at)))); + let distance = |ring: &Vec| ring.windows(2).map(|pair| distance_to_segment(at, pair[0], pair[1])).fold(f32::INFINITY, f32::min); + handles.extend((0..3).map(|axis| (RoundGrab::Ring(axis), distance(&self.rings[axis])))); + nearest(handles) + } + + fn same_projection(&self, other: &RoundGizmo) -> bool { + self.target == other.target + } + + fn edit(&self, app: &TextureCraftApp, rect: Rect, grab: RoundGrab, from: Pos2, to: Pos2) -> Option<(&'static str, Value)> { + Some(("layer.fill.projection", self.params(app, rect, grab, from, to)?)) + } + + /// A size handle's resize cursor runs along its arrow + fn cursor(&self, grab: RoundGrab, dragging: bool) -> egui::CursorIcon { + match grab { + RoundGrab::Slide if dragging => egui::CursorIcon::Grabbing, + RoundGrab::Slide => egui::CursorIcon::Grab, + RoundGrab::Axis(_) | RoundGrab::Ring(_) => egui::CursorIcon::Move, + RoundGrab::Size(axes) => self.sizes.iter().find(|size| size.axes == axes).map_or(egui::CursorIcon::ResizeNeSw, SizeHandle::cursor), + } + } +} + +/// A size handle that stretches one way: a double arrow through `at` along `along`, `fill` over a dark halo like the axis arrows +fn size_arrow(painter: &egui::Painter, at: Pos2, along: egui::Vec2, fill: Color32) { + let side = along.rot90() * SIZE_ARROW_HEAD_HALF_WIDTH; + let shaft = [at - along * (SIZE_ARROW - SIZE_ARROW_HEAD), at + along * (SIZE_ARROW - SIZE_ARROW_HEAD)]; + painter.line_segment(shaft, Stroke::new(SHAFT_WIDTH + SHAFT_HALO_EXTRA_WIDTH, SHAFT_HALO)); + painter.line_segment(shaft, Stroke::new(SHAFT_WIDTH, fill)); + for direction in [along, -along] { + let base = at + direction * (SIZE_ARROW - SIZE_ARROW_HEAD); + painter.add(egui::Shape::convex_polygon(vec![at + direction * SIZE_ARROW, base + side, base - side], fill, HANDLE_EDGE)); + } +} + +/// Corner `index` of a box from -1 to 1: the index's three low bits pick its low (0) or high (1) side along X, Y and Z +pub(crate) fn box_corner(index: usize) -> Vec3 { + let side = |bit: usize| if index & bit == 0 { -1.0 } else { 1.0 }; + Vec3::new(side(BOX_AXIS_BITS[0]), side(BOX_AXIS_BITS[1]), side(BOX_AXIS_BITS[2])) +} + +/// A box's twelve edges as pairs of corner indices, each once: from a corner on an axis's low side to the corner across that axis +pub(crate) fn box_edges() -> impl Iterator { + (0..BOX_CORNERS).flat_map(|corner| BOX_AXIS_BITS.into_iter().filter(move |bit| corner & bit == 0).map(move |bit| (corner, corner | bit))) +} + +/// Which projector directions a handle along `axis` alone works on +fn only_axis(axis: usize) -> [bool; 3] { + let mut axes = [false; 3]; + axes[axis] = true; + axes +} + +/// `point` kept inside `view`, where a handle past its edge can still be grabbed +fn kept_in(view: Rect, point: Pos2) -> Pos2 { + point.clamp(view.min, view.max) +} + +/// A closed circle of screen points from `at` (given the unit circle's points); empty when a point is off screen +fn circle(at: impl Fn(Vec2) -> Option) -> Vec { + (0..=CIRCLE_POINTS) + .map(|index| { + let angle = index as f32 / CIRCLE_POINTS as f32 * std::f32::consts::TAU; + at(Vec2::new(angle.cos(), angle.sin())) + }) + .collect::>>() + .unwrap_or_default() +} + +/// Where screen point `p` meets the plane facing the camera through `origin` +fn on_view_plane(app: &TextureCraftApp, rect: Rect, origin: Vec3, forward: Vec3, p: Pos2) -> Option { + let ray = view_ray(app, rect, p); + let facing = ray.dir.dot(forward); + if facing.abs() < EDGE_ON_FACING { + return None; + } + + let hit = ray.origin + ray.dir * ((origin - ray.origin).dot(forward) / facing); + hit.is_finite().then_some(hit) +} + +/// The projector over the 3D view: dashed shape, rings, arrows, centre square and dots, the handle under the pointer lit +pub(crate) fn overlay(app: &TextureCraftApp, ui: &Ui, rect: Rect, gizmo: &RoundGizmo) { + let tokens = Tokens::get(ui.ctx()); + let painter = ui.painter_at(rect); + let active = dragging::(ui.ctx()).map(|drag| drag.grab); + + // A held Move on model button lights none + let hovered = ui.ctx().pointer_hover_pos().filter(|hover| rect.contains(*hover) && app.moving_on_model.is_none()).and_then(|hover| gizmo.grab(hover)); + let lit = |grab: RoundGrab| active == Some(grab) || (active.is_none() && hovered == Some(grab)); + let fill = |grab: RoundGrab| if lit(grab) { tokens.viewport_accent } else { Color32::WHITE }; + let axis_color = |axis: usize, grab: RoundGrab| if lit(grab) { tokens.viewport_accent } else { AXIS_COLORS[axis] }; + for line in &gizmo.outline { + dashed_outline(&painter, line); + } + for (axis, ring) in gizmo.rings.iter().enumerate() { + painter.add(egui::Shape::line(ring.clone(), Stroke::new(SHAFT_WIDTH + SHAFT_HALO_EXTRA_WIDTH, SHAFT_HALO))); + painter.add(egui::Shape::line(ring.clone(), Stroke::new(SHAFT_WIDTH, axis_color(axis, RoundGrab::Ring(axis))))); + } + for size in &gizmo.sizes { + let color = fill(RoundGrab::Size(size.axes)); + match size.along { + Some(along) => size_arrow(&painter, size.at, along, color), + None => handle_dot(&painter, size.at, SIZE_DOT, color), + } + } + move_handles(&painter, gizmo.center, gizmo.arrows, |axis| axis_color(axis, RoundGrab::Axis(axis)), fill(RoundGrab::Slide)); +} + +#[cfg(test)] +pub(crate) mod tests { + use egui::{Modifiers, PointerButton, vec2}; + use texturecraft_engine::core::{Fill, LayerId, LayerKind, Projection, Projector}; + + use super::*; + + fn gizmo(harness: &egui_kittest::Harness<'_, TextureCraftApp>) -> RoundGizmo { + RoundGizmo::of(harness.state(), harness.state().viewport_rect).unwrap() + } + + fn projector_and_offset(projection: &Projection) -> (Projector, [f32; 3]) { + match projection { + Projection::Triplanar { projector, offset, .. } + | Projection::Spherical { projector, offset, .. } + | Projection::Cylindrical { projector, offset, .. } => (*projector, *offset), + other => panic!("a round projection: {other:?}"), + } + } + + #[test] + fn round_projections_show_their_projector_while_their_fill_is_selected() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + for kind in ["triplanar", "spherical", "cylindrical"] { + let (mut harness, _) = fill_app(kind); + harness.run_steps(2); + let shown = gizmo(&harness); + assert!(shown.arrows.iter().all(Option::is_some) && shown.rings.iter().all(|ring| ring.len() > 8), "{kind}: arrows and rings {shown:?}"); + assert!(!shown.outline.is_empty(), "{kind}: its shape is drawn"); + + // A box's corner and a double arrow per face (the ball is seen from above and aside, no face head on); a sphere's one dot; a cylinder's top rim and side + let size_handles = match kind { + "triplanar" => 4, + "spherical" => 1, + _ => 2, + }; + assert_eq!(shown.sizes.len(), size_handles, "{kind}: size handles {:?}", shown.sizes); + } + let (harness, _) = fill_app("planar"); + assert!(RoundGizmo::of(harness.state(), harness.state().viewport_rect).is_none(), "planar projections show their frame instead"); + } + + #[test] + fn a_cylinder_axis_past_z_shows_round_y_as_the_compositor_wraps_it() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = fill_app_with(json!({"projection": "cylindrical", "axis": 1})); + let round_y = gizmo(&harness).outline; + + // A hand-edited project can store an axis past Z: no command writes one + let stored = &mut harness.state_mut().session.doc.project.layer_mut(layer).unwrap().kind; + let LayerKind::Fill(Fill { projection: Projection::Cylindrical { axis, .. }, .. }) = stored else { panic!("a cylindrical fill") }; + *axis = 3; + assert_eq!(gizmo(&harness).outline, round_y); + } + + #[test] + fn the_arrows_move_the_rings_turn_and_the_dots_scale_the_projector_one_step_per_drag() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = fill_app("spherical"); + let steps = harness.state().session.history_labels().len(); + + let start = gizmo(&harness); + let tip = start.arrows[0].unwrap(); + drag(&mut harness, tip, tip + (tip - start.center).normalized() * 30.0, Modifiers::NONE); + let (projector, offset) = projector_and_offset(&projection(&harness, layer)); + assert!(offset[0] < -0.05 && offset[1].abs() < 1e-3 && offset[2].abs() < 1e-3, "the X arrow moves the centre along X: {offset:?}"); + assert_eq!(projector.rotation, [0.0; 3]); + let moved = gizmo(&harness); + assert!(moved.center.x > start.center.x + 20.0, "the centre follows: {moved:?}"); + + // The Z ring (seen face on) turns it round Z; the centre stays where it is + let clear = |p: &&Pos2| moved.rings[..2].iter().flatten().map(|other| other.distance(**p)).fold(f32::INFINITY, f32::min); + let on_ring = *moved.rings[2].iter().max_by(|a, b| clear(a).total_cmp(&clear(b))).unwrap(); + assert_eq!(moved.grab(on_ring), Some(RoundGrab::Ring(2))); + drag(&mut harness, on_ring, moved.center + (on_ring - moved.center).rot90(), Modifiers::NONE); + let (turned, _) = projector_and_offset(&projection(&harness, layer)); + assert!(turned.rotation[2].abs() > 30.0 && turned.rotation[0].abs() < 1e-2, "{:?}", turned.rotation); + assert!(gizmo(&harness).center.distance(moved.center) < 1.0, "turning keeps the centre"); + + let scaling = gizmo(&harness); + let dot = scaling.sizes.iter().find(|size| size.axes == [true; 3]).expect("the even-scale dot").at; + let center = scaling.center; + assert_eq!(gizmo(&harness).grab(dot), Some(RoundGrab::Size([true; 3]))); + drag(&mut harness, dot, center + (dot - center) * 1.5, Modifiers::NONE); + let (scaled, _) = projector_and_offset(&projection(&harness, layer)); + assert!(scaled.scale.iter().all(|scale| (scale - 1.5).abs() < 0.05), "the side dot scales it evenly: {:?}", scaled.scale); + assert!(gizmo(&harness).center.distance(center) < 1.0, "scaling keeps the centre"); + assert_eq!(harness.state().session.history_labels().len(), steps + 3, "one undo step per drag"); + } + + #[test] + fn a_cylinders_top_dot_stretches_its_height_and_a_tri_planar_box_moves_by_its_texture_offset() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = fill_app("cylindrical"); + let cylinder = gizmo(&harness); + let height = cylinder.sizes.iter().find(|size| size.axes == [false, true, false]).expect("the height handle"); + let SizeHandle { at: top, axes, along } = *height; + assert_eq!(axes, [false, true, false], "the top handle works along the axis"); + let along = along.expect("the height handle is a double arrow"); + assert!(along.y.abs() > 0.99, "drawn upright, along the upright axis: {along:?}"); + assert_eq!(cylinder.cursor(RoundGrab::Size(axes), false), egui::CursorIcon::ResizeVertical); + drag(&mut harness, top, cylinder.center + (top - cylinder.center) * 0.5, Modifiers::NONE); + let (projector, _) = projector_and_offset(&projection(&harness, layer)); + assert!(projector.scale[1] < 0.7 && projector.scale[0] == 1.0 && projector.scale[2] == 1.0, "{:?}", projector.scale); + + let (mut harness, layer) = fill_app("triplanar"); + harness.state_mut().run("layer.fill.projection", json!({"layer": layer.0, "scale": 4})).unwrap(); + harness.run_steps(2); + let box_gizmo = gizmo(&harness); + drag(&mut harness, box_gizmo.center, box_gizmo.center + vec2(0.0, -30.0), Modifiers::NONE); + let (_, offset) = projector_and_offset(&projection(&harness, layer)); + assert!(offset[1] < -0.1 && offset[0].abs() < 0.05, "sliding up shifts the texture by the tiling: {offset:?}"); + assert!(gizmo(&harness).center.distance(box_gizmo.center + vec2(0.0, -30.0)) < 1.5, "the centre sits under the pointer"); + } + + /// Every drag on the projector shows in the panel the same frame: its Offset, Rotation and Scale fields hold the projector's values and the preview square re-renders, every frame of the drag; one undo step per drag + #[test] + fn the_panel_and_its_preview_follow_every_frame_of_a_projector_drag() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + for kind in ["spherical", "cylindrical"] { + let (mut harness, layer) = fill_app(kind); + let steps = harness.state().session.history_labels().len(); + let read = |harness: &egui_kittest::Harness<'_, TextureCraftApp>| { + let (projector, offset) = projector_and_offset(&projection(harness, layer)); + let (row_offset, row_rotation, row_scale) = (panel_xyz(harness, "Offset"), panel_xyz(harness, "Rotation"), panel_xyz(harness, "Scale")); + for (row, field, value) in + [("Offset", row_offset, offset), ("Rotation", row_rotation, projector.rotation), ("Scale", row_scale, projector.scale)] + { + for axis in 0..3 { + assert!((field[axis] - value[axis]).abs() < 1e-3, "{kind}: the panel's {row} shows the projector's {value:?}, not {field:?}"); + } + } + }; + + // A sphere's one dot scales it evenly, a cylinder's height arrow stretches it along its axis + let start = gizmo(&harness); + let axes = if kind == "spherical" { [true; 3] } else { [false, true, false] }; + let dot = start.sizes.iter().find(|size| size.axes == axes).unwrap_or_else(|| panic!("{kind}: its size handle {axes:?}")).at; + drag_frames(&mut harness, layer, dot, start.center + (dot - start.center) * 1.5, Modifiers::NONE, true, read); + let tip = gizmo(&harness).arrows[0].unwrap(); + let center = gizmo(&harness).center; + drag_frames(&mut harness, layer, tip, tip + (tip - center).normalized() * 30.0, Modifiers::NONE, true, read); + let turned = gizmo(&harness); + let clear = |p: &&Pos2| turned.rings[..2].iter().flatten().map(|other| other.distance(**p)).fold(f32::INFINITY, f32::min); + let on_ring = *turned.rings[2].iter().max_by(|a, b| clear(a).total_cmp(&clear(b))).unwrap(); + drag_frames(&mut harness, layer, on_ring, turned.center + (on_ring - turned.center).rot90(), Modifiers::NONE, true, read); + let (projector, _) = projector_and_offset(&projection(&harness, layer)); + assert!( + projector.scale.iter().copied().fold(0.0, f32::max) > 1.3 && projector.rotation[2].abs() > 30.0, + "{kind}: resized and turned: {projector:?}" + ); + assert_eq!(harness.state().session.history_labels().len(), steps + 3, "{kind}: one undo step per drag"); + } + } + + /// Whether a projector drag is under way + fn round_dragging(harness: &egui_kittest::Harness<'_, TextureCraftApp>) -> bool { + dragging::(&harness.ctx).is_some() + } + + /// Losing the focus mid-drag (Alt+Tab) ends a projector drag as a release does: one undo step, and moves after it (egui still has the button down) leave the projector alone + #[test] + fn losing_the_window_focus_ends_a_projector_drag() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = fill_app("spherical"); + let steps = harness.state().session.history_labels().len(); + let center = gizmo(&harness).center; + let to = center + vec2(40.0, 0.0); + press_and_move(&mut harness, center, to, Modifiers::NONE); + assert!(round_dragging(&harness), "the centre square is held"); + + harness.event(egui::Event::WindowFocused(false)); + harness.run_steps(1); + let left = projection(&harness, layer); + assert!(!round_dragging(&harness), "the focus loss ends the drag"); + assert_eq!(harness.state().session.history_labels().len(), steps + 1, "as one undo step"); + + for step in 1..=3 { + harness.event(egui::Event::PointerMoved(to + vec2(20.0, 10.0) * step as f32)); + harness.run_steps(1); + } + assert_eq!(projection(&harness, layer), left, "moves after it leave the projector where it was"); + } + + /// Alt pressed mid-drag hands the pointer to the camera and ends the projector drag where it is: let go of Alt with the button still down, the drag does not resume; one undo step + #[test] + fn alt_mid_drag_ends_a_projector_drag() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = fill_app("spherical"); + let steps = harness.state().session.history_labels().len(); + let center = gizmo(&harness).center; + let to = center + vec2(40.0, 0.0); + press_and_move(&mut harness, center, to, Modifiers::NONE); + let slid = projection(&harness, layer); + let camera = harness.state().session.camera; + + harness.event_modifiers(egui::Event::PointerMoved(to + vec2(20.0, 0.0)), Modifiers::ALT); + harness.run_steps(1); + assert_ne!(harness.state().session.camera, camera, "Alt turns the camera"); + assert!(!round_dragging(&harness), "and ends the projector drag"); + + for step in 2..=4 { + harness.event(egui::Event::PointerMoved(to + vec2(20.0, 5.0) * step as f32)); + harness.run_steps(1); + } + assert_eq!(projection(&harness, layer), slid, "Alt let go, the projector stays where the drag left it"); + harness.event(egui::Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(2); + assert_eq!(harness.state().session.history_labels().len(), steps + 1, "one undo step"); + } + + /// Seen edge on a ring is a line, whose screen-angle turn would jump half a turn across the centre: from straight in front (no yaw) the X ring is neither drawn nor grabbed while the Y and Z rings stay; turned aside, it opens and shows again + #[test] + fn a_ring_seen_edge_on_is_neither_drawn_nor_grabbed() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, _) = fill_app("spherical"); + harness.state_mut().session.camera.yaw = 0.0; + harness.run_steps(2); + + let front = gizmo(&harness); + assert!(front.rings[0].is_empty(), "the X ring seen edge on is left out: {:?}", front.rings[0]); + assert!(front.rings[1..].iter().all(|ring| !ring.is_empty()), "the Y and Z rings show"); + let on_the_line = front.center + vec2(0.0, 40.0); + assert_ne!(front.grab(on_the_line), Some(RoundGrab::Ring(0)), "a press where its line would be does not grab it"); + + harness.state_mut().session.camera.yaw = 0.5; + harness.run_steps(2); + assert!(gizmo(&harness).rings.iter().all(|ring| !ring.is_empty()), "turned aside, every ring shows"); + } + + /// A point on the model clear of every handle of the shown gizmo + pub(crate) fn on_the_model_off_the_handles(harness: &egui_kittest::Harness<'_, TextureCraftApp>) -> Pos2 { + let app = harness.state(); + let rect = app.viewport_rect; + let round = RoundGizmo::of(app, rect); + let frame = crate::frame_gizmo::FrameGizmo::of(app, rect); + let clear = |p: Pos2| { + round.as_ref().is_none_or(|gizmo| gizmo.grab(p).is_none()) + && frame.as_ref().is_none_or(|gizmo| gizmo.grab(p).is_none()) + && app.session.pick(texturecraft_engine::geom::glam::Vec2::new(p.x - rect.left(), p.y - rect.top()), app.session.viewport).is_some() + }; + (1..12) + .flat_map(|ring| (0..16).map(move |step| rect.center() + egui::Vec2::angled(step as f32 / 16.0 * std::f32::consts::TAU) * (ring as f32 * 14.0))) + .find(|p| clear(*p) && clear(*p + vec2(30.0, 0.0))) + .expect("the model shows past the handles") + } + + /// A sphere has one size handle (it only scales evenly); a tri-planar box scales evenly from its corner and along one direction from a face's double arrow + #[test] + fn a_sphere_scales_from_one_dot_and_a_tri_planar_box_from_its_corner_and_faces() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = fill_app("spherical"); + let start = gizmo(&harness); + assert_eq!(start.sizes.len(), 1, "one dot: {:?}", start.sizes); + let dot = start.sizes[0].at; + assert_eq!(start.grab(dot), Some(RoundGrab::Size([true; 3]))); + drag(&mut harness, dot, start.center + (dot - start.center) * 1.4, Modifiers::NONE); + let (scaled, _) = projector_and_offset(&projection(&harness, layer)); + assert!(scaled.scale.iter().all(|scale| (scale - 1.4).abs() < 0.08), "it scales evenly: {:?}", scaled.scale); + + let (mut harness, layer) = fill_app("triplanar"); + let start = gizmo(&harness); + let corner = start.sizes.iter().find(|size| size.axes == [true; 3]).expect("a corner dot").at; + drag(&mut harness, corner, start.center + (corner - start.center) * 1.25, Modifiers::NONE); + let (scaled, _) = projector_and_offset(&projection(&harness, layer)); + assert!(scaled.scale.iter().all(|scale| (scale - 1.25).abs() < 0.05), "the corner scales it evenly: {:?}", scaled.scale); + assert!(gizmo(&harness).center.distance(start.center) < 1.0, "scaling keeps the centre"); + + let box_gizmo = gizmo(&harness); + let across = *box_gizmo.sizes.iter().find(|size| size.axes == [true, false, false]).expect("an X face arrow"); + assert!(across.along.is_some_and(|along| along.x.abs() > 0.95), "it points across: {across:?}"); + assert_eq!( + box_gizmo.grab(across.at + across.along.unwrap_or_default() * (SIZE_ARROW - 1.0)), + Some(RoundGrab::Size([true, false, false])), + "grabbed from its tip" + ); + drag(&mut harness, across.at, box_gizmo.center + (across.at - box_gizmo.center) * 0.5, Modifiers::NONE); + let (stretched, _) = projector_and_offset(&projection(&harness, layer)); + assert!((stretched.scale[0] - scaled.scale[0] * 0.5).abs() < 0.05, "the X face halves it across: {:?}", stretched.scale); + assert!( + (stretched.scale[1] - scaled.scale[1]).abs() < 1e-4 && (stretched.scale[2] - scaled.scale[2]).abs() < 1e-4, + "and only across: {:?}", + stretched.scale + ); + } + + /// A projector a project file mirrors along X (a negative scale, as the projection reads it) reads mirrored in the gizmo and stays mirrored through a slide, a move along an arrow, a turn and a resize + #[test] + fn a_mirrored_projector_keeps_its_mirror_through_every_handle() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = fill_app("spherical"); + let mirrored = [-1.0, 1.0, 1.0]; + match &mut harness.state_mut().session.doc.project.layer_mut(layer).unwrap().kind { + texturecraft_engine::core::LayerKind::Fill(fill) => match &mut fill.projection { + Projection::Spherical { projector, .. } => projector.scale = mirrored, + other => panic!("a spherical projection: {other:?}"), + }, + other => panic!("a fill layer: {other:?}"), + } + harness.run_steps(2); + + let start = gizmo(&harness); + assert_eq!(start.stretch, Vec3::from(mirrored), "the gizmo reads the mirror as the projection does"); + drag(&mut harness, start.center, start.center + vec2(30.0, -20.0), Modifiers::NONE); + let (slid, offset) = projector_and_offset(&projection(&harness, layer)); + assert_eq!(slid.scale, mirrored, "a slide keeps the mirror"); + assert!(offset.iter().any(|axis| axis.abs() > 0.05), "and slides it: {offset:?}"); + + let tip = gizmo(&harness).arrows[1].unwrap(); + let center = gizmo(&harness).center; + drag(&mut harness, tip, tip + (tip - center).normalized() * 20.0, Modifiers::NONE); + assert_eq!(projector_and_offset(&projection(&harness, layer)).0.scale, mirrored, "so does a move along an arrow"); + + let before_turn = projector_and_offset(&projection(&harness, layer)).0; + let ring = gizmo(&harness).rings[2].clone(); + drag(&mut harness, ring[CIRCLE_POINTS / 8], ring[CIRCLE_POINTS / 8 + 3], Modifiers::NONE); + let turned = projector_and_offset(&projection(&harness, layer)).0; + assert_ne!(turned.rotation, before_turn.rotation, "the ring turns it"); + assert_eq!(turned.scale, mirrored, "and keeps the mirror"); + + let resized = gizmo(&harness); + let dot = resized.sizes.iter().find(|size| size.axes == [true; 3]).expect("the even-scale dot").at; + drag(&mut harness, dot, resized.center + (dot - resized.center) * 1.5, Modifiers::NONE); + let scale = projector_and_offset(&projection(&harness, layer)).0.scale; + let expected = [-1.5, 1.5, 1.5]; + assert!(scale.iter().zip(expected).all(|(axis, wanted)| (axis - wanted).abs() < 1e-3), "a resize scales it evenly, still mirrored: {scale:?}"); + } + + /// A box mirrored along X (a negative scale from a project file) keeps its X double arrow on the face toward the camera, where the unmirrored box shows it + #[test] + fn a_mirrored_box_keeps_its_face_arrow_toward_the_camera() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = fill_app("triplanar"); + let x_face_arrow = |harness: &egui_kittest::Harness<'_, TextureCraftApp>| { + gizmo(harness).sizes.iter().find(|size| size.axes == [true, false, false]).map(|size| size.at) + }; + let unmirrored = x_face_arrow(&harness).expect("an X face arrow"); + match &mut harness.state_mut().session.doc.project.layer_mut(layer).unwrap().kind { + LayerKind::Fill(fill) => match &mut fill.projection { + Projection::Triplanar { projector, .. } => projector.scale = [-1.0, 1.0, 1.0], + other => panic!("a tri-planar projection: {other:?}"), + }, + other => panic!("a fill layer: {other:?}"), + } + harness.run_steps(2); + + let mirrored = x_face_arrow(&harness).expect("the mirrored box's X face arrow"); + assert!(mirrored.distance(unmirrored) < 0.5, "the arrow stays on the near face: {mirrored:?}, unmirrored {unmirrored:?}"); + } + + /// The pointer over a handle shows what it does only while the gizmo takes input: with Alt held the camera orbits, and the handle's cursor is not shown + #[test] + fn alt_over_a_handle_shows_no_handle_cursor() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, _) = fill_app("triplanar"); + let center = gizmo(&harness).center; + harness.hover_at(center); + harness.run_steps(2); + assert_eq!(harness.output().platform_output.cursor_icon, egui::CursorIcon::Grab, "the centre square shows it slides"); + + harness.event(egui::Event::ModifiersChanged(Modifiers::ALT)); + harness.event(egui::Event::PointerMoved(center + vec2(1.0, 0.0))); + harness.run_steps(2); + assert_ne!(harness.output().platform_output.cursor_icon, egui::CursorIcon::Grab, "with Alt held it does not"); + harness.event(egui::Event::ModifiersChanged(Modifiers::NONE)); + harness.run_steps(2); + } + + /// A tri-planar fill selected while the quick mask is edited with the Paint tool: brushes act and the projector shows + fn quick_mask_paint_app() -> (egui_kittest::Harness<'static, TextureCraftApp>, LayerId) { + let (mut harness, layer) = fill_app("triplanar"); + harness.state_mut().run("viewport.quickMask", json!({"enabled": true})).unwrap(); + harness.state_mut().run("viewport.quickMask.edit", json!({"editing": true})).unwrap(); + harness.state_mut().session.tool.tool = texturecraft_engine::Tool::Paint; + harness.run_steps(2); + assert!(gizmo(&harness).sizes.len() > 1, "the projector shows"); + (harness, layer) + } + + /// A Ctrl+drag that starts on a handle changes the brush only: the projector stays where it is + #[test] + fn a_ctrl_drag_on_a_handle_changes_the_brush_and_not_the_projection() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = quick_mask_paint_app(); + let before = projection(&harness, layer); + let flow = harness.state().session.tool.brush.flow; + let center = gizmo(&harness).center; + + harness.event(egui::Event::ModifiersChanged(Modifiers::COMMAND)); + drag(&mut harness, center, center + vec2(-40.0, 0.0), Modifiers::COMMAND); + harness.event(egui::Event::ModifiersChanged(Modifiers::NONE)); + harness.run_steps(2); + assert_ne!(harness.state().session.tool.brush.flow, flow, "the drag changes the brush"); + assert_eq!(projection(&harness, layer), before, "and leaves the projection"); + } + + /// A press on a handle's edge that drifts just off it before release (still a click) is the handle's: it paints no dab + #[test] + fn a_click_that_drifts_off_a_handle_paints_nothing() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, _) = quick_mask_paint_app(); + let shown = gizmo(&harness); + let rect = harness.state().viewport_rect; + let on_model = |p: Pos2| { + harness + .state() + .session + .pick(texturecraft_engine::geom::glam::Vec2::new(p.x - rect.left(), p.y - rect.top()), harness.state().session.viewport) + .is_some() + }; + let drift = 2.0; + + // The centre square's last point along some direction whose point a drift further is off every handle and on the model + let (edge, off) = (0..16) + .filter_map(|step| { + let toward = egui::Vec2::angled(step as f32 / 16.0 * std::f32::consts::TAU); + let edge = (0..200).map(|half| shown.center + toward * (half as f32 * 0.5)).take_while(|p| shown.grab(*p).is_some()).last()?; + let off = edge + toward * drift; + (shown.grab(off).is_none() && on_model(off)).then_some((edge, off)) + }) + .next() + .expect("a handle edge on the model"); + let click = |harness: &mut egui_kittest::Harness<'_, TextureCraftApp>, from: Pos2, to: Pos2| { + harness.hover_at(from); + harness.run_steps(1); + harness.event(egui::Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(1); + harness.event(egui::Event::PointerMoved(to)); + harness.run_steps(1); + harness.event(egui::Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(2); + }; + + let painted = harness.state().session.quick_mask.revision; + click(&mut harness, edge, off); + assert_eq!(harness.state().session.quick_mask.revision, painted, "a press that began on the handle paints no dab"); + + // The same click a little past the handle paints + click(&mut harness, off, off + (off - edge)); + assert_ne!(harness.state().session.quick_mask.revision, painted, "a press off the handle paints"); + } + + /// A cylinder seen straight down its axis keeps the dot that scales it across, on its rim's right + #[test] + fn a_cylinder_seen_end_on_keeps_its_across_dot() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = fill_app_with(json!({"projection": "cylindrical", "axis": 2})); + harness.state_mut().session.camera.yaw = 0.0; + harness.state_mut().session.camera.pitch = 0.0; + harness.run_steps(2); + + let end_on = gizmo(&harness); + let across = [true, true, false]; + let dot = end_on.sizes.iter().find(|size| size.axes == across).unwrap_or_else(|| panic!("the across dot: {:?}", end_on.sizes)).at; + assert_eq!(end_on.grab(dot), Some(RoundGrab::Size(across))); + drag(&mut harness, dot, end_on.center + (dot - end_on.center) * 1.5, Modifiers::NONE); + let (projector, _) = projector_and_offset(&projection(&harness, layer)); + assert!(projector.scale[0] > 1.2 && projector.scale[1] > 1.2 && projector.scale[2] == 1.0, "it scales across only: {:?}", projector.scale); + } +} diff --git a/crates/ui-egui/src/round_gizmo/round_grab.rs b/crates/ui-egui/src/round_gizmo/round_grab.rs new file mode 100644 index 00000000..321c7b20 --- /dev/null +++ b/crates/ui-egui/src/round_gizmo/round_grab.rs @@ -0,0 +1,12 @@ +/// What a drag on the projector does +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) enum RoundGrab { + /// The centre square: slide it across the view + Slide, + /// Along the projector's X (0), Y (1) or Z (2) direction + Axis(usize), + /// Turn it round its X, Y or Z direction + Ring(usize), + /// A size dot: scale it along the directions marked + Size([bool; 3]), +} diff --git a/crates/ui-egui/src/round_gizmo/shape.rs b/crates/ui-egui/src/round_gizmo/shape.rs new file mode 100644 index 00000000..3cd4ebd8 --- /dev/null +++ b/crates/ui-egui/src/round_gizmo/shape.rs @@ -0,0 +1,8 @@ +/// Which shape the projector shows +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) enum Shape { + Box, + Sphere, + /// Round the axis 0, 1 or 2 + Cylinder(usize), +} diff --git a/crates/ui-egui/src/round_gizmo/size_handle.rs b/crates/ui-egui/src/round_gizmo/size_handle.rs new file mode 100644 index 00000000..f2f3c57f --- /dev/null +++ b/crates/ui-egui/src/round_gizmo/size_handle.rs @@ -0,0 +1,33 @@ +use egui::Pos2; + +use super::SIZE_ARROW; +use crate::frame_gizmo::distance_to_segment; + +/// A handle that resizes the projector +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct SizeHandle { + pub at: Pos2, + /// The projector directions it scales + pub axes: [bool; 3], + /// A double arrow's direction on screen; None for a dot + pub along: Option, +} + +impl SizeHandle { + /// How far screen point `p` is from the handle (a double arrow: from anywhere along it) + pub(super) fn distance(&self, p: Pos2) -> f32 { + match self.along { + Some(along) => distance_to_segment(p, self.at - along * SIZE_ARROW, self.at + along * SIZE_ARROW), + None => self.at.distance(p), + } + } + + /// The resize cursor along its arrow, or a diagonal one for a dot + pub(super) fn cursor(&self) -> egui::CursorIcon { + match self.along { + Some(along) if along.y.abs() >= along.x.abs() => egui::CursorIcon::ResizeVertical, + Some(_) => egui::CursorIcon::ResizeHorizontal, + None => egui::CursorIcon::ResizeNeSw, + } + } +}