1use crate::aim::{aim_lanes, AimFit, AimSol, AimStart};
11use crate::batch;
12use crate::coating::{self, Coatings, C64};
13use crate::error::{Error, Result};
14use crate::glass::Glass;
15use crate::interp2d::interp_weights;
16use crate::math::*;
17use crate::surface::{After, Bire, Material, Surface};
18use crate::trace::{self, CryKind, PolKind, PolSurf, RayOut, RayStatus, RecEntry, CV3};
19use crate::LockExt;
20use crate::{invalid, notimpl, par::scoped};
21use rayon::prelude::*;
22use std::collections::HashMap;
23use std::path::PathBuf;
24use std::sync::{Arc, Mutex, OnceLock};
25
26pub(crate) const ENPP_MAX: f64 = 1e10;
27
28#[derive(Debug, Default)]
29struct Cache {
30 frames: OnceLock<Frames>,
31 par: OnceLock<Paraxial>,
32 expp: OnceLock<f64>,
33 expd: OnceLock<f64>,
34 rs: OnceLock<(f64, f64)>,
35 realh: Mutex<HashMap<(FieldCond, usize, u64, u64), ObjSpec>>,
37 conj: OnceLock<Vec<f64>>,
39 kinds: OnceLock<Vec<crate::shape::SurfKind>>,
41 signs: OnceLock<Vec<f64>>,
43 plans: crate::batch::PlanCache,
45 pub(crate) focus: Option<crate::focus::FocusShift>,
47 pupils: crate::pupil::PupilCache,
49}
50
51const PAR_MIN_RAYS: usize = 512;
53const PAR_CHUNK: usize = 256;
55const AIM_FIT_MIN: usize = 1024;
57const CUSP_FIELD_DEG: f64 = 0.01;
59
60#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
63pub struct Prescription {
64 pub surfaces: Vec<Surface>,
65 pub wavelengths: Vec<f64>,
66 pub weights: Vec<f64>,
67 pub primary: usize,
68 pub fields: Vec<Field>,
69 pub field_type: FieldType,
70 pub field_norm: FieldNorm,
71 pub aperture: (ApertureKind, f64),
72 pub telecentric: bool,
73 pub aiming: Aiming,
74 pub glasses: Arc<HashMap<String, Glass>>,
76 pub temperature: f64,
77 pub pressure: f64,
78 pub glrs: usize,
79 pub ropd: i64,
80 #[serde(default, skip_serializing_if = "crate::pupil::Apodization::is_uniform")]
83 pub apodization: crate::pupil::Apodization,
84 #[serde(default, skip_serializing_if = "AimPupil::is_default")]
88 pub aim_pupil: AimPupil,
89 #[serde(default, skip_serializing_if = "InputPolarization::is_default")]
91 pub input_pol: InputPolarization,
92 #[serde(default, skip_serializing_if = "GlassTemplate::is_default")]
94 pub glass_template: GlassTemplate,
95 #[serde(default)]
99 pub afocal: bool,
100 #[serde(default)]
102 pub afocal_unit: AfocalUnit,
103 #[serde(default)]
105 pub vig_interp: VigInterp,
106 #[serde(
109 default = "crate::configs::yes",
110 skip_serializing_if = "crate::configs::is_yes"
111 )]
112 pub floating_clip: bool,
113 #[serde(
116 default = "crate::configs::yes",
117 skip_serializing_if = "crate::configs::is_yes"
118 )]
119 pub mech_clip: bool,
120 #[serde(skip)]
123 pub field_wave: Option<usize>,
124 pub coating_file: Option<PathBuf>,
125 #[serde(default, skip_serializing_if = "HashMap::is_empty")]
128 pub coat_tables: HashMap<String, crate::coating::Table>,
129 pub name: String,
130 pub adjust_index: bool,
131 pub pickups: Vec<crate::pickup::Pickup>,
133 pub solves: Vec<crate::solves::Solve>,
135 #[serde(default, skip_serializing_if = "Vec::is_empty")]
137 pub macros: Vec<crate::zpl_solve::Macro>,
138 #[serde(default, skip_serializing_if = "Vec::is_empty")]
140 pub macro_parms: Vec<crate::zpl_solve::MacroParm>,
141 #[serde(default, skip_serializing_if = "Vec::is_empty")]
144 pub macro_notes: Vec<String>,
145 #[serde(default, skip_serializing_if = "Vec::is_empty")]
147 pub import_notes: Vec<String>,
148 #[serde(default)]
150 pub units: Vec<crate::units::Unit>,
151 #[serde(default, skip_serializing_if = "Vec::is_empty")]
154 pub mechanics: Vec<crate::mech::MechPart>,
155 #[serde(default, skip_serializing_if = "Option::is_none")]
157 pub configs: Option<crate::configs::Configs>,
158}
159
160#[derive(Debug)]
163pub struct System {
164 rx: Arc<Prescription>,
165 media: Arc<crate::media::Media>,
167 cache: Cache,
168 pub(crate) batch: Batch,
170}
171
172#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
174pub(crate) enum Batch {
175 #[default]
177 Off,
178 On,
180 SemiPending,
182}
183
184impl std::ops::Deref for System {
185 type Target = Prescription;
186 fn deref(&self) -> &Prescription {
187 &self.rx
188 }
189}
190
191impl Clone for System {
192 fn clone(&self) -> Self {
193 self.clone_keep(Keep::default())
194 }
195}
196
197impl Prescription {
198 pub fn find_surface(&self, target: &str) -> Result<usize> {
200 let t = target.trim();
201 if let Ok(j) = t.parse::<usize>() {
202 if j >= self.surfaces.len() {
203 let last = self.surfaces.len() - 1;
204 invalid!("surface {j} (surfaces are 0 to {last})");
205 }
206 return Ok(j);
207 }
208 let hits: Vec<usize> = (0..self.surfaces.len())
209 .filter(|&j| self.surfaces[j].comment.trim().eq_ignore_ascii_case(t))
210 .collect();
211 match hits.as_slice() {
212 [j] => Ok(*j),
213 [] => invalid!("no surface named {t}"),
214 _ => invalid!("several surfaces are named {t} ({hits:?}); use the number"),
215 }
216 }
217
218 pub fn dispersion_warnings(&self) -> Vec<String> {
221 let mut out = Vec::new();
222 let mut seen = std::collections::HashSet::new();
223 for (k, d) in self.surfaces.iter().enumerate() {
224 if d.ignore {
225 continue;
226 }
227 let Some(g) = d.mat.glass().and_then(|m| self.glasses.get(m)) else {
228 continue;
229 };
230 let Some([lo, hi]) = g.ld else {
231 continue;
232 };
233 for &l in &self.wavelengths {
234 if (l < lo || l > hi) && seen.insert((d.mat.name(), l.to_bits())) {
235 out.push(format!(
236 "surface {k} material {} ({}): wavelength {l} µm is outside the dispersion formula range {lo} to {hi} µm (the formula is extended)",
237 d.mat, g.catalog
238 ));
239 }
240 }
241 }
242 out
243 }
244
245 pub fn stop(&self) -> usize {
246 self.surfaces.iter().position(|d| d.stop).unwrap_or(0)
247 }
248
249 pub fn surf_label(&self, j: usize) -> String {
251 let Some(d) = self.surfaces.get(j) else {
252 return format!("surface {j}");
253 };
254 let mut what = crate::edit::surf_type_name(d.typ()).to_string();
255 if !matches!(d.mat, Material::Air | Material::Inherit) {
256 what = format!("{what}, {}", d.mat);
257 }
258 if !d.coat.is_empty() {
259 what = format!("{what}, coating {}", d.coat);
260 }
261 if !d.comment.is_empty() {
262 what = format!("{what}, 「{}」", d.comment);
263 }
264 format!("surface {j}({what})")
265 }
266
267 pub fn image(&self) -> usize {
268 self.surfaces.len() - 1
269 }
270
271 pub fn infinite(&self) -> bool {
272 !self.surfaces[0].t.is_finite()
273 }
274
275 pub fn image_point(&self, xyz: [f64; 3], lmn: [f64; 3]) -> (f64, f64) {
278 if self.afocal {
279 let u = self.afocal_unit.radians();
280 ((lmn[0] / lmn[2]).atan() / u, (lmn[1] / lmn[2]).atan() / u)
281 } else {
282 (xyz[0], xyz[1])
283 }
284 }
285
286 pub fn image_unit(&self) -> &'static str {
288 if self.afocal {
289 self.afocal_unit.label()
290 } else {
291 "mm"
292 }
293 }
294
295 pub fn build(self) -> Result<System> {
298 let mut s = System::from_rx(self)?;
299 s.refresh()?;
300 Ok(s)
301 }
302
303 pub fn build_raw(self) -> Result<System> {
305 let s = System::from_rx(self)?;
306 s.check()?;
307 Ok(s)
308 }
309}
310
311impl System {
312 pub(crate) fn from_rx(rx: Prescription) -> Result<System> {
314 let media = Arc::new(crate::media::resolve(&rx)?);
315 Ok(System {
316 rx: Arc::new(rx),
317 media,
318 cache: Cache::default(),
319 batch: Batch::Off,
320 })
321 }
322
323 pub(crate) fn resolve_media(&mut self) -> Result<()> {
325 self.media = Arc::new(crate::media::resolve(&self.rx)?);
326 Ok(())
327 }
328
329 pub fn n(&self, j: usize) -> &[f64] {
331 &self.media.n[j]
332 }
333
334 pub fn base_index(&self, j: usize, w: usize) -> f64 {
336 self.media.base[j][w]
337 }
338
339 pub fn index_before(&self, j: usize, w: usize) -> f64 {
341 let mut n = self.media.n[0][w];
342 for (k, d) in self.surfaces.iter().enumerate().take(j.max(1)).skip(1) {
343 if !d.ignore && !d.is_coord_break() {
344 n = self.media.n[k][w];
345 }
346 }
347 n
348 }
349
350 pub fn image_index(&self, w: usize) -> f64 {
351 self.index_before(self.image(), w)
352 }
353}
354
355impl serde::Serialize for System {
356 fn serialize<S: serde::Serializer>(&self, s: S) -> std::result::Result<S::Ok, S::Error> {
357 self.rx.serialize(s)
358 }
359}
360
361impl<'de> serde::Deserialize<'de> for System {
362 fn deserialize<D: serde::Deserializer<'de>>(d: D) -> std::result::Result<System, D::Error> {
363 let p = Prescription::deserialize(d)?;
364 System::from_rx(p).map_err(serde::de::Error::custom)
365 }
366}
367
368impl schemars::JsonSchema for System {
369 fn schema_name() -> std::borrow::Cow<'static, str> {
370 Prescription::schema_name()
371 }
372 fn json_schema(g: &mut schemars::SchemaGenerator) -> schemars::Schema {
373 Prescription::json_schema(g)
374 }
375}
376
377#[derive(Debug, Clone, Copy, Default)]
379pub(crate) struct Keep {
380 pub frames: bool,
382 pub paraxial: bool,
384}
385
386impl System {
387 pub(crate) fn clone_keep(&self, keep: Keep) -> System {
389 let cache = Cache::default();
390 if keep.frames {
391 if let Some(f) = self.cache.frames.get() {
392 let _ = cache.frames.set(f.clone());
393 }
394 }
395 if keep.paraxial {
396 if let Some(p) = self.cache.par.get() {
397 let _ = cache.par.set(p.clone());
398 }
399 if let Some(c) = self.cache.conj.get() {
400 let _ = cache.conj.set(c.clone());
401 }
402 }
403 System {
404 rx: self.rx.clone(),
405 media: self.media.clone(),
406 cache,
407 batch: self.batch,
408 }
409 }
410
411 pub(crate) fn rx_mut(&mut self) -> &mut Prescription {
414 Arc::make_mut(&mut self.rx)
415 }
416
417 pub fn without_vignetting(&self) -> System {
420 let mut c = self.clone();
421 for f in c.rx_mut().fields.iter_mut() {
422 (f.vdx, f.vdy, f.vcx, f.vcy, f.van) = (0.0, 0.0, 0.0, 0.0, 0.0);
423 }
424 c
425 }
426
427 pub fn prescription(&self) -> &Prescription {
429 &self.rx
430 }
431
432 pub fn into_prescription(self) -> Prescription {
434 Arc::try_unwrap(self.rx).unwrap_or_else(|a| (*a).clone())
435 }
436}
437
438const ON_AXIS_PUPIL_FIELD: f64 = 10.0;
440
441impl System {
442 #[allow(clippy::too_many_arguments)]
443 pub fn new(
444 surfaces: Vec<Surface>,
445 wavelengths: Vec<f64>,
446 weights: Vec<f64>,
447 primary: usize,
448 fields: Vec<Field>,
449 field_type: FieldType,
450 field_norm: FieldNorm,
451 aperture: (ApertureKind, f64),
452 telecentric: bool,
453 aiming: Aiming,
454 glasses: impl Into<Arc<HashMap<String, Glass>>>,
455 ) -> Result<System> {
456 let s = Prescription {
457 surfaces,
458 wavelengths,
459 weights,
460 primary,
461 fields: if fields.is_empty() {
462 vec![Field::xy(0.0, 0.0)]
463 } else {
464 fields
465 },
466 field_type,
467 field_norm,
468 aperture,
469 telecentric,
470 aiming,
471 glasses: glasses.into(),
472 temperature: 20.0,
473 pressure: 1.0,
474 glrs: 1,
475 ropd: 2,
476 apodization: crate::pupil::Apodization::Uniform,
477 aim_pupil: AimPupil::default(),
478 input_pol: InputPolarization::default(),
479 glass_template: GlassTemplate::default(),
480 afocal: false,
481 afocal_unit: AfocalUnit::Milliradians,
482 vig_interp: VigInterp::Continuous,
483 floating_clip: true,
484 mech_clip: true,
485 field_wave: None,
486 coating_file: None,
487 coat_tables: HashMap::new(),
488 name: String::new(),
489 adjust_index: true,
490 pickups: Vec::new(),
491 solves: Vec::new(),
492 macros: Vec::new(),
493 macro_parms: Vec::new(),
494 macro_notes: Vec::new(),
495 import_notes: Vec::new(),
496 units: Vec::new(),
497 mechanics: Vec::new(),
498 configs: None,
499 }
500 .build_raw()?;
501 Ok(s)
502 }
503
504 pub fn check(&self) -> Result<()> {
505 let sf = &self.surfaces;
506 if sf.len() < 3 {
507 invalid!("too few surfaces ({})", sf.len());
508 }
509 if self.telecentric && !sf[0].t.is_finite() {
510 notimpl!("object-space telecentric with an object at infinity");
511 }
512 if self.telecentric && self.aiming != Aiming::Off {
513 notimpl!("ray aiming with object-space telecentric");
514 }
515 if !sf[0].t.is_finite() && self.field_type == FieldType::ObjH {
516 invalid!("object height field with an object at infinity");
517 }
518 if self.telecentric && !matches!(self.aperture.0, ApertureKind::Na | ApertureKind::Cone) {
519 invalid!("object-space telecentric needs an object-space NA or cone angle aperture");
520 }
521 if let Some(j) = sf
523 .iter()
524 .position(|d| d.typ() == crate::surface::SurfType::Jones && d.c != 0.0)
525 {
526 notimpl!("Jones matrix surface {j} on a curved surface");
527 }
528 if let Some(j) = sf.iter().position(|d| {
530 d.typ() == crate::surface::SurfType::UserShape && d.user_shape().is_none() && !d.ignore
531 }) {
532 invalid!("user-defined shape (surface {j}) has no model (shape)");
533 }
534 if let Some((j, d)) = sf.iter().enumerate().find(|(_, d)| {
535 !(d.chip_zone >= 0.0 && d.chip_zone.is_finite())
536 || d.mech_semi.is_some_and(|m| !(m >= 0.0 && m.is_finite()))
537 }) {
538 invalid!(
539 "surface {j}: mechanical semi-diameter {:?}, chip zone {}",
540 d.mech_semi,
541 d.chip_zone
542 );
543 }
544 let st = self.stop();
545 if st == 0 || st >= sf.len() - 1 {
546 invalid!("stop surface {st}");
547 }
548 for (j, d) in sf.iter().enumerate() {
550 if d.ignore || d.is_mirror() || d.grin().is_none() {
551 continue;
552 }
553 if let Some((k, e)) = sf
554 .iter()
555 .enumerate()
556 .skip(j + 1)
557 .find(|(_, e)| !e.ignore && !e.is_coord_break())
558 {
559 if !crate::grin::next_ok(e) {
560 let typ = e.typ();
561 notimpl!("surface {k} ({typ:?}) after the GRIN medium of surface {j}");
562 }
563 }
564 }
565 Ok(())
566 }
567
568 pub(crate) fn invalidate_frames(&mut self) {
570 self.cache = Cache::default();
571 }
572
573 #[doc(hidden)]
575 pub fn set_focus(&mut self, f: crate::focus::FocusShift) {
576 self.cache.focus = Some(f);
577 self.cache.pupils.clear();
578 }
579
580 pub(crate) fn pupil_cache(&self) -> &crate::pupil::PupilCache {
582 &self.cache.pupils
583 }
584
585 pub(crate) fn changed(&mut self) -> Result<()> {
587 if self.surfaces.iter().any(|d| d.coord_return.is_some()) {
588 crate::coord_return::resolve(self.rx_mut())?;
589 }
590 self.cache = Cache::default();
591 self.resolve_media()?;
592 self.check()
593 }
594
595 pub(crate) fn surf_kinds(&self) -> &[crate::shape::SurfKind] {
597 self.cache
598 .kinds
599 .get_or_init(|| self.surfaces.iter().map(crate::shape::surf_kind).collect())
600 }
601
602 pub(crate) fn plan_cache(&self) -> &crate::batch::PlanCache {
604 &self.cache.plans
605 }
606
607 pub(crate) fn space_signs(&self) -> &[f64] {
608 self.cache
609 .signs
610 .get_or_init(|| crate::trace::space_signs(self))
611 }
612
613 pub fn frames(&self) -> &Frames {
614 self.cache.frames.get_or_init(|| frames(self))
615 }
616
617 pub(crate) fn extraordinary_entry(&self, last: usize) -> Option<usize> {
622 (1..=last.min(self.surfaces.len().saturating_sub(1))).find(|&j| {
623 let d = &self.surfaces[j];
624 !d.ignore && matches!(d.bire, Some(crate::surface::Bire::In { mode: 1 | 3, .. }))
625 })
626 }
627
628 pub fn check_crystals(&self) -> Result<()> {
632 for (j, d) in self.surfaces.iter().enumerate() {
633 let Some(crate::surface::Bire::In {
634 mode: mode @ (1 | 3),
635 ..
636 }) = &d.bire
637 else {
638 continue;
639 };
640 if d.ignore || d.is_mirror() {
641 if d.is_mirror() {
642 notimpl!(
643 "{}: a mirror at the entrance of a birefringent plate Mode {mode} can't be traced",
644 self.surf_label(j)
645 );
646 }
647 continue;
648 }
649 for (k, e) in self.surfaces.iter().enumerate().skip(j + 1) {
650 if e.ignore {
651 continue;
652 }
653 if matches!(e.bire, Some(crate::surface::Bire::Out)) {
654 if e.is_mirror() {
655 notimpl!(
656 "{}: a mirror at the exit of a birefringent plate Mode {mode} can't be traced",
657 self.surf_label(k)
658 );
659 }
660 break;
661 }
662 let refracts = !e.is_coord_break() && e.mat != d.mat;
663 if e.is_mirror() || e.grin().is_some() || refracts || e.bire.is_some() {
664 notimpl!(
665 "{}: a mirror, GRIN medium or refracting surface inside the birefringent plate Mode {mode} of {} can't be traced",
666 self.surf_label(k),
667 self.surf_label(j)
668 );
669 }
670 }
671 }
672 Ok(())
673 }
674
675 pub fn validate(&self) -> Result<()> {
677 for (j, d) in self.surfaces.iter().enumerate() {
678 let action = d.action();
679 if matches!(action, crate::action::Action::User(_)) && !d.ignore {
680 if d.user().is_none() {
681 invalid!("user-defined surface (surface {j}) has no model (user)");
682 }
683 let w = self.primary;
684 let (nb, na) = (self.index_before(j, w), self.n(j)[w]);
685 if nb != 1.0 || na != 1.0 || d.is_mirror() {
686 notimpl!("user-defined surface in a medium other than air or on a mirror (surface {j}: {nb} → {na})");
687 }
688 }
689 if let (crate::action::Action::Paraxial { .. }, false) = (action, d.ignore) {
690 let w = self.primary;
691 let (nb, na) = (self.index_before(j, w), self.n(j)[w]);
692 if nb != 1.0 || na != 1.0 {
693 notimpl!("paraxial lens in a medium other than air (surface {j}: {nb} → {na})");
694 }
695 }
698 }
699 if self.surfaces[0].before.is_some() || self.surfaces[0].after != After::None {
700 notimpl!("tilt or decenter of the object surface");
701 }
702 Ok(())
703 }
704}
705
706mod aiming;
707mod field;
708mod launch;
709mod near;
710mod paraxial;
711mod pol;
712pub use pol::PolIn;
713mod raybuf;
714mod rays;
715mod types;
716use launch::StartGeom;
717use near::NearGrid;
718pub use raybuf::{Cols, RayBuf};
719use raybuf::{Done, Dst};
720pub use rays::*;
721pub use types::*;
722
723mod frame_calc;
724pub use frame_calc::{apply_cb, frames, step_frame};
725
726mod field_cond;
727
728#[cfg(test)]
729mod tests {
730 use super::*;
731
732 fn defocused(obj: &str, aperture: &str, image_t: f64) -> System {
734 let t = format!(
735 "VERS 260327 42\nMODE SEQ\nUNIT MM X W X CM MR CPMM\n{aperture}\nFTYP 2 0 1 1 0 0 0\n\
736 XFLN 0\nYFLN 5\nFWGN 1\nWAVM 1 0.5876 1\nPWAV 1\n\
737 SURF 0\n TYPE STANDARD\n CURV 0.0\n DISZ {obj}\n\
738 SURF 1\n STOP\n TYPE PARAXIAL\n PARM 1 50\n PARM 2 1\n DISZ {image_t}\n\
739 SURF 2\n TYPE STANDARD\n CURV 0.0\n DISZ 0\n"
740 );
741 let raw = crate::test_zmx::parse_text(&t).unwrap();
742 crate::test_zmx::build(&raw, &Default::default(), &[], None).unwrap()
743 }
744
745 #[test]
746 fn paraxial_image_height_is_taken_at_the_paraxial_image_plane() {
747 for t in [50.0, 40.0, 60.0] {
749 let s = defocused("INFINITY", "ENPD 10", t);
750 match s.object_spec(0.0, 1.0).unwrap() {
751 ObjSpec::Dir(d) => assert!(((d[1] / d[2]).abs() - 0.1).abs() < 1e-14, "{t}: {d:?}"),
752 o => panic!("{o:?}"),
753 }
754 }
755 for t in [100.0, 80.0, 120.0] {
757 let s = defocused("100", "OBNA 0.05 0", t);
758 match s.object_spec(0.0, 1.0).unwrap() {
759 ObjSpec::Point(p) => assert!((p[1].abs() - 5.0).abs() < 1e-12, "{t}: {p:?}"),
760 o => panic!("{o:?}"),
761 }
762 }
763 }
764}