1use 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 pub path: Vec<PathPoint>,
51 #[serde(default)]
54 pub space: TouchSpace,
55 #[serde(default = "primary")]
57 pub button: Button,
58 pub camera: Option<Value>,
61 #[serde(default)]
64 pub previews: Vec<usize>,
65}
66
67fn primary() -> Button {
68 Button::Primary
69}
70
71pub const MAX_PATH: usize = 4096;
73
74#[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
94pub struct Replayed {
96 pub gesture: Gesture,
97 pub drag_started_at: Option<usize>,
99 pub previews: Vec<(usize, Value)>,
100}
101
102fn engine_button(button: Button) -> i32 {
104 match button {
105 Button::Secondary => BUTTON_RIGHT,
106 Button::Middle => BUTTON_MIDDLE,
107 _ => BUTTON_LEFT,
108 }
109}
110
111fn 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
126pub 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 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 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 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 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 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 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];