1use crate::error::{Error, Result};
9use crate::glass;
10use crate::invalid;
11use crate::surface::{Bire, Material};
12use crate::system::{Prescription, System};
13
14#[derive(Debug, Clone, Default)]
16pub(crate) struct Media {
17 pub n: Vec<Vec<f64>>,
19 pub base: Vec<Vec<f64>>,
21}
22
23fn medium_index_at(p: &Prescription, j: usize, lams: &[f64]) -> Result<Option<Vec<f64>>> {
25 let d = &p.surfaces[j];
26 if j > 0 && (d.is_mirror() || d.is_coord_break()) {
27 return Ok(None);
28 }
29 if let Some(g) = d.grin() {
30 if d.dnd != 0.0 || d.dvd != 0.0 {
31 invalid!(
32 "surface {j}: nd and vd offsets need a glass or a model glass, not a GRIN surface"
33 );
34 }
35 return lams
36 .iter()
37 .map(|&l| {
38 g.vertex_index(l).ok_or_else(|| {
39 Error::Invalid(format!(
40 "surface {j}: the GRIN vertex is outside the profile range"
41 ))
42 })
43 })
44 .collect::<Result<Vec<f64>>>()
45 .map(Some);
46 }
47 let mut n = p
48 .material_index_at(&d.mat, lams)
49 .map_err(|e| Error::Invalid(format!("surface {j}: {e}")))?;
50 if d.dnd != 0.0 || d.dvd != 0.0 {
51 let (nd, vd, dpgf) = p
52 .glass_nd_vd(&d.mat)
53 .map_err(|e| Error::Invalid(format!("surface {j}: {e}")))?;
54 for (x, &l) in n.iter_mut().zip(lams) {
55 *x += glass::model_index(nd + d.dnd, vd + d.dvd, dpgf, l)
56 - glass::model_index(nd, vd, dpgf, l);
57 }
58 }
59 Ok(Some(n))
60}
61
62pub(crate) fn resolve(p: &Prescription) -> Result<Media> {
64 let ns = p.surfaces.len();
65 let wp = p.primary;
66 let mut m = Media {
67 n: Vec::with_capacity(ns),
68 base: Vec::with_capacity(ns),
69 };
70 let mut prev = vec![1.0; p.wavelengths.len()];
71 for j in 0..ns {
72 let d = &p.surfaces[j];
73 let (n, base) = match medium_index_at(p, j, &p.wavelengths)? {
74 None => (prev.clone(), prev.clone()),
76 Some(b) => {
77 let n = if (d.dn != 0.0 || d.disp != 0.0) && wp < b.len() {
78 let bp = b[wp];
79 b.iter().map(|&x| x + d.dn + d.disp * (x - bp)).collect()
80 } else {
81 b.clone()
82 };
83 (n, b)
84 }
85 };
86 if !d.ignore || j == 0 {
87 prev = n.clone();
88 }
89 m.n.push(n);
90 m.base.push(base);
91 }
92 Ok(m)
93}
94
95impl Prescription {
96 pub fn material_index(&self, mat: &Material) -> Result<Vec<f64>> {
98 self.material_index_at(mat, &self.wavelengths)
99 }
100
101 pub fn glass_nd_vd(&self, mat: &Material) -> Result<(f64, f64, f64)> {
104 let (nd, vd, dpgf) = match mat {
105 Material::Model { nd, vd, dpgf } => (*nd, *vd, *dpgf),
106 Material::Glass(m) => {
107 let n = self.material_index_at(mat, &[glass::WL_D, glass::WL_F, glass::WL_C])?;
108 let dpgf = self
109 .glasses
110 .get(m)
111 .and_then(|g| g.props.map(|x| x.dpgf))
112 .unwrap_or(0.0);
113 (n[0], (n[0] - 1.0) / (n[1] - n[2]), dpgf)
114 }
115 _ => invalid!(
116 "nd and vd offsets need a glass or a model glass (nd, vd), not {}",
117 mat.name()
118 ),
119 };
120 if !(vd.is_finite() && vd > 0.0) {
121 invalid!("nd and vd offsets need a glass with dispersion (vd {vd})");
122 }
123 Ok((nd, vd, dpgf))
124 }
125
126 pub fn surface_medium_index_at(&self, j: usize, lams: &[f64]) -> Result<Option<Vec<f64>>> {
129 medium_index_at(self, j, lams)
130 }
131
132 pub fn material_index_at(&self, mat: &Material, lams: &[f64]) -> Result<Vec<f64>> {
134 match mat {
135 Material::Air => Ok(vec![1.0; lams.len()]),
136 Material::Index(n) => Ok(vec![*n; lams.len()]),
137 Material::Model { nd, vd, dpgf } => Ok(lams
138 .iter()
139 .map(|&l| glass::model_index(*nd, *vd, *dpgf, l))
140 .collect()),
141 Material::Glass(m) => {
142 let Some(g) = self.glasses.get(m) else {
143 invalid!("no glass {m} (add catalogs: add_glasses, add_glass_catalogs)");
144 };
145 if let Some(e) = crate::usermaterial::missing(g) {
146 invalid!("{e}");
147 }
148 let (t, p, a) = (self.temperature, self.pressure, self.adjust_index);
149 Ok(lams.iter().map(|&l| g.index(l, t, p, a)).collect())
150 }
151 Material::Mirror | Material::Inherit => invalid!("{} is not a medium", mat.name()),
152 }
153 }
154}
155
156impl System {
157 pub(crate) fn refresh_media(&mut self) -> Result<()> {
159 let nw = self.wavelengths.len();
160 for j in 0..self.surfaces.len() {
161 let d = &self.surfaces[j];
162 let Some(Bire::In { ne, .. }) = &d.bire else {
163 continue;
164 };
165 if ne.len() == nw {
166 continue;
167 }
168 let en = Bire::e_name(&d.mat.name());
169 let v = self
170 .material_index(&Material::Glass(en.clone()))
171 .map_err(|e| {
172 Error::Invalid(format!(
173 "surface {j}: extraordinary material {en} of the birefringent material: {e}"
174 ))
175 })?;
176 if let Some(Bire::In { ne, .. }) = &mut self.rx_mut().surfaces[j].bire {
177 *ne = v;
178 }
179 }
180 Ok(())
181 }
182
183 fn rebuild_extraordinary(&mut self) -> Result<()> {
185 if !self
186 .surfaces
187 .iter()
188 .any(|d| matches!(d.bire, Some(Bire::In { .. })))
189 {
190 return Ok(());
191 }
192 for d in self.rx_mut().surfaces.iter_mut() {
193 if let Some(Bire::In { ne, .. }) = &mut d.bire {
194 ne.clear();
195 }
196 }
197 self.refresh_media()
198 }
199
200 pub(crate) fn set_wavelengths(&mut self, waves: &[(usize, f64)]) -> Result<()> {
203 for &(i, lam) in waves {
204 if i >= self.wavelengths.len() || !(lam > 0.0) {
205 invalid!(
206 "wavelength {} = {lam} µm (there are {} wavelengths)",
207 i + 1,
208 self.wavelengths.len()
209 );
210 }
211 }
212 for &(i, lam) in waves {
213 self.rx_mut().wavelengths[i] = lam;
214 }
215 self.rebuild_extraordinary()
216 }
217
218 pub fn with_wavelength(&self, lam: f64) -> Result<(System, usize)> {
221 if !(lam > 0.0) {
222 invalid!("wavelength {lam} µm");
223 }
224 let mut d = self.clone();
225 d.rx_mut().wavelengths.push(lam);
226 d.rx_mut().weights.push(0.0);
227 d.rebuild_extraordinary()?;
228 d.changed()?;
229 Ok((d, self.wavelengths.len()))
230 }
231}