1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
//! The interactive viewer camera (R21/R25): orthographic default + perspective
//! toggle with state-preserving switch, zoom-to-fit, dynamic depth-range fit,
//! world-per-pixel and world→screen queries. Pure f64 math — shared verbatim by
//! the wasm canvas shell and the winit desktop shell (dual-target directive).
//!
//! Screen coordinates throughout are CSS pixels with the origin at the canvas
//! top-left, y down (what browser pointer events deliver); the DPR only matters at
//! surface-size time, never in camera math (matching the retired viewer, whose
//! thresholds were CSS-pixel based).
use crate::camera::{Aabb, Camera};
pub fn norm3(v: [f64; 3]) -> [f64; 3] {
let len = (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt();
if len <= 0.0 {
return [0.0, 0.0, 1.0];
}
[v[0] / len, v[1] / len, v[2] / len]
}
pub fn cross3(a: [f64; 3], b: [f64; 3]) -> [f64; 3] {
[
a[1] * b[2] - a[2] * b[1],
a[2] * b[0] - a[0] * b[2],
a[0] * b[1] - a[1] * b[0],
]
}
pub fn dot3(a: [f64; 3], b: [f64; 3]) -> f64 {
a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
}
pub fn sub3(a: [f64; 3], b: [f64; 3]) -> [f64; 3] {
[a[0] - b[0], a[1] - b[1], a[2] - b[2]]
}
pub fn add3(a: [f64; 3], b: [f64; 3]) -> [f64; 3] {
[a[0] + b[0], a[1] + b[1], a[2] + b[2]]
}
pub fn scale3(a: [f64; 3], s: f64) -> [f64; 3] {
[a[0] * s, a[1] * s, a[2] * s]
}
pub fn len3(a: [f64; 3]) -> f64 {
dot3(a, a).sqrt()
}
/// Rotate `v` around unit `axis` by `angle` (Rodrigues).
pub fn rotate3(v: [f64; 3], axis: [f64; 3], angle: f64) -> [f64; 3] {
let (sin, cos) = angle.sin_cos();
let cross = cross3(axis, v);
let dot = dot3(axis, v);
[
v[0] * cos + cross[0] * sin + axis[0] * dot * (1.0 - cos),
v[1] * cos + cross[1] * sin + axis[1] * dot * (1.0 - cos),
v[2] * cos + cross[2] * sin + axis[2] * dot * (1.0 - cos),
]
}
/// Inverse of a column-major 4×4 matrix (index = `col*4 + row`
/// layout). Returns `None` if singular. Used to invert the view-projection for
/// the host overlays' screen→world path.
pub fn invert4_columns(m: &[f64; 16]) -> Option<[f64; 16]> {
let a00 = m[0]; let a01 = m[1]; let a02 = m[2]; let a03 = m[3];
let a10 = m[4]; let a11 = m[5]; let a12 = m[6]; let a13 = m[7];
let a20 = m[8]; let a21 = m[9]; let a22 = m[10]; let a23 = m[11];
let a30 = m[12]; let a31 = m[13]; let a32 = m[14]; let a33 = m[15];
let b00 = a00 * a11 - a01 * a10;
let b01 = a00 * a12 - a02 * a10;
let b02 = a00 * a13 - a03 * a10;
let b03 = a01 * a12 - a02 * a11;
let b04 = a01 * a13 - a03 * a11;
let b05 = a02 * a13 - a03 * a12;
let b06 = a20 * a31 - a21 * a30;
let b07 = a20 * a32 - a22 * a30;
let b08 = a20 * a33 - a23 * a30;
let b09 = a21 * a32 - a22 * a31;
let b10 = a21 * a33 - a23 * a31;
let b11 = a22 * a33 - a23 * a32;
let det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
if det.abs() < 1e-300 {
return None;
}
let inv = 1.0 / det;
Some([
(a11 * b11 - a12 * b10 + a13 * b09) * inv,
(a02 * b10 - a01 * b11 - a03 * b09) * inv,
(a31 * b05 - a32 * b04 + a33 * b03) * inv,
(a22 * b04 - a21 * b05 - a23 * b03) * inv,
(a12 * b08 - a10 * b11 - a13 * b07) * inv,
(a00 * b11 - a02 * b08 + a03 * b07) * inv,
(a32 * b02 - a30 * b05 - a33 * b01) * inv,
(a20 * b05 - a22 * b02 + a23 * b01) * inv,
(a10 * b10 - a11 * b08 + a13 * b06) * inv,
(a01 * b08 - a00 * b10 - a03 * b06) * inv,
(a30 * b04 - a31 * b02 + a33 * b00) * inv,
(a21 * b02 - a20 * b04 - a23 * b00) * inv,
(a11 * b07 - a10 * b09 - a12 * b06) * inv,
(a00 * b09 - a01 * b07 + a02 * b06) * inv,
(a31 * b01 - a30 * b03 - a32 * b00) * inv,
(a20 * b03 - a21 * b01 + a22 * b00) * inv,
])
}
/// The projection kind (R21): orthographic is the default; the toggle keeps the
/// apparent size at the target plane.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Projection {
/// `half_height` is half the vertical world span at the target plane.
Orthographic { half_height: f64 },
Perspective { fov_y_deg: f64 },
}
/// A world-space ray for picking.
#[derive(Debug, Clone, Copy)]
pub struct Ray {
pub origin: [f64; 3],
pub dir: [f64; 3],
}
#[derive(Debug, Clone)]
pub struct ViewCamera {
pub eye: [f64; 3],
pub target: [f64; 3],
pub up: [f64; 3],
pub projection: Projection,
/// Viewport CSS size.
pub width: f64,
pub height: f64,
/// View-space depth window (positive distances along the view direction);
/// maintained by [`ViewCamera::fit_depth_range`]. Ortho near may go
/// negative (scene behind the eye plane is still projectable).
///
/// DEPTH-BUFFER WINDOW ONLY. `near`/`far` exist to map the GPU depth buffer
/// over everything drawn (re-fitted each frame from the render path's
/// depth bbox = `depth_range_bbox` ∪ the full widget overlay's world bounds
/// ∪ the world origin, so construction geometry — datums / axes / gizmos —
/// is always bracketed) — they are NEVER a visibility decision. No label, anchor, chip, or hit-region may consult them: the
/// ONE screen-visibility rule for all of those is
/// [`ViewCamera::projectable`]. Anything gating on `near`/`far` (or a bare
/// `depth > 0` in ortho) is a bug — labels would vanish while their
/// geometry still renders.
pub near: f64,
pub far: f64,
}
impl Default for ViewCamera {
fn default() -> Self {
// The retired viewer's startup vantage: eye (15,12,15) → origin, Y-up,
// ortho half-height 10 ("viewSize").
Self {
eye: [15.0, 12.0, 15.0],
target: [0.0, 0.0, 0.0],
up: [0.0, 1.0, 0.0],
projection: Projection::Orthographic { half_height: 10.0 },
width: 800.0,
height: 600.0,
near: -100000.0,
far: 100000.0,
}
}
}
impl ViewCamera {
pub fn aspect(&self) -> f64 {
(self.width / self.height.max(1.0)).max(1e-6)
}
/// Camera basis: (right, true-up, forward) with forward pointing INTO the
/// scene (eye → target).
pub fn basis(&self) -> ([f64; 3], [f64; 3], [f64; 3]) {
let forward = norm3(sub3(self.target, self.eye));
let right = norm3(cross3(forward, self.up));
let up = cross3(right, forward);
(right, up, forward)
}
pub fn distance(&self) -> f64 {
len3(sub3(self.eye, self.target)).max(1e-9)
}
/// World units per CSS pixel at the target plane (R21/R25 — the query the
/// pickers, gizmos and sketch glyph sizing key off).
pub fn world_per_pixel(&self) -> f64 {
match self.projection {
Projection::Orthographic { half_height } => 2.0 * half_height / self.height.max(1.0),
Projection::Perspective { fov_y_deg } => {
let fov = fov_y_deg.to_radians();
2.0 * (fov * 0.5).tan() * self.distance() / self.height.max(1.0)
}
}
}
/// The view-space depth of a world point: the signed distance along the
/// forward view axis from the eye (identical to `project`'s third return).
/// Positive in front of the eye plane. The screen-space region builder
/// ([`brep_gizmos::hit_region`]) keys the perspective front-clip off this.
pub fn view_depth(&self, world: [f64; 3]) -> f64 {
let (_, _, forward) = self.basis();
dot3(sub3(world, self.eye), forward)
}
/// Whether a world point is PROJECTABLE to a usable screen position — THE
/// screen-visibility policy for every label / anchor / chip / hit-region
/// consumer, in ONE place so no consumer can re-invent a depth cull:
///
/// * ORTHOGRAPHIC (the app default): always `true`. Behind-eye-plane
/// geometry still renders in ortho, so its labels must too.
/// * PERSPECTIVE: `false` only for a point at/behind the eye plane, where
/// the projection itself is mathematically undefined — the same
/// `FRONT_EPS` rule the region builder ([`brep_gizmos::hit_region`])
/// applies.
///
/// The `near`/`far` fields NEVER factor in — they are the GPU depth-buffer
/// window (see their field doc), not visibility. Route ANY new "should this
/// world-anchored UI draw?" question through here.
pub fn projectable(&self, world: [f64; 3]) -> bool {
matches!(self.projection, Projection::Orthographic { .. })
|| self.view_depth(world) > 1e-6
}
/// Whether a world-anchored TEXT LABEL should draw: [`Self::projectable`]
/// AND the anchor projects INSIDE the viewport rect. The second half is a
/// screen-BOUNDS test, never a depth test — `near`/`far` still cull nothing
/// (see [`Self::projectable`]) — so a chip whose 3D anchor scrolled out of
/// view disappears instead of piling up clamped at the viewport edge (egui
/// Areas constrain themselves on-screen). This is the `inFront` flag every
/// app label pass keys its skip off (`world_to_screen_json`); hit-testable
/// ANCHORS (gizmo handles, hit regions) intentionally stay on the pure
/// `projectable` policy — an off-screen handle just can't be clicked.
pub fn label_anchor_visible(&self, world: [f64; 3]) -> bool {
if !self.projectable(world) {
return false;
}
let (sx, sy, _) = self.project(world);
sx >= 0.0 && sx <= self.width && sy >= 0.0 && sy <= self.height
}
/// The world→clip view-projection as column-major `[col][row]` in f64. This
/// is the exact matrix [`resolve`] feeds the GPU, kept in f64 so the
/// CSS-pixel projection the host overlays derive from it matches [`project`]
/// to sub-pixel precision. wgpu clip space: x,y in −1..1, z in 0..1.
pub fn view_proj_cols(&self) -> [[f64; 4]; 4] {
let (right, up, forward) = self.basis();
let half_h = match self.projection {
Projection::Orthographic { half_height } => half_height,
Projection::Perspective { fov_y_deg } => (fov_y_deg.to_radians() * 0.5).tan(),
};
let half_w = half_h * self.aspect();
// View matrix rows from the basis (world → view; view looks down -Z).
let ex = -dot3(right, self.eye);
let ey = -dot3(up, self.eye);
let ez = dot3(forward, self.eye);
let view = [
[right[0], up[0], -forward[0], 0.0],
[right[1], up[1], -forward[1], 0.0],
[right[2], up[2], -forward[2], 0.0],
[ex, ey, ez, 1.0],
];
let proj = match self.projection {
Projection::Orthographic { .. } => {
// wgpu clip space: z in 0..1.
let sx = 1.0 / half_w;
let sy = 1.0 / half_h;
let sz = -1.0 / (self.far - self.near);
[
[sx, 0.0, 0.0, 0.0],
[0.0, sy, 0.0, 0.0],
[0.0, 0.0, sz, 0.0],
[0.0, 0.0, -self.near / (self.far - self.near), 1.0],
]
}
Projection::Perspective { .. } => {
// Finite-far wgpu perspective (z in 0..1, forward-Z: near→0,
// far→1). TODO(depth): an INFINITE-FAR limit (col2 → [0,0,-1,-1],
// col3 → [0,0,-near,0]) would stop anything clipping at `far` in
// perspective, but is DEFERRED: the screen→ray unproject in
// `GizmoCamera::ray_from_screen` (datum pick, transform drag,
// ViewCube — all in `brep-gizmos`) reconstructs rays from NDC
// z=0 AND z=1, and at z=1 the infinite-far inverse's w passes
// through zero as the camera orbits → intermittently backward
// pick rays. It is also redundant now: the render path folds the
// FULL overlay (+origin) into the depth fit, so construction
// geometry is bracketed regardless. Revisit alongside a
// reversed-Z depth precision pass (would fix the unproject too).
let near = self.near.max(1e-6);
let far = self.far.max(near * 1.0001);
let f = 1.0 / half_h;
[
[f / self.aspect(), 0.0, 0.0, 0.0],
[0.0, f, 0.0, 0.0],
[0.0, 0.0, far / (near - far), -1.0],
[0.0, 0.0, near * far / (near - far), 0.0],
]
}
};
let mut view_proj = [[0.0f64; 4]; 4];
for col in 0..4 {
for row in 0..4 {
let mut sum = 0.0;
for k in 0..4 {
sum += proj[k][row] * view[col][k];
}
view_proj[col][row] = sum;
}
}
view_proj
}
/// Resolve to the GPU camera (column-major view-proj, f32).
pub fn resolve(&self) -> Camera {
let cols = self.view_proj_cols();
let mut view_proj = [[0.0f32; 4]; 4];
for col in 0..4 {
for row in 0..4 {
view_proj[col][row] = cols[col][row] as f32;
}
}
let fwd = norm3(sub3(self.target, self.eye));
Camera {
view_proj,
forward: [fwd[0] as f32, fwd[1] as f32, fwd[2] as f32],
}
}
/// The view-projection flattened column-major (index = `col*4 + row`) — the
/// world→clip matrix for the host overlays'
/// per-frame world→screen hot path (dimensions + sketch), letting them drop
/// the compat mirror camera. Pair with the CSS `viewport` for NDC→pixel.
pub fn view_proj_flat(&self) -> [f64; 16] {
let cols = self.view_proj_cols();
let mut out = [0.0f64; 16];
for col in 0..4 {
for row in 0..4 {
out[col * 4 + row] = cols[col][row];
}
}
out
}
/// Inverse of [`view_proj_flat`] (clip→world), column-major, for the host
/// overlays' screen→world / screen→ray path. Falls back to the identity if
/// the matrix is singular (never in practice for a valid camera).
pub fn view_proj_inverse_flat(&self) -> [f64; 16] {
invert4_columns(&self.view_proj_flat())
.unwrap_or([1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0])
}
/// Project a world point to CSS-pixel screen coordinates (origin top-left,
/// y down). Returns `(x, y, view_depth)`; `view_depth` is the distance
/// along the view direction (positive in front of the eye plane).
pub fn project(&self, world: [f64; 3]) -> (f64, f64, f64) {
let (right, up, forward) = self.basis();
let rel = sub3(world, self.eye);
let vx = dot3(rel, right);
let vy = dot3(rel, up);
let depth = dot3(rel, forward);
match self.projection {
Projection::Orthographic { half_height } => {
let half_w = half_height * self.aspect();
let sx = (vx / half_w * 0.5 + 0.5) * self.width;
let sy = (0.5 - vy / half_height * 0.5) * self.height;
(sx, sy, depth)
}
Projection::Perspective { fov_y_deg } => {
let half_h = (fov_y_deg.to_radians() * 0.5).tan();
let half_w = half_h * self.aspect();
let d = depth.max(1e-9);
let sx = (vx / (half_w * d) * 0.5 + 0.5) * self.width;
let sy = (0.5 - vy / (half_h * d) * 0.5) * self.height;
(sx, sy, depth)
}
}
}
/// A world-space picking ray through CSS-pixel `(x, y)`. Ortho rays start
/// far behind the eye plane so huge scenes are always in front (the retired
/// picker pushed its ray origin back the same way).
pub fn pick_ray(&self, x: f64, y: f64) -> Ray {
let (right, up, forward) = self.basis();
let ndc_x = (x / self.width.max(1.0)) * 2.0 - 1.0;
let ndc_y = -((y / self.height.max(1.0)) * 2.0 - 1.0);
match self.projection {
Projection::Orthographic { half_height } => {
let half_w = half_height * self.aspect();
let span = self.far.abs().max(self.near.abs()).max(half_height * 40.0).max(1.0);
let on_plane = add3(
self.eye,
add3(scale3(right, ndc_x * half_w), scale3(up, ndc_y * half_height)),
);
Ray {
origin: sub3(on_plane, scale3(forward, span)),
dir: forward,
}
}
Projection::Perspective { fov_y_deg } => {
let half_h = (fov_y_deg.to_radians() * 0.5).tan();
let half_w = half_h * self.aspect();
let dir = norm3(add3(
forward,
add3(scale3(right, ndc_x * half_w), scale3(up, ndc_y * half_h)),
));
Ray {
origin: self.eye,
dir,
}
}
}
}
/// Fit the depth window to the scene (the `_updateDepthRange` port): the
/// whole bbox lands inside `[near, far]` with generous padding.
pub fn fit_depth_range(&mut self, bbox: &Aabb) {
if bbox.is_empty() {
// An EMPTY input (no solids, no overlay geometry) must NOT ride the
// stale near/far from an earlier populated frame — that stale-tight
// window would CLIP a newly-shown construction-only scene (datum
// planes / world axes / gizmos). Reset to the SAME generous window
// the camera constructs with (see `Default`: ortho ±100000;
// perspective a sane 0.1 / 1e5) so an empty scene never clips. This
// is a depth-WINDOW choice only — near/far are the depth-buffer
// range, never a visibility decision (see their field doc).
match self.projection {
Projection::Orthographic { .. } => {
self.near = -100000.0;
self.far = 100000.0;
}
Projection::Perspective { .. } => {
self.near = 0.1;
self.far = 1e5;
}
}
return;
}
let (_, _, forward) = self.basis();
let mut min_d = f64::INFINITY;
let mut max_d = f64::NEG_INFINITY;
for i in 0..8 {
let corner = [
if i & 1 == 0 { bbox.min[0] } else { bbox.max[0] },
if i & 2 == 0 { bbox.min[1] } else { bbox.max[1] },
if i & 4 == 0 { bbox.min[2] } else { bbox.max[2] },
];
let d = dot3(sub3(corner, self.eye), forward);
min_d = min_d.min(d);
max_d = max_d.max(d);
}
let diag = len3(sub3(bbox.max, bbox.min));
let pad = ((max_d - min_d) * 0.1).max(diag * 0.1).max(0.5);
match self.projection {
Projection::Orthographic { .. } => {
self.near = min_d - pad;
self.far = max_d + pad;
}
Projection::Perspective { .. } => {
let far = (max_d + pad).max(1.0);
self.near = (far * 0.001).clamp(1e-4, 1.0).min((min_d - pad).max(1e-4));
self.far = far;
}
}
}
/// Zoom-to-fit (R21): recenters the target on the bbox and scales the
/// frustum/distance so the whole bbox fits with `margin`, preserving the
/// view direction (the ArcballControls `focus` behavior).
pub fn zoom_to_fit(&mut self, bbox: &Aabb, margin: f64) {
if bbox.is_empty() {
return;
}
let margin = margin.max(1.0);
let (right, up, forward) = self.basis();
let center = bbox.center();
let mut half_w = 0.0f64;
let mut half_h = 0.0f64;
for i in 0..8 {
let corner = [
if i & 1 == 0 { bbox.min[0] } else { bbox.max[0] },
if i & 2 == 0 { bbox.min[1] } else { bbox.max[1] },
if i & 4 == 0 { bbox.min[2] } else { bbox.max[2] },
];
let rel = sub3(corner, center);
half_w = half_w.max(dot3(rel, right).abs());
half_h = half_h.max(dot3(rel, up).abs());
}
half_w = (half_w * margin).max(1e-6);
half_h = (half_h * margin).max(1e-6);
let dist = self.distance();
let aspect = self.aspect();
self.target = center;
match self.projection {
Projection::Orthographic { ref mut half_height } => {
*half_height = half_h.max(half_w / aspect);
self.eye = sub3(center, scale3(forward, dist));
}
Projection::Perspective { fov_y_deg } => {
let fov = fov_y_deg.to_radians();
let dist_h = half_h / (fov * 0.5).tan().max(1e-6);
let tan_half_h_fov = (fov * 0.5).tan() * aspect;
let dist_w = half_w / tan_half_h_fov.max(1e-6);
let target_dist = dist_h.max(dist_w).max(1e-3);
self.eye = sub3(center, scale3(forward, target_dist));
}
}
self.fit_depth_range(bbox);
}
/// Toggle ortho ↔ perspective preserving the apparent size at the target
/// plane (the `toggleCameraProjection` port). Returns the new kind name.
pub fn toggle_projection(&mut self) -> &'static str {
const FOV: f64 = 50.0;
let forward = norm3(sub3(self.target, self.eye));
match self.projection {
Projection::Orthographic { half_height } => {
let denom = (FOV.to_radians() * 0.5).tan();
let mut distance = half_height / denom.max(1e-9);
if !distance.is_finite() || distance < 1e-4 {
distance = 10.0;
}
self.eye = sub3(self.target, scale3(forward, distance));
self.projection = Projection::Perspective { fov_y_deg: FOV };
"perspective"
}
Projection::Perspective { fov_y_deg } => {
let dist = self.distance();
let half_height = ((fov_y_deg.to_radians() * 0.5).tan() * dist).max(1e-6);
self.projection = Projection::Orthographic { half_height };
"orthographic"
}
}
}
/// Snap to a standard view (future ViewCube seam), preserving distance and
/// frustum scale. Directions are world-axis views with sensible ups.
pub fn standard_view(&mut self, name: &str) -> bool {
let dist = self.distance();
let iso = norm3([1.0, 1.0, 1.0]);
let (dir, up): ([f64; 3], [f64; 3]) = match name.to_ascii_uppercase().as_str() {
"FRONT" => ([0.0, 0.0, 1.0], [0.0, 1.0, 0.0]),
"BACK" => ([0.0, 0.0, -1.0], [0.0, 1.0, 0.0]),
"RIGHT" => ([1.0, 0.0, 0.0], [0.0, 1.0, 0.0]),
"LEFT" => ([-1.0, 0.0, 0.0], [0.0, 1.0, 0.0]),
"TOP" => ([0.0, 1.0, 0.0], [0.0, 0.0, -1.0]),
"BOTTOM" => ([0.0, -1.0, 0.0], [0.0, 0.0, 1.0]),
"ISO" => (iso, [0.0, 1.0, 0.0]),
_ => return false,
};
self.eye = add3(self.target, scale3(dir, dist));
self.up = up;
true
}
/// Serialize the full camera state (R3: the host holds plain JSON only).
pub fn state_json(&self) -> String {
let (kind, scale) = match self.projection {
Projection::Orthographic { half_height } => ("orthographic", half_height),
Projection::Perspective { fov_y_deg } => ("perspective", fov_y_deg),
};
serde_json::json!({
"kind": kind,
"eye": self.eye,
"target": self.target,
"up": self.up,
// half_height for ortho, fov_y_deg for perspective.
"scale": scale,
"near": self.near,
"far": self.far,
"width": self.width,
"height": self.height,
"worldPerPixel": self.world_per_pixel(),
})
.to_string()
}
/// Restore from [`ViewCamera::state_json`] output (viewport size is NOT
/// restored — it belongs to the canvas).
pub fn apply_state_json(&mut self, json: &str) -> Result<(), String> {
let value: serde_json::Value =
serde_json::from_str(json).map_err(|error| format!("camera state parse: {error}"))?;
let vec3 = |key: &str| -> Option<[f64; 3]> {
let arr = value.get(key)?.as_array()?;
Some([arr.first()?.as_f64()?, arr.get(1)?.as_f64()?, arr.get(2)?.as_f64()?])
};
if let Some(eye) = vec3("eye") {
self.eye = eye;
}
if let Some(target) = vec3("target") {
self.target = target;
}
if let Some(up) = vec3("up") {
self.up = up;
}
let scale = value.get("scale").and_then(|v| v.as_f64());
match value.get("kind").and_then(|v| v.as_str()) {
Some("perspective") => {
self.projection = Projection::Perspective {
fov_y_deg: scale.unwrap_or(50.0),
}
}
Some("orthographic") => {
self.projection = Projection::Orthographic {
half_height: scale.unwrap_or(10.0).max(1e-9),
}
}
_ => {}
}
if let Some(near) = value.get("near").and_then(|v| v.as_f64()) {
self.near = near;
}
if let Some(far) = value.get("far").and_then(|v| v.as_f64()) {
self.far = far;
}
Ok(())
}
}
/// The render camera projects dimension-gizmo handle points to viewport-local px
/// for the shared screen-space region builder, so a gizmo's hit-test + its debug
/// outline share ONE projection (see [`brep_gizmos::hit_region`]).
impl brep_gizmos::hit_region::RegionCamera for ViewCamera {
fn is_orthographic(&self) -> bool {
matches!(self.projection, Projection::Orthographic { .. })
}
fn depth(&self, p: [f64; 3]) -> f64 {
self.view_depth(p)
}
fn project_px(&self, p: [f64; 3]) -> Option<[f32; 2]> {
// ONE policy: [`ViewCamera::projectable`] (ortho always projects;
// perspective omits only at/behind the eye plane).
if !self.projectable(p) {
return None;
}
let (sx, sy, _) = self.project(p);
Some([sx as f32, sy as f32])
}
}
#[cfg(test)]
mod tests {
use super::*;
fn unit_bbox() -> Aabb {
Aabb {
min: [-5.0, -5.0, -5.0],
max: [5.0, 5.0, 5.0],
}
}
/// THE near/far regression fence: `projectable` — the one screen-visibility
/// policy every label/anchor/chip flag derives from — must NEVER cull by the
/// depth window. Ortho projects EVERYTHING (behind the eye plane, beyond
/// `far`, before `near` — ortho renders all of it); perspective refuses only
/// at/behind the eye plane, no matter how tight `near`/`far` are. If this
/// test breaks, labels are vanishing while their geometry still renders.
#[test]
fn projectable_ignores_near_far_and_ortho_never_culls() {
let mut camera = ViewCamera::default(); // ortho, eye (15,12,15) → origin
// A hostile depth window: nothing may consult it.
camera.near = 0.5;
camera.far = 1.0;
// Ortho: in front, far behind the eye plane, and light-years out — all
// projectable (and `project` yields finite coords for each).
let (_, _, fwd) = camera.basis();
let behind_eye = sub3(camera.eye, scale3(fwd, 500.0));
let beyond_far = add3(camera.eye, scale3(fwd, 90000.0));
for p in [[0.0, 0.0, 0.0], behind_eye, beyond_far] {
assert!(camera.projectable(p), "ortho must project {p:?}");
let (sx, sy, _) = camera.project(p);
assert!(sx.is_finite() && sy.is_finite());
}
// Perspective: the SAME hostile near/far still never cull — only the
// eye plane does (projection is undefined at/behind it).
camera.projection = Projection::Perspective { fov_y_deg: 45.0 };
assert!(camera.projectable([0.0, 0.0, 0.0]), "in front projects");
assert!(
camera.projectable(beyond_far),
"beyond `far` still projects in perspective — far never culls"
);
assert!(
!camera.projectable(behind_eye),
"behind the eye plane cannot project in perspective"
);
// And the RegionCamera view agrees (hit outlines share the policy).
use brep_gizmos::hit_region::RegionCamera;
assert!(camera.project_px(beyond_far).is_some());
assert!(camera.project_px(behind_eye).is_none());
}
/// The label layer on top of `projectable`: a chip draws ONLY when its 3D
/// anchor projects inside the viewport — an off-screen anchor hides its
/// label (instead of the egui Area clamping it to the edge) — while depth /
/// near / far still cull nothing (an ortho behind-eye anchor that lands
/// on-viewport keeps its label, matching its still-rendered geometry).
#[test]
fn label_anchor_visible_requires_on_viewport_projection() {
let mut camera = ViewCamera::default(); // ortho 800×600, eye → origin
let (right, _, fwd) = camera.basis();
// The target projects to the viewport center → label shown.
assert!(camera.label_anchor_visible(camera.target));
// Way off to the side (world units ≫ the ortho half-width) → the anchor
// projects outside the viewport → label hidden, even though the point
// is perfectly projectable.
let far_right = add3(camera.target, scale3(right, 1000.0));
assert!(camera.projectable(far_right), "still projectable…");
assert!(!camera.label_anchor_visible(far_right), "…but off-screen → no label");
// Ortho behind the eye plane but projecting on-viewport → label SHOWN
// (its geometry renders; the depth policy never culls).
let behind_on_screen = sub3(camera.target, scale3(fwd, 500.0));
assert!(camera.label_anchor_visible(behind_on_screen));
// Perspective behind the eye stays hidden (not projectable at all).
camera.projection = Projection::Perspective { fov_y_deg: 45.0 };
let behind_eye = sub3(camera.eye, scale3(fwd, 10.0));
assert!(!camera.label_anchor_visible(behind_eye));
}
#[test]
fn camera_state_roundtrip() {
let mut camera = ViewCamera::default();
camera.eye = [3.0, 4.0, 5.0];
camera.target = [1.0, 1.0, 1.0];
camera.projection = Projection::Orthographic { half_height: 7.25 };
let json = camera.state_json();
let mut restored = ViewCamera::default();
restored.apply_state_json(&json).unwrap();
assert_eq!(restored.eye, camera.eye);
assert_eq!(restored.target, camera.target);
assert_eq!(restored.projection, camera.projection);
}
#[test]
fn projection_toggle_preserves_apparent_size() {
let mut camera = ViewCamera {
width: 800.0,
height: 600.0,
..ViewCamera::default()
};
camera.zoom_to_fit(&unit_bbox(), 1.1);
let wpp_ortho = camera.world_per_pixel();
assert_eq!(camera.toggle_projection(), "perspective");
let wpp_persp = camera.world_per_pixel();
assert!(
(wpp_ortho - wpp_persp).abs() < wpp_ortho * 1e-9,
"wpp {wpp_ortho} vs {wpp_persp}"
);
assert_eq!(camera.toggle_projection(), "orthographic");
let wpp_back = camera.world_per_pixel();
assert!((wpp_ortho - wpp_back).abs() < wpp_ortho * 1e-9);
}
#[test]
fn zoom_to_fit_centers_and_contains_bbox() {
let bbox = Aabb {
min: [10.0, -2.0, 3.0],
max: [16.0, 6.0, 9.0],
};
let mut camera = ViewCamera {
width: 640.0,
height: 480.0,
..ViewCamera::default()
};
camera.zoom_to_fit(&bbox, 1.1);
let center = bbox.center();
let (sx, sy, depth) = camera.project(center);
assert!((sx - 320.0).abs() < 1e-6, "sx {sx}");
assert!((sy - 240.0).abs() < 1e-6, "sy {sy}");
assert!(depth > 0.0);
for i in 0..8 {
let corner = [
if i & 1 == 0 { bbox.min[0] } else { bbox.max[0] },
if i & 2 == 0 { bbox.min[1] } else { bbox.max[1] },
if i & 4 == 0 { bbox.min[2] } else { bbox.max[2] },
];
let (sx, sy, _) = camera.project(corner);
assert!((-1.0..=641.0).contains(&sx), "corner sx {sx}");
assert!((-1.0..=481.0).contains(&sy), "corner sy {sy}");
}
}
#[test]
fn project_and_pick_ray_are_consistent() {
let mut camera = ViewCamera::default();
camera.zoom_to_fit(&unit_bbox(), 1.1);
let world = [1.25, -0.5, 2.0];
let (sx, sy, _) = camera.project(world);
let ray = camera.pick_ray(sx, sy);
// The ray must pass within numerical tolerance of the world point.
let rel = sub3(world, ray.origin);
let along = dot3(rel, ray.dir);
let closest = add3(ray.origin, scale3(ray.dir, along));
assert!(len3(sub3(world, closest)) < 1e-9);
}
#[test]
fn depth_range_contains_scene() {
let mut camera = ViewCamera::default();
let bbox = unit_bbox();
camera.fit_depth_range(&bbox);
let (_, _, forward) = camera.basis();
for i in 0..8 {
let corner = [
if i & 1 == 0 { bbox.min[0] } else { bbox.max[0] },
if i & 2 == 0 { bbox.min[1] } else { bbox.max[1] },
if i & 4 == 0 { bbox.min[2] } else { bbox.max[2] },
];
let d = dot3(sub3(corner, camera.eye), forward);
assert!(d >= camera.near && d <= camera.far);
}
}
/// The staleness reset (the construction-clipping root cause): after fitting
/// to a small non-empty scene — which TIGHTENS near/far well inside the
/// default — fitting to an EMPTY scene must RESET to the generous default,
/// never ride the stale-tight window (that stale window is exactly what
/// clipped a newly-shown datum-only scene). Both projections.
#[test]
fn fit_depth_range_empty_resets_to_generous_default_not_stale() {
// A ±1 box tightens the window far inside the ±100000 default.
let small = Aabb {
min: [-1.0, -1.0, -1.0],
max: [1.0, 1.0, 1.0],
};
// Ortho: a small box tightens the window…
let mut camera = ViewCamera::default();
camera.fit_depth_range(&small);
assert!(
camera.near > -100000.0 && camera.far < 100000.0,
"a small scene must tighten the window: near {} far {}",
camera.near,
camera.far
);
// …then an EMPTY scene resets to the generous ortho default, NOT the
// stale-tight values (which would clip construction geometry).
camera.fit_depth_range(&Aabb::empty());
assert_eq!(camera.near, -100000.0);
assert_eq!(camera.far, 100000.0);
// Perspective: same policy, the sane perspective default.
let mut camera = ViewCamera {
projection: Projection::Perspective { fov_y_deg: 45.0 },
..ViewCamera::default()
};
camera.fit_depth_range(&small);
assert!(camera.far < 1e5, "small scene tightens far: {}", camera.far);
camera.fit_depth_range(&Aabb::empty());
assert_eq!(camera.near, 0.1);
assert_eq!(camera.far, 1e5);
}
/// A datum-only / overlay-only scene (no solids) still gets a depth window
/// that brackets it: fitting to an overlay bbox spanning the origin encloses
/// the origin and every corner between near and far, so construction
/// geometry never clips at the projection stage.
#[test]
fn fit_depth_range_brackets_overlay_only_bbox() {
let mut camera = ViewCamera::default();
// A world-sized datum plane spanning ±50 about the origin — the scene has
// no solids, so this overlay bbox is the ONLY depth-fit input.
let overlay = Aabb {
min: [-50.0, -50.0, -50.0],
max: [50.0, 50.0, 50.0],
};
camera.fit_depth_range(&overlay);
let (_, _, forward) = camera.basis();
// The origin and every corner sit inside [near, far].
let mut points = vec![[0.0, 0.0, 0.0]];
for i in 0..8 {
points.push([
if i & 1 == 0 { overlay.min[0] } else { overlay.max[0] },
if i & 2 == 0 { overlay.min[1] } else { overlay.max[1] },
if i & 4 == 0 { overlay.min[2] } else { overlay.max[2] },
]);
}
for p in points {
let d = dot3(sub3(p, camera.eye), forward);
assert!(
d >= camera.near && d <= camera.far,
"overlay point {p:?} depth {d} outside [{}, {}]",
camera.near,
camera.far
);
}
}
#[test]
fn standard_views_look_at_target() {
let mut camera = ViewCamera::default();
camera.target = [2.0, 3.0, 4.0];
let dist = camera.distance();
for name in ["FRONT", "BACK", "LEFT", "RIGHT", "TOP", "BOTTOM", "ISO"] {
assert!(camera.standard_view(name), "{name}");
assert!((camera.distance() - dist).abs() < 1e-9);
}
assert!(!camera.standard_view("DIAGONAL"));
}
/// Apply a column-major 4×4 (index = `col*4+row`) to a point with the
/// perspective divide — the exact math the host overlays run.
fn apply4(m: &[f64; 16], x: f64, y: f64, z: f64) -> [f64; 3] {
let w = 1.0 / (m[3] * x + m[7] * y + m[11] * z + m[15]);
[
(m[0] * x + m[4] * y + m[8] * z + m[12]) * w,
(m[1] * x + m[5] * y + m[9] * z + m[13]) * w,
(m[2] * x + m[6] * y + m[10] * z + m[14]) * w,
]
}
/// The CSS-pixel projection the host overlays build from `view_proj_flat`
/// (NDC→pixel with the same y-down convention) must match `project` — this
/// is what lets dimensions/sketch drop the mirror camera without drift.
#[test]
fn view_proj_flat_matches_project() {
for persp in [false, true] {
let mut camera = ViewCamera { width: 800.0, height: 600.0, ..ViewCamera::default() };
camera.zoom_to_fit(&unit_bbox(), 1.1);
if persp {
camera.toggle_projection();
}
let vp = camera.view_proj_flat();
for world in [[1.25, -0.5, 2.0], [-3.0, 4.0, -1.5], [0.0, 0.0, 0.0]] {
let clip = apply4(&vp, world[0], world[1], world[2]);
let sx = (clip[0] * 0.5 + 0.5) * camera.width;
let sy = (0.5 - clip[1] * 0.5) * camera.height;
let (px, py, _) = camera.project(world);
assert!((sx - px).abs() < 1e-6, "persp={persp} sx {sx} vs {px}");
assert!((sy - py).abs() < 1e-6, "persp={persp} sy {sy} vs {py}");
}
}
}
/// `view_proj_inverse_flat` must invert `view_proj_flat`, and unprojecting a
/// screen point at two clip depths must yield a ray hitting the world point
/// (the sketch screen→ray path).
#[test]
fn view_proj_inverse_round_trips_and_rays() {
for persp in [false, true] {
let mut camera = ViewCamera { width: 640.0, height: 480.0, ..ViewCamera::default() };
camera.zoom_to_fit(&unit_bbox(), 1.1);
if persp {
camera.toggle_projection();
}
let vp = camera.view_proj_flat();
let inv = camera.view_proj_inverse_flat();
let world = [1.25, -0.5, 2.0];
let clip = apply4(&vp, world[0], world[1], world[2]);
let back = apply4(&inv, clip[0], clip[1], clip[2]);
for k in 0..3 {
assert!((back[k] - world[k]).abs() < 1e-6, "persp={persp} roundtrip {back:?}");
}
// screen→ray: unproject NDC at wgpu near (z=0) and far (z=1).
let (sx, sy, _) = camera.project(world);
let ndc_x = (sx / camera.width) * 2.0 - 1.0;
let ndc_y = -((sy / camera.height) * 2.0 - 1.0);
let near = apply4(&inv, ndc_x, ndc_y, 0.0);
let far = apply4(&inv, ndc_x, ndc_y, 1.0);
let dir = norm3(sub3(far, near));
let rel = sub3(world, near);
let along = dot3(rel, dir);
let closest = add3(near, scale3(dir, along));
assert!(len3(sub3(world, closest)) < 1e-6, "persp={persp} ray miss");
}
}
}