lensbench_core/
usersource.rs1use crate::error::Result;
14use crate::math::V3;
15use crate::plugin::{Config, ParamSpec};
16use crate::{invalid, System};
17use std::sync::Arc;
18
19pub trait SourceModel: Send + Sync {
21 fn name(&self) -> &str;
23 fn doc(&self) -> String {
25 String::new()
26 }
27 fn params(&self) -> Vec<ParamSpec> {
29 Vec::new()
30 }
31 fn prepare(&self, config: &Config) -> Result<Arc<dyn SourceInstance>>;
33 fn example_config(&self) -> Option<Config> {
36 self.params()
37 .into_iter()
38 .map(|p| Some((p.name, p.default?)))
39 .collect()
40 }
41}
42
43pub trait SourceInstance: Send + Sync {
45 fn rays(&self, wl: f64) -> Result<SourceRays>;
47}
48
49#[derive(Debug, Clone, Default, PartialEq)]
51pub struct SourceRays {
52 pub p: Vec<V3>,
53 pub k: Vec<V3>,
54 pub w: Vec<f64>,
55}
56
57impl SourceRays {
58 pub fn len(&self) -> usize {
60 self.p.len()
61 }
62
63 pub fn is_empty(&self) -> bool {
64 self.p.is_empty()
65 }
66
67 pub fn check(&self) -> Result<()> {
69 let n = self.p.len();
70 if self.k.len() != n || self.w.len() != n {
71 invalid!(
72 "the source gave different numbers of starts, directions and weights ({n}, {} and {})",
73 self.k.len(),
74 self.w.len()
75 );
76 }
77 for i in 0..n {
78 let (p, k, w) = (self.p[i], self.k[i], self.w[i]);
79 if !p.iter().chain(&k).all(|x| x.is_finite()) || k == [0.0; 3] {
80 invalid!("ray {i} of the source has a start {p:?} or direction {k:?} that is not finite or is zero");
81 }
82 if !(w.is_finite() && w >= 0.0) {
83 invalid!(
84 "ray {i} of the source has the weight {w} (must be finite and not negative)"
85 );
86 }
87 }
88 Ok(())
89 }
90}
91
92pub fn check_source(m: &dyn SourceModel, config: &Config) -> Result<()> {
95 let inst = m.prepare(config)?;
96 for wl in [0.4861327, 0.5875618, 0.6562725] {
97 let r = inst.rays(wl)?;
98 r.check()?;
99 if r.is_empty() {
100 invalid!("the source gave no rays at {wl} µm");
101 }
102 if inst.rays(wl)? != r {
103 invalid!("the source gave different rays for the same setting at {wl} µm");
104 }
105 }
106 Ok(())
107}
108
109impl System {
110 pub fn source_rays(&self, src: &dyn SourceInstance, w: usize) -> Result<SourceRays> {
113 let Some(&wl) = self.wavelengths.get(w) else {
114 invalid!(
115 "no wavelength {} (the system has {})",
116 w + 1,
117 self.wavelengths.len()
118 );
119 };
120 let mut r = src.rays(wl)?;
121 r.check()?;
122 let f = self.object_frame();
123 let mv = |v: V3| [0, 1, 2].map(|c| f.r[c][0] * v[0] + f.r[c][1] * v[1] + f.r[c][2] * v[2]);
124 for q in r.p.iter_mut() {
125 let g = mv(*q);
126 *q = [f.o[0] + g[0], f.o[1] + g[1], f.o[2] + g[2]];
127 }
128 for q in r.k.iter_mut() {
129 *q = mv(*q);
130 }
131 Ok(r)
132 }
133}