1use lensbench_core::coating::{Coatings, C64};
13use lensbench_core::math::V3;
14use lensbench_core::par::scoped;
15use lensbench_core::system::{FieldSel, Launch, PolIn, RecSel, System};
16use lensbench_core::{invalid, Result};
17use rayon::prelude::*;
18
19fn czero() -> C64 {
20 C64::new(0.0, 0.0)
21}
22
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29pub struct PupilGrid {
30 g: usize,
31}
32
33impl PupilGrid {
34 pub fn new(g: usize) -> Self {
36 debug_assert!(
37 g >= 2,
38 "the pupil grid needs at least 2 points per side (got {g})"
39 );
40 Self { g }
41 }
42
43 #[inline]
45 pub fn g(&self) -> usize {
46 self.g
47 }
48
49 #[inline]
51 pub fn coords(&self, q: usize) -> [f64; 2] {
52 let g = self.g;
53 [
54 -1.0 + 2.0 * (q % g) as f64 / (g - 1) as f64,
55 -1.0 + 2.0 * (q / g) as f64 / (g - 1) as f64,
56 ]
57 }
58
59 #[inline]
61 pub fn inside(&self, q: usize) -> bool {
62 let [x, y] = self.coords(q);
63 x * x + y * y <= 1.0
64 }
65
66 pub fn rays(&self) -> (Vec<usize>, Vec<f64>, Vec<f64>) {
68 self.rays_where(|q| self.inside(q))
69 }
70
71 #[inline]
74 pub fn rim(&self, q: usize) -> bool {
75 let [x, y] = self.coords(q);
76 let h = 2.0 / (self.g - 1) as f64;
77 !self.inside(q) && x.hypot(y) <= 1.0 + 3.0 * h
79 }
80
81 pub fn rays_rim(&self) -> (Vec<usize>, Vec<f64>, Vec<f64>) {
83 self.rays_where(|q| self.inside(q) || self.rim(q))
84 }
85
86 fn rays_where(&self, f: impl Fn(usize) -> bool) -> (Vec<usize>, Vec<f64>, Vec<f64>) {
87 let idx: Vec<usize> = (0..self.g * self.g).filter(|&q| f(q)).collect();
88 let px = idx.iter().map(|&q| self.coords(q)[0]).collect();
89 let py = idx.iter().map(|&q| self.coords(q)[1]).collect();
90 (idx, px, py)
91 }
92}
93
94#[derive(Debug, Clone, PartialEq)]
96pub struct RayGrid {
97 pub g: usize,
98 pub ok: Vec<bool>,
100 pub xs: Vec<f64>,
102 pub ys: Vec<f64>,
103 pub sx: Vec<f64>,
105 pub sy: Vec<f64>,
106 pub l: Vec<Vec<f64>>,
109 pub ex: Vec<C64>,
111 pub ey: Vec<C64>,
112 pub mode_fallback: bool,
115}
116
117impl RayGrid {
118 pub fn new(g: usize, nw: usize) -> RayGrid {
119 let n = g * g;
120 RayGrid {
121 g,
122 ok: vec![false; n],
123 xs: vec![0.0; n],
124 ys: vec![0.0; n],
125 sx: vec![0.0; n],
126 sy: vec![0.0; n],
127 l: vec![vec![0.0; n]; nw],
128 ex: vec![czero(); n],
129 ey: vec![czero(); n],
130 mode_fallback: false,
131 }
132 }
133
134 pub fn check(&self) -> Result<()> {
136 let n = self.g * self.g;
137 if self.g < 2
138 || self.ok.len() != n
139 || [&self.xs, &self.ys, &self.sx, &self.sy]
140 .iter()
141 .any(|v| v.len() != n)
142 || self.l.is_empty()
143 || self.l.iter().any(|v| v.len() != n)
144 || self.ex.len() != n
145 || self.ey.len() != n
146 {
147 invalid!("the ray grid size doesn't match (G = {})", self.g);
148 }
149 Ok(())
150 }
151}
152
153#[derive(Debug, Clone)]
155pub struct PixelData {
156 pub n: usize,
157 pub x0: f64,
158 pub y0: f64,
159 pub dx: f64,
160 pub ok: Vec<bool>,
161 pub i: Vec<f64>,
163 pub l: Vec<Vec<f64>>,
164 pub ex: Vec<C64>,
165 pub ey: Vec<C64>,
166 pub fold_fraction: f64,
168}
169
170pub fn mode_weight(sx: f64, sy: f64, na: f64) -> f64 {
172 if na == f64::INFINITY {
173 return 1.0;
174 }
175 (-2.0 * (sx * sx + sy * sy) / (na * na)).exp() / (std::f64::consts::PI * na * na / 2.0)
176}
177
178fn tri_area(x: &[f64], y: &[f64], t: [usize; 3]) -> f64 {
179 0.5 * ((x[t[1]] - x[t[0]]) * (y[t[2]] - y[t[0]]) - (x[t[2]] - x[t[0]]) * (y[t[1]] - y[t[0]]))
180}
181
182pub fn rasterize(r: &RayGrid, npx: usize, x0: f64, y0: f64, dx: f64, na: f64) -> PixelData {
184 rasterize_with(r, None, npx, x0, y0, dx, na).0
185}
186
187pub fn rasterize_with(
190 r: &RayGrid,
191 extra: Option<&[C64]>,
192 npx: usize,
193 x0: f64,
194 y0: f64,
195 dx: f64,
196 na: f64,
197) -> (PixelData, Vec<C64>) {
198 let nw = r.l.len();
199 let g = r.g;
200 let mut tris = Vec::new();
201 for iy in 0..g - 1 {
202 for ix in 0..g - 1 {
203 let a = iy * g + ix;
204 let (b, c) = (a + 1, a + g);
205 let d = c + 1;
206 if r.ok[a] && r.ok[b] && r.ok[d] {
207 tris.push([a, b, d]);
208 }
209 if r.ok[a] && r.ok[d] && r.ok[c] {
210 tris.push([a, d, c]);
211 }
212 }
213 }
214 let pos = tris
216 .iter()
217 .filter(|t| tri_area(&r.xs, &r.ys, **t) > 0.0)
218 .count();
219 let sgn = if pos * 2 >= tris.len() { 1.0 } else { -1.0 };
220 let mut fold = 0usize;
221 let mut good: Vec<([usize; 3], f64, usize, usize)> = Vec::with_capacity(tris.len());
223 let last = npx as i64 - 1;
224 for t in &tris {
225 let a_s = tri_area(&r.xs, &r.ys, *t);
226 if a_s * sgn <= 0.0 {
227 fold += 1;
228 continue;
229 }
230 let a_d = tri_area(&r.sx, &r.sy, *t).abs();
231 let w = (mode_weight(r.sx[t[0]], r.sy[t[0]], na)
232 + mode_weight(r.sx[t[1]], r.sy[t[1]], na)
233 + mode_weight(r.sx[t[2]], r.sy[t[2]], na))
234 / 3.0;
235 let (ya, yb, yc) = (r.ys[t[0]], r.ys[t[1]], r.ys[t[2]]);
236 let j0 = (((ya.min(yb.min(yc)) - y0) / dx).floor() as i64).max(0);
237 let j1 = (((ya.max(yb.max(yc)) - y0) / dx).ceil() as i64).min(last);
238 if j0 > j1 {
239 good.push((*t, w * a_d / a_s.abs(), 1, 0));
240 continue;
241 }
242 good.push((*t, w * a_d / a_s.abs(), j0 as usize, j1 as usize));
243 }
244 let mut start = vec![0usize; npx + 1];
246 for &(_, _, j0, j1) in &good {
247 for j in j0..=j1 {
248 start[j + 1] += 1;
249 }
250 }
251 for j in 0..npx {
252 start[j + 1] += start[j];
253 }
254 let mut fill = start.clone();
255 let mut by_row = vec![0usize; start[npx]];
256 for (k, &(_, _, j0, j1)) in good.iter().enumerate() {
257 for j in j0..=j1 {
258 by_row[fill[j]] = k;
259 fill[j] += 1;
260 }
261 }
262 let n2 = npx * npx;
263 let mut ok = vec![false; n2];
264 let mut ii = vec![0.0; n2];
265 let mut ll = vec![0.0; n2 * nw];
266 let mut ex = vec![czero(); n2];
267 let mut ey = vec![czero(); n2];
268 let mut ez = vec![czero(); n2];
270 type Cols<'a> = ((&'a mut [bool], &'a mut [f64]), &'a mut [f64]);
272 type Row<'a> = (
273 usize,
274 ((Cols<'a>, (&'a mut [C64], &'a mut [C64])), &'a mut [C64]),
275 );
276 let row = |(j, ((((okr, ir), lr), (exr, eyr)), ezr)): Row| {
277 let y = y0 + j as f64 * dx;
278 for &k in &by_row[start[j]..start[j + 1]] {
279 let (t, irr, _, _) = good[k];
280 let (xa, ya, xb, yb, xc, yc) = (
281 r.xs[t[0]], r.ys[t[0]], r.xs[t[1]], r.ys[t[1]], r.xs[t[2]], r.ys[t[2]],
282 );
283 let i0 = (((xa.min(xb.min(xc)) - x0) / dx).floor() as i64).max(0);
284 let i1 = (((xa.max(xb.max(xc)) - x0) / dx).ceil() as i64).min(last);
285 if i0 > i1 {
286 continue;
287 }
288 let den = (yb - yc) * (xa - xc) + (xc - xb) * (ya - yc);
289 for i in i0 as usize..=i1 as usize {
290 if okr[i] {
291 continue;
292 }
293 let x = x0 + i as f64 * dx;
294 let l1 = ((yb - yc) * (x - xc) + (xc - xb) * (y - yc)) / den;
295 let l2 = ((yc - ya) * (x - xc) + (xa - xc) * (y - yc)) / den;
296 let l3 = 1.0 - l1 - l2;
297 if l1 < -1e-12 || l2 < -1e-12 || l3 < -1e-12 {
298 continue;
299 }
300 okr[i] = true;
301 ir[i] = irr;
302 for w in 0..nw {
303 lr[w * npx + i] = l1 * r.l[w][t[0]] + l2 * r.l[w][t[1]] + l3 * r.l[w][t[2]];
304 }
305 exr[i] = r.ex[t[0]] * l1 + r.ex[t[1]] * l2 + r.ex[t[2]] * l3;
306 eyr[i] = r.ey[t[0]] * l1 + r.ey[t[1]] * l2 + r.ey[t[2]] * l3;
307 if let Some(z) = extra {
308 ezr[i] = z[t[0]] * l1 + z[t[1]] * l2 + z[t[2]] * l3;
309 }
310 }
311 }
312 };
313 if lensbench_core::par::sequential() {
315 ok.chunks_mut(npx)
316 .zip(ii.chunks_mut(npx))
317 .zip(ll.chunks_mut(npx * nw))
318 .zip(ex.chunks_mut(npx).zip(ey.chunks_mut(npx)))
319 .zip(ez.chunks_mut(npx))
320 .enumerate()
321 .for_each(row);
322 } else {
323 ok.par_chunks_mut(npx)
324 .zip(ii.par_chunks_mut(npx))
325 .zip(ll.par_chunks_mut(npx * nw))
326 .zip(ex.par_chunks_mut(npx).zip(ey.par_chunks_mut(npx)))
327 .zip(ez.par_chunks_mut(npx))
328 .enumerate()
329 .for_each(scoped(row));
330 }
331 let mut l = vec![vec![0.0; n2]; nw];
333 for j in 0..npx {
334 for w in 0..nw {
335 l[w][j * npx..(j + 1) * npx]
336 .copy_from_slice(&ll[j * npx * nw + w * npx..j * npx * nw + (w + 1) * npx]);
337 }
338 }
339 let p = PixelData {
340 n: npx,
341 x0,
342 y0,
343 dx,
344 ok,
345 i: ii,
346 l,
347 ex,
348 ey,
349 fold_fraction: if tris.is_empty() {
350 0.0
351 } else {
352 fold as f64 / tris.len() as f64
353 },
354 };
355 (p, if extra.is_some() { ez } else { Vec::new() })
356}
357
358#[derive(Debug, Clone, Copy, PartialEq)]
363pub enum InputPol {
364 X,
365 Y,
366 Angle(f64),
368 CircularPlus,
370 CircularMinus,
371}
372
373impl InputPol {
374 pub fn jones(self) -> [C64; 2] {
375 let r = 0.5f64.sqrt();
376 match self {
377 InputPol::X => [C64::new(1.0, 0.0), czero()],
378 InputPol::Y => [czero(), C64::new(1.0, 0.0)],
379 InputPol::Angle(d) => [
380 C64::new(d.to_radians().cos(), 0.0),
381 C64::new(d.to_radians().sin(), 0.0),
382 ],
383 InputPol::CircularPlus => [C64::new(r, 0.0), C64::new(0.0, -r)],
384 InputPol::CircularMinus => [C64::new(r, 0.0), C64::new(0.0, r)],
385 }
386 }
387
388 pub fn parse(s: &str) -> Result<InputPol> {
389 let t = s.trim().to_ascii_lowercase();
390 Ok(match t.as_str() {
391 "x" | "s" => InputPol::X,
392 "y" | "p" => InputPol::Y,
393 "+" | "circ+" | "circular+" | "rcp" => InputPol::CircularPlus,
394 "-" | "circ-" | "circular-" | "lcp" => InputPol::CircularMinus,
395 _ => match t.parse::<f64>() {
396 Ok(d) => InputPol::Angle(d),
397 Err(_) => invalid!("input polarization {s} (x, y, angle [deg], circ+, circ-)"),
398 },
399 })
400 }
401}
402
403fn has_phase_terms(sys: &System) -> bool {
405 sys.surfaces
406 .iter()
407 .any(|s| !s.ignore && s.action().is_ideal())
408}
409
410pub fn trace_path(
419 sys: &System,
420 field: FieldSel,
421 g: usize,
422 input: InputPol,
423 coat: &Coatings,
424) -> Result<RayGrid> {
425 let t = trace_jones(sys, field, g, coat, None)?;
426 let jin = input.jones();
427 let mut r = t.rays;
428 for q in 0..g * g {
429 if r.ok[q] {
430 let j = t.jones[q];
431 r.ex[q] = j[0][0] * jin[0] + j[0][1] * jin[1];
432 r.ey[q] = j[1][0] * jin[0] + j[1][1] * jin[1];
433 }
434 }
435 Ok(r)
436}
437
438#[derive(Debug, Clone)]
441#[non_exhaustive]
442pub struct JonesGrid {
443 pub rays: RayGrid,
444 pub jones: Vec<[[C64; 2]; 2]>,
445 pub xf: Vec<f64>,
447 pub yf: Vec<f64>,
448 pub landing: Vec<Vec<f64>>,
451 pub edge: Vec<f64>,
455 pub edge_surf: Vec<usize>,
458 pub edge_dm: Vec<[f64; 2]>,
459}
460
461pub fn trace_jones(
464 sys: &System,
465 field: FieldSel,
466 g: usize,
467 coat: &Coatings,
468 surf: Option<usize>,
469) -> Result<JonesGrid> {
470 trace_jones_in(sys, field, g, coat, surf, false)
471}
472
473pub fn trace_jones_edge(
480 sys: &System,
481 field: FieldSel,
482 g: usize,
483 coat: &Coatings,
484 surf: Option<usize>,
485) -> Result<JonesGrid> {
486 if !sys.floating_clip {
487 return trace_jones_in(sys, field, g, coat, surf, true);
488 }
489 let mut s = sys.clone();
490 s.edit(|p| {
491 p.floating_clip = false;
492 Ok(())
493 })?;
494 trace_jones_in(&s, field, g, coat, surf, true)
495}
496
497fn distance_by_gradient(g: usize, m: &[f64]) -> Vec<(f64, f64)> {
501 let h = 2.0 / (g - 1) as f64;
502 let at = |i: i64, j: i64| -> Option<f64> {
503 if i < 0 || j < 0 || i >= g as i64 || j >= g as i64 {
504 return None;
505 }
506 let v = m[j as usize * g + i as usize];
507 v.is_finite().then_some(v)
508 };
509 let diff = |c: f64, lo: Option<f64>, hi: Option<f64>| match (lo, hi) {
510 (Some(a), Some(b)) => Some((b - a) / (2.0 * h)),
511 (None, Some(b)) => Some((b - c) / h),
512 (Some(a), None) => Some((c - a) / h),
513 (None, None) => None,
514 };
515 (0..g * g)
516 .map(|q| {
517 let c = m[q];
518 if !c.is_finite() {
519 return (c, f64::NAN);
520 }
521 let (i, j) = ((q % g) as i64, (q / g) as i64);
522 let gx = diff(c, at(i - 1, j), at(i + 1, j));
523 let gy = diff(c, at(i, j - 1), at(i, j + 1));
524 let n = gx.unwrap_or(0.0).hypot(gy.unwrap_or(0.0));
525 if (gx.is_none() && gy.is_none()) || !(n > 0.0) {
526 (0.5 * h * c.signum(), f64::NAN)
527 } else {
528 (c / n, n)
529 }
530 })
531 .collect()
532}
533
534fn trace_jones_in(
535 sys: &System,
536 field: FieldSel,
537 g: usize,
538 coat: &Coatings,
539 surf: Option<usize>,
540 with_edge: bool,
541) -> Result<JonesGrid> {
542 if let Some(s) = surf {
543 if s == 0 || s > sys.image() {
544 invalid!("surface {s} is out of range (1 to {})", sys.image());
545 }
546 }
547 if g < 2 {
548 invalid!("the pupil grid must be 2 or more");
549 }
550 if sys.primary != 0 {
551 invalid!("the primary wavelength must be the center wavelength (wavelength 1)");
552 }
553 let nw = sys.wavelengths.len();
554 let mut r = RayGrid::new(g, nw);
555 let pg = PupilGrid::new(g);
556 let (idx, pxs, pys) = if with_edge { pg.rays_rim() } else { pg.rays() };
557 let pass = |t: &lensbench_core::system::Trace, m: usize| {
559 if with_edge {
560 t.rays[m].status.is_ok()
561 } else {
562 t.ok(m)
563 }
564 };
565 let mut good = vec![false; g * g];
566 for &q in &idx {
567 good[q] = true;
568 }
569 let phase = has_phase_terms(sys);
570 let mut zs0 = vec![0.0; g * g];
572 let mut landing = vec![vec![0.0; g * g]; nw];
573 let mut t0 = None;
574 let (hx, hy) = sys.field_sel_norm(field, 0)?;
577 let launch = Launch::Pupil {
578 spec: sys.object_spec(hx, hy)?,
579 signed: false,
580 px: &pxs,
581 py: &pys,
582 vig: Some(sys.vig_factors(hx, hy)?),
583 hxy: Some((hx, hy)),
584 };
585 let surfs = surf.map(|s| [s]);
586 let rec = surfs.as_ref().map_or(RecSel::Off, |s| RecSel::Surfs(s));
587 let pols = [[C64::new(1.0, 0.0), czero()], [czero(), C64::new(1.0, 0.0)]];
588 let pt = sys.trace_pol_launch(&launch, 0, PolIn::new(&pols, coat).no_phase(), rec)?;
589 let (mut center, pol_e) = (Some(pt.trace), pt.e);
590 for w in 0..nw {
591 let t = match center.take() {
592 Some(mut t) => {
593 t.hx_hy = (hx, hy);
594 t
595 }
596 None => sys.try_trace(field, &pxs, &pys, Some(w), None, false)?,
597 };
598 let chief = if phase {
599 let c = sys.try_trace(field, &[0.0], &[0.0], Some(w), None, false)?;
600 if !c.traced(0) {
601 invalid!("the chief ray doesn't reach the sensor");
602 }
603 Some((c.opl_os[0], c.opl_os[0] + c.rays[0].lens_opd))
604 } else {
605 None
606 };
607 let nimg = sys.image_index(w).abs();
609 for (m, &q) in idx.iter().enumerate() {
610 if !pass(&t, m) {
611 good[q] = false;
612 continue;
613 }
614 let lraw = t.opl_os[m];
615 let mut l = match chief {
616 Some((craw, cpath)) => craw + (lraw + t.rays[m].lens_opd - cpath),
617 None => lraw,
618 };
619 if w == 0 {
620 r.xs[q] = t.rays[m].xyz[0];
621 r.ys[q] = t.rays[m].xyz[1];
622 zs0[q] = t.rays[m].xyz[2];
623 } else if good[q] {
624 let (p, d) = (t.rays[m].xyz, t.rays[m].lmn);
627 let dl = nimg
628 * (d[0] * (r.xs[q] - p[0]) + d[1] * (r.ys[q] - p[1]) + d[2] * (zs0[q] - p[2]));
629 landing[w][q] = dl;
630 l += dl;
631 }
632 r.l[w][q] = l;
633 }
634 if w == 0 {
635 t0 = Some(t);
636 }
637 }
638 let t0 = t0.expect("first sample set above");
639 if !sys.infinite() {
641 let of = sys.object_frame();
642 for (m, &q) in idx.iter().enumerate() {
643 let d = lensbench_core::math::mtv(&of.r, t0.k0[m]);
645 r.sx[q] = d[0];
646 r.sy[q] = d[1];
647 }
648 } else {
649 let probe = [(0.0, 0.0), (0.7, 0.0), (-0.7, 0.0), (0.0, 0.7), (0.0, -0.7)];
650 let ppx: Vec<f64> = probe.iter().map(|p| p.0).collect();
651 let ppy: Vec<f64> = probe.iter().map(|p| p.1).collect();
652 let ima = sys.image();
653 let tp = sys.try_trace(field, &ppx, &ppy, Some(0), None, RecSel::All)?;
654 let mut fs = None;
655 for k in 1..ima {
656 let Some(rec) = tp.rec_at(k) else { continue };
657 let pts: Vec<V3> = rec.xyz.clone();
658 if pts.iter().any(|p| !p[0].is_finite()) {
659 continue;
660 }
661 if pts
662 .iter()
663 .all(|p| (p[0] - pts[0][0]).abs() < 1e-6 && (p[1] - pts[0][1]).abs() < 1e-6)
664 {
665 fs = Some(k);
666 break;
667 }
668 }
669 match fs {
670 None => {
671 r.mode_fallback = true;
672 for (m, &q) in idx.iter().enumerate() {
673 r.sx[q] = 1e-4 * pxs[m];
674 r.sy[q] = 1e-4 * pys[m];
675 }
676 }
677 Some(fsurf) => {
678 let ta =
679 sys.try_trace(field, &pxs, &pys, Some(0), None, RecSel::Surfs(&[fsurf]))?;
680 let rec = ta.rec_at(fsurf).expect("record");
681 for (m, &q) in idx.iter().enumerate() {
682 let d = rec.lmn[m];
683 if !d[0].is_finite() {
684 good[q] = false;
685 continue;
686 }
687 r.sx[q] = d[0];
688 r.sy[q] = d[1];
689 }
690 }
691 }
692 }
693 let mut jones = vec![[[czero(); 2]; 2]; g * g];
696 for (m, &q) in idx.iter().enumerate() {
697 if !pass(&t0, m) || !good[q] {
698 good[q] = false;
699 continue;
700 }
701 for (b, pol) in pol_e[m].iter().enumerate().take(2) {
702 jones[q][0][b] = pol[0];
703 jones[q][1][b] = pol[1];
704 }
705 }
706 let (mut xf, mut yf) = (Vec::new(), Vec::new());
707 if let Some(s) = surf {
708 xf = vec![f64::NAN; g * g];
709 yf = vec![f64::NAN; g * g];
710 let tr = &t0;
711 if let Some(rec) = tr.rec_at(s) {
712 for (m, &q) in idx.iter().enumerate() {
713 if good[q] && pass(tr, m) && rec.xyz[m][0].is_finite() {
714 xf[q] = rec.xyz[m][0];
715 yf[q] = rec.xyz[m][1];
716 }
717 }
718 }
719 }
720 let (mut edge_surf, mut edge_dm) = (Vec::new(), Vec::new());
721 let edge = if with_edge {
722 let mut vs: Vec<usize> = t0.rays.iter().map(|r| r.vig).filter(|&v| v > 0).collect();
724 vs.sort_unstable();
725 vs.dedup();
726 edge_surf = vec![0usize; g * g];
727 edge_dm = vec![[0.0; 2]; g * g];
728 let mut edge: Vec<f64> = (0..g * g)
729 .map(|q| {
730 if good[q] {
731 let [x, y] = pg.coords(q);
732 1.0 - (x * x + y * y).sqrt()
734 } else {
735 f64::NAN
736 }
737 })
738 .collect();
739 if !vs.is_empty() {
740 let ta = sys.try_trace(field, &pxs, &pys, Some(0), None, RecSel::Surfs(&vs))?;
741 for &k in &vs {
742 let ap = sys.surfaces[k].ap;
743 let rec = ta.rec_at(k).expect("record");
744 let mut m = vec![f64::NAN; g * g];
745 let mut at = vec![[f64::NAN; 2]; g * g];
746 for (i, &q) in idx.iter().enumerate() {
747 let p = rec.xyz[i];
748 if good[q] && p[0].is_finite() {
749 m[q] = lensbench_core::trace::aperture_margin(ap, p[0], p[1]);
750 at[q] = [p[0], p[1]];
751 }
752 }
753 for (q, (d, n)) in distance_by_gradient(g, &m).into_iter().enumerate() {
754 if !edge[q].is_finite() {
755 continue;
756 }
757 let d = if d.is_nan() { f64::NEG_INFINITY } else { d };
758 if d < edge[q] {
759 edge[q] = d;
760 edge_surf[q] = k;
761 let [x, y] = at[q];
763 let dl = 1e-6 * x.abs().max(y.abs()).max(1.0);
764 let mg = |a: f64, b: f64| lensbench_core::trace::aperture_margin(ap, a, b);
765 edge_dm[q] = if n.is_finite() {
766 [
767 (mg(x + dl, y) - mg(x - dl, y)) / (2.0 * dl * n),
768 (mg(x, y + dl) - mg(x, y - dl)) / (2.0 * dl * n),
769 ]
770 } else {
771 [0.0; 2]
772 };
773 }
774 }
775 }
776 }
777 for (q, (o, e)) in good.iter_mut().zip(&edge).enumerate() {
779 *o = *o && *e >= 0.0 && pg.inside(q);
780 }
781 edge
782 } else {
783 Vec::new()
784 };
785 r.ok = good;
786 Ok(JonesGrid {
787 rays: r,
788 jones,
789 xf,
790 yf,
791 landing,
792 edge,
793 edge_surf,
794 edge_dm,
795 })
796}