Skip to content
108 changes: 108 additions & 0 deletions crates/engine/src/camera_cmds.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,23 @@ pub fn specs() -> Vec<CommandSpec> {
cmd!("camera.bookmark7", "Go to camera 7", ["Viewport"], Some("Ctrl+7"), "{}", always, |s, _| bookmark(s, 6)),
cmd!("camera.bookmark8", "Go to camera 8", ["Viewport"], Some("Ctrl+8"), "{}", always, |s, _| bookmark(s, 7)),
cmd!("camera.bookmark9", "Go to camera 9", ["Viewport"], Some("Ctrl+9"), "{}", always, |s, _| bookmark(s, 8)),
cmd!(
"camera.view",
"Fixed view",
[],
None,
"{view: front|back|left|right|top|bottom} → the camera (looks at the mesh from that side and frames it; the projection stays)",
always,
|s, p| fixed_view(s, strp(p, "view").ok_or_else(|| bad("camera.view", "`view` is required"))?)
),
cmd!("camera.view.front", "Front view", ["Viewport"], None, "{}", always, |s, _| fixed_view(s, "front")),
cmd!("camera.view.back", "Back view", ["Viewport"], None, "{}", always, |s, _| fixed_view(s, "back")),
cmd!("camera.view.left", "Left view", ["Viewport"], None, "{}", always, |s, _| fixed_view(s, "left")),
cmd!("camera.view.right", "Right view", ["Viewport"], None, "{}", always, |s, _| fixed_view(s, "right")),
cmd!("camera.view.top", "Top view", ["Viewport"], None, "{}", always, |s, _| fixed_view(s, "top")),
cmd!("camera.view.bottom", "Bottom view", ["Viewport"], None, "{}", always, |s, _| fixed_view(s, "bottom")),
cmd!("camera.perspective", "Perspective", ["Viewport"], Some("F5"), "{}", always, |s, _| projection(s, false)),
cmd!("camera.orthographic", "Orthographic", ["Viewport"], Some("F6"), "{}", always, |s, _| projection(s, true)),
cmd!("viewport.focusAt", "Focus depth of field here", [], None, "{x, y (viewport pixels), viewport?: [w, h]}", always, focus_at),
]
}
Expand Down Expand Up @@ -141,6 +158,31 @@ fn select(s: &mut Session, p: &Value) -> Result<Value> {
Ok(crate::view_cmds::camera_json(s))
}

/// The fixed views: name, yaw and pitch in degrees. Yaw 0 puts the eye on +Z (the front), yaw 90
/// on +X (the right side); top and bottom stop at the orbit's ±89° pitch limit.
pub const VIEWS: [(&str, f32, f32); 6] =
[("front", 0.0, 0.0), ("back", 180.0, 0.0), ("left", -90.0, 0.0), ("right", 90.0, 0.0), ("top", 0.0, 89.0), ("bottom", 0.0, -89.0)];

/// Look at the mesh from fixed view `name` and frame it, keeping the projection. The yaw is the
/// one nearest the current yaw, so the desktop UI's glide takes the short way round.
fn fixed_view(s: &mut Session, name: &str) -> Result<Value> {
let Some(&(_, yaw, pitch)) = VIEWS.iter().find(|(view, ..)| *view == name) else {
return Err(bad("camera.view", format!("unknown view `{name}`: one of front, back, left, right, top, bottom")));
};
let current = if s.camera.yaw.is_finite() { s.camera.yaw } else { 0.0 };
let turn = std::f32::consts::TAU;
s.camera.yaw = current + (yaw.to_radians() - current + turn * 0.5).rem_euclid(turn) - turn * 0.5;
s.camera.pitch = pitch.to_radians();
crate::execute(s, "viewport.frame", &Value::Null)
}

/// Switch to a perspective or orthographic projection; position and rotation stay.
fn projection(s: &mut Session, ortho: bool) -> Result<Value> {
s.camera.ortho = ortho;
s.revision = s.revision.wrapping_add(1);
Ok(crate::view_cmds::camera_json(s))
}

