1use super::*;
4use lensbench_core::sync::LockExt;
5pub type CatalogLookup<'a> = &'a dyn Fn(&str, &str) -> lensbench_core::Result<String>;
7
8#[derive(Default)]
15pub struct SourceCache {
16 lenses: std::sync::Mutex<HashMap<(String, String), CachedLens>>,
17 files: std::sync::Mutex<HashMap<(PathBuf, usize), (lensbench_core::vfs::Stamp, System)>>,
18 scope: std::sync::Mutex<String>,
19}
20
21type CachedLens = std::sync::Arc<(Element, std::sync::Arc<HashMap<String, Glass>>)>;
22
23impl std::fmt::Debug for SourceCache {
24 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
25 f.debug_struct("SourceCache")
26 .field("lenses", &self.lenses.lock_ok().len())
27 .field("files", &self.files.lock_ok().len())
28 .finish()
29 }
30}
31
32impl SourceCache {
33 pub fn file_count(&self) -> usize {
35 self.files.lock_ok().len()
36 }
37
38 pub fn scope(&self, key: &str) {
41 let mut s = self.scope.lock_ok();
42 if *s != key {
43 self.lenses.lock_ok().clear();
44 self.files.lock_ok().clear();
45 *s = key.to_string();
46 }
47 }
48
49 fn file(&self, k: &(PathBuf, usize), st: &lensbench_core::vfs::Stamp) -> Option<System> {
50 match self.files.lock_ok().get(k) {
51 Some((s, sys)) if s == st => Some(sys.clone()),
52 _ => None,
53 }
54 }
55}
56
57pub type StepLookup<'a> = &'a (dyn Fn(&str, &str) -> Option<PathBuf> + Sync);
60
61#[derive(Default)]
63pub struct Env<'a> {
64 pub base: PathBuf,
66 pub glass_dirs: Vec<PathBuf>,
67 pub catalog: Option<CatalogLookup<'a>>,
68 pub step_files: Option<StepLookup<'a>>,
71}
72
73impl<'a> Env<'a> {
74 pub fn for_file(
76 path: &Path,
77 glass_dirs: &[PathBuf],
78 catalog: Option<CatalogLookup<'a>>,
79 ) -> Env<'a> {
80 Env::in_dir(path.parent().unwrap_or(Path::new("")), glass_dirs, catalog)
81 }
82
83 pub fn in_dir(
85 base: &Path,
86 glass_dirs: &[PathBuf],
87 catalog: Option<CatalogLookup<'a>>,
88 ) -> Env<'a> {
89 Env {
90 base: base.to_path_buf(),
91 glass_dirs: glass_dirs.to_vec(),
92 catalog,
93 step_files: None,
94 }
95 }
96}
97
98pub(crate) struct Ctx<'a, 'b> {
99 pub(crate) env: &'a Env<'b>,
100 pub(crate) cache: Option<&'a SourceCache>,
101 pub(crate) base: PathBuf,
103 pub(crate) loading: Vec<Loading>,
106 pub(crate) outer: usize,
108 pub(crate) sf: Vec<Surface>,
109 pub(crate) map: Vec<SurfOrigin>,
111 pub(crate) noted: Vec<String>,
113 pub(crate) nflip: usize,
115 pub(crate) flip_err: Option<lensbench_core::Error>,
117 pub(crate) zpicks: Vec<ZmxLinks>,
120 pub(crate) lead: f64,
122 pub(crate) parity: f64,
124 pub(crate) glasses: std::sync::Arc<HashMap<String, Glass>>,
126 pub(crate) coats: HashMap<String, lensbench_core::coating::Table>,
128 pub(crate) nstop: usize,
129 pub(crate) gaps: Vec<Gap>,
131 pub(crate) split: SplitState,
133 pub(crate) turn: TurnState,
135 pub(crate) frames: Vec<(String, MechSpec)>,
137 pub(crate) zenv: Vec<(String, f64, f64, bool, Option<std::path::PathBuf>)>,
140 pub(crate) nodes: HashMap<usize, NodePath>,
142 pub(crate) leaf: Vec<usize>,
144 pub(crate) failed: Option<NodePath>,
146 pub(crate) notes: Vec<String>,
148 pub(crate) media: HashMap<usize, Material>,
150}
151
152pub(crate) type ItemFrame = Option<(MechSpec, bool)>;
154
155pub(crate) fn is_air(m: &Material) -> bool {
156 m.is_air()
157}
158
159pub(crate) fn is_air_name(m: &str) -> bool {
161 m.trim().is_empty() || m.trim().eq_ignore_ascii_case("AIR")
162}
163
164pub(crate) fn plate_face(s: &Surface) -> Surface {
166 Surface {
167 semi: s.semi,
168 semi_auto: s.semi_auto,
169 ap: s.ap,
170 ..Default::default()
171 }
172}
173
174pub(crate) fn round_unit(v: f64) -> f64 {
176 if v.abs() < 1e-15 {
177 0.0
178 } else if (v.abs() - 1.0).abs() < 1e-15 {
179 v.signum()
180 } else {
181 v
182 }
183}
184
185pub(crate) fn ideal_face(t: f64) -> String {
187 let f = (t.sqrt() * 1e8).floor().min(99_999_999.0) as u64;
188 format!("I.{f:08}")
189}
190
191pub(crate) fn check_crystal_order(v: &[Surface]) -> lensbench_core::Result<()> {
194 use lensbench_core::surface::Bire;
195 let mut inside = false;
196 for (i, s) in v.iter().enumerate() {
197 match (&s.bire, inside) {
198 (Some(Bire::In { .. }), false) => inside = true,
199 (Some(Bire::Out), true) => {
200 inside = false;
201 if !is_air(&s.mat) {
202 let next_in = matches!(
203 v.get(i + 1).and_then(|n| n.bire.as_ref()),
204 Some(Bire::In { .. })
205 );
206 if !next_in || s.t != 0.0 || v[i + 1].mat != s.mat {
207 return Err(
208 "the glass after the exit of a birefringent plate goes to the entrance of the next plate of the same material with thickness 0"
209 .into(),
210 );
211 }
212 }
213 }
214 (Some(Bire::In { .. }), true) => {
215 return Err("two birefringent plate entrances in a row (an exit is needed)".into())
216 }
217 (Some(Bire::Out), false) => {
218 return Err("no entrance before the exit of a birefringent plate".into())
219 }
220 (None, true) => {
221 return Err(
222 "no other surface can go between the entrance and exit of a birefringent plate"
223 .into(),
224 )
225 }
226 (None, false) => {
227 if !s.is_coord_break() && !is_air(&s.mat) {
228 return Err(
229 "a surface list block holds only surfaces in air (glass goes in lenses)"
230 .into(),
231 );
232 }
233 }
234 }
235 }
236 if inside {
237 return Err("a birefringent plate has no exit".into());
238 }
239 Ok(())
240}
241
242pub(crate) fn cb(d: [f64; 5], order: u8, t: f64) -> Surface {
244 Surface {
245 form: Form::CoordBrk { cb: d, order },
246 mat: "-".into(),
247 t,
248 ..Default::default()
249 }
250}
251
252pub(crate) struct ZmxLinks {
254 pub(crate) path: String,
255 pub(crate) sign: f64,
257 pub(crate) pickups: Vec<Pickup>,
258 pub(crate) solves: Vec<Solve>,
259 pub(crate) image: usize,
261 pub(crate) obj_comment: String,
263 pub(crate) obj_mat: Material,
265 pub(crate) macro_notes: Vec<String>,
267 pub(crate) macros: Vec<lensbench_core::zpl_solve::Macro>,
269 pub(crate) macro_parms: Vec<lensbench_core::zpl_solve::MacroParm>,
270}
271
272impl<'a, 'b> Ctx<'a, 'b> {
273 pub(crate) fn crystal_plates(&self, v: Vec<Surface>) -> lensbench_core::Result<Vec<Surface>> {
277 let mut out = Vec::with_capacity(v.len());
278 for s in v {
279 let Some(r0) = s.retarder.as_ref().filter(|r| !r.plates.is_empty()) else {
280 out.push(s);
281 continue;
282 };
283 if s.before.is_some() {
284 return Err("tilt is not supported on a birefringent waveplate".into());
285 }
286 let mut r = r0.clone();
287 r.resolve(&self.glasses)?;
288 let coat = if !s.coat.is_empty() {
289 s.coat.clone()
290 } else {
291 ideal_face(r.tx * r.tx)
292 };
293 let n = r.plates.len();
294 for (i, p) in r.plates.iter().enumerate() {
295 let fast = r.axis_deg + p.axis_deg;
297 let oa = if p.dn(r.wl0) > 0.0 { fast + 90.0 } else { fast }.to_radians();
298 let axis = [round_unit(oa.cos()), round_unit(oa.sin()), 0.0];
299 out.push(Surface {
300 mat: Material::Glass(p.material.clone()),
301 t: p.thickness,
302 stop: s.stop && i == 0,
303 coat: if i == 0 { coat.clone() } else { String::new() },
304 comment: if i == 0 {
305 s.comment.clone()
306 } else {
307 String::new()
308 },
309 bire: Some(lensbench_core::surface::Bire::In {
310 mode: 2,
311 axis,
312 ne: Vec::new(),
313 }),
314 ..plate_face(&s)
315 });
316 let last = i + 1 == n;
317 out.push(Surface {
318 mat: if last {
319 Material::Air
320 } else {
321 Material::Glass(r.plates[i + 1].material.clone())
322 },
323 t: if last { s.t } else { 0.0 },
324 coat: if last { coat.clone() } else { String::new() },
325 bire: Some(lensbench_core::surface::Bire::Out),
326 ..plate_face(&s)
327 });
328 }
329 }
330 Ok(out)
331 }
332
333 pub(crate) fn put(&mut self, s: Surface) {
335 self.sf.push(s);
336 self.map.push(SurfOrigin {
337 leaf: self.cur_leaf(),
338 ..Default::default()
339 });
340 }
341
342 pub(crate) fn cur_leaf(&self) -> usize {
344 self.leaf.last().copied().unwrap_or(0)
345 }
346
347 pub(crate) fn in_node<T>(
349 &mut self,
350 b: &Block,
351 f: impl FnOnce(&mut Self) -> lensbench_core::Result<T>,
352 ) -> lensbench_core::Result<T> {
353 let k = b as *const Block as usize;
354 let on = self.nodes.contains_key(&k);
355 if on {
356 self.leaf.push(k);
357 }
358 let r = f(self);
359 if on {
360 if r.is_err() && self.failed.is_none() {
362 self.failed = self.nodes.get(&k).cloned();
363 }
364 self.leaf.pop();
365 }
366 r
367 }
368
369 pub(crate) fn note_gap(&mut self, id: &str) {
371 if !id.is_empty() {
372 self.gaps.push((id.to_string(), self.sf.len(), self.parity));
373 }
374 }
375
376 pub(crate) fn gap(&mut self, t: f64) {
377 match self.sf.last_mut() {
378 Some(s) => s.t += t * self.parity,
379 None => self.lead += t,
380 }
381 }
382
383 fn flip(&mut self, s: &mut Surface) {
385 if let Err(e) = s.flip_z() {
386 if self.flip_err.is_none() {
387 let j = self.sf.len() + 1;
388 self.flip_err = Some(e.map_message(|e| format!("surface {j} after a mirror: {e}")));
389 }
390 }
391 }
392
393 pub(crate) fn push(&mut self, mut s: Surface) {
395 if self.parity < 0.0 {
396 self.flip(&mut s);
397 s.t = -s.t;
398 }
399 if s.stop {
400 self.nstop += 1;
401 }
402 self.put(s);
403 }
404
405 pub(crate) fn medium(&self) -> Material {
407 self.sf
408 .iter()
409 .rev()
410 .map(|s| &s.mat)
411 .find(|m| !matches!(m, Material::Mirror | Material::Inherit))
412 .cloned()
413 .unwrap_or_default()
414 }
415
416 fn fill_gap(&mut self, m: &str) -> lensbench_core::Result<()> {
418 let s = self
419 .sf
420 .last_mut()
421 .ok_or("a gap filled with a medium needs a surface before it")?;
422 if !s.mat.is_air() {
423 return Err(format!(
424 "a gap filled with {m}: the medium before it is not air (the gap after a mirror or a glass)"
425 )
426 .into());
427 }
428 s.mat = match m.trim().parse::<f64>() {
429 Ok(nd) => Material::Index(nd),
430 Err(_) => Material::parse(m),
431 };
432 Ok(())
433 }
434
435 pub(crate) fn push_mirror(&mut self, mut s: Surface) {
437 if self.parity < 0.0 {
438 self.flip(&mut s);
439 }
440 self.parity = -self.parity;
441 s.t *= self.parity;
442 if s.stop {
443 self.nstop += 1;
444 }
445 self.put(s);
446 }
447
448 pub(crate) fn has_mirror_since(&self, start: usize) -> bool {
451 self.sf[start.min(self.sf.len())..]
452 .iter()
453 .any(|s| s.is_mirror())
454 }
455
456 pub(crate) fn length_since(&self, start: usize) -> f64 {
458 self.sf[start..].iter().map(|s| s.t).sum::<f64>() * self.parity
459 }
460
461 pub(crate) fn placed(
463 &mut self,
464 place: &Place,
465 body: &mut dyn FnMut(&mut Self) -> lensbench_core::Result<()>,
466 ) -> lensbench_core::Result<()> {
467 if !place.on {
468 if place.off == OffMode::Air {
469 let start = self.sf.len();
472 let (p0, n0, lead0) = (self.parity, self.nstop, self.lead);
473 let lens = (self.noted.len(), self.gaps.len(), self.zpicks.len());
474 body(self)?;
475 if self.parity != p0 {
476 return Err("a block with a mirror can't be 'kept as air'".into());
477 }
478 let l = self.length_since(start) + (self.lead - lead0);
479 self.sf.truncate(start);
480 self.map.truncate(start);
481 self.noted.truncate(lens.0);
482 self.gaps.truncate(lens.1);
483 self.zpicks.truncate(lens.2);
484 self.nstop = n0;
485 self.lead = lead0;
486 self.gap(l);
487 }
488 return Ok(());
489 }
490 if !place.moved() {
491 return body(self);
492 }
493 let [dx, dy] = place.decenter;
494 let [tx, ty, tz] = place.tilt;
495 self.push(cb([dx, dy, tx, ty, tz], 0, 0.0));
496 self.mark_placed();
497 let start = self.sf.len();
498 let p0 = self.parity;
499 body(self)?;
500 if self.parity != p0 {
501 return Err(
502 "a mirror can't go in a decentered or tilted block (tilt the mirror itself)".into(),
503 );
504 }
505 let tail = self.sf.last().map(|s| s.t).unwrap_or(0.0);
507 if let Some(s) = self.sf.last_mut() {
508 s.t = 0.0;
509 }
510 let l: f64 = self.sf[start..].iter().map(|s| s.t).sum(); let (dx2, dy2, t2) = cb_return(place, l);
512 self.put(cb([dx2, dy2, -tx, -ty, -tz], 1, t2 + tail));
514 self.mark_placed();
515 Ok(())
516 }
517
518 pub(crate) fn mark_placed(&mut self) {
520 if let Some(m) = self.map.last_mut() {
521 m.placed = true;
522 }
523 }
524
525 pub(crate) fn element(&mut self, e: &Element, sign: f64) {
528 self.element_from(e, sign, None)
529 }
530
531 pub(crate) fn element_from(&mut self, e: &Element, sign: f64, inst: Option<usize>) {
533 if e.kind == Kind::Air {
534 match self.sf.last_mut() {
535 Some(s) => s.t += e.t * sign,
536 None => self.lead += e.t * sign,
537 }
538 return;
539 }
540 for (i, s) in e.surfaces.iter().enumerate() {
541 let mut s = s.clone();
542 if sign < 0.0 {
543 self.flip(&mut s);
544 s.t = -s.t;
545 }
546 if s.is_mirror() {
547 self.parity = -self.parity;
548 }
549 if s.stop {
550 self.nstop += 1;
551 }
552 self.sf.push(s);
553 self.map.push(SurfOrigin {
554 zmx: inst.map(|k| (k, e.from + i)),
555 leaf: self.cur_leaf(),
556 ..Default::default()
557 });
558 }
559 }
560
561 pub(crate) fn note(&mut self, id: &str, faces: Option<&FaceMods>, start: usize) {
564 if let Some(k) = faces.map(|f| f.site).filter(|&k| k > 0) {
565 let k = k - 1;
566 for o in &mut self.map[start..] {
567 if !o.mods.contains(&k) {
568 o.mods.push(k);
569 }
570 }
571 }
572 if !id.is_empty() && self.sf.len() > start {
573 for o in &mut self.map[start..] {
574 if !o.blocks.iter().any(|b| b == id) {
575 o.blocks.push(id.to_string());
576 }
577 }
578 if !self.noted.iter().any(|b| b == id) {
579 self.noted.push(id.to_string());
580 }
581 }
582 }
583
584 pub(crate) fn back_block(&mut self, b: &Block) -> lensbench_core::Result<()> {
586 let start = self.sf.len();
587 self.in_node(b, |c| c.back_block_inner(b))?;
588 self.note(block_id(b), b.faces(), start);
589 for o in &mut self.map[start..] {
590 o.back = true;
591 }
592 Ok(())
593 }
594
595 pub(crate) fn back_block_inner(&mut self, b: &Block) -> lensbench_core::Result<()> {
596 match b {
597 Block::Air { id, t, medium } => {
598 if let Some(m) = medium {
600 let m = match m.trim().parse::<f64>() {
601 Ok(nd) => Material::Index(nd),
602 Err(_) => Material::parse(m),
603 };
604 if let Some(s) = self.sf.last_mut().filter(|s| !s.is_mirror()) {
605 s.mat = m;
606 }
607 }
608 self.note_gap(id);
609 self.gap(*t)
610 }
611 Block::Stop { semi, .. } => {
612 self.push(Surface {
614 semi: *semi,
615 comment: "STOP (return)".into(),
616 ..Default::default()
617 });
618 }
619 Block::Lens {
620 source,
621 reversed,
622 place,
623 ..
624 } => {
625 let mut e = self.lens_element(source)?;
626 if *reversed {
627 e = elements::reverse(&e)?;
628 }
629 let len = e.length();
630 if !place.on {
631 if place.off == OffMode::Air {
632 self.gap(len);
633 }
634 return Ok(());
635 }
636 let mut r = elements::reverse_folded(&e)?;
637 r.surfaces.iter_mut().for_each(|s| s.stop = false);
638 self.back_placed(place, len, &r.surfaces)?;
639 }
640 Block::Surfaces {
641 surfaces, place, ..
642 } => {
643 let v: Vec<Surface> = surfaces.iter().map(surf).collect::<Result<_, _>>()?;
644 if v.iter().any(|s| s.bire.is_some()) {
645 return Err(
646 "birefringent surfaces are not supported in a surface list on the return path".into(),
647 );
648 }
649 if v.iter()
650 .any(|s| s.before.is_some() || s.after != After::None)
651 {
652 return Err(
653 "surfaces with tilts or decenters (before, after) are not supported in a surface list on the return path".into(),
654 );
655 }
656 if v.iter().any(|s| {
658 (!lensbench_core::elements::reversible(s)
659 && !matches!(
660 s.typ(),
661 SurfType::Paraxial | SurfType::Jones | SurfType::CoordBrk
662 ))
663 || s.grin().is_some()
664 }) {
665 return Err(
666 "GRIN and user-defined surfaces are not supported in a surface list on the return path".into(),
667 );
668 }
669 if !place.on {
670 if place.off == OffMode::Air {
671 let l: f64 = v.iter().map(|s| s.t).sum();
672 self.gap(l);
673 }
674 return Ok(());
675 }
676 let tail = v.last().map(|s| s.t).unwrap_or(0.0);
678 let len: f64 = v.iter().map(|s| s.t).sum::<f64>() - tail;
679 self.gap(tail);
680 let before = self
681 .media
682 .get(&(b as *const Block as usize))
683 .cloned()
684 .unwrap_or_default();
685 self.back_placed(place, len, &reverse_surfaces(&v, &before)?)?;
686 }
687 Block::Group {
688 blocks,
689 place,
690 shift,
691 ..
692 } => {
693 if place.moved() {
694 return Err(
695 "decentered or tilted groups are not supported on the return path (put it on the lenses in the group)"
696 .into(),
697 );
698 }
699 if !place.on {
700 return Err("groups that are OFF are not supported on the return path".into());
701 }
702 self.gap(-shift);
704 for x in blocks.iter().rev() {
705 self.back_block(x)?;
706 if self.split.stopped {
707 return Ok(());
708 }
709 }
710 self.gap(*shift);
711 }
712 Block::User { .. } => {
713 let (g, dir, key) = self.user_group(b)?;
714 let base = std::mem::replace(&mut self.base, dir);
715 self.loading.push(key);
716 let r = self.back_block(&g);
717 self.loading.pop();
718 self.base = base;
719 r?;
720 }
721 Block::Mirror { .. } => return Err("a mirror on the return path".into()),
722 Block::Splitter { id, spec, .. } => {
723 if spec.has_branches() {
724 return Err(format!(
725 "BS {id}: a BS with branches is never passed backwards (internal error)"
726 )
727 .into());
728 }
729 self.splitter_back(id)?;
730 }
731 Block::Detector(_) => return Err("a detector must be the last block".into()),
732 Block::Zmx { .. } => {
733 return Err(
734 "importing a .zmx on the return path is not supported (use a lens block)"
735 .into(),
736 )
737 }
738 }
739 Ok(())
740 }
741
742 pub(crate) fn back_placed(
744 &mut self,
745 place: &Place,
746 len: f64,
747 rev: &[Surface],
748 ) -> lensbench_core::Result<()> {
749 if !place.moved() {
750 for s in rev {
751 self.push(s.clone());
752 }
753 return Ok(());
754 }
755 let pf = -self.parity;
758 let l = len * pf;
759 let (dx2, dy2, t2) = cb_return(place, l);
760 let [dx, dy] = place.decenter;
761 let [tx, ty, tz] = place.tilt;
762 self.gap(-t2 * self.parity);
764 self.put(cb([-dx2, -dy2, tx, ty, tz], 0, 0.0));
765 self.mark_placed();
766 for s in rev {
767 self.push(s.clone());
768 }
769 if let Some(s) = self.sf.last_mut() {
770 s.t = 0.0;
771 }
772 self.put(cb([-dx, -dy, -tx, -ty, -tz], 1, 0.0));
773 self.mark_placed();
774 Ok(())
775 }
776
777 pub(crate) fn not_loading(&self, key: &Loading) -> lensbench_core::Result<()> {
779 let Some(i) = self.loading.iter().position(|l| l == key) else {
780 return Ok(());
781 };
782 let chain: Vec<String> = self.loading[i..]
783 .iter()
784 .chain([key])
785 .map(ToString::to_string)
786 .collect();
787 Err(format!("a loop of imports: {}", chain.join(" → ")).into())
788 }
789
790 pub(crate) fn load_zmx(
792 &mut self,
793 path: &str,
794 cfg: usize,
795 pick: (Option<&str>, Option<&str>),
796 ) -> lensbench_core::Result<System> {
797 if cfg == 0 {
798 return Err(format!("{path}: the configuration number must be 1 or more").into());
799 }
800 let p = self.base.join(path);
801 let picked = pick.0.is_some() || pick.1.is_some();
802 if picked
803 && !p
804 .extension()
805 .is_some_and(|x| x.eq_ignore_ascii_case("json"))
806 {
807 return Err(format!("{path}: state and beam_path are for a project file").into());
808 }
809 let file = lensbench_core::vfs::canonicalize(&p).unwrap_or_else(|_| p.clone());
811 let key = (file.clone(), cfg);
812 let stamp = self.cache.and_then(|_| lensbench_core::vfs::stamp(&p).ok());
813 if let (Some(c), Some(st), false) = (self.cache, &stamp, picked) {
814 if let Some(s) = c.file(&key, st) {
815 let mut s = s;
816 self.merge_glasses(&mut s, path)?;
817 return Ok(s);
818 }
819 }
820 let keep = |c: &Self, s: &System| {
821 if let (Some(c), Some(st)) = (c.cache, stamp) {
822 c.files.lock_ok().insert(key, (st, s.clone()));
823 }
824 };
825 if p.extension()
827 .is_some_and(|x| x.eq_ignore_ascii_case("json"))
828 {
829 if cfg != 1 {
830 return Err(format!("{path}: a .json system has only configuration 1").into());
831 }
832 let txt = lensbench_core::vfs::read_to_string(&p)
834 .map_err(lensbench_core::Error::io_at(p.display()))?;
835 if sysfile::is_system_json(&txt) {
836 if picked {
837 return Err(
838 format!("{path}: state and beam_path are for a project file").into(),
839 );
840 }
841 let mut s = sysfile::load_text_with(&p, &txt, &self.env.glass_dirs)?.0;
842 keep(self, &s);
843 self.merge_glasses(&mut s, path)?;
844 return Ok(s);
845 }
846 let me = Loading { file, item: None };
847 self.not_loading(&me)?;
848 let mut within = self.loading.clone();
849 within.push(me);
850 let mut s = Project::from_json(&txt)
852 .and_then(|q| {
853 let env = Env::for_file(&p, &self.env.glass_dirs, self.env.catalog);
854 let o = ExpandOpts {
855 state: pick.0,
856 path: pick.1,
857 cache: self.cache,
858 within: &within,
859 };
860 expand(&q, &env, &o)
861 .map(|x| x.system)
862 .map_err(lensbench_core::Error::from)
863 })
864 .map_err(|e| e.at(p.display()))?;
865 self.merge_glasses(&mut s, path)?;
866 return Ok(s);
867 }
868 let opt = zmx::LoadOptions {
869 cfg,
870 catalog_dirs: self.env.glass_dirs.clone(),
871 ..Default::default()
872 };
873 let mut s = zmx::load_with(&p, &opt).map_err(|e| format!("{}: {e}", p.display()))?;
874 keep(self, &s);
875 self.merge_glasses(&mut s, path)?;
876 Ok(s)
877 }
878
879 pub(crate) fn user_group(
881 &mut self,
882 b: &Block,
883 ) -> lensbench_core::Result<(Block, PathBuf, Loading)> {
884 self.user_group_frame(b).map(|(g, d, k, _)| (g, d, k))
885 }
886
887 #[allow(clippy::type_complexity)]
889 pub(crate) fn user_group_frame(
890 &mut self,
891 b: &Block,
892 ) -> lensbench_core::Result<(Block, PathBuf, Loading, ItemFrame)> {
893 let Block::User {
894 id,
895 catalog,
896 item,
897 place,
898 ..
899 } = b
900 else {
901 unreachable!()
902 };
903 let path = self.base.join(catalog);
904 let key = Loading {
905 file: lensbench_core::vfs::canonicalize(&path).unwrap_or_else(|_| path.clone()),
906 item: Some(item.clone()),
907 };
908 self.not_loading(&key)?;
909 let cat = UserCatalog::load_shared(&path)?;
910 let it = cat
911 .items
912 .get(item)
913 .ok_or_else(|| format!("{}: no item {item}", path.display()))?;
914 let dirs = glass::catalog_dirs(&self.env.glass_dirs);
915 let (g, missing) = glass::load_catalogs_shared(&it.glass_catalogs, &dirs);
916 if !missing.is_empty() {
917 return Err(lensbench_core::Error::Invalid(format!(
918 "{item}: glass catalog not found: {}. Pass catalog folders with --glass-dir (CLI), glass_dirs (serve, Python) or LENSBENCH_GLASSCAT",
919 missing.join(", ")
920 ))
921 .with_code(lensbench_core::error::code::GLASS_NOT_FOUND));
922 }
923 self.add_glasses(&g);
924 for (k, spec) in &cat.coatings {
926 let t = spec
927 .table()
928 .map_err(|e| format!("{}: coating {k}: {e}", path.display()))?;
929 match self.coats.get(k) {
930 Some(old) if *old != t => {
931 return Err(format!(
932 "{}: coating {k} differs from another catalog",
933 path.display()
934 )
935 .into())
936 }
937 Some(_) => {}
938 None => {
939 self.coats.insert(k.clone(), t);
940 }
941 }
942 }
943 let dir = path.parent().map(Path::to_path_buf).unwrap_or_default();
944 Ok((
945 Block::Group {
946 id: id.clone(),
947 name: item.clone(),
948 role: None,
949 shift: 0.0,
950 blocks: it.blocks().to_vec(),
951 place: place.clone(),
952 faces: FaceMods::default(),
954 },
955 dir,
956 key,
957 it.frame().map(|f| (f.spec.clone(), f.reversed)),
958 ))
959 }
960
961 pub(crate) fn merge_glasses(
965 &mut self,
966 s: &mut System,
967 from: &str,
968 ) -> lensbench_core::Result<()> {
969 let clash: Vec<String> = s
970 .glasses
971 .iter()
972 .filter(|(k, g)| self.glasses.get(*k).is_some_and(|h| h != *g))
973 .map(|(k, _)| k.clone())
974 .collect();
975 if clash.is_empty() {
976 self.add_glasses(&s.glasses);
977 return Ok(());
978 }
979 let mut own = (*s.glasses).clone();
980 let mut renamed = HashMap::new();
981 for k in clash {
982 let Some(g) = own.remove(&k) else { continue };
983 let cat = if g.catalog.is_empty() {
984 from
985 } else {
986 g.catalog.as_str()
987 };
988 let base = glass::qualified(&k, cat);
989 let mut key = base.clone();
991 let mut n = 1;
992 while self.glasses.get(&key).is_some_and(|h| *h != g) || own.contains_key(&key) {
993 n += 1;
994 key = format!("{base}#{n}");
995 }
996 let theirs = &self.glasses[&k];
997 self.notes.push(format!(
998 "glass {}: {} uses catalog {}, not {} of glass_catalogs; named {} in this system",
999 k,
1000 from,
1001 cat,
1002 if theirs.catalog.is_empty() {
1003 "-"
1004 } else {
1005 theirs.catalog.as_str()
1006 },
1007 key,
1008 ));
1009 own.insert(key.clone(), g);
1010 renamed.insert(k, key);
1011 }
1012 let mut rx = s.clone().into_prescription();
1013 for d in &mut rx.surfaces {
1014 if let Material::Glass(m) = &mut d.mat {
1015 if let Some(k) = renamed.get(m.as_str()) {
1016 *m = k.clone();
1017 }
1018 }
1019 }
1020 rx.glasses = std::sync::Arc::new(own);
1021 *s = rx.build_raw()?;
1023 self.add_glasses(&s.glasses);
1024 Ok(())
1025 }
1026
1027 pub(crate) fn add_glasses(&mut self, g: &std::sync::Arc<HashMap<String, Glass>>) {
1029 if std::sync::Arc::ptr_eq(&self.glasses, g)
1030 || g.keys().all(|k| self.glasses.contains_key(k))
1031 {
1032 return;
1033 }
1034 if self.glasses.is_empty() {
1035 self.glasses = g.clone();
1036 return;
1037 }
1038 let m = std::sync::Arc::make_mut(&mut self.glasses);
1039 for (k, v) in g.iter() {
1040 m.entry(k.clone()).or_insert_with(|| v.clone());
1041 }
1042 }
1043
1044 pub(crate) fn lens_element(&mut self, src: &LensSource) -> lensbench_core::Result<Element> {
1045 match src {
1046 LensSource::Zmx { zmx, lens, config } => {
1047 let s = self.load_zmx(zmx, *config, (None, None))?;
1048 Ok(pick_lens(&s, *lens).map_err(|e| format!("{zmx}: {e}"))?)
1049 }
1050 LensSource::Catalog { vendor, part } => {
1051 let key = (vendor.clone(), part.clone());
1052 let hit = self
1053 .cache
1054 .and_then(|c| c.lenses.lock_ok().get(&key).cloned());
1055 if let Some(h) = hit {
1056 self.add_glasses(&h.1);
1057 return Ok(h.0.clone());
1058 }
1059 let f = self.env.catalog.ok_or_else(|| {
1060 format!("lens catalog {vendor} {part}: the catalog can't be read")
1061 })?;
1062 let txt = f(vendor, part).map_err(|e| match e.code() == e.kind() {
1065 true => e.with_code(lensbench_core::error::code::LENS_NOT_FOUND),
1066 false => e,
1067 })?;
1068 let raw = zmx::parse_text(&txt)?;
1069 let s = crate::catalog_system(&raw, &self.env.glass_dirs, None)
1070 .map_err(|e| format!("{vendor} {part}: {e}"))?;
1071 self.add_glasses(&s.glasses);
1072 let el = pick_lens(&s, 1).map_err(|e| format!("{vendor} {part}: {e}"))?;
1074 if let Some(c) = self.cache {
1075 let v = std::sync::Arc::new((el.clone(), s.glasses.clone()));
1076 c.lenses.lock_ok().insert(key, v);
1077 }
1078 Ok(el)
1079 }
1080 LensSource::Surfaces { surfaces } => {
1081 if surfaces.len() < 2 {
1082 return Err("a lens needs 2 or more surfaces".into());
1083 }
1084 let n = surfaces.len();
1085 let mut v = Vec::new();
1086 for (i, q) in surfaces.iter().enumerate() {
1087 let mut s = surf(q)?;
1088 if s.is_mirror() && (i == 0 || i + 1 == n) {
1090 return Err(format!(
1091 "lens surface {}: the first and last surfaces of a lens can't be mirrors",
1092 i + 1
1093 )
1094 .into());
1095 }
1096 if i + 1 == n {
1097 s.t = 0.0;
1098 s.mat = Material::Air;
1099 } else if is_air(&s.mat) {
1100 return Err(format!("lens surface {}: not glass after it", i + 1).into());
1101 }
1102 v.push(s);
1103 }
1104 Ok(Element {
1105 kind: Kind::Lens,
1106 from: 0,
1107 surfaces: v,
1108 n: Vec::new(),
1109 t: 0.0,
1110 reversed: false,
1111 })
1112 }
1113 }
1114 }
1115
1116 pub(crate) fn block(
1117 &mut self,
1118 b: &Block,
1119 siblings: &[Block],
1120 idx: usize,
1121 ) -> lensbench_core::Result<()> {
1122 let start = self.sf.len();
1123 self.in_node(b, |c| c.block_inner(b, siblings, idx))?;
1124 if !matches!(b, Block::Mirror { .. } | Block::Splitter { .. }) {
1126 self.note(block_id(b), b.faces(), start);
1127 }
1128 if self.turn.pending {
1129 self.finish_turn(siblings, idx)?;
1130 }
1131 Ok(())
1132 }
1133
1134 pub(crate) fn block_inner(
1135 &mut self,
1136 b: &Block,
1137 siblings: &[Block],
1138 idx: usize,
1139 ) -> lensbench_core::Result<()> {
1140 match b {
1141 Block::Air { id, t, medium } => {
1142 if let Some(m) = medium {
1143 self.fill_gap(m)?;
1144 }
1145 self.note_gap(id);
1146 self.gap(*t)
1147 }
1148 Block::Stop { semi, .. } => {
1149 let s = Surface {
1150 stop: true,
1151 semi: *semi,
1152 comment: "STOP".into(),
1153 ..Default::default()
1154 };
1155 self.push(s);
1156 }
1157 Block::Lens {
1158 source,
1159 reversed,
1160 stop,
1161 place,
1162 ..
1163 } => {
1164 let mut e = self.lens_element(source)?;
1165 if *reversed {
1166 e = elements::reverse(&e)?;
1167 }
1168 e.surfaces.iter_mut().for_each(|s| s.stop = false);
1169 if *stop {
1170 e.surfaces[0].stop = true;
1171 }
1172 if let Some(k) = self.turn_here(b) {
1173 if !place.on {
1174 return Err("turn: the block is OFF".into());
1175 }
1176 return self.turn_lens(&e, place, k);
1177 }
1178 let rev = *reversed;
1179 self.placed(place, &mut |c: &mut Self| {
1180 let start = c.sf.len();
1181 for s in &e.surfaces {
1182 if s.is_mirror() {
1183 c.push_mirror(s.clone());
1184 } else {
1185 c.push(s.clone());
1186 }
1187 }
1188 if rev && c.sf.len() > start {
1189 c.nflip += 1;
1190 let k = c.nflip;
1191 for o in &mut c.map[start..] {
1192 o.flip = Some(k);
1193 }
1194 }
1195 Ok(())
1196 })?;
1197 }
1198 Block::Surfaces {
1199 surfaces, place, ..
1200 } => {
1201 let v: Vec<Surface> = surfaces.iter().map(surf).collect::<Result<_, _>>()?;
1202 if v.iter().any(Surface::is_mirror) {
1203 return Err("a surface list can't have a mirror (use a mirror block)".into());
1204 }
1205 let v = self.crystal_plates(v)?;
1206 check_crystal_order(&v)?;
1207 let m = self.medium();
1208 self.media.insert(b as *const Block as usize, m);
1209 self.placed(place, &mut |c: &mut Self| {
1210 for s in &v {
1211 c.push(s.clone());
1212 }
1213 Ok(())
1214 })?;
1215 }
1216 Block::Mirror {
1217 id,
1218 radius,
1219 conic,
1220 tilt,
1221 semi,
1222 aperture,
1223 coat,
1224 on,
1225 back,
1226 row,
1227 faces,
1228 } => {
1229 if !on {
1230 return Ok(());
1231 }
1232 let start = self.sf.len();
1233 let back = *back;
1234 let fold = tilt[0] != 0.0 || tilt[1] != 0.0;
1235 let m = match row {
1236 Some(r) => {
1237 if radius.is_some_and(|x| x != 0.0)
1238 || *conic != 0.0
1239 || *semi != 0.0
1240 || aperture.is_some()
1241 || !coat.is_empty()
1242 {
1243 return Err("a mirror written as row can't have radius, conic, semi, aperture or coat (write them in the row)".into());
1244 }
1245 let m = mirror_row(r)?;
1246 if fold && (m.before.is_some() || m.after != After::None) {
1247 return Err("a mirror can't have both tilt of the block and tilts or decenters in the row".into());
1248 }
1249 m
1250 }
1251 None => Surface {
1252 mat: Material::Mirror,
1253 c: curv(*radius),
1254 k: *conic,
1255 semi: *semi,
1256 coat: coat.clone(),
1257 ap: surf_ap(*aperture, *semi),
1258 ..Default::default()
1259 },
1260 };
1261 if fold {
1262 self.put(cb([0.0, 0.0, tilt[0], tilt[1], 0.0], 0, 0.0));
1263 self.mark_placed();
1264 }
1265 let mut m = m;
1266 if self.parity < 0.0 {
1267 if row.is_some() {
1268 self.flip(&mut m);
1269 } else {
1270 m.c = -m.c;
1271 }
1272 }
1273 self.put(m);
1274 self.parity = -self.parity;
1275 if fold && back {
1276 self.put(cb([0.0, 0.0, -tilt[0], -tilt[1], 0.0], 1, 0.0));
1279 self.mark_placed();
1280 } else if fold {
1281 self.put(cb([0.0, 0.0, tilt[0], tilt[1], 0.0], 1, 0.0));
1285 self.mark_placed();
1286 }
1287 self.note(id, Some(faces), start);
1288 if back {
1289 self.go_back(siblings, idx)?;
1291 self.split.stopped = false;
1292 if self.split.done && idx + 1 < siblings.len() {
1293 return Err(
1294 "both blocks after a mirror and BS branches (a return path going into a BS branch)".into(),
1295 );
1296 }
1297 }
1298 }
1299 Block::Zmx {
1300 path,
1301 from,
1302 to,
1303 config,
1304 stop,
1305 groups,
1306 place,
1307 state,
1308 beam_path,
1309 ..
1310 } => {
1311 let s = self.load_zmx(path, *config, (state.as_deref(), beam_path.as_deref()))?;
1312 self.zenv.push((
1313 path.clone(),
1314 s.temperature,
1315 s.pressure,
1316 s.adjust_index,
1317 s.coating_file.clone(),
1318 ));
1319 let els = elements::split_any(&s);
1321 for n in &s.import_notes {
1324 if !self.notes.contains(n) {
1325 self.notes.push(n.clone());
1326 }
1327 }
1328 let inst = self.zpicks.len();
1329 self.zpicks.push(ZmxLinks {
1330 path: path.clone(),
1331 sign: 1.0,
1332 pickups: s.pickups.clone(),
1333 solves: s.solves.clone(),
1334 image: s.image(),
1335 obj_comment: s.surfaces[0].comment.clone(),
1336 obj_mat: s.surfaces[0].mat.clone(),
1337 macro_notes: s.macro_notes.clone(),
1338 macros: s.macros.clone(),
1339 macro_parms: s.macro_parms.clone(),
1340 });
1341 let (a, z) = (from.unwrap_or(1), to.unwrap_or(s.image() - 1));
1342 let mut keep = Vec::new();
1344 let mut last_in = false;
1345 for e in els {
1346 if e.kind == Kind::Air {
1347 if last_in {
1348 keep.push(e);
1349 }
1350 } else {
1351 last_in = e.from >= a && e.from <= z;
1352 if last_in {
1353 keep.push(e);
1354 }
1355 }
1356 }
1357 if !*stop {
1358 for e in &mut keep {
1359 e.surfaces.iter_mut().for_each(|s| s.stop = false);
1360 }
1361 }
1362 let spans = zmx_group_spans(&keep, groups).map_err(|e| format!("{path}: {e}"))?;
1363 self.placed(place, &mut |c: &mut Self| {
1364 let sign = c.parity;
1365 c.zpicks[inst].sign = sign;
1366 let mut i = 0;
1367 while i < keep.len() {
1368 let Some(&(g, a, z)) = spans.iter().find(|q| q.1 == i) else {
1369 c.element_from(&keep[i], sign, Some(inst));
1370 i += 1;
1371 continue;
1372 };
1373 let gr = &groups[g];
1374 c.element(&Element::air(gr.shift), sign);
1375 let start = c.sf.len();
1376 c.placed(&gr.place, &mut |c: &mut Self| {
1377 for e in &keep[a..=z] {
1378 c.element_from(e, sign, Some(inst));
1379 }
1380 Ok(())
1381 })?;
1382 c.note(&gr.id, Some(&gr.faces), start);
1383 if gr.shift != 0.0 && c.has_mirror_since(start) {
1384 return Err(
1385 "a group with a mirror can't be moved (set shift to 0)".into()
1386 );
1387 }
1388 c.element(&Element::air(-gr.shift), sign);
1389 i = z + 1;
1390 }
1391 Ok(())
1392 })?;
1393 }
1394 Block::User { id, item, .. } => {
1395 let (g, dir, key, frame) = self.user_group_frame(b)?;
1396 let base = std::mem::replace(&mut self.base, dir);
1397 self.loading.push(key);
1398 let start = self.sf.len();
1399 let r = self.block(&g, &[], 0);
1400 self.loading.pop();
1401 self.base = base;
1402 r?;
1403 if let Some((f, rev)) =
1405 frame.filter(|_| self.loading.len() == self.outer && self.sf.len() > start)
1406 {
1407 let name = if id.is_empty() {
1408 item.clone()
1409 } else {
1410 id.clone()
1411 };
1412 let f = if rev {
1414 let t: f64 = self.sf[start..self.sf.len() - 1]
1415 .iter()
1416 .filter(|q| !q.is_coord_break())
1417 .map(|q| q.t)
1418 .sum();
1419 f.flipped(t)
1420 } else {
1421 f
1422 };
1423 let k = self.frames.len();
1424 self.frames.push((name, f));
1425 for o in &mut self.map[start..] {
1426 o.frame = Some(k);
1427 }
1428 }
1429 }
1430 Block::Splitter { id, spec, place } => {
1431 self.splitter_forward(id, spec, place, siblings, idx)?;
1432 }
1433 Block::Detector(_) => {
1434 return Err(
1435 "a detector must be the last block (not inside a group or user catalog)".into(),
1436 )
1437 }
1438 Block::Group {
1439 blocks,
1440 place,
1441 shift,
1442 ..
1443 } => {
1444 let bl = blocks;
1445 self.gap(*shift);
1446 let start = self.sf.len();
1447 self.split.levels.push(Level::Other);
1448 let r = self.placed(place, &mut |c: &mut Self| {
1449 for (i, x) in bl.iter().enumerate() {
1450 if c.split.done {
1451 break;
1452 }
1453 c.block(x, bl, i)?;
1454 }
1455 Ok(())
1456 });
1457 self.split.levels.pop();
1458 r?;
1459 if *shift != 0.0 && self.has_mirror_since(start) {
1460 return Err("a group with a mirror can't be moved (set shift to 0)".into());
1461 }
1462 self.gap(-shift);
1463 }
1464 }
1465 Ok(())
1466 }
1467}
1468
1469pub(crate) fn block_id(b: &Block) -> &str {
1471 match b {
1472 Block::Lens { id, .. }
1473 | Block::Air { id, .. }
1474 | Block::Stop { id, .. }
1475 | Block::Mirror { id, .. }
1476 | Block::Surfaces { id, .. }
1477 | Block::Zmx { id, .. }
1478 | Block::User { id, .. }
1479 | Block::Detector(DetectorBlock { id, .. })
1480 | Block::Splitter { id, .. }
1481 | Block::Group { id, .. } => id,
1482 }
1483}
1484
1485fn mirror_row(r: &crate::sysfile_v2::Row) -> lensbench_core::Result<Surface> {
1488 if r.stop || r.object || r.image || r.t != 0.0 || r.medium.is_some() {
1489 return Err("row of a mirror can't have stop, object, image, thickness or medium".into());
1490 }
1491 let m = crate::sysfile_v2::read::surface(r.clone())?;
1492 if !m.is_mirror() || m.reflect.is_some() {
1493 return Err("row of a mirror needs a reflecting action".into());
1494 }
1495 if m.typ() == SurfType::CoordBrk {
1496 return Err("row of a mirror can't be a coordinate break (use tilt of the block)".into());
1497 }
1498 Ok(m)
1499}