BREP_app 0.36.0

The next.BREP.io CAD application on the Rust B-rep kernel: an eframe (egui + wgpu) host that draws the brep-render 3D engine into an egui frame, native + wasm from one codebase.
Documentation
//! Batched mouse navigation: an ordered pointer path replayed through the
//! viewport's own camera routing in ONE command, with no pass per sample.
//!
//! `pointer_move` / `pointer_down` / `pointer_up` reach the camera through
//! egui: each needs a pass of its own (the input is applied by the pass that
//! receives it), and the camera moves in that pass. A 64-sample drag is then
//! 64+ passes, each drawing the 3D view: seconds on a software rasteriser
//! (a drag took that long in a reported session). This command takes the path and makes
//! the same calls the viewport makes for it (`viewport::interaction`'s
//! `handle_viewport_input`), in order and without coalescing (the arcball is
//! path-dependent):
//!
//! - the PRESS (the path's first sample) routes the gesture: on the ViewCube
//!   the cube snaps the camera, as a drag or click starting there does;
//! - a drag starts at the first sample farther than egui's click radius
//!   (`InputOptions::max_click_dist`) from the press, and the camera anchors
//!   THERE (`pointer_down` at that sample), not at the press;
//! - primary (and the extra buttons) orbit, secondary and middle pan;
//! - every later sample is a `pointer_move`, the release a `pointer_up`;
//! - a path that never leaves the click radius is a click: on the ViewCube it
//!   snaps the camera at the release point; elsewhere it changes nothing (this
//!   is navigation: it never selects).
//!
//! Whatever the native router would hand to something other than the camera
//! is refused by name instead of being navigated: sketch modes (a drag there
//! may move geometry), an open drawing sheet, a press outside the 3D view or
//! under a window over it, and a press on a gizmo, dimension or constraint
//! handle. Samples carry no time, so egui's hold-to-drag (a press held still
//! past `max_click_duration`) is not modelled, and held modifiers are not read
//! (a Shift drag is a box selection natively, not navigation).
use crate::automation::command::{app_command, parse_args, CommandSpec, Ctx, Outcome};
use crate::automation::pointer::{Button, TouchSpace};
use brep_render::controls::{BUTTON_LEFT, BUTTON_MIDDLE, BUTTON_RIGHT};
use brep_render::engine_state::EngineState;
use serde::Deserialize;
use serde_json::{json, Value};

#[derive(Debug, Clone, Copy, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct PathPoint {
    pub x: f64,
    pub y: f64,
}

#[derive(Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct NavigateArgs {
    /// The pointer path, in order: the first point is the press, the last the
    /// release. 1..=4096 points.
    pub path: Vec<PathPoint>,
    /// viewport (default): points from the 3D viewport's top-left; surface:
    /// egui points as `pointer_move` takes (`sdk.pointer.touch`'s `space`).
    #[serde(default)]
    pub space: TouchSpace,
    /// The held button (default primary: orbit; secondary/middle: pan).
    #[serde(default = "primary")]
    pub button: Button,
    /// A base camera applied first (the shape `camera_get` returns; partial
    /// fields allowed where `camera_set` accepts them).
    pub camera: Option<Value>,
    /// Path indices whose camera to return as well: the camera after that
    /// sample was applied, e.g. for a preview frame mid-drag.
    #[serde(default)]
    pub previews: Vec<usize>,
}

fn primary() -> Button {
    Button::Primary
}

/// The most samples one call replays.
pub const MAX_PATH: usize = 4096;

/// What the path did.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Gesture {
    Orbit,
    Pan,
    ViewCube,
    Click,
}

impl Gesture {
    fn name(self) -> &'static str {
        match self {
            Gesture::Orbit => "orbit",
            Gesture::Pan => "pan",
            Gesture::ViewCube => "viewcube",
            Gesture::Click => "click",
        }
    }
}

/// The replay result before it is put in JSON.
pub struct Replayed {
    pub gesture: Gesture,
    /// The index of the sample the drag started at (`None`: a click).
    pub drag_started_at: Option<usize>,
    pub previews: Vec<(usize, Value)>,
}