/// Shortcut slot `slot` (0-based): the n-th saved camera, in list order.
fn bookmark(s: &mut Session, slot: usize) -> Result<Value> {
if slot >= s.doc.project.cameras.len() {
Expand Down Expand Up @@ -238,6 +280,72 @@ mod tests {
assert!(ids.iter().all(|c| c.shortcut.is_some()));
}

#[test]
fn fixed_views_look_from_their_side_frame_the_mesh_and_keep_the_projection() {
let mut s = session();
execute(&mut s, "camera.set", &json!({"yaw": 37, "pitch": 21, "distance": 9, "target": [0.4, -0.3, 0.2]})).unwrap();
let (lo, hi) = s.mesh.bounds();
let mut framed = s.camera;
framed.frame(lo, hi);
let sides = [("front", Vec3::Z), ("back", Vec3::NEG_Z), ("left", Vec3::NEG_X), ("right", Vec3::X), ("top", Vec3::Y), ("bottom", Vec3::NEG_Y)];
for ortho in [false, true] {
execute(&mut s, "camera.set", &json!({"ortho": ortho})).unwrap();
for (view, side) in sides {
// Through the parameterized command and through the menu command alike
let menu_id = format!("camera.view.{view}");
for (id, params) in [("camera.view", json!({"view": view})), (menu_id.as_str(), Value::Null)] {
execute(&mut s, "camera.orbit", &json!({"dx": 123, "dy": 17})).unwrap();
let back = execute(&mut s, id, &params).unwrap();
let looking_from = (s.camera.eye() - s.camera.target).normalize();
assert!(looking_from.dot(side) > 0.999, "{id} {view}: the eye is on the {side} side, not at {looking_from}");
assert_eq!(s.camera.ortho, ortho, "{id} {view} keeps the projection");
assert!((s.camera.target - framed.target).length() < 1e-5, "{view} centres the mesh");
assert!((s.camera.distance - framed.distance).abs() < 1e-4, "{view} frames the mesh");
assert_eq!(back["ortho"], ortho);
}
}
}
// Orbit still works from a fixed view, and a view is not an undo step.
let steps = s.history_labels().len();
execute(&mut s, "camera.view.top", &Value::Null).unwrap();
assert!((s.camera.pitch - 89f32.to_radians()).abs() < 1e-6, "top stops at the orbit limit");
execute(&mut s, "camera.orbit", &json!({"dx": 30, "dy": -40})).unwrap();
assert!((s.camera.pitch - 49f32.to_radians()).abs() < 1e-5 && s.camera.yaw.to_degrees().rem_euclid(360.0) > 1.0);
assert_eq!(s.history_labels().len(), steps);
}

#[test]
fn fixed_views_take_the_nearest_turn_and_reject_unknown_views() {
let mut s = session();
execute(&mut s, "camera.set", &json!({"yaw": 715})).unwrap();
execute(&mut s, "camera.view", &json!({"view": "front"})).unwrap();
assert!((s.camera.yaw - 720f32.to_radians()).abs() < 1e-4, "two whole turns, not a spin back to 0: {}", s.camera.yaw.to_degrees());
let before = s.camera;
assert!(execute(&mut s, "camera.view", &json!({"view": "sideways"})).is_err());
assert!(execute(&mut s, "camera.view", &json!({})).is_err(), "`view` is required");
assert!(execute(&mut s, "camera.view", &json!({"view": 3})).is_err());
assert_eq!(s.camera, before, "a rejected view leaves the camera");
let menu: Vec<_> = crate::command_specs().iter().filter(|c| c.id.starts_with("camera.view.")).collect();
assert_eq!(menu.len(), 6);
assert!(menu.iter().all(|c| c.shortcut.is_none() && c.menu == ["Viewport"]), "no default keys: users bind their own");
}

#[test]
fn perspective_and_orthographic_change_only_the_projection() {
let mut s = session();
execute(&mut s, "camera.set", &json!({"yaw": 30, "pitch": 10, "distance": 4})).unwrap();
let before = s.camera;
let r = execute(&mut s, "camera.orthographic", &Value::Null).unwrap();
assert!(s.camera.ortho && r["ortho"] == true);
assert_eq!(OrbitCamera { ortho: false, ..s.camera }, before, "position and rotation stay");
execute(&mut s, "camera.orthographic", &Value::Null).unwrap();
assert!(s.camera.ortho, "a second press keeps it orthographic: two actions, not a toggle");
execute(&mut s, "camera.perspective", &Value::Null).unwrap();
assert_eq!(s.camera, before);
let key = |id: &str| crate::find(id).and_then(|c| c.shortcut);
assert_eq!((key("camera.perspective"), key("camera.orthographic")), (Some("F5"), Some("F6")));
}

#[test]
fn cameras_round_trip_through_the_project_file() {
let mut s = session();
Expand Down
9 changes: 8 additions & 1 deletion crates/ui-egui/src/control.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,8 +95,15 @@ pub fn handle(app: &mut TextureCraftApp, ctx: &egui::Context, method: &str, p: &
"command.run" => {
let Some(id) = p.get("id").and_then(Value::as_str) else { return err("`id` is required") };
let params = p.get("params").cloned().unwrap_or(Value::Null);
let before = app.session.camera;
match texturecraft_engine::execute(&mut app.session, id, &params) {
Ok(v) => ok(v),
Ok(v) => {
// A command that moved the camera takes over from a glide in progress, which would put it back
if app.session.camera != before {
app.camera_glide = None;
}
ok(v)
}
Err(e) => err(e),
}
}
Expand Down
5 changes: 3 additions & 2 deletions crates/ui-egui/src/keymap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -529,10 +529,11 @@ mod tests {
#[test]
fn a_stored_shortcut_replaces_the_default_and_an_empty_one_unbinds() {
let mut keymap = Keymap::new();
keymap.insert("file.save".into(), "F5".into());
// F7 is bound to nothing else, so the stored shortcut alone decides (F5 is Perspective)
keymap.insert("file.save".into(), "F7".into());
keymap.insert("edit.undo".into(), String::new());
let resolved = bindings_for(&keymap);
assert_eq!(resolved.command_of(&press(Key::F5, Modifiers::NONE)).as_deref(), Some("file.save"));
assert_eq!(resolved.command_of(&press(Key::F7, Modifiers::NONE)).as_deref(), Some("file.save"));
assert_eq!(resolved.command_of(&press(Key::S, Modifiers::COMMAND)), None);
assert_eq!(resolved.command_of(&press(Key::Z, Modifiers::COMMAND)), None);
}
Expand Down
27 changes: 22 additions & 5 deletions crates/ui-egui/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,8 @@ pub struct TextureCraftApp {
pub session: Session,
/// A smooth move to a saved camera in progress.
camera_glide: Option<CameraGlide>,
/// Yaw and pitch an Alt+Shift drag has reached before snapping to 90° steps (see `viewport`).
orbit_snap: Option<(f32, f32)>,
pub ui: UiState,
/// Where `ui` is saved between runs
ui_store: ui_state_store::UiStateStore,
Expand Down Expand Up @@ -225,6 +227,7 @@ impl TextureCraftApp {

let mut app = TextureCraftApp {
camera_glide: None,
orbit_snap: None,
session,
ui,
ui_store,
Expand Down Expand Up @@ -295,17 +298,31 @@ impl TextureCraftApp {
pub fn run(&mut self, id: &str, params: Value) -> Option<Value> {
self.ui.prefs.apply_resource_limits();

// Going to a saved camera glides there; the control channel and CLI jump straight away
let glide_from = (id.starts_with("camera.select") || id.starts_with("camera.bookmark")).then_some(self.session.camera);
// Going to a saved camera or a fixed view glides there; the control channel and CLI jump straight away
let glides = id.starts_with("camera.select") || id.starts_with("camera.bookmark") || id.starts_with("camera.view");
Comment thread
vangel76 marked this conversation as resolved.
Resolved
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
let glide_from = glides.then_some(self.session.camera);
match texturecraft_engine::execute(&mut self.session, id, &params) {
Ok(v) => {
// A pending dialog must not import its old source into the replacement project
if matches!(id, "file.open" | "file.close" | "project.new" | "project.sample") {
self.pbr_import = None;
}
if let Some(from) = glide_from.filter(|f| *f != self.session.camera) {
self.camera_glide = Some(CameraGlide { from, to: self.session.camera, start: self.last_time });
self.session.camera = from;
match glide_from {
Some(from) if from != self.session.camera => {
self.camera_glide = Some(CameraGlide { from, to: self.session.camera, start: self.last_time });
Comment thread
vangel76 marked this conversation as resolved.
Resolved
self.session.camera = from;
}
// Already at the destination: drop a glide an earlier command in the same frame started
Some(_) => self.camera_glide = None,
None => {}
}

// The glide would put back the projection it recorded, so it follows the switch
if matches!(id, "camera.perspective" | "camera.orthographic")
&& let Some(glide) = &mut self.camera_glide
{
glide.from.ortho = self.session.camera.ortho;
glide.to.ortho = self.session.camera.ortho;
}
Some(v)
}
Expand Down
11 changes: 11 additions & 0 deletions crates/ui-egui/src/menus.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,15 @@ pub const CATALOG: &[Item] = &[
it("Viewport", "UV checker", "ui.uvChecker", None),
sep("Viewport"),
it("Viewport", "Show entire mesh", "viewport.frame", Some("F")),
it("Viewport", "Front view", "camera.view.front", None),
it("Viewport", "Back view", "camera.view.back", None),
it("Viewport", "Left view", "camera.view.left", None),
it("Viewport", "Right view", "camera.view.right", None),
it("Viewport", "Top view", "camera.view.top", None),
it("Viewport", "Bottom view", "camera.view.bottom", None),
sep("Viewport"),
it("Viewport", "Perspective", "camera.perspective", Some("F5")),
it("Viewport", "Orthographic", "camera.orthographic", Some("F6")),
sep("Viewport"),
it("Viewport", "3D/2D views", "ui.layout.split", Some("F1")),
it("Viewport", "3D view only", "ui.layout.3d", Some("F2")),
Expand Down Expand Up @@ -256,6 +265,8 @@ fn menu_item(app: &mut TextureCraftApp, ctx: &egui::Context, ui: &mut egui::Ui,
"ui.mode.paint" => Some(app.ui.mode == Mode::Painting),
"ui.mode.bake" => Some(app.ui.mode == Mode::Baking),
"ui.mode.render" => Some(app.ui.mode == Mode::Rendering),
"camera.perspective" => Some(!app.session.camera.ortho),
"camera.orthographic" => Some(app.session.camera.ortho),
id => crate::docking::view_panel(id).map(|p| app.ui.dock.is_open(p)),
};
if let Some(c) = checked {
Expand Down
30 changes: 29 additions & 1 deletion crates/ui-egui/src/viewport.rs
Original file line number Diff line number Diff line change
Expand Up @@ -546,6 +546,19 @@ const MAX_STENCIL_SCALE: f32 = 10.0;
/// Smallest viewport the camera projects into, so a collapsed view keeps a usable aspect (points)
const MIN_CAMERA_VIEWPORT: f32 = 16.0;

/// Alt+Shift+left drag: orbit in 90° steps. The drag's own yaw and pitch follow the pointer; the
/// camera takes the nearest step, with the pitch held inside the orbit's ±89° limit.
fn snapped_orbit(app: &mut TextureCraftApp, delta: egui::Vec2) {
let step = std::f32::consts::FRAC_PI_2;
let limit = 89f32.to_radians();
let camera = &mut app.session.camera;
let (yaw, pitch) = app.orbit_snap.get_or_insert((camera.yaw, camera.pitch));
*yaw -= delta.x * ORBIT_RADIANS_PER_POINT;
*pitch = (*pitch + delta.y * ORBIT_RADIANS_PER_POINT).clamp(-step, step);
camera.yaw = (*yaw / step).round() * step;
camera.pitch = ((*pitch / step).round() * step).clamp(-limit, limit);
}

fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut PendingSync) {
let response = ui.interact(rect, ui.scope_id().with("view3d"), Sense::click_and_drag());
app.viewport_rect = rect;
Expand All @@ -566,10 +579,18 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
if stencil_drag || adjusting {
// The stencil or the brush changes instead of the camera
} else if response.dragged_by(PointerButton::Middle) {
app.camera_glide = None;
app.session.camera.pan(delta.x / size.y, delta.y / size.y);
} else if alt && response.dragged_by(PointerButton::Primary) {
app.session.camera.orbit(delta.x * ORBIT_RADIANS_PER_POINT, delta.y * ORBIT_RADIANS_PER_POINT);
// Navigating takes over from a glide in progress, which would put the camera back
app.camera_glide = None;
if shift {
snapped_orbit(app, delta);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
} else {
app.session.camera.orbit(delta.x * ORBIT_RADIANS_PER_POINT, delta.y * ORBIT_RADIANS_PER_POINT);
}
} else if response.dragged_by(PointerButton::Secondary) {
app.camera_glide = None;
if alt {
app.session.camera.zoom(-delta.y * DRAG_ZOOM_PER_POINT);
} else if shift {
Expand All @@ -580,6 +601,11 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
}
}

// The next snapping drag starts again from where the camera is
if !(alt && shift && response.dragged_by(PointerButton::Primary)) {
app.orbit_snap = None;
}

if response.hovered() {
let scroll = ui.input(|input| input.smooth_scroll_delta.y);
if scroll != 0.0 {
Expand All @@ -590,6 +616,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
brush.size = (brush.size * (1.0 + scroll * WHEEL_BRUSH_SIZE_PER_POINT)).clamp(MIN_BRUSH_SIZE, MAX_BRUSH_SIZE);
}
} else {
app.camera_glide = None;
app.session.camera.zoom(scroll * WHEEL_ZOOM_PER_POINT);
}
}
Expand All @@ -602,6 +629,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
app.session.cancel_stroke();
}

app.camera_glide = None;
let moved = gesture.translation_delta;
if gesture.num_touches >= 3 {
app.session.camera.pan(moved.x / size.y, moved.y / size.y);
Expand Down
Loading
Loading