1use lensbench_core::error::{Error, Result};
7use lensbench_core::glass::{self, Glass};
8use lensbench_core::import::{MacroRequest, MacroTarget};
9use lensbench_core::param::Kind;
10use lensbench_core::pickup::{surf_parm, Pickup};
11use lensbench_core::solves::{Solve, SolveKind};
12use lensbench_core::surface::{After, Aperture, Form, SurfType, Surface, Tilt};
13use lensbench_core::system::{
14 Aiming, ApertureKind, Field, FieldNorm, FieldType, Prescription, System,
15};
16use lensbench_core::{invalid, notimpl};
17use std::collections::{BTreeMap, HashMap, HashSet};
18use std::path::{Path, PathBuf};
19
20const HARMLESS: &[&str] = &[
21 "HIDE", "MIRR", "SLAB", "POPS", "SSID", "FIMP", "VPAR", "VDSZ", "VCRV", "VCON", "BLNK",
22 "NAME", "EDGE", "SCOL",
25];
26const MCE_HANDLED: &[&str] = &[
27 "PSHX", "PSHY", "PSHZ", "PSCX", "PSCY", "THIC", "IGNR", "APMX", "SDIA", "MCSD", "CHZN", "STPS",
28 "SATP", "APER", "TELE", "CRVT", "CONN", "WAVE", "GLSS", "XFIE", "YFIE", "MOFF", "LTTL", "PRAM",
29 "WLWT", "PRWV", "FLWT", "FLTP", "TEMP", "PRES", "AFOC", "APDT", "APDF", "RAAM", "OPDR", "APMN",
30 "APDX", "APDY", "APTP", "CBDX", "CBDY", "CBTX", "CBTY", "CBTZ", "CBOR", "CADX", "CADY", "CATX",
31 "CATY", "CATZ", "CAOR", "MIND", "MABB", "MDPG", "TCEX", "FVDX", "FVDY", "FVCX", "FVCY", "FVAN",
32 "FTAN", "COTN", "CROR", "CRSR", "GPIU", "GPJX", "GPJY", "GPPX", "GPPY", "CSP1", "CSP2", "TSP1",
33 "TSP2", "TSP3", "PSP1", "PSP2", "PSP3",
34 "PUCN",
36 "MCOM", "CWGT",
38];
39
40#[derive(Debug, Clone, Default)]
41pub struct RawSurf {
42 pub n: i64,
43 pub typ: Option<String>,
44 pub coat: Option<String>,
45 pub glas: Option<String>,
46 pub model_glass: Option<(f64, f64, f64)>,
48 pub glas_pickup: Option<usize>,
50 pub curv: Option<f64>,
51 pub curv_pickup: Option<(usize, f64, Option<Kind>)>,
53 pub coni: Option<f64>,
54 pub disz: Option<f64>,
55 pub tced: Option<f64>,
57 pub diam: Option<f64>,
58 pub diam_mode: Option<u8>,
60 pub diam_fixed: bool,
62 pub mema: Option<f64>,
64 pub oema: f64,
66 pub comment: String,
67 pub parm: BTreeMap<i64, f64>,
68 pub ppar: BTreeMap<i64, (usize, f64, f64, Option<Kind>)>,
70 pub pzup: Option<(usize, f64, f64, Option<Kind>)>,
71 pub tsolve: Option<(SolveKind, f64)>,
73 pub csolve: Option<(SolveKind, f64)>,
75 pub cmacro: Option<String>,
77 pub tmacro: Option<String>,
79 pub kmacro: Option<String>,
81 pub smacro: Option<String>,
83 pub mmacro: Option<String>,
85 pub pmacros: Vec<(u8, String)>,
87 pub pkup: Option<(usize, f64, f64, Option<Kind>)>,
89 pub diam_pickup: Option<(usize, f64, Option<Kind>)>,
91 pub mema_pickup: Option<(usize, f64)>,
93 pub xdat: BTreeMap<i64, f64>,
95 pub gdat: Option<Vec<f64>>,
97 pub garr: Vec<(usize, [f64; 5])>,
98 pub fimp: Option<String>,
99 pub clap: Option<Vec<f64>>,
100 pub sqap: Option<Vec<f64>>,
101 pub elap: Option<Vec<f64>>,
102 pub flap: Option<Vec<f64>>,
103 pub obsc: Option<Vec<f64>>,
104 pub spid: Option<Vec<f64>>,
106 pub obdc: Option<Vec<f64>>,
107 pub scbd: Vec<Vec<String>>,
108 pub stop: bool,
109 pub ignore: bool,
110}
111
112#[derive(Debug, Clone, Default)]
113pub struct Raw {
114 pub surfs: Vec<RawSurf>,
115 pub mce: Vec<(String, i64, i64, String, Vec<String>)>,
117 pub mce_rows: Vec<(String, i64, i64)>,
119 pub sysl: HashMap<String, Vec<Vec<String>>>,
120 pub merit: Vec<merit::MeritRow>,
122 pub notes: Vec<String>,
124}
125
126pub(crate) mod configs;
127mod macros;
128pub mod merit;
129mod parse;
130mod pickups;
131mod surfaces;
132mod system_lines;
133mod units;
134mod values;
135
136use configs::config_table;
137pub use parse::parse_text;
138use units::to_mm;
139
140fn fv(v: &str) -> Result<f64> {
141 if v.eq_ignore_ascii_case("INFINITY") {
142 return Ok(f64::INFINITY);
143 }
144 v.parse::<f64>()
145 .map_err(|_| Error::Invalid(format!("not a number: {v}")))
146}
147
148const MAX_CONFIGS: usize = 1000;
150const MAX_FIELDS: usize = 10_000;
151const MAX_WAVES: usize = 1000;
152const MAX_GRID: usize = 16_000_000;
154
155fn count_in(v: f64, what: &str, lo: usize, hi: usize) -> Result<usize> {
158 if !(v.fract() == 0.0 && v >= lo as f64 && v <= hi as f64) {
159 invalid!("{what} {v} (an integer {lo} to {hi})");
160 }
161 Ok(v as usize)
162}
163
164fn sys_str<'a>(raw: &'a Raw, key: &str, i: usize) -> Option<&'a str> {
165 raw.sysl.get(key)?.first()?.get(i).map(|s| s.as_str())
166}
167fn sys_f(raw: &Raw, key: &str, i: usize, default: f64) -> Result<f64> {
170 match sys_str(raw, key, i) {
171 None => Ok(default),
172 Some(v) => fv(v).map_err(|e| e.at(format!("zmx {key} value {}", i + 1))),
173 }
174}
175
176impl Raw {
177 pub fn configurations(&self) -> usize {
179 (sys_f(self, "MNUM", 0, 1.0).unwrap_or(1.0) as usize).clamp(1, MAX_CONFIGS)
181 }
182
183 fn check_counts(&self) -> Result<()> {
185 count_in(
186 sys_f(self, "MNUM", 0, 1.0)?,
187 "number of zmx configurations MNUM",
188 1,
189 MAX_CONFIGS,
190 )?;
191 if let Some(v) = self.sysl.get("FTYP").and_then(|v| v.first()) {
192 if v.is_empty() {
193 invalid!("the zmx FTYP has no value");
194 }
195 for x in v {
196 fv(x).map_err(|e| e.at("zmx FTYP"))?;
197 }
198 if let Some(x) = v.get(2) {
199 count_in(fv(x)?, "zmx field count (FTYP 3)", 1, MAX_FIELDS)?;
200 }
201 if let Some(x) = v.get(3) {
202 count_in(fv(x)?, "zmx wavelength count (FTYP 4)", 1, MAX_WAVES)?;
203 }
204 }
205 Ok(())
206 }
207
208 pub fn catalogs(&self) -> Vec<String> {
210 self.sysl
211 .get("GCAT")
212 .and_then(|v| v.first())
213 .cloned()
214 .unwrap_or_default()
215 }
216
217 pub fn grd_file_name(&self) -> String {
219 self.sysl
220 .get("COFN")
221 .into_iter()
222 .flatten()
223 .flatten()
224 .map(|v| v.trim_matches('"'))
225 .find(|v| v.to_uppercase().ends_with(".GRD"))
226 .unwrap_or("PROFILE.GRD")
227 .to_string()
228 }
229
230 pub fn coating_file_name(&self) -> Option<String> {
232 let rows = self.sysl.get("COFN")?;
233 let pick = |a: &Vec<String>| {
234 let a: Vec<&String> = a.iter().filter(|v| v.as_str() != "QF").collect();
235 a.first().map(|v| v.trim_matches('"').to_string())
236 };
237 rows.iter()
238 .find(|a| a.first().map(|v| v.as_str()) == Some("QF"))
239 .and_then(pick)
240 .or_else(|| rows.first().and_then(pick))
241 }
242}
243
244#[derive(Debug, Clone, Default)]
246pub struct LoadOptions {
247 pub cfg: usize,
248 pub catalog_dirs: Vec<PathBuf>,
249 pub wavelengths: Option<Vec<f64>>,
251 pub glasses: Option<HashMap<String, Glass>>,
253 pub macro_dirs: Vec<PathBuf>,
256 pub fixed_semi: bool,
259}
260
261pub fn load(path: &Path) -> Result<System> {
262 load_with(
263 path,
264 &LoadOptions {
265 cfg: 1,
266 ..Default::default()
267 },
268 )
269}
270
271pub fn load_with(path: &Path, opt: &LoadOptions) -> Result<System> {
272 load_text_with(&read_zmx(path)?, path, opt)
273}
274
275pub fn load_text_with(txt: &str, path: &Path, opt: &LoadOptions) -> Result<System> {
277 build(&parse_text(txt)?, opt, &file_dirs(opt, path), path.parent())
278}
279
280fn read_zmx(path: &Path) -> Result<String> {
281 glass::read_text(path).map_err(|e| Error::Io(format!("{}: {e}", path.display())))
282}
283
284fn file_dirs(opt: &LoadOptions, path: &Path) -> Vec<PathBuf> {
286 let mut dirs = opt.catalog_dirs.clone();
287 dirs.extend(path.parent().map(Path::to_path_buf));
288 glass::catalog_dirs(&dirs)
289}
290
291pub fn load_configs(path: &Path, opt: &LoadOptions, cfgs: &[usize]) -> Result<Vec<System>> {
294 load_configs_text(&read_zmx(path)?, path, opt, cfgs)
295}
296
297pub fn load_configs_text(
299 txt: &str,
300 path: &Path,
301 opt: &LoadOptions,
302 cfgs: &[usize],
303) -> Result<Vec<System>> {
304 let raw = parse_text(txt)?;
305 let dirs = file_dirs(opt, path);
306 let all: Vec<usize>;
307 let cfgs = if cfgs.is_empty() {
308 all = (1..=raw.configurations()).collect();
309 &all[..]
310 } else {
311 cfgs
312 };
313 cfgs.iter()
314 .map(|&c| {
315 if c == 0 {
316 invalid!("configurations start at 1 (0)");
317 }
318 let o = LoadOptions {
319 cfg: c,
320 ..opt.clone()
321 };
322 build(&raw, &o, &dirs, path.parent())
323 })
324 .collect()
325}
326
327type Ops = HashMap<(String, i64), String>;
329
330fn fop(ops: &Ops, op: &str, p1: i64, default: f64) -> f64 {
332 ops.get(&(op.to_string(), p1))
333 .and_then(|v| fv(v).ok())
334 .unwrap_or(default)
335}
336
337pub fn build(
339 raw: &Raw,
340 opt: &LoadOptions,
341 dirs: &[PathBuf],
342 base: Option<&Path>,
343) -> Result<System> {
344 let (rx, macros) = document(raw, opt, dirs, base)?;
345 System::from_import(rx, macros)
346}
347
348pub fn document(
351 raw: &Raw,
352 opt: &LoadOptions,
353 dirs: &[PathBuf],
354 base: Option<&Path>,
355) -> Result<(Prescription, Vec<MacroRequest>)> {
356 let cfg = opt.cfg.max(1) as i64;
357 let mode = sys_str(raw, "MODE", 0).unwrap_or("SEQ");
358 if mode != "SEQ" {
359 notimpl!("mode {mode} (sequential only)");
360 }
361 let unit = sys_str(raw, "UNIT", 0).unwrap_or("MM");
362 let scaled;
363 let raw = if unit.eq_ignore_ascii_case("MM") {
364 raw
365 } else {
366 scaled = to_mm(raw, unit)?;
367 &scaled
368 };
369 if raw.sysl.contains_key("AFOC") && sys_f(raw, "AFOC", 0, 0.0)? != 0.0 {
370 notimpl!("afocal image space");
371 }
372 let ncfg = count_in(
373 sys_f(raw, "MNUM", 0, 1.0)?,
374 "number of zmx configurations MNUM",
375 1,
376 MAX_CONFIGS,
377 )? as i64;
378 if !(1..=ncfg).contains(&cfg) {
379 invalid!("configuration {cfg} ({ncfg} in all)");
380 }
381 let ops = values::config_ops(raw, cfg)?;
382 let temp = sys_f(raw, "ENVD", 0, 20.0)?;
383 let pres = sys_f(raw, "ENVD", 1, 1.0)?;
384 let adjust = sys_f(raw, "ENVD", 2, 0.0)? != 0.0;
385 let waves = values::wavelengths(raw, &ops, opt)?;
386 let glasses = values::glasses(raw, opt, dirs);
387 let th = pickups::thicknesses(raw, &ops)?;
388 let parm = pickups::parms(raw, cfg)?;
389 let mats = surfaces::materials(raw, &ops)?;
390 let stop_default = raw.surfs.iter().position(|s| s.stop).unwrap_or(1) as f64;
391 let stop = fop(&ops, "STPS", 0, stop_default) as usize;
392 let grin_data = if raw
394 .surfs
395 .iter()
396 .any(|r| matches!(r.typ.as_deref(), Some("GRINSUR8") | Some("GRINSUR9")))
397 {
398 Some(lensbench_core::grin::GrinData::load(
399 dirs,
400 &raw.grd_file_name(),
401 )?)
402 } else {
403 None
404 };
405 let (mut sf, after) = surfaces::Ctx {
406 raw,
407 opt,
408 ops: &ops,
409 th: &th,
410 parm: &parm,
411 mats: &mats,
412 stop,
413 grin: grin_data.as_ref(),
414 wl: &waves.wl,
415 glasses: &glasses,
416 env: (temp, pres, adjust),
417 }
418 .surfaces()?;
419 pickups::after_tilts(&mut sf, &after);
420 pickups::conics(raw, &mut sf)?;
421 let pickups = pickups::links(raw, &sf, &after);
422 let aperture = values::aperture_kind(raw, &ops, &mut sf)?;
423 let fields = values::fields(raw, &ops, &waves.ftyp)?;
424 let set = values::settings(raw, dirs, base)?;
425 let mut s = System::new(
426 sf,
427 waves.wl,
428 waves.wwt,
429 waves.primary,
430 fields.list,
431 fields.typ,
432 fields.norm,
433 aperture,
434 fields.tele,
435 set.aiming,
436 glasses.map,
437 )?;
438 s.edit_raw(|rx| {
440 rx.aim_pupil = set.aim_pupil;
441 rx.input_pol = set.input_pol;
442 rx.glass_template = set.glass_template;
443 Ok(())
444 })?;
445 let solves = macros::solves(raw);
447 let mut config_notes = Vec::new();
448 let configs = (ncfg > 1).then(|| {
449 config_table(
450 raw,
451 &s,
452 (&solves, &pickups),
453 ncfg as usize,
454 cfg as usize,
455 &mut config_notes,
456 )
457 });
458 let mut rx = s.into_prescription();
459 rx.temperature = temp;
460 rx.pressure = pres;
461 rx.adjust_index = adjust;
462 rx.glrs = set.glrs;
463 rx.ropd = set.ropd;
464 rx.apodization = system_lines::apodization(raw, opt.fixed_semi)?;
465 rx.afocal = waves.ftyp.get(6) == Some(&1);
467 if let Some(u) = sys_str(raw, "UNIT", 5) {
470 match lensbench_core::system::AfocalUnit::from_code(u) {
471 Some(a) => rx.afocal_unit = a,
472 None if rx.afocal => invalid!("UNIT Afocal Mode Units {u}"),
473 None => {}
474 }
475 }
476 configs::apply_config_values(&ops, &mut rx);
477 rx.coating_file = set.coating_file;
478 rx.name = set.name;
479 rx.import_notes = raw.notes.clone();
480 rx.import_notes.extend(raw.system_notes(opt.fixed_semi)?);
481 if opt.glasses.is_none() {
482 let n = glass::builtin::note_for(&rx, &glasses.cats, dirs); rx.import_notes.extend(n);
484 }
485 match configs {
486 Some(Ok(c)) => {
487 rx.configs = Some(c);
488 rx.import_notes.extend(config_notes);
489 }
490 Some(Err(why)) => rx.import_notes.push(format!(
491 "only configuration {cfg} (of {ncfg}) of the multi-configuration was read ({why} can't be expressed in the multi-configuration table)"
492 )),
493 None => {}
494 }
495 for (j, d) in rx.surfaces.iter().enumerate() {
497 let Some(lensbench_core::surface::Bire::In { mode, axis, .. }) = &d.bire else {
498 continue;
499 };
500 let mode = *mode;
501 if matches!(mode, 1 | 3) {
502 rx.import_notes.push(format!(
503 "zmx surface {j}: Birefringent In Mode {mode}: the optical path along the extraordinary ray is counted from its wave vector (n(θ) cos ρ per ray length); OpticStudio counts no per ray length, so OPL and OPD differ from OpticStudio"
504 ));
505 }
506 let az = axis[2] / axis.iter().map(|v| v * v).sum::<f64>().sqrt();
507 if matches!(mode, 2 | 3) && az.abs() > 1e-12 && az.abs() < 1.0 - 1e-12 {
508 rx.import_notes.push(format!(
509 "zmx surface {j}: Birefringent In Mode {mode}: the crystal axis is tilted from the surface normal, so the retardance differs from OpticStudio, which adds 2π no t (1/cos ρ − 1)/λ for the walk-off"
510 ));
511 }
512 }
513 rx.pickups = pickups;
514 rx.solves = solves;
515 configs::apply_solve_values(&ops, &mut rx);
516 Ok((rx, macros::requests(raw, opt, base)))
517}