1use super::*;
4use lensbench_core::error::code;
5use lensbench_core::glass::DIRS_HINT as HINT;
6pub(crate) fn zmx_group_spans(
8 keep: &[Element],
9 groups: &[ZmxGroup],
10) -> lensbench_core::Result<Vec<(usize, usize, usize)>> {
11 let mut out: Vec<(usize, usize, usize)> = Vec::new();
12 for (g, gr) in groups.iter().enumerate() {
13 let label = if gr.id.is_empty() { &gr.name } else { &gr.id };
14 if gr.from > gr.to {
15 return Err(format!(
16 "group {label}: surfaces {} to {} are in reverse order",
17 gr.from, gr.to
18 )
19 .into());
20 }
21 let inside: Vec<usize> = (0..keep.len())
22 .filter(|&i| keep[i].kind != Kind::Air && (gr.from..=gr.to).contains(&keep[i].from))
23 .collect();
24 let (Some(&a), Some(&z)) = (inside.first(), inside.last()) else {
25 return Err(format!(
26 "group {label}: no imported lenses or surfaces in surfaces {} to {}",
27 gr.from, gr.to
28 )
29 .into());
30 };
31 if let Some(o) = out.iter().find(|o| a <= o.2 && o.1 <= z) {
32 return Err(format!("group {label} overlaps group {}", groups[o.0].name).into());
33 }
34 out.push((g, a, z));
35 }
36 Ok(out)
37}
38
39pub(crate) fn curv(r: Option<f64>) -> f64 {
40 match r {
41 Some(r) if r != 0.0 && r.is_finite() => 1.0 / r,
42 _ => 0.0,
43 }
44}
45
46pub(crate) fn surf_ap(ap: Option<SurfAperture>, semi: f64) -> Aperture {
48 match ap {
49 None => Aperture::None,
50 Some(SurfAperture::Circular { min, max, dx, dy }) => {
51 Aperture::Circular { min, max, dx, dy }
52 }
53 Some(SurfAperture::Rect { hx, hy, dx, dy }) => Aperture::Rect { hx, hy, dx, dy },
54 Some(SurfAperture::Ellipse { hx, hy, dx, dy }) => Aperture::Ellipse { hx, hy, dx, dy },
55 Some(SurfAperture::Obscuration { min, max, dx, dy }) => Aperture::Obsc { min, max, dx, dy },
56 Some(SurfAperture::Spider {
57 width,
58 arms,
59 dx,
60 dy,
61 }) => Aperture::Spider {
62 width,
63 arms,
64 dx,
65 dy,
66 },
67 Some(SurfAperture::Floating) => Aperture::Floating { semi },
68 }
69}
70
71pub(crate) fn surf(q: &SurfSpec) -> lensbench_core::Result<Surface> {
72 if let Some(r) = &q.row {
73 let alone = SurfSpec {
74 row: None,
75 ..q.clone()
76 };
77 if serde_json::to_value(&alone).ok() != serde_json::to_value(SurfSpec::default()).ok() {
78 return Err("a surface written as row can't have the other keys".into());
79 }
80 if r.stop || r.object || r.image {
81 return Err(
82 "row of a surface can't have stop, object or image (use set_stop of the block)"
83 .into(),
84 );
85 }
86 return crate::sysfile_v2::read::surface((**r).clone()).map_err(Into::into);
87 }
88 let mut s = Surface {
89 form: match q.shape {
90 SurfShape::Standard if q.asph.iter().any(|a| *a != 0.0) => Form::EvenAsph {
91 asph: q.asph.clone(),
92 },
93 SurfShape::Standard => Form::Standard,
94 SurfShape::OddAsph => Form::OddAsph {
95 asph: q.asph.clone(),
96 },
97 SurfShape::Toroidal => Form::Toroidal {
98 cx: curv(q.radius_x),
99 asph: q.asph.clone(),
100 },
101 SurfShape::Fresnel => Form::Fresnel {
102 asph: q.asph.clone(),
103 },
104 },
105 c: curv(q.radius),
106 k: q.conic,
107 t: q.t,
108 semi: q.semi.value(),
109 semi_auto: q.semi.is_auto(),
110 coat: q.coat.clone(),
111 comment: q.comment.clone(),
112 ignore: q.ignore,
113 ..Default::default()
114 };
115 s.ap = surf_ap(q.aperture, q.semi.value());
116 let special = q.jones.is_some() as u8
117 + q.coordbrk.is_some() as u8
118 + q.polarizer.is_some() as u8
119 + q.waveplate.is_some() as u8
120 + q.birefringent.is_some() as u8;
121 if special > 1 {
122 return Err(
123 "a surface can't have two or more of jones, polarizer, waveplate, coordbrk and birefringent"
124 .into(),
125 );
126 }
127 if let Some(b) = q.birefringent {
128 s.bire = Some(match b {
129 BireSpec::In { mode, axis } => {
130 if mode > 3 {
131 return Err(format!("birefringent plate mode {mode} (0 to 3)").into());
132 }
133 if !(axis.iter().all(|v| v.is_finite()) && axis.iter().any(|v| *v != 0.0)) {
134 return Err(
135 "the crystal axis of the birefringent plate is 0 or not a number".into(),
136 );
137 }
138 if q.glass.as_deref().is_none_or(is_air_name) {
139 return Err("write glass (the ordinary material) on the entrance surface of a birefringent plate".into());
140 }
141 lensbench_core::surface::Bire::In {
142 mode,
143 axis,
144 ne: Vec::new(),
145 }
146 }
147 BireSpec::Out => lensbench_core::surface::Bire::Out,
148 });
149 }
150 if special == 1 && q.birefringent.is_none() {
151 let what = if q.jones.is_some() {
152 "jones"
153 } else if q.polarizer.is_some() {
154 "polarizer"
155 } else if q.waveplate.is_some() {
156 "waveplate"
157 } else {
158 "coordbrk"
159 };
160 if curv(q.radius) != 0.0
161 || q.conic != 0.0
162 || s.typ() == SurfType::EvenAsph
163 || q.shape != SurfShape::Standard
164 {
165 return Err(
166 format!("a {what} surface can't have curvature, conic or asphere terms").into(),
167 );
168 }
169 if what == "coordbrk" && q.glass.as_deref().is_some_and(|g| !is_air_name(g)) {
171 return Err(format!("no glass after a {what} surface").into());
172 }
173 }
174 if let Some(j) = q.jones {
175 s.form = Form::Jones { jones: j };
176 }
177 let ret = match (&q.polarizer, &q.waveplate) {
178 (Some(p), _) => Some(p.retarder()?),
179 (_, Some(w)) => Some(w.retarder()?),
180 _ => None,
181 };
182 if let Some(r) = ret {
183 s.form = Form::Jones {
185 jones: r.jones8(r.wl0),
186 };
187 s.retarder = Some(r);
188 }
189 if let Some([tx, ty]) = q.tilt {
190 if q.coordbrk.is_some() {
191 return Err("a coordinate break surface can't have tilt".into());
192 }
193 if !(tx.is_finite() && ty.is_finite()) {
194 return Err("tilt is not a number".into());
195 }
196 if tx != 0.0 || ty != 0.0 {
197 s.before = Some(lensbench_core::surface::Tilt {
198 d: [0.0, 0.0, tx, ty, 0.0],
199 order: 0,
200 });
201 s.after = After::Reverse;
202 }
203 }
204 if let Some(d) = q.coordbrk {
205 if q.order > 1 {
206 return Err(format!("coordinate break order {} (0 or 1)", q.order).into());
207 }
208 s.form = Form::CoordBrk {
209 cb: d,
210 order: q.order,
211 };
212 s.mat = "-".into();
213 return Ok(s);
214 }
215 if let Some(g) = &q.glass {
216 if let Ok(nd) = g.trim().parse::<f64>() {
217 s.mat = Material::Index(nd);
219 } else {
220 s.mat = Material::parse(g);
221 }
222 }
223 Ok(s)
224}
225
226pub(crate) fn pick_lens(s: &System, k: usize) -> lensbench_core::Result<Element> {
227 let els = elements::split(s)?;
228 let lenses: Vec<&Element> = els.iter().filter(|e| e.kind == Kind::Lens).collect();
229 match lenses.get(k.wrapping_sub(1)) {
230 Some(e) => Ok((*e).clone()),
231 None => Err(lensbench_core::Error::Invalid(format!(
232 "no lens {k} ({} lenses)",
233 lenses.len()
234 ))),
235 }
236}
237
238#[derive(Clone, Copy, Default)]
240pub struct ExpandOpts<'a> {
241 pub state: Option<&'a str>,
243 pub path: Option<&'a str>,
245 pub cache: Option<&'a SourceCache>,
247 pub within: &'a [Loading],
249}
250
251#[derive(Debug, Clone, PartialEq, Eq)]
253pub struct Loading {
254 pub file: PathBuf,
255 pub item: Option<String>,
256}
257
258impl std::fmt::Display for Loading {
259 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
260 match &self.item {
261 Some(it) => write!(f, "{} item {it}", self.file.display()),
262 None => write!(f, "{}", self.file.display()),
263 }
264 }
265}
266
267#[derive(Debug, Clone)]
269pub struct Expansion {
270 pub system: System,
272 pub notes: Vec<Note>,
274 pub gaps: Vec<Gap>,
276 pub map: Vec<SurfOrigin>,
278}
279
280#[derive(Debug, Clone, Default, PartialEq)]
282pub struct SurfOrigin {
283 pub blocks: Vec<String>,
285 pub back: bool,
287 pub flip: Option<usize>,
289 pub(crate) frame: Option<usize>,
291 pub(crate) zmx: Option<(usize, usize)>,
293 pub(crate) mods: Vec<usize>,
295 pub face: Option<FaceId>,
298 pub(crate) leaf: usize,
300 pub(crate) placed: bool,
303}
304
305#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
307pub struct NodePath(pub Vec<NodeStep>);
308
309#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
311pub enum NodeStep {
312 Block(usize),
314 Arm(u8, usize),
316}
317
318#[derive(Debug, Clone, PartialEq, Eq, Hash)]
321pub struct FaceId {
322 pub node: NodePath,
324 pub back: bool,
326 pub pass: usize,
328 pub cb: bool,
330 pub index: usize,
333}
334
335pub(crate) fn node_paths(blocks: &[Block]) -> HashMap<usize, NodePath> {
337 fn walk(
338 v: &[Block],
339 pre: &mut Vec<NodeStep>,
340 arm: Option<u8>,
341 out: &mut HashMap<usize, NodePath>,
342 ) {
343 for (i, b) in v.iter().enumerate() {
344 pre.push(match arm {
345 Some(a) => NodeStep::Arm(a, i),
346 None => NodeStep::Block(i),
347 });
348 out.insert(b as *const Block as usize, NodePath(pre.clone()));
349 match b {
350 Block::Group { blocks, .. } => walk(blocks, pre, None, out),
351 Block::Splitter { spec, .. } => {
352 for (a, l) in [&spec.t, &spec.r, &spec.d].into_iter().enumerate() {
353 walk(l, pre, Some(a as u8), out);
354 }
355 }
356 _ => {}
357 }
358 pre.pop();
359 }
360 }
361 let mut out = HashMap::new();
362 walk(blocks, &mut Vec::new(), None, &mut out);
363 out
364}
365
366fn name_faces(map: &mut [SurfOrigin], sf: &[Surface], nodes: &HashMap<usize, NodePath>) {
368 let mut passes: HashMap<(usize, bool), usize> = HashMap::new();
370 let mut prev: Option<(usize, bool)> = None;
371 let mut k = [0usize; 2];
373 for (j, o) in map.iter_mut().enumerate() {
374 let leaf = std::mem::take(&mut o.leaf);
375 let Some(node) = nodes.get(&leaf) else {
376 prev = None;
377 continue;
378 };
379 let key = (leaf, o.back);
380 let n = passes.entry(key).or_insert(0);
381 if prev != Some(key) {
382 *n += 1;
383 k = [0, 0];
384 }
385 let cb = sf[j].is_coord_break();
386 o.face = Some(FaceId {
387 node: node.clone(),
388 back: o.back,
389 pass: *n - 1,
390 cb,
391 index: k[cb as usize],
392 });
393 k[cb as usize] += 1;
394 prev = Some(key);
395 }
396}
397
398impl Expansion {
399 pub fn find_face(&self, id: &FaceId) -> Option<usize> {
401 self.map.iter().position(|o| o.face.as_ref() == Some(id))
402 }
403}
404
405impl SurfOrigin {
406 pub fn is_in(&self, id: &str) -> bool {
408 self.blocks.iter().any(|b| b == id)
409 }
410}
411
412#[derive(Debug, Clone, Default, PartialEq, serde::Serialize)]
414pub struct BlockSpans {
415 pub id: String,
416 pub forward: Vec<[usize; 2]>,
418 #[serde(skip_serializing_if = "Vec::is_empty")]
420 pub back: Vec<[usize; 2]>,
421}
422
423pub fn block_spans(map: &[SurfOrigin]) -> Vec<BlockSpans> {
425 let mut ids: Vec<&str> = Vec::new();
426 for o in map {
427 for b in o.blocks.iter().rev() {
429 if !ids.contains(&b.as_str()) {
430 ids.push(b);
431 }
432 }
433 }
434 ids.into_iter()
435 .map(|id| BlockSpans {
436 id: id.to_string(),
437 forward: block_runs(map, id, Some(false)),
438 back: block_runs(map, id, Some(true)),
439 })
440 .collect()
441}
442
443impl Expansion {
444 pub fn block_spans(&self) -> Vec<BlockSpans> {
446 block_spans(&self.map)
447 }
448}
449
450pub fn block_runs(map: &[SurfOrigin], id: &str, back: Option<bool>) -> Vec<[usize; 2]> {
453 if id.is_empty() {
454 return Vec::new();
455 }
456 runs_where(map, |o| o.is_in(id), back)
457}
458
459pub(crate) fn runs_where(
461 map: &[SurfOrigin],
462 f: impl Fn(&SurfOrigin) -> bool,
463 back: Option<bool>,
464) -> Vec<[usize; 2]> {
465 let mut out: Vec<[usize; 2]> = Vec::new();
466 let mut prev: Option<(usize, bool)> = None;
467 for (j, o) in map.iter().enumerate() {
468 if !f(o) {
469 prev = None;
470 continue;
471 }
472 match (prev, out.last_mut()) {
473 (Some((pj, pb)), Some(r)) if pj + 1 == j && pb == o.back => r[1] = j,
474 _ => out.push([j, j]),
475 }
476 prev = Some((j, o.back));
477 }
478 out.retain(|r| back.is_none_or(|b| map[r[0]].back == b));
479 out
480}
481
482pub(crate) fn fwd_run(map: &[SurfOrigin], id: &str) -> Option<[usize; 2]> {
484 block_runs(map, id, Some(false)).into_iter().next()
485}
486
487pub type Gap = (String, usize, f64);
490
491pub fn expand(p: &Project, env: &Env, o: &ExpandOpts) -> Result<Expansion, ExpandError> {
494 let with;
495 let p = match o.state {
496 Some(n) => {
497 with = p.with_state_and_path(n, o.path.is_some())?;
498 &with
499 }
500 None => p,
501 };
502 match expand_inner(
503 p,
504 env,
505 o.path.or(p.path.as_deref()),
506 false,
507 o.cache,
508 o.within,
509 )? {
510 Walk::Done(x) => Ok(*x),
511 _ => Err(lensbench_core::Error::from(
512 "internal error: the BS path is short outside the path search",
513 )
514 .into()),
515 }
516}
517
518pub(crate) fn splitter_ids<'x>(v: &'x [Block], out: &mut Vec<&'x str>) {
520 for b in v {
521 match b {
522 Block::Splitter { id, spec, .. } => {
523 out.push(id);
524 for l in [&spec.t, &spec.r, &spec.d] {
525 splitter_ids(l, out);
526 }
527 }
528 Block::Group { blocks, .. } => splitter_ids(blocks, out),
529 _ => {}
530 }
531 }
532}
533
534pub(crate) enum Walk {
536 Need,
538 Walked,
540 Done(Box<Expansion>),
541}
542
543pub(crate) fn expand_inner(
546 p: &Project,
547 env: &Env,
548 path: Option<&str>,
549 search: bool,
550 cache: Option<&SourceCache>,
551 within: &[Loading],
552) -> Result<Walk, ExpandError> {
553 let mut failed = None;
554 expand_body(p, env, path, search, cache, within, &mut failed).map_err(|error| ExpandError {
555 error,
556 block: failed.map(|n| BlockAt::new(&p.blocks, n)),
557 })
558}
559
560fn expand_body(
561 p: &Project,
562 env: &Env,
563 path: Option<&str>,
564 search: bool,
565 cache: Option<&SourceCache>,
566 within: &[Loading],
567 failed: &mut Option<NodePath>,
568) -> lensbench_core::Result<Walk> {
569 {
570 let mut ids = Vec::new();
571 splitter_ids(&p.blocks, &mut ids);
572 for (i, id) in ids.iter().enumerate() {
573 if id.is_empty() {
574 return Err("a BS (splitter) needs an id".into());
575 }
576 if ids[..i].contains(id) {
577 return Err(format!("BS id {id} appears twice or more").into());
578 }
579 }
580 }
581 if p.wavelengths.is_empty() {
582 return Err("no wavelengths".into());
583 }
584 if p.primary == 0 || p.primary > p.wavelengths.len() {
585 return Err(format!(
586 "primary wavelength {} (there are {} wavelengths)",
587 p.primary,
588 p.wavelengths.len()
589 )
590 .into());
591 }
592 let mut dirs = env.glass_dirs.clone();
593 crate::model::zmx_dirs(&p.blocks, &env.base, &mut dirs);
594 let dirs = glass::catalog_dirs(&dirs);
595 let (glasses, missing) = glass::load_catalogs_shared(&p.glass_catalogs, &dirs);
596 if !missing.is_empty() {
597 return Err(lensbench_core::Error::Invalid(format!(
598 "glass catalog not found: {}. Pass catalog folders with --glass-dir (CLI), glass_dirs (serve, Python) or LENSBENCH_GLASSCAT",
599 missing.join(", ")
600 ))
601 .with_code(code::GLASS_NOT_FOUND));
602 }
603 let keyed;
605 let p = match number_sites(p) {
606 Some(q) => {
607 keyed = q;
608 &keyed
609 }
610 None => p,
611 };
612 let mut sites = Vec::new();
613 face_sites(&p.blocks, &mut sites);
614 let mut c = Ctx {
615 env,
616 cache,
617 base: env.base.clone(),
618 loading: within.to_vec(),
619 outer: within.len(),
620 sf: Vec::new(),
621 map: Vec::new(),
622 noted: Vec::new(),
623 nflip: 0,
624 flip_err: None,
625 zpicks: Vec::new(),
626 lead: 0.0,
627 parity: 1.0,
628 glasses,
629 coats: HashMap::new(),
630 nstop: 0,
631 gaps: Vec::new(),
632 split: SplitState {
633 path: splitter::parse_path(path.unwrap_or(""))?,
634 strict: search,
635 ..Default::default()
636 },
637 turn: TurnState::new(p),
638 media: HashMap::new(),
639 frames: Vec::new(),
640 zenv: Vec::new(),
641 nodes: node_paths(&p.blocks),
642 leaf: Vec::new(),
643 failed: None,
644 notes: Vec::new(),
645 };
646 for (i, b) in p.blocks.iter().enumerate() {
647 if c.split.done {
648 break;
649 }
650 if matches!(b, Block::Detector(_)) && i + 1 == p.blocks.len() {
652 continue;
653 }
654 match c.block(b, &p.blocks, i) {
655 Err(_) if c.split.need => return Ok(Walk::Need),
657 Err(e) => {
658 *failed = c.failed.take();
659 return Err(e);
660 }
661 Ok(()) => {}
662 }
663 if let Some(e) = c.flip_err.take() {
664 return Err(e);
665 }
666 }
667 if let Some(t) = c.turn.at.as_ref().filter(|_| c.turn.turned.is_empty()) {
668 return Err(format!(
669 "turn: block {} (pass {}) is not on the path",
670 t.block, t.pass
671 )
672 .into());
673 }
674 if c.split.pos < c.split.path.len() {
675 return Err(format!(
676 "path {}: too many letters (the BS is passed {} times)",
677 path.unwrap_or(""),
678 c.split.pos
679 )
680 .into());
681 }
682 let stop_op = sites.iter().any(|(_, f)| {
684 f.surface_ops
685 .iter()
686 .any(|o| matches!(o, SurfaceOp::SetStop(_)))
687 });
688 if c.nstop > 1 || (c.nstop == 0 && !stop_op) {
689 return Err(format!("{} stops (exactly one is needed)", c.nstop).into());
690 }
691 if search {
692 return Ok(Walk::Walked);
693 }
694 if c.nstop == 0 {
695 if let Some(f) = c.sf.first_mut() {
697 f.stop = true;
698 }
699 }
700 let wl: Vec<f64> = p.wavelengths.iter().map(|w| w.um).collect();
701 let wt: Vec<f64> = p.wavelengths.iter().map(|w| w.weight).collect();
702 let mut obj = crate::zmx_links::object_surface(p.object.as_deref())?;
703 obj.t = p.object_distance.unwrap_or(f64::INFINITY);
704 let mut sf = vec![obj];
705 if p.object_distance.is_some() {
706 sf[0].t += c.lead;
707 }
708 if c.sf.len() != c.map.len() {
709 return Err(format!(
711 "internal error: {} surfaces but {} sources",
712 c.sf.len(),
713 c.map.len()
714 )
715 .into());
716 }
717 sf.append(&mut c.sf);
718 let org: Vec<Option<(usize, usize)>> = c.map.iter().map(|o| o.zmx).collect();
719 let mut map = vec![SurfOrigin::default()];
721 map.append(&mut c.map);
722 map.push(SurfOrigin::default());
723 let zpicks = std::mem::take(&mut c.zpicks);
724 sf.push(match &p.image {
725 None => Surface::default(),
726 Some(r) => {
727 if r.stop
728 || r.object
729 || r.t != 0.0
730 || r.medium.is_some()
731 || r.coordinate_break.is_some()
732 {
733 return Err(
734 "image: stop, object, t, medium and coordinate_break can't be written".into(),
735 );
736 }
737 let mut r = (**r).clone();
738 r.image = false;
739 crate::sysfile_v2::read::surface(r).map_err(|e| format!("image: {e}"))?
740 }
741 });
742 name_faces(&mut map, &sf, &c.nodes);
743 let envr = p.environment;
745 let named: Vec<String> = sf
747 .iter()
748 .filter_map(|d| {
749 d.mat
750 .glass()
751 .filter(|g| g.contains('@'))
752 .map(str::to_string)
753 })
754 .filter(|g| !c.glasses.contains_key(g))
755 .collect();
756 if !named.is_empty() {
757 let t = std::sync::Arc::make_mut(&mut c.glasses);
758 glass::resolve_qualified(t, named.iter().map(String::as_str), &dirs);
759 }
760 for (j, d) in sf.iter_mut().enumerate() {
761 let known = (j > 0 && (d.is_mirror() || d.is_coord_break()))
762 || is_air(&d.mat)
763 || d.mat.glass().is_some_and(|g| c.glasses.contains_key(g))
764 || matches!(d.mat, Material::Index(_) | Material::Model { .. })
765 || d.grin().is_some();
766 if !known {
767 return Err(glass_missing(j, &d.mat.name()));
768 }
769 if let Some(lensbench_core::surface::Bire::In { ne, .. }) = d.bire.as_mut() {
771 let en = lensbench_core::surface::Bire::e_name(&d.mat.name());
772 let g = c.glasses.get(&en).ok_or_else(|| {
773 format!(
774 "surface {j}: extraordinary glass {en} of birefringent material {} is not in the catalogs",
775 d.mat
776 )
777 })?;
778 *ne = wl
779 .iter()
780 .map(|&l| g.index(l, envr.temperature_c, envr.pressure_atm, envr.adjust_index))
781 .collect();
782 }
783 if let Some(r) = d.retarder.as_mut().filter(|r| !r.plates.is_empty()) {
785 r.resolve(&c.glasses)
786 .map_err(|e| format!("surface {j}: {e}"))?;
787 let m = r.jones8(r.wl0);
788 if let Some(j) = d.jones_mut() {
789 *j = m;
790 }
791 }
792 if let Some(r) = &mut d.reflect {
794 r.n = if is_air_name(&r.mat) {
795 vec![1.0; wl.len()]
796 } else if let Some(g) = c.glasses.get(r.mat.trim()) {
797 wl.iter()
798 .map(|&l| g.index(l, envr.temperature_c, envr.pressure_atm, envr.adjust_index))
799 .collect()
800 } else if matches!(
801 Material::parse(&r.mat),
802 Material::Index(_) | Material::Model { .. }
803 ) {
804 Vec::new() } else {
806 return Err(format!("surface {j}: glass {} is not in the catalogs", r.mat).into());
807 };
808 }
809 }
810 let ft = p.fields.kind.plain().unwrap_or(FieldType::Angle);
812 if p.fields.vignetting.len() > p.fields.points.len() {
813 return Err(format!(
814 "fields: {} vignetting rows for {} fields",
815 p.fields.vignetting.len(),
816 p.fields.points.len()
817 )
818 .into());
819 }
820 let fields: Vec<Field> = p
821 .fields
822 .points
823 .iter()
824 .enumerate()
825 .map(|(i, q)| {
826 let mut f = Field::xy(q[0], q[1]);
827 f.w = p.fields.weights.get(i).copied().unwrap_or(1.0);
828 if let Some(&[vdx, vdy, vcx, vcy, van]) = p.fields.vignetting.get(i) {
829 (f.vdx, f.vdy, f.vcx, f.vcy, f.van) = (vdx, vdy, vcx, vcy, van);
830 }
831 f
832 })
833 .collect();
834 let mut s = System::new(
835 sf,
836 wl,
837 wt,
838 p.primary - 1,
839 fields,
840 ft,
841 p.fields.norm,
842 (p.aperture.kind, p.aperture.value),
843 p.telecentric,
844 p.aiming,
845 c.glasses,
846 )?
847 .into_prescription();
848 s.name = p.name.clone();
849 s.macros = crate::zmx_links::project_macros(&p.macros)?;
851 let b = glass::builtin::note_for(&s, &p.glass_catalogs, &dirs);
853 s.import_notes.extend(b);
854 s.import_notes.extend(std::mem::take(&mut c.notes));
855 s.temperature = envr.temperature_c;
856 s.pressure = envr.pressure_atm;
857 s.adjust_index = envr.adjust_index;
858 s.floating_clip = p.floating_clip;
859 s.mech_clip = p.mech_clip;
860 s.apodization = p.apodization;
861 s.ropd = p.ropd;
862 (s.aim_pupil, s.input_pol, s.glass_template) = (p.aim_pupil, p.input_pol, p.glass_template);
863 if let Some(v) = p.vig_interp {
864 s.vig_interp = v;
865 }
866 s.coat_tables = c.coats;
868 for (k, spec) in &p.coatings {
869 let t = spec.table().map_err(|e| format!("coating {k}: {e}"))?;
870 s.coat_tables.insert(k.clone(), t);
871 }
872 if let Some(u) = &p.afocal {
873 s.afocal = true;
874 s.afocal_unit = AfocalUnit::from_code(u)
875 .ok_or_else(|| format!("afocal unit {u} (ur, mr, rr, as, am or dg)"))?;
876 }
877 if p.fields.kind == FieldKind::Solve {
878 let Some(c) = &p.fields.solve else {
879 return Err("when the fields type is solve, write the condition in solve".into());
880 };
881 let f = |t: &str| {
882 s.find_surface(t)
883 .map_err(|e| format!("field condition: {e}"))
884 };
885 let cond = match c {
886 FieldSolveSpec::Position { surface } => FieldCond::Position { surf: f(surface)? },
887 FieldSolveSpec::DirSum { s1, s2 } => FieldCond::DirSum {
888 s1: f(s1)?,
889 s2: f(s2)?,
890 },
891 FieldSolveSpec::DirDiff { s1, s2 } => FieldCond::DirDiff {
892 s1: f(s1)?,
893 s2: f(s2)?,
894 },
895 };
896 s.field_type = FieldType::Solve(cond);
897 } else if p.fields.solve.is_some() {
898 return Err("fields solve only with type solve".into());
899 }
900 let mut s = s.build_raw()?;
901 fill_turned(&mut s, &c.turn.turned)?;
902 let (picks, medium) = keep_pickups(&mut s, &org, &zpicks)?;
903 let mut warn = Note::all(NoteKind::Pickup, None, picks);
904 warn.extend(Note::all(NoteKind::Medium, None, medium));
905 for (path, t, pr, adj, _) in &c.zenv {
906 let e = &p.environment;
907 if !*adj && !e.adjust_index {
909 continue;
910 }
911 let off_ref = e.temperature_c != 20.0 || e.pressure_atm != 1.0;
913 if (t - e.temperature_c).abs() > 1e-9
914 || (pr - e.pressure_atm).abs() > 1e-9
915 || (off_ref && *adj != e.adjust_index)
916 {
917 warn.push(Note::new(NoteKind::Environment, None, format!(
918 "{path}: the .zmx environment ({t} °C, {pr} atm) differs from the project environment ({} °C, {} atm); indices are computed in the project environment (change it with environment)",
919 e.temperature_c, e.pressure_atm
920 )));
921 }
922 }
923 let mut rx = s.prescription().clone();
925 rx.units = s.lens_units();
926 crate::zmx_links::carry_notes(&mut rx, &zpicks);
928 crate::zmx_links::coating_file(
929 &mut rx,
930 &c.zenv,
931 p.coating_file.as_deref(),
932 &env.base,
933 &env.glass_dirs,
934 &mut warn,
935 );
936 let mut s = rx.build_raw()?;
937 for id in &c.noted {
938 let id = id.as_str();
939 let spans = block_runs(&map, id, None);
940 match s.define_unit(id, &spans, [0.0; 3]) {
941 Ok(u) => {
944 let shift = group_shift(&p.blocks, id).unwrap_or(0.0);
945 s.edit_raw(|rx| {
946 rx.units[u].shift = shift;
947 Ok(())
948 })?
949 }
950 Err(e) => warn.push(Note::new(
951 NoteKind::Unit,
952 Some(id.to_string()),
953 format!("block {id} is not made a lens or group parameter: {e}"),
954 )),
955 }
956 }
957 let flipped = |s: &System, r: &[usize; 2]| -> bool {
960 let faces: Vec<usize> = (r[0]..=r[1].min(map.len() - 1))
961 .filter(|&j| !s.surfaces[j].is_coord_break())
962 .collect();
963 let Some(k) = faces.first().and_then(|&j| map[j].flip) else {
964 return false;
965 };
966 faces.iter().all(|&j| map[j].flip == Some(k))
967 && map.iter().filter(|o| o.flip == Some(k)).count() == faces.len()
968 };
969 let marks: Vec<bool> = s
970 .units
971 .iter()
972 .map(|u| u.spans.first().is_some_and(|r| flipped(&s, r)))
973 .collect();
974 s.edit_raw(|rx| {
975 for (u, f) in rx.units.iter_mut().zip(marks) {
976 u.flipped = f;
977 }
978 Ok(())
979 })?;
980 apply_surface_edits(&mut s, &sites, &map)?;
981 let (w, stopped) = apply_surface_ops(&mut s, &sites, &map)?;
982 if c.nstop == 0 && !stopped {
983 return Err("0 stops (no set_stop block in surface_ops; exactly one is needed)".into());
985 }
986 warn.extend(w);
987 if let Some(r) = &p.glrs {
988 let g = match r {
989 BlockRef::Sys(r) => Some(edit_ops::surf_of(&s, r, "glrs")?),
990 BlockRef::Block(f) => {
991 let j = block_face_of(&s, f, &map).map_err(|x| format!("glrs: {x}"))?;
992 if j.is_none() {
993 warn.push(Note::new(
994 NoteKind::Glrs,
995 Some(f.block.clone()),
996 format!(
997 "glrs: block {} not found, so the global reference stays at surface {}",
998 f.block, s.glrs
999 ),
1000 ));
1001 }
1002 j
1003 }
1004 };
1005 if let Some(g) = g {
1006 s.edit_raw(|rx| {
1007 rx.glrs = g;
1008 Ok(())
1009 })?;
1010 if !s.macros.is_empty() {
1012 s.resolve_links()?;
1013 }
1014 }
1015 }
1016 crate::lens_edge::lens_edge_apertures(&mut s)?;
1017 s.update_semi();
1019 let mut mw = Vec::new();
1020 let mut mech = place_mechanics(&s, &p.mechanics, env, &map, &mut mw)?;
1021 mech.extend(place_frames(&s, &c.frames, &map, &mut mw));
1022 warn.extend(Note::all(NoteKind::Mechanics, None, mw));
1023 s.edit_raw(|rx| {
1024 rx.mechanics = mech;
1025 Ok(())
1026 })?;
1027 warn.extend(crate::expand_error::in_medium_notes(&s, &map));
1028 s.validate()?;
1029 Ok(Walk::Done(Box::new(Expansion {
1030 system: s,
1031 notes: warn,
1032 gaps: c.gaps,
1033 map,
1034 })))
1035}
1036
1037pub(crate) fn place_mechanics(
1039 s: &System,
1040 ms: &[MechPlacement],
1041 env: &Env<'_>,
1042 map: &[SurfOrigin],
1043 warn: &mut Vec<String>,
1044) -> lensbench_core::Result<Vec<lensbench_core::mech::MechPart>> {
1045 let mut out = Vec::new();
1046 let mut specs: Vec<MechSpec> = Vec::new();
1048 for (k, m) in ms.iter().enumerate() {
1049 let tag = format!("mechanics {}", k + 1);
1050 let mut step_file = String::new();
1052 let (spec, item_name) = match (&m.mech, &m.catalog, &m.item) {
1053 (Some(x), None, None) => (x.clone(), String::new()),
1054 (None, Some(cat), Some(item)) => {
1055 let path = env.base.join(cat);
1056 let c = UserCatalog::load_shared(&path)?;
1057 let it = c
1058 .items
1059 .get(item)
1060 .ok_or_else(|| format!("{tag}: no item {item} in {}", path.display()))?;
1061 let x = it.mech().cloned().ok_or_else(|| {
1062 format!("{tag}: item {item} is not a mechanical part (no mech)")
1063 })?;
1064 if let Some(f) = env.step_files.and_then(|look| look(item, &it.cad.step)) {
1066 step_file = f.display().to_string();
1067 }
1068 (x, item.clone())
1069 }
1070 _ => {
1071 return Err(format!(
1072 "{tag}: write a part with mech, or with catalog and item, not both"
1073 )
1074 .into())
1075 }
1076 };
1077 spec.validate().map_err(|e| format!("{tag}: {e}"))?;
1078 let spec = if m.reversed {
1080 let t = if m.seat {
1081 m.holds
1082 .first()
1083 .and_then(|b| fwd_run(map, b))
1084 .map_or(0.0, |x| {
1085 (x[0]..x[1])
1086 .filter(|&j| j < s.surfaces.len() && !s.surfaces[j].is_coord_break())
1087 .map(|j| s.surfaces[j].t)
1088 .sum::<f64>()
1089 })
1090 } else {
1091 0.0
1092 };
1093 spec.flipped(t)
1094 } else {
1095 spec
1096 };
1097 let name = if !m.name.is_empty() {
1098 m.name.clone()
1099 } else if !item_name.is_empty() {
1100 item_name.clone()
1101 } else {
1102 format!("mech{}", k + 1)
1103 };
1104 if let Some(prev_name) = &m.after {
1106 if m.seat || !m.at.is_unset() {
1107 return Err(format!("{tag}: after can't be used with at or seat").into());
1108 }
1109 if m.tilt != [0.0, 0.0] {
1110 return Err(format!(
1111 "{tag}: tilt can't be used with after (it takes the previous part's tilt)"
1112 )
1113 .into());
1114 }
1115 let Some((prev, prev_spec)) = out
1116 .iter()
1117 .zip(&specs)
1118 .rev()
1119 .find(|(p, _): &(&lensbench_core::mech::MechPart, _)| &p.name == prev_name)
1120 else {
1121 return Err(format!("{tag}: the after part {prev_name} is not before it").into());
1122 };
1123 let (prev, prev_spec): (&lensbench_core::mech::MechPart, &MechSpec) = (prev, prev_spec);
1124 let overlap = match (&prev_spec.back_thread, &spec.front_thread) {
1125 (Some(a), Some(b)) => {
1126 if a.thread != b.thread || a.male == b.male {
1127 let kind = |t: &ThreadEnd| {
1128 if t.male {
1129 format!("{} male", t.thread)
1130 } else {
1131 format!("{} female", t.thread)
1132 }
1133 };
1134 warn.push(format!(
1135 "{tag}: the threads of the back end of {prev_name} ({why}) and the front end of {name} ({hint}) don't match",
1136 why = kind(a),
1137 hint = kind(b)
1138 ));
1139 0.0
1140 } else if b.male {
1141 b.length + a.recess
1142 } else {
1143 a.length + b.recess
1144 }
1145 }
1146 _ => 0.0,
1147 };
1148 let mut part0 = spec.part(&name, prev.surface, [0.0; 3], prev.tilt);
1149 let z = prev.z_range()[1] - overlap - part0.z_range()[0];
1150 let r = lensbench_core::math::mm(
1151 &lensbench_core::math::rot(0, prev.tilt[0]),
1152 &lensbench_core::math::rot(1, prev.tilt[1]),
1153 );
1154 let d = lensbench_core::math::mv(&r, [m.offset[0], m.offset[1], m.offset[2] + z]);
1155 part0.offset = [
1156 prev.offset[0] + d[0],
1157 prev.offset[1] + d[1],
1158 prev.offset[2] + d[2],
1159 ];
1160 if !part0.offset.iter().all(|v| v.is_finite()) {
1161 return Err(format!("{tag}: offset is not a number").into());
1162 }
1163 for b in &m.holds {
1164 match fwd_run(map, b) {
1165 Some(x) => part0
1166 .holds
1167 .extend((x[0]..=x[1]).filter(|&j| !s.surfaces[j].is_coord_break())),
1168 None => warn.push(format!("{tag}: no block {b} for holds")),
1169 }
1170 }
1171 part0.step = step_file;
1172 part0.step_flip = m.reversed;
1173 out.push(part0);
1174 specs.push(spec);
1175 continue;
1176 }
1177 let mut offset = m.offset;
1178 let seat_at = if m.seat {
1180 let seat = spec
1181 .holds
1182 .ok_or_else(|| {
1183 format!("{tag}: seat needs holds (the seat position) in the part size")
1184 })?
1185 .seat_z;
1186 let b = m
1187 .holds
1188 .first()
1189 .ok_or_else(|| format!("{tag}: seat needs holds (the held element)"))?;
1190 offset[2] -= seat;
1191 match block_face(s, b, 0, map).map_err(|e| format!("{tag}: {e}"))? {
1192 Some(j) => Some(j),
1193 None => {
1194 warn.push(format!("{tag}: no block {b}, not placed"));
1195 continue;
1196 }
1197 }
1198 } else {
1199 None
1200 };
1201 let surface = match (seat_at, &m.at.block) {
1202 (Some(j), _) => j,
1203 (None, block) => match block {
1204 Some(b) => {
1205 match block_face(s, b, m.at.surface, map).map_err(|e| format!("{tag}: {e}"))? {
1206 Some(j) => j,
1207 None => {
1208 warn.push(format!("{tag}: no block {b}, not placed"));
1209 continue;
1210 }
1211 }
1212 }
1213 None => {
1214 if m.at.is_unset() {
1215 return Err(format!("{tag}: a place (at) or seat is needed").into());
1216 }
1217 if m.at.surface == 0 || m.at.surface > s.image() {
1218 return Err(format!(
1219 "{tag}: surface {} (1 to {})",
1220 m.at.surface,
1221 s.image()
1222 )
1223 .into());
1224 }
1225 m.at.surface
1226 }
1227 },
1228 };
1229 if !offset.iter().chain(&m.tilt).all(|v| v.is_finite()) {
1230 return Err(format!("{tag}: offset or tilt is not a number").into());
1231 }
1232 let mut part = spec.part(&name, surface, offset, m.tilt);
1233 for b in &m.holds {
1234 match fwd_run(map, b) {
1235 Some(x) => part
1236 .holds
1237 .extend((x[0]..=x[1]).filter(|&j| !s.surfaces[j].is_coord_break())),
1238 None => warn.push(format!("{tag}: no block {b} for holds")),
1239 }
1240 }
1241 part.step = step_file;
1242 part.step_flip = m.reversed;
1243 out.push(part);
1244 specs.push(spec);
1245 }
1246 Ok(out)
1247}
1248
1249pub(crate) fn place_frames(
1252 s: &System,
1253 frames: &[(String, MechSpec)],
1254 map: &[SurfOrigin],
1255 warn: &mut Vec<String>,
1256) -> Vec<lensbench_core::mech::MechPart> {
1257 let mut out = Vec::new();
1258 for (k, (name, f)) in frames.iter().enumerate() {
1259 let tag = format!("{name} mount");
1260 if let Err(e) = f.validate() {
1261 warn.push(format!("{tag}: {e} (not placed)"));
1262 continue;
1263 }
1264 let faces: Vec<usize> = (0..s.surfaces.len().min(map.len()))
1265 .filter(|&j| map[j].frame == Some(k) && !s.surfaces[j].is_coord_break())
1266 .collect();
1267 let Some(&first) = faces.first() else {
1268 continue;
1269 };
1270 let seat = f.holds.map_or(0.0, |h| h.seat_z);
1271 let mut part = f.part(&tag, first, [0.0, 0.0, -seat], [0.0, 0.0]);
1272 part.holds = faces;
1273 out.push(part);
1274 }
1275 out
1276}
1277
1278pub(crate) fn group_shift(blocks: &[Block], id: &str) -> Option<f64> {
1280 for b in blocks {
1281 match b {
1282 Block::Group {
1283 id: g,
1284 shift,
1285 blocks,
1286 ..
1287 } => {
1288 if g == id {
1289 return Some(*shift);
1290 }
1291 if let Some(v) = group_shift(blocks, id) {
1292 return Some(v);
1293 }
1294 }
1295 Block::Zmx { groups, .. } => {
1296 if let Some(g) = groups.iter().find(|g| g.id == id) {
1297 return Some(g.shift);
1298 }
1299 }
1300 Block::Splitter { spec, .. } => {
1301 for arm in [&spec.t, &spec.r, &spec.d] {
1302 if let Some(v) = group_shift(arm, id) {
1303 return Some(v);
1304 }
1305 }
1306 }
1307 _ => {}
1308 }
1309 }
1310 None
1311}
1312
1313pub(crate) fn keep_pickups(
1318 s: &mut System,
1319 org: &[Option<(usize, usize)>],
1320 zpicks: &[ZmxLinks],
1321) -> lensbench_core::Result<(Vec<String>, Vec<String>)> {
1322 let mut at: HashMap<(usize, usize), usize> = HashMap::new();
1323 for (i, o) in org.iter().enumerate() {
1324 if let Some(k) = o {
1325 at.insert(*k, i + 1);
1327 }
1328 }
1329 let medium = crate::zmx_links::carry_object(s, zpicks, &mut at)?;
1330 let mut warn = Vec::new();
1331 for (inst, z) in zpicks.iter().enumerate() {
1332 let (path, picks) = (&z.path, &z.pickups);
1333 for q in picks {
1334 let (Some(&dst), src) = (at.get(&(inst, q.dst)), at.get(&(inst, q.src))) else {
1335 continue; };
1337 let Some(&src) = src else {
1338 warn.push(format!(
1339 "{path}: surface {} {:?} is a pickup from surface {} outside the range (fixed to the value)",
1340 q.dst, q.what, q.src
1341 ));
1342 continue;
1343 };
1344 use lensbench_core::param::Kind as Pk;
1348 let flips = |k: Pk| matches!(k, Pk::Curv | Pk::Thick | Pk::Radius);
1349 let sd = if flips(q.what) { z.sign } else { 1.0 };
1350 let ss = if flips(q.from.unwrap_or(q.what)) {
1351 z.sign
1352 } else {
1353 1.0
1354 };
1355 let mut cands = vec![Pickup {
1356 dst,
1357 src,
1358 scale: sd * ss * q.scale,
1359 offset: sd * q.offset,
1360 ..*q
1361 }];
1362 for (a, b) in [(1.0, 1.0), (1.0, -1.0), (-1.0, 1.0), (-1.0, -1.0)] {
1363 let c = Pickup {
1364 dst,
1365 src,
1366 scale: a * q.scale,
1367 offset: b * q.offset,
1368 ..*q
1369 };
1370 if !cands.contains(&c) {
1371 cands.push(c);
1372 }
1373 }
1374 match cands.iter().position(|c| c.holds(s)) {
1375 Some(0) => s.edit_raw(|rx| {
1376 rx.pickups.push(cands[0]);
1377 Ok(())
1378 })?,
1379 Some(k) => {
1380 s.edit_raw(|rx| {
1382 rx.pickups.push(cands[k]);
1383 Ok(())
1384 })?;
1385 warn.push(format!(
1386 "{path}: the sign of the scale and offset of surface {} {:?} (from surface {}) was chosen by matching values (scale {}, offset {}); check it is as intended",
1387 q.dst, q.what, q.src, cands[k].scale, cands[k].offset
1388 ));
1389 }
1390 None => warn.push(format!(
1391 "{path}: the value relation of surface {} {:?} (from surface {}) changed in the expansion (fixed to the value)",
1392 q.dst, q.what, q.src
1393 )),
1394 }
1395 }
1396 }
1397 if !s.pickups.is_empty() {
1398 s.resolve_links()?;
1399 }
1400 let moff = crate::zmx_links::carry_macros(s, zpicks, &at)?;
1401 for (inst, z) in zpicks.iter().enumerate() {
1404 for q in &z.solves {
1405 let Some(&k) = at.get(&(inst, q.surf)) else {
1406 continue;
1407 };
1408 let same = |j: usize| -> bool {
1410 at.get(&(inst, j))
1411 .is_some_and(|&n| n as i64 - k as i64 == j as i64 - q.surf as i64)
1412 };
1413 use lensbench_core::solves::SolveKind as Sk;
1414 let mut ok = true;
1415 if !q.kind.is_curv() && !matches!(q.kind, Sk::Position { .. }) {
1417 ok &= same(q.surf + 1) || (q.surf + 1 == z.image && k + 1 == s.image());
1418 }
1419 if matches!(q.kind, Sk::ElementPower { .. }) {
1420 ok &= q.surf >= 1 && same(q.surf - 1);
1421 }
1422 let mut kind = q.kind;
1423 crate::zmx_links::shift_macro(&mut kind, moff[inst]);
1424 if let Some(o) = q.kind.other_surface() {
1425 ok &= same(o);
1426 if matches!(
1428 q.kind,
1429 Sk::Position { .. }
1430 | Sk::CenterOfCurvature { .. }
1431 | Sk::ConcentricSurface { .. }
1432 | Sk::ConcentricRadius { .. }
1433 ) {
1434 ok &= (o.min(q.surf)..=o.max(q.surf)).all(same);
1435 }
1436 if let Some(&n) = at.get(&(inst, o)) {
1437 kind = kind.with_other_surface(n);
1438 }
1439 }
1440 if ok {
1441 s.edit_raw(|rx| {
1442 rx.solves.push(Solve { surf: k, kind });
1443 Ok(())
1444 })?;
1445 } else {
1446 warn.push(format!(
1447 "{}: the solve of surface {} ({:?}) involves surfaces outside the range or far away (fixed to the value)",
1448 z.path, q.surf, q.kind
1449 ));
1450 }
1451 }
1452 }
1453 if !s.solves.is_empty() || !s.macro_parms.is_empty() {
1454 let val = |s: &System, q: &Solve| {
1455 let d = &s.surfaces[q.surf];
1456 if q.kind.is_curv() {
1457 d.c
1458 } else {
1459 d.t
1460 }
1461 };
1462 let before: Vec<f64> = s.solves.iter().map(|q| val(s, q)).collect();
1463 s.resolve_links()?;
1464 for (q, b) in s.solves.iter().zip(before) {
1465 let a = val(s, q);
1466 if (a - b).abs() > 1e-9 * (1.0 + b.abs()) {
1467 let what = if q.kind.is_curv() {
1468 "curvature"
1469 } else {
1470 "thickness"
1471 };
1472 warn.push(format!(
1473 "solved the {what} of surface {} again with the solve ({}, value {}): {b} → {a}",
1474 q.surf,
1475 lensbench_core::solves::solve_kind_info(q.kind).0,
1476 q.kind.value()
1477 ));
1478 }
1479 }
1480 }
1481 Ok((warn, medium))
1482}
1483
1484fn glass_missing(j: usize, mat: &str) -> lensbench_core::Error {
1486 lensbench_core::Error::Invalid(format!(
1487 "surface {j}: glass {mat} is not in the catalogs{HINT}"
1488 ))
1489 .with_code(code::GLASS_NOT_FOUND)
1490}