/// The engine's button code for a drag with `button`, as the viewport picks it.
fn engine_button(button: Button) -> i32 {
    match button {
        Button::Secondary => BUTTON_RIGHT,
        Button::Middle => BUTTON_MIDDLE,
        _ => BUTTON_LEFT,
    }
}

/// The handle under a press that the native router would grab instead of the
/// camera, read without arming anything (`route_drag_start`'s `*_press` calls
/// start the drag they test for).
fn handle_under(state: &EngineState, x: f64, y: f64) -> Option<&'static str> {
    if state.transform_pick(x, y) != 0 {
        Some("a transform gizmo handle")
    } else if state.dimension_arrow_pick(x, y).is_some() {
        Some("a dimension arrow")
    } else if state.constraint_arrow_pick(x, y).is_some() {
        Some("an assembly constraint handle")
    } else {
        None
    }
}

/// Replay `path` (viewport-local points) with `button` through the camera,
/// as the viewport does for the same input. `click_radius` is egui's.
pub fn replay(state: &mut EngineState, path: &[(f64, f64)], button: Button, click_radius: f64, previews: &[usize]) -> Result<Replayed, String> {
    let (&press, _) = path.split_first().ok_or("bad_args: the path is empty")?;
    if path.iter().any(|(x, y)| !(x.is_finite() && y.is_finite())) {
        return Err("bad_args: every path point must be finite".into());
    }
    let (px, py) = press;
    let on_cube = crate::viewport::viewcube_local(state, px, py).is_some();
    if !on_cube {
        if let Some(what) = handle_under(state, px, py) {
            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"));
        }
    }
    let mut out = Replayed { gesture: Gesture::Click, drag_started_at: None, previews: Vec::new() };
    let mut wanted = previews.to_vec();
    wanted.sort_unstable();
    wanted.dedup();
    let mut wanted = wanted.into_iter().peekable();
    let mut dragging = false;
    for (i, &(x, y)) in path.iter().enumerate() {
        if out.drag_started_at.is_none() && i > 0 && ((x - px).powi(2) + (y - py).powi(2)).sqrt() > click_radius {
            out.drag_started_at = Some(i);
            if on_cube {
                // A drag that starts on the cube snaps at the press.
                if let Some((cx, cy)) = crate::viewport::viewcube_local(state, px, py) {
                    state.viewcube_click(cx, cy);
                }
                out.gesture = Gesture::ViewCube;
            } else {
                let code = engine_button(button);
                // The viewport anchors at the current sample: the camera's
                // first delta runs from here, not from the press.
                state.pointer_down(x, y, code);
                dragging = true;
                out.gesture = if code == BUTTON_LEFT { Gesture::Orbit } else { Gesture::Pan };
            }
        } else if dragging {
            state.pointer_move(x, y);
        }
        while wanted.peek().is_some_and(|&w| w <= i) {
            let w = wanted.next().expect("peeked");
            if w == i {
                out.previews.push((i, state.camera_state_value()));
            }
        }
    }
    if dragging {
        state.pointer_up();
    } else if out.drag_started_at.is_none() && on_cube {
        // A plain click on the cube snaps at the release point (the viewport's
        // `clicked()` branch); it lies within the click radius of the press.
        let &(rx, ry) = path.last().expect("non-empty");
        if let Some((cx, cy)) = crate::viewport::viewcube_local(state, rx, ry) {
            state.viewcube_click(cx, cy);
            out.gesture = Gesture::ViewCube;
        }
    }
    if let Some(bad) = previews.iter().find(|&&i| i >= path.len()) {
        return Err(format!("bad_args: preview index {bad} is past the path's {} points", path.len()));
    }
    Ok(out)
}

