brep_render/engine_state/camera_widgets.rs
1use super::*;
2
3impl EngineState {
4 /// Per-frame overlay upkeep — the ONE call the app viewport makes each frame
5 /// (see `BREP_app/src/viewport/interaction.rs`).
6 ///
7 /// Everything fed through the general `set_overlay` channel is pre-expanded
8 /// into GPU vertices AT FEED TIME (see the "Why not one uniform feed" note in
9 /// [`crate::widgets`]), so — unlike the specialized widgets (transform gizmo,
10 /// datums, ViewCube), which are rebuilt against the LIVE camera every frame —
11 /// a baked overlay group keeps whatever screen-constant sizing it was baked
12 /// with. A ZOOM changes `world_per_pixel` and nothing else re-bakes them, so
13 /// the draggable gizmos keep their old pixel size — and where a handle's world
14 /// position is ITSELF `px × world_per_pixel` (the angular arc), their old
15 /// POSITION too, drifting away from the live-computed grab region.
16 ///
17 /// So: re-bake on a MATERIAL `world_per_pixel` change, keyed on that ONE
18 /// quantity rather than on any particular gesture. Every zoom path moves it —
19 /// the wheel, [`Self::zoom_to_fit`], [`Self::standard_view`] (which fits), a
20 /// viewport [`Self::resize`] — so they are all covered without a per-path
21 /// hook. What does NOT move it needs no re-bake, and correctly gets none:
22 /// pan and orbit hold the eye→target distance, the ViewCube (face, corner AND
23 /// navigation arrow) is a fixed-pivot reorient, and
24 /// [`Self::toggle_projection`] preserves apparent size by construction
25 /// (`ViewCamera::toggle_projection` solves for the distance/half-height that
26 /// keeps `world_per_pixel` — see `projection_toggle_preserves_apparent_size`).
27 /// The baked buffers are world-space, so the GPU re-projects them for free.
28 /// Re-bakes only on actual change, so a quiet frame stays quiet (no per-frame
29 /// dirty loop).
30 pub fn ensure_overlays_current(&mut self) {
31 // Assembly-constraint leaders + grabbable distance/angle handles (§8.4).
32 self.ensure_constraint_overlay_current();
33 // The ◎ feature-DIMENSION gizmo: draggable leaders/arrowheads + the
34 // angular sweep handle, whose arc radius is itself px × world_per_pixel.
35 self.ensure_feature_dimension_overlay_current();
36 // Live sketch mode: draggable dimension leaders, constraint glyphs and
37 // construction dashes, all sized in pixels at bake time.
38 self.ensure_sketch_overlay_current();
39 self.ensure_sketch3d_overlay_current();
40 // The active PMI view's annotation graphics (screen-constant arrows
41 // that also face the camera).
42 self.ensure_pmi_overlay_current();
43 // The Draft Analysis tint, re-read when the shown solids changed.
44 self.ensure_draft_analysis_current();
45 }
46
47 /// Frame the whole scene (used right after the first history feed).
48 pub fn zoom_to_fit(&mut self) {
49 self.camera.zoom_to_fit(&self.scene.bbox(), 1.15);
50 self.dirty = true;
51 }
52
53 // --- Sizing -----------------------------------------------------------
54
55 /// Update the CSS viewport size (used by all camera math). The physical
56 /// framebuffer size + DPR are the presentation shell's concern.
57 /// The viewport calls this every frame, so it marks the frame dirty only
58 /// when the size really changes: an unconditional mark re-rendered the
59 /// whole scene on every repaint (about 0.34 s a frame for a large CAM stock
60 /// on a machine without a GPU), whether or not anything had changed.
61 pub fn resize(&mut self, css_width: f64, css_height: f64) {
62 let (width, height) = (css_width.max(1.0), css_height.max(1.0));
63 if self.camera.width != width || self.camera.height != height {
64 self.camera.width = width;
65 self.camera.height = height;
66 self.dirty = true;
67 }
68 }
69
70 // --- Pointer / wheel ingestion (R22) ----------------------------------
71
72 pub fn pointer_down(&mut self, x: f64, y: f64, button: i32) -> bool {
73 // Sketch camera lock: while locked, the view is held flat-on to the sketch
74 // plane, so a LEFT press must NOT drive the camera at all — neither orbit
75 // (which would tilt off the plane) NOR pan. Suppressing it keeps left-drag
76 // free for sketch interaction and leaves pan on right/middle. Modeling mode
77 // and the UNLOCKED sketch view (where left orbits) are unaffected.
78 if self.sketch_mode()
79 && self.sketch_camera_locked
80 && button == crate::controls::BUTTON_LEFT
81 {
82 return false;
83 }
84 self.controls.pointer_down(x, y, button)
85 }
86
87 pub fn pointer_move(&mut self, x: f64, y: f64) -> bool {
88 let changed = self.controls.pointer_move(&mut self.camera, x, y);
89 if changed {
90 self.dirty = true;
91 }
92 changed
93 }
94
95 pub fn pointer_up(&mut self) -> bool {
96 self.controls.pointer_up()
97 }
98
99 /// A pointer orbit or pan is in progress (between `pointer_down` and
100 /// `pointer_up`).
101 pub fn camera_gesture_active(&self) -> bool {
102 self.controls.active_gesture() != crate::controls::Gesture::None
103 }
104
105 pub fn wheel(&mut self, delta_y: f64, cursor: Option<[f64; 2]>) -> bool {
106 let changed = self.controls.wheel(&mut self.camera, delta_y, cursor);
107 if changed {
108 self.dirty = true;
109 }
110 changed
111 }
112
113 pub fn set_controls_enabled(&mut self, enabled: bool) {
114 self.controls.enabled = enabled;
115 }
116
117 /// Two-finger pan/pinch, also available with the sketch camera locked:
118 /// neither operation changes its orientation relative to the sketch plane.
119 pub fn touch_navigation(&mut self, from: [f64; 2], to: [f64; 2], scale: f64) -> bool {
120 let changed = self
121 .controls
122 .touch_navigation(&mut self.camera, from, to, scale);
123 self.dirty |= changed;
124 changed
125 }
126
127 /// The sketch camera is locked flat to its plane: nothing may turn the
128 /// view (the rule `pointer_down` applies to an orbit drag). Pan and zoom
129 /// keep the orientation and stay available.
130 pub fn camera_rotation_locked(&self) -> bool {
131 self.sketch_mode() && self.sketch_camera_locked
132 }
133
134 /// One frame of SpaceMouse / Spaceball motion: pan and zoom only while
135 /// [`Self::camera_rotation_locked`].
136 pub fn six_dof(&mut self, motion: &crate::controls::SixDofMotion) -> bool {
137 let allow_rotate = !self.camera_rotation_locked();
138 let changed = self.controls.six_dof(&mut self.camera, motion, allow_rotate);
139 self.dirty |= changed;
140 changed
141 }
142
143 // --- Camera commands (R21) --------------------------------------------
144
145 pub fn toggle_projection(&mut self) -> &'static str {
146 let kind = self.camera.toggle_projection();
147 self.dirty = true;
148 kind
149 }
150
151 pub fn set_projection(&mut self, kind: &str) {
152 let is_persp = matches!(self.camera.projection, crate::view::Projection::Perspective { .. });
153 let want_persp = kind.to_ascii_lowercase().starts_with("pers");
154 if is_persp != want_persp {
155 self.camera.toggle_projection();
156 self.dirty = true;
157 }
158 }
159
160 /// Snap to a named view and fit, the name read in [`Self::view_frame`] —
161 /// so with a board shown TOP looks down on its component side.
162 pub fn standard_view(&mut self, name: &str) -> bool {
163 let ok = self.camera.standard_view_in(self.view_frame(), name);
164 if ok {
165 self.camera.zoom_to_fit(&self.scene.bbox(), 1.15);
166 self.dirty = true;
167 }
168 ok
169 }
170
171 /// The frame the named views and the ViewCube are read in: Z-up
172 /// ([`crate::view::ViewFrame::Board`]) while the document shows a board, Y-up otherwise.
173 ///
174 /// Keyed on the DOCUMENT, not the workbench: the board is seen in 3D from
175 /// every workbench that draws the 3D view (Modeling, Assembly…) — the PCB
176 /// workbench itself draws its 2D editor there instead — so a frame the PCB
177 /// workbench switched on would never be in force where the board is looked
178 /// at. A document that has a board is one whose 3D view is about the board.
179 pub fn view_frame(&self) -> crate::view::ViewFrame {
180 if self.shown_board_ids.is_empty() {
181 crate::view::ViewFrame::World
182 } else {
183 crate::view::ViewFrame::Board
184 }
185 }
186
187 /// Put the ViewCube in the frame [`Self::view_frame`] reads now, after the
188 /// board bodies were fed or removed. The first time a board appears the
189 /// camera turns to the board's ISO view and frames it, so a board document
190 /// opens looking down on the component side from the front right, as a
191 /// board viewer does, rather than at the Y-up startup vantage that shows
192 /// the board as a standing wall. Losing the board leaves the camera alone.
193 pub(super) fn sync_view_frame(&mut self) {
194 let frame = self.view_frame();
195 if frame == self.widgets.view_frame() {
196 return;
197 }
198 self.widgets.set_view_frame(frame);
199 if frame == crate::view::ViewFrame::Board {
200 self.camera.standard_view_in(frame, "ISO");
201 self.camera.zoom_to_fit(&self.scene.bbox(), 1.15);
202 }
203 self.dirty = true;
204 }
205
206 pub fn camera_state_json(&self) -> String {
207 self.camera.state_json()
208 }
209
210 /// [`Self::camera_state_json`] as a JSON value.
211 pub fn camera_state_value(&self) -> serde_json::Value {
212 self.camera.state_value()
213 }
214
215 pub fn apply_camera_state_json(&mut self, json: &str) -> Result<(), String> {
216 self.camera.apply_state_json(json)?;
217 self.dirty = true;
218 Ok(())
219 }
220
221 pub fn world_per_pixel(&self) -> f64 {
222 self.camera.world_per_pixel()
223 }
224
225 // --- World → screen (R25) ---------------------------------------------
226
227 /// Project world points to CSS-pixel screen coords for host anchoring. Input
228 /// is `[[x,y,z], …]`; output `[[sx, sy, depth, inFront], …]` where inFront
229 /// is 1 when a LABEL anchored at the point should draw
230 /// ([`crate::view::ViewCamera::label_anchor_visible`], THE one label policy:
231 /// the point is projectable — ortho always, perspective unless at/behind the
232 /// eye plane, near/far NEVER cull — AND its projection lands inside the
233 /// viewport, so an off-screen anchor's chip vanishes instead of clamping to
234 /// the viewport edge). Every app label pass (sketch dims, feature dims,
235 /// constraint chips, gizmo axis text) keys its skip off THIS flag, so the
236 /// policy lives in exactly one place.
237 pub fn world_to_screen_json(&self, points_json: &str) -> Result<String, String> {
238 let points: Vec<[f64; 3]> = serde_json::from_str(points_json)
239 .map_err(|error| format!("world_to_screen points parse: {error}"))?;
240 let out = self.world_to_screen_points(&points);
241 Ok(serde_json::to_string(&out).unwrap_or_else(|_| "[]".to_string()))
242 }
243
244 /// [`Self::world_to_screen_json`] without the JSON: what a native pass
245 /// that projects every frame calls.
246 pub fn world_to_screen_points(&self, points: &[[f64; 3]]) -> Vec<[f64; 4]> {
247 points
248 .iter()
249 .map(|&p| {
250 let (sx, sy, depth) = self.camera.project(p);
251 let visible = self.camera.label_anchor_visible(p);
252 [sx, sy, depth, if visible { 1.0 } else { 0.0 }]
253 })
254 .collect()
255 }
256
257 /// The camera matrices for the host overlays' per-frame world→screen /
258 /// screen→world hot path: `{ viewProj:[16], viewProjInverse:[16],
259 /// viewport:[w,h] }`. Both matrices are column-major (index =
260 /// `col*4 + row`); `viewProj` maps world → wgpu clip
261 /// (x,y in −1..1, z in 0..1) and `viewport` is the CSS-pixel size. This lets
262 /// dimensions + sketch drop the compat mirror camera and read the engine's
263 /// own view-projection directly (see `world_to_screen_json` for one-shots).
264 pub fn camera_matrices_json(&self) -> String {
265 let view_proj = self.camera.view_proj_flat();
266 let view_proj_inverse = self.camera.view_proj_inverse_flat();
267 serde_json::json!({
268 "viewProj": view_proj,
269 "viewProjInverse": view_proj_inverse,
270 "viewport": [self.camera.width, self.camera.height],
271 })
272 .to_string()
273 }
274
275 // --- Picking (R23/R24) ------------------------------------------------
276
277}
278
279impl EngineState {
280 /// One hash per kind of render input, for the app's stale-frame check
281 /// (automation builds): a frame whose inputs hash differently from the last
282 /// rendered frame's but that is not marked dirty would show a stale view.
283 /// Selection and hover highlight are `emphasis`; sketch previews and every
284 /// other `set_overlay` geometry, the gizmos and the ViewCube are `widgets`;
285 /// theme and background colours bump `settings_generation`; tessellation
286 /// arriving later bumps a solid's `revision` in `scene`.
287 pub fn render_fingerprint(&self) -> [(&'static str, u64); 5] {
288 use std::hash::{Hash, Hasher};
289 let hash = |f: &dyn Fn(&mut std::collections::hash_map::DefaultHasher)| {
290 let mut h = std::collections::hash_map::DefaultHasher::new();
291 f(&mut h);
292 h.finish()
293 };
294 let camera = self.camera.resolve();
295 [
296 ("camera", hash(&|h| {
297 for v in camera.view_proj.iter().flatten() {
298 v.to_bits().hash(h);
299 }
300 self.camera.width.to_bits().hash(h);
301 self.camera.height.to_bits().hash(h);
302 self.camera.world_per_pixel().to_bits().hash(h);
303 })),
304 ("settings", self.settings_generation),
305 ("scene", hash(&|h| {
306 for solid in self.scene.solids().iter().chain(self.context_scene.solids()) {
307 solid.name.hash(h);
308 solid.revision.hash(h);
309 }
310 })),
311 ("emphasis", hash(&|h| {
312 format!("{:?}", self.emphasis).hash(h);
313 self.context_scene.highlight.hash(h);
314 self.context_scene.tint.map(|rgba| rgba.map(f32::to_bits)).hash(h);
315 for solid in self.context_scene.solids() {
316 solid.visible.hash(h);
317 }
318 })),
319 ("widgets", self.widgets.render_fingerprint(&gizmo_camera(&self.camera))),
320 ]
321 }
322
323 /// Build this frame's overlay-widget geometry, or None when nothing is
324 /// enabled (skips the overlay passes entirely).
325 pub fn build_widget_overlay(&self) -> Option<WidgetOverlay> {
326 if !self.widgets.any_visible() {
327 return None;
328 }
329 Some(self.widgets.build_overlay(&gizmo_camera(&self.camera)))
330 }
331
332 /// Fit the per-frame depth window to EVERYTHING drawn, then resolve the GPU
333 /// camera — the ONE path both frame loops (wasm `Engine::render`, desktop
334 /// `redraw`) use so they can't drift. The overlay is built FIRST, then its
335 /// WORLD bounds are folded into the fit: near/far never affect the overlay
336 /// geometry (it depends only on view direction + `world_per_pixel`), so
337 /// building it before the fit lets construction geometry — datum planes,
338 /// world axes, frames, the transform gizmo — be bracketed by the depth
339 /// window instead of clipping against the solids-only bounds. The world
340 /// ORIGIN is always folded in too, so the origin triad stays bracketed even
341 /// when every geometry channel is momentarily empty (an all-empty frame then
342 /// yields a tiny origin-centred window — harmless, re-fit next frame). The
343 /// ViewCube is excluded (it draws with its own mini-camera; see
344 /// [`WidgetOverlay::world_bbox`]). Returns the resolved camera + the built
345 /// overlay for the frame to hand to the render core.
346 pub fn fit_camera_and_overlay(&mut self) -> (crate::camera::Camera, Option<WidgetOverlay>) {
347 let overlay = self.build_widget_overlay();
348 let mut depth_bbox = self.depth_range_bbox();
349 if let Some(overlay) = &overlay {
350 depth_bbox.union(&overlay.world_bbox());
351 }
352 depth_bbox.expand([0.0, 0.0, 0.0]);
353 self.camera.fit_depth_range(&depth_bbox);
354 (self.camera.resolve(), overlay)
355 }
356
357 pub fn set_datums_json(&mut self, json: &str) -> Result<(), String> {
358 self.widgets.set_datums_json(json)?;
359 self.dirty = true;
360 Ok(())
361 }
362
363 /// Feed the general overlay geometry channel (`set_overlay`): arbitrary named
364 /// tri/line/point groups (feature-dialog previews and other display-only
365 /// geometry), drawn in the widget overlay pass.
366 pub fn set_overlay_json(&mut self, json: &str) -> Result<(), String> {
367 self.widgets.set_overlay_json(json)?;
368 self.dirty = true;
369 Ok(())
370 }
371
372 pub fn set_dimensions_json(&mut self, json: &str) -> Result<(), String> {
373 self.widgets.set_dimensions_json(json)?;
374 self.dirty = true;
375 Ok(())
376 }
377
378 pub fn set_transform_json(&mut self, json: &str) -> Result<(), String> {
379 self.widgets.set_transform_json(json)?;
380 self.dirty = true;
381 Ok(())
382 }
383
384 pub fn set_viewcube_enabled(&mut self, enabled: bool) {
385 self.widgets.set_viewcube_enabled(enabled);
386 self.dirty = true;
387 }
388
389 /// The ViewCube corner rect `{x,y,w,h}` (CSS px) so the host can decide
390 /// whether to forward a pointer event.
391 pub fn viewcube_rect_json(&self) -> String {
392 let r = self.widgets.viewcube_rect(&gizmo_camera(&self.camera));
393 serde_json::json!({ "x": r[0], "y": r[1], "w": r[2], "h": r[3] }).to_string()
394 }
395
396 /// Update the ViewCube hover from cube-local pixels; returns whether it
397 /// changed (a hover-out is `(None)` with local coords outside).
398 pub fn viewcube_hover(&mut self, local_x: f64, local_y: f64) -> bool {
399 let cam = gizmo_camera(&self.camera);
400 let handle = self.widgets.viewcube_hit(&cam, local_x as f32, local_y as f32);
401 let changed = self.widgets.set_viewcube_hover(handle);
402 if changed {
403 self.dirty = true;
404 }
405 changed
406 }
407
408 pub fn viewcube_clear_hover(&mut self) -> bool {
409 let changed = self.widgets.set_viewcube_hover(None);
410 if changed {
411 self.dirty = true;
412 }
413 changed
414 }
415
416 /// Click the ViewCube at cube-local pixels: snap the shared camera to the
417 /// region's standard view (keeping the current pivot distance). Returns
418 /// true if a region was hit.
419 pub fn viewcube_click(&mut self, local_x: f64, local_y: f64) -> bool {
420 let cam = gizmo_camera(&self.camera);
421 let Some(handle) = self.widgets.viewcube_hit(&cam, local_x as f32, local_y as f32) else {
422 return false;
423 };
424 // Navigation arrows apply a RELATIVE camera rotation (orbit / roll) to
425 // the current view instead of snapping to an absolute standard view.
426 if brep_gizmos::view_cube::ViewCube::is_arrow(handle) {
427 self.apply_viewcube_arrow(handle);
428 self.dirty = true;
429 return true;
430 }
431 let (dir, fallback_up) = self.widgets.viewcube_target(handle);
432 // Minimal-rotation snap with a LEVELLED roll: the view direction snaps to
433 // the region, and the up is snapped to the nearest member of a discrete
434 // per-kind set (see [`snap_view_up`]) so a face lands flat-on with its
435 // bottom edge horizontal and a corner lands on a proper top-vertex-up
436 // isometric — always the orientation that rotates the camera the least.
437 let kind = brep_gizmos::view_cube::ViewCube::region_kind(handle);
438 let dirf = [dir[0] as f64, dir[1] as f64, dir[2] as f64];
439 let up = snap_view_up(kind, dirf, self.camera.up, fallback_up);
440 self.apply_look_direction(dir, up);
441 self.dirty = true;
442 true
443 }
444
445 /// Reorient the camera to look along `dir` (world eye→target) with `up`,
446 /// preserving the current pivot distance.
447 pub(super) fn apply_look_direction(&mut self, dir: [f32; 3], up: [f32; 3]) {
448 let dir = [dir[0] as f64, dir[1] as f64, dir[2] as f64];
449 let dist = self.camera.distance();
450 self.camera.eye = [
451 self.camera.target[0] - dir[0] * dist,
452 self.camera.target[1] - dir[1] * dist,
453 self.camera.target[2] - dir[2] * dist,
454 ];
455 self.camera.up = [up[0] as f64, up[1] as f64, up[2] as f64];
456 }
457
458 /// Apply a ViewCube navigation-arrow rotation to the CURRENT camera (a
459 /// relative 90° orbit / roll), keeping the pivot (`target`) fixed. The
460 /// rotation axes are the camera's own screen axes so the motion follows the
461 /// on-screen arrow direction: the eye moves toward the pan arrow it points
462 /// at, and the roll arcs spin the up vector about the view direction.
463 fn apply_viewcube_arrow(&mut self, handle: u32) {
464 use crate::view::{add3, rotate3, sub3};
465 use brep_gizmos::view_cube::ViewCube;
466 // World-space screen axes of the current view: right, up, forward(eye→target).
467 let (right, up_axis, fwd) = self.camera.basis();
468 let target = self.camera.target;
469 let rel = sub3(self.camera.eye, target); // eye relative to pivot
470 let q = std::f64::consts::FRAC_PI_2; // 90° per click
471 match handle {
472 // Orbit about the screen-up axis; eye moves toward the arrow side.
473 ViewCube::ARROW_RIGHT => {
474 self.camera.eye = add3(target, rotate3(rel, up_axis, q));
475 }
476 ViewCube::ARROW_LEFT => {
477 self.camera.eye = add3(target, rotate3(rel, up_axis, -q));
478 }
479 // Orbit about the screen-right axis; carry the up vector along so the
480 // view stays upright (eye moves toward the arrow side).
481 ViewCube::ARROW_UP => {
482 self.camera.eye = add3(target, rotate3(rel, right, -q));
483 self.camera.up = rotate3(self.camera.up, right, -q);
484 }
485 ViewCube::ARROW_DOWN => {
486 self.camera.eye = add3(target, rotate3(rel, right, q));
487 self.camera.up = rotate3(self.camera.up, right, q);
488 }
489 // Roll about the view direction; only the up vector changes.
490 ViewCube::ROLL_CCW => {
491 self.camera.up = rotate3(self.camera.up, fwd, q);
492 }
493 ViewCube::ROLL_CW => {
494 self.camera.up = rotate3(self.camera.up, fwd, -q);
495 }
496 _ => {}
497 }
498 }
499
500 /// Pick the datum plane/axis under a screen pixel; returns its name (empty
501 /// when none).
502 ///
503 /// NOT the selection path any more: construction planes are ordinary pick
504 /// candidates ([`Self::pick_candidates_at`] → the widget's `datum_plane_hits`,
505 /// which reports EVERY card the ray crosses rather than the first), so the
506 /// viewport click router no longer calls this. It survives as the AXIS-aware
507 /// second line of defense inside [`Self::ref_select_click`]'s total-miss arm.
508 pub fn datum_pick(&self, x: f64, y: f64) -> String {
509 self.widgets
510 .datum_pick(&gizmo_camera(&self.camera), x as f32, y as f32)
511 .unwrap_or_default()
512 }
513
514 /// Update the transform-gizmo hover from a screen pixel; returns the handle
515 /// under the pointer (0 = none). Marks dirty when the highlight changed.
516 pub fn transform_hover(&mut self, x: f64, y: f64) -> u32 {
517 let cam = gizmo_camera(&self.camera);
518 let handle = self.widgets.transform_hit(&cam, x as f32, y as f32);
519 if self.widgets.set_transform_hover(handle) {
520 self.dirty = true;
521 }
522 handle
523 }
524
525 /// The transform-gizmo handle under a screen pixel (0 = none) — the host
526 /// echoes it back to start a drag.
527 pub fn transform_pick(&self, x: f64, y: f64) -> u32 {
528 self.widgets.transform_hit(&gizmo_camera(&self.camera), x as f32, y as f32)
529 }
530
531 /// Compute a transform drag (frame-space + world delta) as JSON for the
532 /// feature-edit commit. Marks the handle active for the highlight.
533 pub fn transform_drag(
534 &mut self,
535 handle: u32,
536 sx: f64,
537 sy: f64,
538 cx: f64,
539 cy: f64,
540 ) -> String {
541 let cam = gizmo_camera(&self.camera);
542 self.widgets.set_transform_active(handle);
543 self.dirty = true;
544 self.widgets
545 .transform_drag_json(&cam, handle, sx as f32, sy as f32, cx as f32, cy as f32)
546 }
547
548 pub fn transform_drag_end(&mut self) {
549 self.widgets.set_transform_active(0);
550 self.dirty = true;
551 }
552
553 /// Per-dimension label placement: `[{id, anchor:[x,y,z],
554 /// screen:[sx,sy,inFront]}]` — the host pins each text label at `screen`.
555 pub fn dimension_anchors_json(&self) -> String {
556 let anchors = self.widgets.dimension_anchors(&gizmo_camera(&self.camera));
557 let out: Vec<serde_json::Value> = anchors
558 .into_iter()
559 .map(|(id, p)| {
560 let world = [p[0] as f64, p[1] as f64, p[2] as f64];
561 let (sx, sy, _) = self.camera.project(world);
562 // Same ONE label policy as `world_to_screen_json` — near/far
563 // never cull; off-viewport anchors hide their label.
564 let visible = if self.camera.label_anchor_visible(world) { 1.0 } else { 0.0 };
565 serde_json::json!({
566 "id": id,
567 "anchor": p,
568 "screen": [sx, sy, visible],
569 })
570 })
571 .collect();
572 serde_json::to_string(&out).unwrap_or_else(|_| "[]".to_string())
573 }
574
575 // --- Undo / redo (engine-owned) ---------------------------------------
576 //
577 // The model is engine-owned, so its undo history lives in the engine core
578 // too: `History` holds the stacks and snapshots itself BEFORE each model
579 // mutation (edit / add / delete / reorder), while roll-to-step is view state
580 // and is NOT snapshotted. The UI only TRIGGERS these; it never holds a stack.
581
582}
583
584/// Choose the camera `up` when the ViewCube snaps to a face / edge / corner.
585///
586/// `dir` is the world eye→target direction the view snaps to
587/// ([`brep_gizmos::view_cube::ViewCube::target_view`]): axis-aligned for a face,
588/// a 45° blend for an edge, a body-diagonal for a corner. `current_up` is the
589/// live camera up; `fallback` the region's canonical up.
590///
591/// The roll is snapped to a DISCRETE set and the member closest to the current
592/// up wins (max dot ⇒ least roll), so the reorient rotates by the smallest angle
593/// while still landing "level":
594/// - **face** (`kind == 1`): the 4 signed world axes lying in the face plane
595/// (the two axes `dir` is perpendicular to) — the face ends flat-on with its
596/// bottom edge horizontal, choosing whichever of the 4 edges was already
597/// nearest the top.
598/// - **corner** (`kind == 3`): the 3 cube axes that point up for this corner
599/// (top-vertex-up isometric), 120° apart — the axis whose sign opposes each
600/// component of `dir` (so the near vertex reads upright, not inverted).
601/// - **edge / other**: no discrete set — the current up is projected onto the
602/// plane ⟂ `dir` (free roll preserved), falling back to `fallback` when that
603/// projection degenerates (up nearly parallel to `dir`).
604pub(super) fn snap_view_up(
605 kind: u8,
606 dir: [f64; 3],
607 current_up: [f64; 3],
608 fallback: [f32; 3],
609) -> [f32; 3] {
610 let mut candidates: Vec<[f64; 3]> = Vec::new();
611 match kind {
612 // Face: both signs of each axis the (axis-aligned) view dir is ⟂ to.
613 1 => {
614 for a in 0..3 {
615 if dir[a].abs() < 0.5 {
616 let mut p = [0.0; 3];
617 p[a] = 1.0;
618 candidates.push(p);
619 p[a] = -1.0;
620 candidates.push(p);
621 }
622 }
623 }
624 // Corner: the axis direction opposite each component of the view dir
625 // (dir = -normalize(signs), so -sign(dir[a]) recovers the corner's sign).
626 3 => {
627 for a in 0..3 {
628 let mut p = [0.0; 3];
629 p[a] = -dir[a].signum();
630 candidates.push(p);
631 }
632 }
633 _ => {}
634 }
635
636 let dot = |v: &[f64; 3]| v[0] * current_up[0] + v[1] * current_up[1] + v[2] * current_up[2];
637 // An EXACT tie — the current up perpendicular to two candidates, as from
638 // an ISO onto its TOP face — goes to the candidate nearest the region's
639 // own up, not to whichever the loop listed last. The listing order only
640 // happened to give TOP's −Z in the Y-up frame; in the board frame it gave
641 // the TOP view upside down (the layout's +Y down the screen).
642 let score = |v: &[f64; 3]| {
643 dot(v) + 1e-6 * (v[0] * fallback[0] as f64 + v[1] * fallback[1] as f64 + v[2] * fallback[2] as f64)
644 };
645 if let Some(best) = candidates
646 .into_iter()
647 .max_by(|x, y| score(x).partial_cmp(&score(y)).unwrap_or(std::cmp::Ordering::Equal))
648 {
649 return [best[0] as f32, best[1] as f32, best[2] as f32];
650 }
651
652 // Edge / fallback: project the current up onto the plane ⟂ dir (keep roll).
653 let d = dot(&dir);
654 let proj = [
655 current_up[0] - dir[0] * d,
656 current_up[1] - dir[1] * d,
657 current_up[2] - dir[2] * d,
658 ];
659 let len = (proj[0] * proj[0] + proj[1] * proj[1] + proj[2] * proj[2]).sqrt();
660 if len > 1e-4 {
661 [
662 (proj[0] / len) as f32,
663 (proj[1] / len) as f32,
664 (proj[2] / len) as f32,
665 ]
666 } else {
667 fallback
668 }
669}
670
671/// Serialize a screen-space [`brep_gizmos::hit_region::HitShape`] to the gizmo
672/// hit-area JSON schema the app strokes: `{ kind:"capsule", a:[x,y], b:[x,y], r }`
673/// or `{ kind:"circle", c:[x,y], r }` — viewport-local px, so the app only offsets
674/// by `rect.min`. The engine hit-tests these SAME shapes, so the drawn outline can
675/// never drift from the pickable region. Shared by both gizmo exposers.
676pub(super) fn hit_shape_json(shape: &brep_gizmos::hit_region::HitShape) -> serde_json::Value {
677 use brep_gizmos::hit_region::HitShape;
678 match *shape {
679 HitShape::Capsule { a, b, r } => {
680 serde_json::json!({ "kind": "capsule", "a": a, "b": b, "r": r })
681 }
682 HitShape::Circle { c, r } => serde_json::json!({ "kind": "circle", "c": c, "r": r }),
683 }
684}
685
686/// Serialize an iterator of [`brep_gizmos::hit_region::HitShape`]s to the app's
687/// gizmo hit-area JSON array (see [`hit_shape_json`]); `"[]"` on failure.
688pub(super) fn hit_shapes_json<'a>(
689 shapes: impl Iterator<Item = &'a brep_gizmos::hit_region::HitShape>,
690) -> String {
691 let out: Vec<serde_json::Value> = shapes.map(hit_shape_json).collect();
692 serde_json::to_string(&out).unwrap_or_else(|_| "[]".to_string())
693}
694
695
696