Skip to main content

brep_app/automation/
cmd_navigate.rs

1//! Batched mouse navigation: an ordered pointer path replayed through the
2//! viewport's own camera routing in ONE command, with no pass per sample.
3//!
4//! `pointer_move` / `pointer_down` / `pointer_up` reach the camera through
5//! egui: each needs a pass of its own (the input is applied by the pass that
6//! receives it), and the camera moves in that pass. A 64-sample drag is then
7//! 64+ passes, each drawing the 3D view: seconds on a software rasteriser
8//! (a drag took that long in a reported session). This command takes the path and makes
9//! the same calls the viewport makes for it (`viewport::interaction`'s
10//! `handle_viewport_input`), in order and without coalescing (the arcball is
11//! path-dependent):
12//!
13//! - the PRESS (the path's first sample) routes the gesture: on the ViewCube
14//!   the cube snaps the camera, as a drag or click starting there does;
15//! - a drag starts at the first sample farther than egui's click radius
16//!   (`InputOptions::max_click_dist`) from the press, and the camera anchors
17//!   THERE (`pointer_down` at that sample), not at the press;
18//! - primary (and the extra buttons) orbit, secondary and middle pan;
19//! - every later sample is a `pointer_move`, the release a `pointer_up`;
20//! - a path that never leaves the click radius is a click: on the ViewCube it
21//!   snaps the camera at the release point; elsewhere it changes nothing (this
22//!   is navigation: it never selects).
23//!
24//! Whatever the native router would hand to something other than the camera
25//! is refused by name instead of being navigated: sketch modes (a drag there
26//! may move geometry), an open drawing sheet, a press outside the 3D view or
27//! under a window over it, and a press on a gizmo, dimension or constraint
28//! handle. Samples carry no time, so egui's hold-to-drag (a press held still
29//! past `max_click_duration`) is not modelled, and held modifiers are not read
30//! (a Shift drag is a box selection natively, not navigation).
31use crate::automation::command::{app_command, parse_args, CommandSpec, Ctx, Outcome};
32use crate::automation::pointer::{Button, TouchSpace};
33use brep_render::controls::{BUTTON_LEFT, BUTTON_MIDDLE, BUTTON_RIGHT};
34use brep_render::engine_state::EngineState;
35use serde::Deserialize;
36use serde_json::{json, Value};
37
38#[derive(Debug, Clone, Copy, Deserialize, schemars::JsonSchema)]
39#[serde(deny_unknown_fields)]
40pub struct PathPoint {
41    pub x: f64,
42    pub y: f64,
43}
44
45#[derive(Deserialize, schemars::JsonSchema)]
46#[serde(deny_unknown_fields)]
47pub struct NavigateArgs {
48    /// The pointer path, in order: the first point is the press, the last the
49    /// release. 1..=4096 points.
50    pub path: Vec<PathPoint>,
51    /// viewport (default): points from the 3D viewport's top-left; surface:
52    /// egui points as `pointer_move` takes (`sdk.pointer.touch`'s `space`).
53    #[serde(default)]
54    pub space: TouchSpace,
55    /// The held button (default primary: orbit; secondary/middle: pan).
56    #[serde(default = "primary")]
57    pub button: Button,
58    /// A base camera applied first (the shape `camera_get` returns; partial
59    /// fields allowed where `camera_set` accepts them).
60    pub camera: Option<Value>,
61    /// Path indices whose camera to return as well: the camera after that
62    /// sample was applied, e.g. for a preview frame mid-drag.
63    #[serde(default)]
64    pub previews: Vec<usize>,
65}
66
67fn primary() -> Button {
68    Button::Primary
69}
70
71/// The most samples one call replays.
72pub const MAX_PATH: usize = 4096;
73
74/// What the path did.
75#[derive(Debug, Clone, Copy, PartialEq, Eq)]
76pub enum Gesture {
77    Orbit,
78    Pan,
79    ViewCube,
80    Click,
81}
82
83impl Gesture {
84    fn name(self) -> &'static str {
85        match self {
86            Gesture::Orbit => "orbit",
87            Gesture::Pan => "pan",
88            Gesture::ViewCube => "viewcube",
89            Gesture::Click => "click",
90        }
91    }
92}
93
94/// The replay result before it is put in JSON.
95pub struct Replayed {
96    pub gesture: Gesture,
97    /// The index of the sample the drag started at (`None`: a click).
98    pub drag_started_at: Option<usize>,
99    pub previews: Vec<(usize, Value)>,
100}
101
102/// The engine's button code for a drag with `button`, as the viewport picks it.
103fn engine_button(button: Button) -> i32 {
104    match button {
105        Button::Secondary => BUTTON_RIGHT,
106        Button::Middle => BUTTON_MIDDLE,
107        _ => BUTTON_LEFT,
108    }
109}
110
111/// The handle under a press that the native router would grab instead of the
112/// camera, read without arming anything (`route_drag_start`'s `*_press` calls
113/// start the drag they test for).
114fn handle_under(state: &EngineState, x: f64, y: f64) -> Option<&'static str> {
115    if state.transform_pick(x, y) != 0 {
116        Some("a transform gizmo handle")
117    } else if state.dimension_arrow_pick(x, y).is_some() {
118        Some("a dimension arrow")
119    } else if state.constraint_arrow_pick(x, y).is_some() {
120        Some("an assembly constraint handle")
121    } else {
122        None
123    }
124}
125
126/// Replay `path` (viewport-local points) with `button` through the camera,
127/// as the viewport does for the same input. `click_radius` is egui's.
128pub fn replay(state: &mut EngineState, path: &[(f64, f64)], button: Button, click_radius: f64, previews: &[usize]) -> Result<Replayed, String> {
129    let (&press, _) = path.split_first().ok_or("bad_args: the path is empty")?;
130    if path.iter().any(|(x, y)| !(x.is_finite() && y.is_finite())) {
131        return Err("bad_args: every path point must be finite".into());
132    }
133    let (px, py) = press;
134    let on_cube = crate::viewport::viewcube_local(state, px, py).is_some();
135    if !on_cube {
136        if let Some(what) = handle_under(state, px, py) {
137            return Err(format!("not_navigation: the press at ({px}, {py}) lands on {what}, which a native drag would move instead of the camera; use pointer input"));
138        }
139    }
140    let mut out = Replayed { gesture: Gesture::Click, drag_started_at: None, previews: Vec::new() };
141    let mut wanted = previews.to_vec();
142    wanted.sort_unstable();
143    wanted.dedup();
144    let mut wanted = wanted.into_iter().peekable();
145    let mut dragging = false;
146    for (i, &(x, y)) in path.iter().enumerate() {
147        if out.drag_started_at.is_none() && i > 0 && ((x - px).powi(2) + (y - py).powi(2)).sqrt() > click_radius {
148            out.drag_started_at = Some(i);
149            if on_cube {
150                // A drag that starts on the cube snaps at the press.
151                if let Some((cx, cy)) = crate::viewport::viewcube_local(state, px, py) {
152                    state.viewcube_click(cx, cy);
153                }
154                out.gesture = Gesture::ViewCube;
155            } else {
156                let code = engine_button(button);
157                // The viewport anchors at the current sample: the camera's
158                // first delta runs from here, not from the press.
159                state.pointer_down(x, y, code);
160                dragging = true;
161                out.gesture = if code == BUTTON_LEFT { Gesture::Orbit } else { Gesture::Pan };
162            }
163        } else if dragging {
164            state.pointer_move(x, y);
165        }
166        while wanted.peek().is_some_and(|&w| w <= i) {
167            let w = wanted.next().expect("peeked");
168            if w == i {
169                out.previews.push((i, state.camera_state_value()));
170            }
171        }
172    }
173    if dragging {
174        state.pointer_up();
175    } else if out.drag_started_at.is_none() && on_cube {
176        // A plain click on the cube snaps at the release point (the viewport's
177        // `clicked()` branch); it lies within the click radius of the press.
178        let &(rx, ry) = path.last().expect("non-empty");
179        if let Some((cx, cy)) = crate::viewport::viewcube_local(state, rx, ry) {
180            state.viewcube_click(cx, cy);
181            out.gesture = Gesture::ViewCube;
182        }
183    }
184    if let Some(bad) = previews.iter().find(|&&i| i >= path.len()) {
185        return Err(format!("bad_args: preview index {bad} is past the path's {} points", path.len()));
186    }
187    Ok(out)
188}
189
190fn camera_navigate(ctx: &mut Ctx<'_>, args: Value) -> Result<Outcome, String> {
191    let a: NavigateArgs = parse_args(args)?;
192    if a.path.is_empty() || a.path.len() > MAX_PATH {
193        return Err(format!("bad_args: the path needs 1..={MAX_PATH} points (got {})", a.path.len()));
194    }
195    if let Some(bad) = a.previews.iter().find(|&&i| i >= a.path.len()) {
196        return Err(format!("bad_args: preview index {bad} is past the path's {} points", a.path.len()));
197    }
198    let rect = ctx.app.view_rect().ok_or("no_viewport: the 3D view was not drawn last frame")?;
199    let surface: Vec<egui::Pos2> = a
200        .path
201        .iter()
202        .map(|p| match a.space {
203            // Summed in f64 and rounded once, as a client adding the view's
204            // origin before `pointer_move` (an f32 position) gets it.
205            TouchSpace::Viewport => egui::pos2((f64::from(rect.min.x) + p.x) as f32, (f64::from(rect.min.y) + p.y) as f32),
206            TouchSpace::Surface => egui::pos2(p.x as f32, p.y as f32),
207        })
208        .collect();
209    let press = surface[0];
210    if !rect.contains(press) {
211        return Err(format!("not_navigation: the press at ({}, {}) is outside the 3D view {:?}", press.x, press.y, [rect.min.x, rect.min.y, rect.width(), rect.height()]));
212    }
213    // A window, menu or popup over the view takes the press natively.
214    if ctx.egui.layer_id_at(press).is_some_and(|layer| layer.order != egui::Order::Background) {
215        return Err(format!("not_navigation: the press at ({}, {}) lands on a window over the 3D view", press.x, press.y));
216    }
217    let click_radius = f64::from(ctx.egui.options(|o| o.input_options.max_click_dist));
218    let local: Vec<(f64, f64)> = surface.iter().map(|p| ((p.x - rect.min.x) as f64, (p.y - rect.min.y) as f64)).collect();
219    let engine = ctx.app.docs.engine_mut();
220    if engine.any_sketch_mode() {
221        return Err("not_navigation: a sketch is being edited, where a drag may move sketch geometry; use pointer input".into());
222    }
223    if engine.sheet_open().is_some() {
224        return Err("not_navigation: a drawing sheet is open in the view; there is no 3D camera to navigate".into());
225    }
226    if engine.camera_gesture_active() {
227        return Err("busy: a pointer orbit or pan is in progress".into());
228    }
229    if let Some(camera) = &a.camera {
230        let text = serde_json::to_string(camera).map_err(|e| e.to_string())?;
231        engine.apply_camera_state_json(&text)?;
232    }
233    let replayed = replay(engine, &local, a.button, click_radius, &a.previews)?;
234    ctx.egui.request_repaint();
235    // The camera with the rest of the frame (viewport, PMI view, document),
236    // exactly as `view_frame` reads it.
237    let frame = super::cmd_camera::view_frame_value(ctx);
238    Ok(Outcome::Done(json!({
239        "camera": frame["camera"].clone(),
240        "viewFrame": frame,
241        "gesture": replayed.gesture.name(),
242        "dragStartedAt": replayed.drag_started_at,
243        "samples": a.path.len(),
244        "previews": replayed.previews.into_iter().map(|(index, camera)| json!({ "index": index, "camera": camera })).collect::<Vec<_>>(),
245    })))
246}
247
248fn navigate_result_schema() -> Value {
249    let camera = super::cmd_camera::camera_result_schema()["properties"]["camera"].clone();
250    let mut frame = super::cmd_camera::view_frame_schema();
251    let defs = frame.as_object_mut().and_then(|o| o.remove("$defs")).unwrap_or(Value::Null);
252    json!({
253        "type":"object",
254        "properties":{
255            "camera":camera,
256            "viewFrame":frame,
257            "gesture":{"enum":["orbit","pan","viewcube","click"],"description":"What the path did: a camera drag, a ViewCube snap, or a click that moved nothing."},
258            "dragStartedAt":{"type":["integer","null"],"minimum":0,"description":"The sample the drag started at (the first past egui's click radius), null for a click."},
259            "samples":{"type":"integer","minimum":1},
260            "previews":{"type":"array","items":{"type":"object","properties":{"index":{"type":"integer","minimum":0},"camera":camera},"required":["index","camera"],"additionalProperties":false}}
261        },
262        "required":["camera","viewFrame","gesture","dragStartedAt","samples","previews"],
263        "additionalProperties":false,
264        "$defs":defs
265    })
266}
267
268pub static COMMANDS: &[CommandSpec] = &[
269    app_command!("camera", "camera_navigate", "Replay an ordered mouse path (press = first point, release = last) through the 3D view's own camera controls in one call, with no rendered frame per sample: the native drag threshold (egui's click radius), buttons (primary orbits, secondary/middle pan) and ViewCube routing (a press on the cube snaps it) are kept, so the final eye, target, up and scale equal what the same pointer_down/move/up input produces. Optional base `camera` (camera_get's shape) applied first; `previews` returns the camera after given samples; `viewFrame` is `view_frame`'s camera, viewport, PMI view and document, read after the path. `space`: viewport (default) or surface points. Refuses a press a native drag would give to something else (sketch mode, a sheet, a handle, a window over the view). Never selects.", NavigateArgs, camera_navigate, Mutate, MUTATE_NOWAIT, navigate_result_schema),
270];