fn camera_navigate(ctx: &mut Ctx<'_>, args: Value) -> Result<Outcome, String> {
    let a: NavigateArgs = parse_args(args)?;
    if a.path.is_empty() || a.path.len() > MAX_PATH {
        return Err(format!("bad_args: the path needs 1..={MAX_PATH} points (got {})", a.path.len()));
    }
    if let Some(bad) = a.previews.iter().find(|&&i| i >= a.path.len()) {
        return Err(format!("bad_args: preview index {bad} is past the path's {} points", a.path.len()));
    }
    let rect = ctx.app.view_rect().ok_or("no_viewport: the 3D view was not drawn last frame")?;
    let surface: Vec<egui::Pos2> = a
        .path
        .iter()
        .map(|p| match a.space {
            // Summed in f64 and rounded once, as a client adding the view's
            // origin before `pointer_move` (an f32 position) gets it.
            TouchSpace::Viewport => egui::pos2((f64::from(rect.min.x) + p.x) as f32, (f64::from(rect.min.y) + p.y) as f32),
            TouchSpace::Surface => egui::pos2(p.x as f32, p.y as f32),
        })
        .collect();
    let press = surface[0];
    if !rect.contains(press) {
        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()]));
    }
    // A window, menu or popup over the view takes the press natively.
    if ctx.egui.layer_id_at(press).is_some_and(|layer| layer.order != egui::Order::Background) {
        return Err(format!("not_navigation: the press at ({}, {}) lands on a window over the 3D view", press.x, press.y));
    }
    let click_radius = f64::from(ctx.egui.options(|o| o.input_options.max_click_dist));
    let local: Vec<(f64, f64)> = surface.iter().map(|p| ((p.x - rect.min.x) as f64, (p.y - rect.min.y) as f64)).collect();
    let engine = ctx.app.docs.engine_mut();
    if engine.any_sketch_mode() {
        return Err("not_navigation: a sketch is being edited, where a drag may move sketch geometry; use pointer input".into());
    }
    if engine.sheet_open().is_some() {
        return Err("not_navigation: a drawing sheet is open in the view; there is no 3D camera to navigate".into());
    }
    if engine.camera_gesture_active() {
        return Err("busy: a pointer orbit or pan is in progress".into());
    }
    if let Some(camera) = &a.camera {
        let text = serde_json::to_string(camera).map_err(|e| e.to_string())?;
        engine.apply_camera_state_json(&text)?;
    }
    let replayed = replay(engine, &local, a.button, click_radius, &a.previews)?;
    ctx.egui.request_repaint();
    // The camera with the rest of the frame (viewport, PMI view, document),
    // exactly as `view_frame` reads it.
    let frame = super::cmd_camera::view_frame_value(ctx);
    Ok(Outcome::Done(json!({
        "camera": frame["camera"].clone(),
        "viewFrame": frame,
        "gesture": replayed.gesture.name(),
        "dragStartedAt": replayed.drag_started_at,
        "samples": a.path.len(),
        "previews": replayed.previews.into_iter().map(|(index, camera)| json!({ "index": index, "camera": camera })).collect::<Vec<_>>(),
    })))
}

fn navigate_result_schema() -> Value {
    let camera = super::cmd_camera::camera_result_schema()["properties"]["camera"].clone();
    let mut frame = super::cmd_camera::view_frame_schema();
    let defs = frame.as_object_mut().and_then(|o| o.remove("$defs")).unwrap_or(Value::Null);
    json!({
        "type":"object",
        "properties":{
            "camera":camera,
            "viewFrame":frame,
            "gesture":{"enum":["orbit","pan","viewcube","click"],"description":"What the path did: a camera drag, a ViewCube snap, or a click that moved nothing."},
            "dragStartedAt":{"type":["integer","null"],"minimum":0,"description":"The sample the drag started at (the first past egui's click radius), null for a click."},
            "samples":{"type":"integer","minimum":1},
            "previews":{"type":"array","items":{"type":"object","properties":{"index":{"type":"integer","minimum":0},"camera":camera},"required":["index","camera"],"additionalProperties":false}}
        },
        "required":["camera","viewFrame","gesture","dragStartedAt","samples","previews"],
        "additionalProperties":false,
        "$defs":defs
    })
}

pub static COMMANDS: &[CommandSpec] = &[
    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),
];