1use std::path::PathBuf;
4
5use lensbench_core::catalog::LensCatalog;
6use lensbench_core::coating::{self, Coatings};
7use lensbench_core::System;
8use lensbench_export::table;
9use lensbench_formats::zmx;
10use lensbench_project::open::{FileKind, OpenSpec, Source};
11use serde_json::{json, Value};
12
13#[derive(Clone, Debug, Default)]
15pub struct SysSpec {
16 pub file: PathBuf,
18 pub glass_dir: Vec<PathBuf>,
20 pub lens_catalog: Vec<PathBuf>,
22 pub cfg: usize,
24 pub state: Option<String>,
26 pub path: Option<String>,
28 pub names: lensbench_project::open::ArgNames,
30 pub strict_macros: bool,
33}
34
35impl SysSpec {
36 pub fn open_spec(&self) -> OpenSpec<'_> {
38 OpenSpec {
39 glass_dirs: &self.glass_dir,
40 lens_catalogs: &self.lens_catalog,
41 cfg: self.cfg,
42 state: self.state.as_deref(),
43 split_path: self.path.as_deref(),
44 wavelengths: None,
45 names: self.names,
46 step_files: Some(&lensbench_cad::cached_step),
48 }
49 }
50}
51
52pub fn load_file(c: &SysSpec) -> Result<System, lensbench_core::Error> {
55 Ok(load_file_notes(c)?.0)
56}
57
58pub fn load_file_notes(c: &SysSpec) -> Result<(System, Vec<String>), lensbench_core::Error> {
60 let r = read_file_notes(c)?;
61 Ok((r.sys, r.notes))
62}
63
64pub struct ReadFile {
66 pub src: Source,
68 pub sys: System,
69 pub notes: Vec<String>,
71 pub blocks: Vec<lensbench_project::BlockSpans>,
73 pub faces: Faces,
75}
76
77pub type Faces = Vec<Option<lensbench_project::FaceId>>;
79
80pub fn read_file_notes(c: &SysSpec) -> Result<ReadFile, lensbench_core::Error> {
82 if c.cfg == 0 {
83 return Err(lensbench_core::Error::Invalid(format!(
84 "{} must be 1 or more",
85 c.names.cfg
86 )));
87 }
88 let src = Source::read(&c.file)?;
89 let o = open_source(&src, c)?;
90 Ok(ReadFile {
91 src,
92 sys: o.system,
93 notes: o.warnings,
94 blocks: o.blocks,
95 faces: o.faces,
96 })
97}
98
99pub fn load_source(src: &Source, c: &SysSpec) -> Result<System, lensbench_core::Error> {
101 if c.cfg == 0 {
102 return Err(lensbench_core::Error::Invalid(format!(
103 "{} must be 1 or more",
104 c.names.cfg
105 )));
106 }
107 Ok(load_source_notes(src, c)?.0)
108}
109
110pub(crate) fn load_source_faces(
112 src: &Source,
113 c: &SysSpec,
114) -> Result<(System, Vec<String>, Faces), lensbench_core::Error> {
115 let o = open_source(src, c)?;
116 Ok((o.system, o.warnings, o.faces))
117}
118
119pub fn load_source_spans(
122 src: &Source,
123 c: &SysSpec,
124) -> Result<(System, Vec<String>, Vec<lensbench_project::BlockSpans>), lensbench_core::Error> {
125 let o = open_source(src, c)?;
126 Ok((o.system, o.warnings, o.blocks))
127}
128
129pub fn load_source_notes(
132 src: &Source,
133 c: &SysSpec,
134) -> Result<(System, Vec<String>), lensbench_core::Error> {
135 let o = open_source(src, c)?;
136 Ok((o.system, o.warnings))
137}
138
139fn open_source(
141 src: &Source,
142 c: &SysSpec,
143) -> Result<lensbench_project::open::Opened, lensbench_core::Error> {
144 let o = src.open(&c.open_spec())?;
145 if c.strict_macros {
146 let w = o.system.macro_warnings();
148 if let Some(e) = w.first() {
149 let n = w.len();
150 return Err(lensbench_core::Error::Invalid(if n == 1 {
151 format!("a macro solve can't be solved (strict macros): {e}")
152 } else {
153 format!("{n} macro solves can't be solved (strict macros); the first: {e}")
154 }));
155 }
156 }
157 let mut o = o;
158 let n = system_notes(&o.system);
159 o.warnings.extend(n);
160 Ok(o)
161}
162
163pub fn system_notes(s: &System) -> Vec<String> {
165 s.dispersion_warnings()
166 .into_iter()
167 .chain(s.macro_warnings())
168 .chain(s.import_notes.iter().cloned())
169 .collect()
170}
171
172pub fn load_file_noted(c: &SysSpec) -> Result<System, lensbench_core::Error> {
175 let (s, notes) = load_file_notes(c)?;
176 for w in notes {
177 eprintln!("{}", lensbench_core::i18n::warning(&w));
178 }
179 crate::provenance::set(&s);
180 Ok(s)
181}
182
183pub fn split_paths(c: &SysSpec) -> Result<Vec<String>, lensbench_core::Error> {
185 if FileKind::of(&c.file) != FileKind::Project {
186 return Ok(Vec::new());
187 }
188 Source::read(&c.file)?.paths(&c.open_spec())
189}
190
191pub fn state_names(c: &SysSpec) -> Vec<String> {
193 if FileKind::of(&c.file) != FileKind::Project {
194 return Vec::new();
195 }
196 Source::read(&c.file)
197 .map(|s| s.states())
198 .unwrap_or_default()
199}
200
201pub fn tolerance_vendors(
204 c: &SysSpec,
205) -> (
206 std::collections::HashMap<String, String>,
207 std::collections::HashSet<String>,
208) {
209 if FileKind::of(&c.file) != FileKind::Project {
210 return Default::default();
211 }
212 Source::read(&c.file)
213 .map(|s| tolerance_vendors_in(&s))
214 .unwrap_or_default()
215}
216
217pub fn tolerance_vendors_in(
219 src: &Source,
220) -> (
221 std::collections::HashMap<String, String>,
222 std::collections::HashSet<String>,
223) {
224 src.project()
225 .map(|p| {
226 (
227 lensbench_design::tolerance::catalog_vendors(p),
228 lensbench_design::tolerance::reversed_lenses(p),
229 )
230 })
231 .unwrap_or_default()
232}
233
234#[derive(Clone, Default, Debug)]
236pub struct Overlay {
237 pub cfgs: Option<String>,
239 pub states: Option<String>,
241 pub paths: Option<String>,
243 pub beams: Option<String>,
245}
246
247impl Overlay {
248 pub fn any(&self) -> bool {
250 self.cfgs.is_some() || self.states.is_some() || self.paths.is_some() || self.beams.is_some()
251 }
252}
253
254pub fn overlay_systems(c: &SysSpec, l: &Overlay) -> lensbench_core::Result<Overlaid> {
256 if !l.any() {
257 let (s, notes) = load_file_notes(c)?;
258 crate::provenance::set(&s);
259 return Ok((vec![(String::new(), s)], notes));
260 }
261 let (v, notes) = overlay_in(c, l, None)?;
262 Ok((v.into_iter().map(|o| (o.name, o.sys)).collect(), notes))
263}
264
265pub(crate) type OverlaidIn = (Vec<OverlaidSys>, Vec<String>);
267
268pub(crate) struct OverlaidSys {
270 pub name: String,
271 pub sys: System,
272 pub edited: bool,
274 pub faces: Faces,
276 pub spans: Vec<lensbench_project::BlockSpans>,
278}
279
280impl OverlaidSys {
281 fn new(name: String, sys: System, edited: bool) -> Self {
282 OverlaidSys {
283 name,
284 sys,
285 edited,
286 faces: Vec::new(),
287 spans: Vec::new(),
288 }
289 }
290}
291
292pub type OverlaidSpans = (
294 Vec<(System, Vec<lensbench_project::BlockSpans>)>,
295 Vec<String>,
296);
297
298pub fn overlay_systems_spans(c: &SysSpec, l: &Overlay) -> lensbench_core::Result<OverlaidSpans> {
300 if !l.any() {
301 let (s, notes, spans) = load_source_spans(&Source::read(&c.file)?, c)?;
302 crate::provenance::set(&s);
303 return Ok((vec![(s, spans)], notes));
304 }
305 let (v, notes) = overlay_in(c, l, None)?;
306 Ok((v.into_iter().map(|o| (o.sys, o.spans)).collect(), notes))
307}
308
309pub(crate) type Loaded<'a> = (&'a Source, &'a System);
311
312pub(crate) fn overlay_in(
316 c: &SysSpec,
317 l: &Overlay,
318 loaded: Option<Loaded>,
319) -> lensbench_core::Result<OverlaidIn> {
320 let kind = FileKind::of(&c.file);
321 let is_json = kind != FileKind::Zmx;
322 if kind == FileKind::SystemFile {
323 return Err("a system file can't draw overlaid configurations (--cfgs, --states and --beam-paths are only for .zmx and projects)".into());
324 }
325 if let Some(v) = &l.cfgs {
326 if is_json {
327 return Err("--cfgs is only for .zmx (projects use --states and --beam-paths)".into());
328 }
329 if let Some(t) = loaded.and_then(|(_, cur)| cur.configs.as_ref().map(|t| (cur, t.n))) {
331 let (cur, n) = t;
332 let mut out = Vec::new();
333 for k in index_list(v, n, "configuration")? {
334 out.push(OverlaidSys::new(
335 format!("C{}", k + 1),
336 cur.config(k + 1)?,
337 true,
338 ));
339 }
340 return Ok((out, Vec::new()));
341 }
342 let opt = zmx::LoadOptions {
343 catalog_dirs: c.glass_dir.clone(),
344 ..Default::default()
345 };
346 let read;
348 let src = match loaded {
349 Some((s, _)) => s,
350 None => {
351 read = Source::read(&c.file)?;
352 &read
353 }
354 };
355 let n = src.configurations()?;
356 let ks: Vec<usize> = index_list(v, n, "configuration")?
357 .into_iter()
358 .map(|k| k + 1)
359 .collect();
360 let ss = src.zmx_configs(&opt, &ks)?;
361 return Ok((
362 ks.iter()
363 .map(|k| format!("C{k}"))
364 .zip(ss)
365 .map(|(n, s)| OverlaidSys::new(n, s, false))
366 .collect(),
367 Vec::new(),
368 ));
369 }
370 if !is_json {
371 return Err(
372 "--states and --beam-paths are only for project files (.json); .zmx uses --cfgs".into(),
373 );
374 }
375 let read;
376 let src = match loaded {
377 Some((s, _)) => s,
378 None => {
379 read = Source::read(&c.file)?;
380 &read
381 }
382 };
383 let Some(p) = src.project() else {
384 return Err("--states and --beam-paths are only for project files (.json)".into());
385 };
386 if l.beams.is_some() && (l.states.is_some() || l.paths.is_some()) {
387 return Err("--beams can't be combined with --states or --beam-paths".into());
388 }
389 let by_state = l.states.is_some() || l.beams.is_some();
390 let states: Vec<Option<String>> = match (&l.states, &l.beams) {
391 (_, Some(v)) if v.eq_ignore_ascii_case("all") => {
392 let n: Vec<Option<String>> = p
393 .beams
394 .iter()
395 .filter(|b| !b.off)
396 .map(|b| Some(b.name.clone()))
397 .collect();
398 if n.is_empty() {
399 return Err("the project has no beams (or every beam is off)".into());
400 }
401 n
402 }
403 (_, Some(v)) => v
404 .split(',')
405 .map(|x| {
406 let x = x.trim();
407 match p.beam(x) {
408 Some(_) => Ok(Some(x.to_string())),
409 None => Err(format!("no beam {x} ({})", p.beam_names().join(", "))),
410 }
411 })
412 .collect::<Result<_, _>>()?,
413 (None, None) => vec![c.state.clone()],
414 (Some(v), None) if v.eq_ignore_ascii_case("all") => {
415 let n: Vec<Option<String>> = p
416 .state_names()
417 .into_iter()
418 .map(|x| Some(x.to_string()))
419 .collect();
420 if n.is_empty() {
421 return Err("the project has no states".into());
422 }
423 n
424 }
425 (Some(v), None) => v.split(',').map(|x| Some(x.trim().to_string())).collect(),
426 };
427 let cat = LensCatalog::load_registered(&c.lens_catalog)?;
428 let look = |v: &str, q: &str| cat.zmx(v, q);
429 let env = lensbench_project::Env {
430 step_files: Some(&lensbench_cad::cached_step),
432 base: c.file.parent().map(|x| x.to_path_buf()).unwrap_or_default(),
433 glass_dirs: c.glass_dir.clone(),
434 catalog: Some(&look),
435 };
436 let mut out = Vec::new();
437 let mut notes = Vec::new();
438 let cache = match src {
440 Source::Project { cache, .. } => cache.clone(),
441 _ => Default::default(),
442 };
443 for st in &states {
444 let ps = match &st {
445 Some(n) => p.with_state(n)?,
446 None => p.clone(),
447 };
448 let own = st
450 .as_deref()
451 .is_some_and(|n| p.beam(n).is_some_and(|b| b.path.is_some()));
452 if let Some(n) = st.as_deref() {
453 p.beam_takes_path(n, l.paths.is_some())?;
454 }
455 let paths: Vec<Option<String>> = match &l.paths {
456 None if own => vec![None],
457 None => vec![c.path.clone()],
458 Some(v) if v.eq_ignore_ascii_case("all") => {
459 let v = lensbench_project::paths_cached(&ps, &env, &cache)?;
460 if v.is_empty() {
461 return Err("the project has no beam splitters".into());
462 }
463 v.into_iter().map(Some).collect()
464 }
465 Some(v) => v.split(',').map(|x| Some(x.trim().to_string())).collect(),
466 };
467 for pa in &paths {
468 let mut name: Vec<&str> = Vec::new();
469 if by_state {
470 name.extend(st.as_deref());
471 }
472 if l.paths.is_some() {
473 name.extend(pa.as_deref());
474 }
475 if let Some((_, cur)) = loaded.filter(|_| *st == c.state && *pa == c.path) {
477 out.push(OverlaidSys::new(name.join("/"), cur.clone(), true));
478 continue;
479 }
480 let (s, warn, map) = lensbench_project::expand(
481 &ps,
482 &env,
483 &lensbench_project::ExpandOpts {
484 path: pa.as_deref(),
485 cache: Some(&cache),
486 ..Default::default()
487 },
488 )
489 .map(|x| (x.system, x.notes, x.map))
490 .map_err(|x| match pa {
491 Some(q) => format!("path {q}: {x}"),
492 None => x.to_string(),
493 })?;
494 for w in warn.into_iter().map(String::from) {
496 if !notes.contains(&w) {
497 notes.push(w);
498 }
499 }
500 out.push(OverlaidSys {
501 name: name.join("/"),
502 sys: s,
503 edited: false,
504 spans: lensbench_project::block_spans(&map),
505 faces: map.into_iter().map(|o| o.face).collect(),
506 });
507 }
508 }
509 Ok((out, notes))
510}
511
512pub type Overlaid = (Vec<(String, System)>, Vec<String>);
514
515pub fn index_list(s: &str, n: usize, what: &str) -> lensbench_core::Result<Vec<usize>> {
517 if s.eq_ignore_ascii_case("all") {
518 return Ok((0..n).collect());
519 }
520 s.split(',')
521 .map(|t| {
522 let k: usize = t
523 .trim()
524 .parse()
525 .map_err(|_| lensbench_core::Error::from(format!("{what} number {t}")))?;
526 if k == 0 || k > n {
527 return Err(format!("no {what} {k} (1 to {n})").into());
528 }
529 Ok(k - 1)
530 })
531 .collect()
532}
533
534pub fn save_value(p: &std::path::Path, v: &Value) -> lensbench_core::Result<()> {
536 let json = p
537 .extension()
538 .is_some_and(|x| x.eq_ignore_ascii_case("json"));
539 if json {
540 let mut v = v.clone();
541 if let Some(o) = v.as_object_mut() {
542 o.insert("provenance".into(), crate::provenance::value());
543 }
544 let s = serde_json::to_string_pretty(&v).expect("a JSON value serializes");
545 Ok(lensbench_core::vfs::write(p, s + "\n").map_err(|x| format!("{}: {x}", p.display()))?)
546 } else {
547 Ok(table::from_json(v).save(p)?)
548 }
549}
550
551pub fn builtin_plugins() -> lensbench_core::plugin::Registry {
554 lensbench_design::plugins::builtin()
555}
556
557pub fn plugins_json() -> Value {
558 let reg = builtin_plugins();
559 let pairs = |v: &[(String, String)]| -> Value {
560 v.iter()
561 .map(|(k, d)| json!({ "name": k, "doc": d }))
562 .collect()
563 };
564 let list: Vec<Value> = reg
565 .list()
566 .into_iter()
567 .filter_map(|(name, kind)| {
568 let pl = reg.get(&name).ok()?;
569 let s = pl.spec();
570 let params: Vec<Value> = pl.params().iter().map(crate::params::param_json).collect();
571 Some(json!({
572 "name": name, "kind": kind.as_str(), "doc": s.doc, "needs_system": s.needs_system,
573 "params": params, "inputs": pairs(&s.inputs), "outputs": s.outputs.iter().map(|o| json!({
574 "name": o.name, "dtype": o.dtype, "shape": o.shape, "unit": o.unit, "doc": o.doc,
575 })).collect::<Vec<_>>(),
576 }))
577 })
578 .collect();
579 json!({ "plugins": list })
580}
581
582pub type AutoCoat = (String, String, String);
584
585pub struct CoatInterfaces {
587 pub list: Vec<Value>,
589 pub needs: Vec<String>,
591 pub auto: Vec<AutoCoat>,
593 pub registered: Vec<(String, String)>,
595 pub notes: Vec<String>,
597}
598
599pub fn coat_interfaces(s: &System, tables: &[PathBuf]) -> lensbench_core::Result<CoatInterfaces> {
601 let e = |e: lensbench_core::Error| e.to_string();
602 let mut c = Coatings::for_system(s).map_err(e)?;
603 for t in tables {
604 c.load_file(t).map_err(e)?;
605 }
606 let mut auto = Vec::new();
607 for (coat, p) in &c.auto {
608 let p = p.display().to_string();
609 let note = match c.models.get(coat) {
611 Some(m) => m.note.clone(),
612 None if p.to_ascii_lowercase().ends_with(".lbcs") => {
613 "approximate coating (a multilayer fitted to the spectral curve)".to_string()
614 }
615 None => String::new(),
616 };
617 auto.push((coat.clone(), p, note));
618 }
619 let (keys, _) = coating::media_keys(s);
620 let mut v = Vec::new();
621 let mut need = Vec::new();
622 for (j, k) in keys.iter().enumerate() {
623 let Some(k) = k else { continue };
624 let kind = c.kind(k);
625 let mut it = json!({ "surface": j, "key": k, "kind": kind.name() });
626 if kind == coating::CoatKind::Model {
627 let coat = k.split('|').next().unwrap_or("");
628 if let Some(m) = c.models.get(coat).filter(|m| !m.note.is_empty()) {
629 it["note"] = json!(m.note);
630 }
631 }
632 if kind == coating::CoatKind::User {
633 let coat = k.split('|').next().unwrap_or("");
634 if let Some(d) = c.user.get(coat).map(|m| m.doc()).filter(|d| !d.is_empty()) {
635 it["note"] = json!(d);
636 }
637 }
638 v.push(it);
639 if kind.needs_table() && !need.contains(k) {
640 need.push(k.clone());
641 }
642 }
643 Ok(CoatInterfaces {
644 list: v,
645 needs: need,
646 auto,
647 registered: c.registered.clone(),
648 notes: c.notes.clone(),
649 })
650}
651
652#[cfg(test)]
653mod strict_tests {
654 use super::*;
655
656 #[test]
658 fn strict_macros_turns_the_macro_warning_into_an_error() {
659 let d = std::env::temp_dir().join(format!("lb_strict_macros_{}", std::process::id()));
660 std::fs::create_dir_all(&d).unwrap();
661 std::fs::write(
662 d.join("LBMID.ZPL"),
663 "SOLVERETURN -0.03\nx = nosuchvar\nSOLVERETURN 1\n",
664 )
665 .unwrap();
666 let zmx = "VERS 260327 42\nMODE SEQ\nUNIT MM X W X CM MR CPMM\nENPD 10\nFTYP 0 0 3 1 0 0 0\n\
667XFLN 0 0 0\nYFLN 0 14 20\nFWGN 1 1 1\nWAVM 1 0.5876 1\nPWAV 1\n\
668SURF 0\n TYPE STANDARD\n CURV 0.0\n DISZ INFINITY\n\
669SURF 1\n STOP\n TYPE STANDARD\n CURV 0.02\n DISZ 5\n GLAS ___BLANK 1 0 1.5168 64.17 0 0 0 0 0\n DIAM 6 1 0 0 1 \"\"\n\
670SURF 2\n TYPE STANDARD\n CURV -1.23e-2 12 0 0 0 \"LBMID\"\n DISZ 45\n DIAM 6 1 0 0 1 \"\"\n\
671SURF 3\n TYPE STANDARD\n CURV 0.0\n DISZ 0\n";
672 let f = d.join("s.zmx");
673 std::fs::write(&f, zmx).unwrap();
674 let mut c = SysSpec {
675 file: f,
676 cfg: 1,
677 ..Default::default()
678 };
679 let (s, notes) = load_file_notes(&c).unwrap();
680 assert_eq!(s.surfaces[2].c, -0.03);
681 assert!(notes.iter().any(|n| n.contains("LBMID")), "{notes:?}");
682 c.strict_macros = true;
683 let e = load_file_notes(&c).unwrap_err().to_string();
684 assert!(e.contains("strict macros") && e.contains("LBMID"), "{e}");
685 lensbench_lang::register();
687 let ja = lensbench_core::i18n::translate(&e);
688 assert!(
689 ja.contains("厳密な読込") && ja.contains("面 2 の") && !ja.contains("macro solve"),
690 "{ja}"
691 );
692 let _ = std::fs::remove_dir_all(&d);
693 }
694}