1use crate::coating::{Iface, C64};
5use crate::math::*;
6use crate::system::System;
7use crate::tol::PARALLEL_SIN;
8use crate::Error;
9
10pub(crate) type CV3 = [C64; 3];
12
13#[derive(Debug, Clone)]
15pub enum PolKind {
16 None,
17 Jones([C64; 4]),
19 Iface(Iface),
21}
22
23#[derive(Debug, Clone)]
24pub struct PolSurf {
25 pub kind: PolKind,
26 pub cry: Option<CryKind>,
28 pub cement: Option<(V3, f64, f64)>,
31 pub cemented: bool,
33 pub it: Option<f64>,
35 pub la: f64,
37 pub user_jones: Option<UserJones>,
39}
40
41#[derive(Clone)]
43pub struct UserJones {
44 src: UserJonesSrc,
45 wl: f64,
46}
47
48#[derive(Clone)]
49enum UserJonesSrc {
50 Shape(crate::usershape::UserShape),
51 Surf(std::sync::Arc<dyn crate::usersurf::SurfaceInstance>),
52}
53
54impl std::fmt::Debug for UserJones {
55 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
56 f.debug_struct("UserJones").field("wl", &self.wl).finish()
57 }
58}
59
60impl UserJones {
61 pub fn of_shape(u: &crate::usershape::UserShape, wl: f64) -> Option<UserJones> {
63 u.has_jones().then(|| UserJones {
64 src: UserJonesSrc::Shape(u.clone()),
65 wl,
66 })
67 }
68
69 pub fn of_surf(u: &crate::usersurf::UserSurf, wl: f64) -> Option<UserJones> {
71 u.instance().jones(0.0, 0.0, 0.55).map(|_| UserJones {
72 src: UserJonesSrc::Surf(u.instance_arc()),
73 wl,
74 })
75 }
76
77 pub fn at(&self, x: f64, y: f64) -> Result<[C64; 4], Error> {
79 let m = match &self.src {
80 UserJonesSrc::Shape(u) => u.jones(x, y, self.wl),
81 UserJonesSrc::Surf(s) => s.jones(x, y, self.wl),
82 };
83 match m {
84 Some(m) if m.iter().all(|z| z.re.is_finite() && z.im.is_finite()) => Ok(m),
85 _ => Err(Error::Invalid(format!(
86 "the user-defined Jones matrix is not given at ({x}, {y})"
87 ))),
88 }
89 }
90}
91
92impl PolSurf {
93 pub fn new(kind: PolKind, it: Option<f64>) -> PolSurf {
94 PolSurf {
95 kind,
96 cry: None,
97 cement: None,
98 cemented: false,
99 it,
100 la: it.map_or(0.0, |t| 0.5 * t.ln()),
101 user_jones: None,
102 }
103 }
104}
105
106#[derive(Debug, Clone, Copy)]
108pub enum CryKind {
109 In {
110 mode: u8,
111 axis: V3,
112 no: f64,
113 ne: f64,
114 },
115 Out,
116}
117
118#[derive(Debug, Clone, Copy)]
120pub(crate) struct CryState {
121 pub mode: u8,
122 pub axis: V3,
123 pub no: f64,
124 pub ne: f64,
125 pub len: f64,
126 pub proj: f64,
128}
129
130fn crystal_phase(c: &CryState, e: &mut [CV3], k: V3, lam: f64) {
134 let k = normalize(k);
135 let a = normalize(c.axis);
136 let ca = dot(a, k);
137 let ep = sub(a, scale(k, ca));
138 let s = norm(ep);
139 if c.mode == 1 {
140 if s > PARALLEL_SIN {
142 let ep = scale(ep, 1.0 / s);
143 for x in e.iter_mut() {
144 let v = cdot(*x, ep);
145 *x = [0, 1, 2].map(|i| v * ep[i]);
146 }
147 }
148 return;
149 }
150 if c.mode == 0 {
151 let es = if s > PARALLEL_SIN {
153 normalize(cross(k, scale(ep, 1.0 / s)))
154 } else {
155 return;
156 };
157 for x in e.iter_mut() {
158 let v = cdot(*x, es);
159 *x = [0, 1, 2].map(|i| v * es[i]);
160 }
161 return;
162 }
163 if !(s > PARALLEL_SIN) {
164 return;
166 }
167 let ep = scale(ep, 1.0 / s);
168 let sa2 = 1.0 - ca * ca;
169 let nth = 1.0 / (ca * ca / (c.no * c.no) + sa2 / (c.ne * c.ne)).sqrt();
170 let ph = -2.0 * std::f64::consts::PI * (nth - c.no) * c.len * c.proj * 1e3 / lam;
171 let (u, ph) = if c.mode == 3 {
173 (normalize(cross(k, ep)), -ph)
174 } else {
175 (ep, ph)
176 };
177 let f = C64::from_polar(1.0, ph) - C64::new(1.0, 0.0);
178 for x in e.iter_mut() {
179 let v = cdot(*x, u) * f;
180 *x = [0, 1, 2].map(|i| x[i] + v * u[i]);
181 }
182}
183
184#[inline]
185pub(crate) fn cmv(m: &M3, e: CV3) -> CV3 {
186 [0, 1, 2].map(|i| e[0] * m[i][0] + e[1] * m[i][1] + e[2] * m[i][2])
187}
188#[inline]
189fn cdot(e: CV3, v: V3) -> C64 {
190 e[0] * v[0] + e[1] * v[1] + e[2] * v[2]
191}
192#[inline]
193fn comb(a: C64, u: V3, b: C64, v: V3) -> CV3 {
194 [0, 1, 2].map(|i| a * u[i] + b * v[i])
195}
196
197pub(crate) fn rotate_min(e: CV3, ax: V3, c: f64) -> CV3 {
199 if 1.0 + c <= 1e-15 {
200 return CNAN3;
201 }
202 let ae = cdot(e, ax);
204 let x = [
205 e[2] * ax[1] - e[1] * ax[2],
206 e[0] * ax[2] - e[2] * ax[0],
207 e[1] * ax[0] - e[0] * ax[1],
208 ];
209 [0, 1, 2].map(|i| e[i] * c + x[i] + ae * (ax[i] / (1.0 + c)))
210}
211
212pub(crate) const CNAN3: CV3 = [C64::new(f64::NAN, f64::NAN); 3];
213
214pub fn apply_jones(e: &mut [[C64; 3]], kl: V3, m: &[C64; 4]) {
217 let sz = if kl[2] > 0.0 {
218 1.0
219 } else if kl[2] < 0.0 {
220 -1.0
221 } else {
222 0.0
223 };
224 let h = scale(add(kl, [0.0, 0.0, sz]), 1.0 / (1.0 + kl[2].abs()));
225 let u = sub([1.0, 0.0, 0.0], scale(h, kl[0]));
226 let v = sub([0.0, 1.0, 0.0], scale(h, kl[1]));
227 for x in e.iter_mut() {
228 let (eu, ev) = (cdot(*x, u), cdot(*x, v));
229 *x = comb(m[0] * eu + m[1] * ev, u, m[2] * eu + m[3] * ev, v);
230 }
231}
232
233fn pol_surface(
235 ps: &PolSurf,
236 e: &mut [CV3],
237 kin: V3,
238 kl: V3,
239 nv: V3,
240 cosi: f64,
241 mirror: bool,
242) -> Result<(), Error> {
243 match &ps.kind {
244 PolKind::None => {}
245 PolKind::Jones(m) => apply_jones(e, kl, m),
246 PolKind::Iface(f) => {
247 let mut sv = cross(kin, nv);
248 if !(norm(sv) > PARALLEL_SIN) {
249 sv = cross(kin, [1.0, 0.0, 0.0]);
250 }
251 let sv = normalize(sv);
252 let pin = cross(sv, kin);
253 let mut pout = cross(sv, kl);
254 if mirror {
255 pout = scale(pout, -1.0);
256 }
257 let tc = f.eval_cos(cosi.abs().clamp(0.0, 1.0))?;
258 for x in e.iter_mut() {
259 let (es, ep) = (cdot(*x, sv), cdot(*x, pin));
260 *x = comb(tc[0] * es, sv, tc[1] * ep, pout);
261 }
262 }
263 }
264 Ok(())
265}
266
267#[allow(clippy::too_many_arguments)]
273fn pol_surface_crystal(
274 ps: &PolSurf,
275 e: &mut [CV3],
276 kin: V3,
277 kl: V3,
278 nv: V3,
279 cosi: f64,
280 x: (V3, f64, f64, V3, bool),
281) -> Result<(), Error> {
282 let (axis, no, ne, kc, entering) = x;
283 let PolKind::Iface(f) = &ps.kind else {
284 return pol_surface(ps, e, kin, kl, nv, cosi, false);
285 };
286 let k = normalize(kc);
287 let a = normalize(axis);
288 let ca = dot(a, k);
289 let ep = sub(a, scale(k, ca));
290 let sn = norm(ep);
291 if !(sn > PARALLEL_SIN) {
292 return pol_surface(ps, e, kin, kl, nv, cosi, false);
293 }
294 let ee = scale(ep, 1.0 / sn);
295 let eo = normalize(cross(k, ee));
296 let nth = 1.0 / (ca * ca / (no * no) + (1.0 - ca * ca) / (ne * ne)).sqrt();
297 let mut sv = cross(kin, nv);
298 if !(norm(sv) > PARALLEL_SIN) {
299 sv = cross(kin, [1.0, 0.0, 0.0]);
300 }
301 let sv = normalize(sv);
302 let pin = cross(sv, kin);
303 let pout = cross(sv, kl);
304 let c0 = cosi.abs().clamp(0.0, 1.0);
305 let to = f.eval_cos(c0)?;
306 let te = f.eval_cos_crystal(c0, entering, nth)?;
307 let sp = |t: &[C64; 2], x: CV3| comb(t[0] * cdot(x, sv), sv, t[1] * cdot(x, pin), pout);
308 for x in e.iter_mut() {
309 *x = if entering {
310 comb(cdot(sp(&to, *x), eo), eo, cdot(sp(&te, *x), ee), ee)
311 } else {
312 let (xo, xe) = (eo.map(|v| cdot(*x, eo) * v), ee.map(|v| cdot(*x, ee) * v));
313 let (a, b) = (sp(&to, xo), sp(&te, xe));
314 [0, 1, 2].map(|i| a[i] + b[i])
315 };
316 }
317 Ok(())
318}
319
320fn crystal_basis(axis: V3, k: V3, no: f64, ne: f64) -> (V3, V3, f64) {
323 let k = normalize(k);
324 let a = normalize(axis);
325 let ca = dot(a, k);
326 let ep = sub(a, scale(k, ca));
327 let sn = norm(ep);
328 if !(sn > PARALLEL_SIN) {
329 let mut u = cross(k, [1.0, 0.0, 0.0]);
330 if !(norm(u) > 1e-6) {
331 u = cross(k, [0.0, 1.0, 0.0]);
332 }
333 let u = normalize(u);
334 return (u, cross(k, u), no);
335 }
336 let ee = scale(ep, 1.0 / sn);
337 let eo = normalize(cross(k, ee));
338 let nth = 1.0 / (ca * ca / (no * no) + (1.0 - ca * ca) / (ne * ne)).sqrt();
339 (eo, ee, nth)
340}
341
342#[allow(clippy::too_many_arguments)]
347fn pol_surface_cement(
348 ps: &PolSurf,
349 e: &mut [CV3],
350 kin: V3,
351 kl: V3,
352 nv: V3,
353 cosi: f64,
354 a: (V3, f64, f64),
355 b: (V3, f64, f64),
356) -> Result<(), Error> {
357 let PolKind::Iface(f) = &ps.kind else {
358 return pol_surface(ps, e, kin, kl, nv, cosi, false);
359 };
360 let (eo1, ee1, n1e) = crystal_basis(a.0, kin, a.1, a.2);
361 let (eo2, ee2, n2e) = crystal_basis(b.0, kl, b.1, b.2);
362 let mut sv = cross(kin, nv);
363 if !(norm(sv) > PARALLEL_SIN) {
364 sv = cross(kin, [1.0, 0.0, 0.0]);
365 }
366 let sv = normalize(sv);
367 let pin = cross(sv, kin);
368 let pout = cross(sv, kl);
369 let c0 = cosi.abs().clamp(0.0, 1.0);
370 let (n1s, n2s) = ([a.1, n1e], [b.1, n2e]);
372 let mut t = [[[C64::new(0.0, 0.0); 2]; 2]; 2];
373 for i in 0..2 {
374 for j in 0..2 {
375 t[i][j] = f.eval_cos_media(c0, Some(n1s[i]), Some(n2s[j]))?;
376 }
377 }
378 let sp = |t: &[C64; 2], x: CV3| comb(t[0] * cdot(x, sv), sv, t[1] * cdot(x, pin), pout);
379 let (b1, b2) = ([eo1, ee1], [eo2, ee2]);
380 for x in e.iter_mut() {
381 let mut y = [C64::new(0.0, 0.0); 3];
382 for i in 0..2 {
383 let xi = b1[i].map(|v| cdot(*x, b1[i]) * v);
384 for j in 0..2 {
385 let c = cdot(sp(&t[i][j], xi), b2[j]);
386 for m in 0..3 {
387 y[m] += c * b2[j][m];
388 }
389 }
390 }
391 *x = y;
392 }
393 Ok(())
394}
395
396#[allow(clippy::too_many_arguments)]
399pub(crate) fn pol_step(
400 sys: &System,
401 surf: &[PolSurf],
402 j: usize,
403 e: &mut [CV3],
404 cry_state: &mut Option<CryState>,
405 err: &mut Option<Error>,
406 g: (V3, V3, V3, f64),
407 mirror: bool,
408 lam: f64,
409) {
410 let (kin, kl, nv, cosi) = g;
411 let cry = surf[j].cry;
413 let mut xc = None;
415 let mut cem = None;
417 if let (Some(CryKind::Out), Some(c)) = (cry, cry_state.take()) {
418 crystal_phase(&c, e, kin, lam);
419 xc = Some((c.axis, c.no, c.ne, kin, false));
420 if let Some(b) = surf[j].cement {
421 cem = Some(((c.axis, c.no, c.ne), b));
422 }
423 }
424 if let Some(CryKind::In { axis, no, ne, .. }) = cry {
425 xc = Some((axis, no, ne, kl, true));
426 }
427 let r = match (xc, cem) {
428 _ if surf[j].cemented && !mirror => Ok(()),
429 (_, Some((a, b))) if !mirror => pol_surface_cement(&surf[j], e, kin, kl, nv, cosi, a, b),
430 (Some(x), _) if !mirror => pol_surface_crystal(&surf[j], e, kin, kl, nv, cosi, x),
431 _ => pol_surface(&surf[j], e, kin, kl, nv, cosi, mirror),
432 };
433 if let Err(x) = r {
434 err.get_or_insert_with(|| x.at(sys.surf_label(j)));
436 }
437 if let Some(CryKind::In { mode, axis, no, ne }) = cry {
438 *cry_state = Some(CryState {
439 mode,
440 axis,
441 no,
442 ne,
443 len: 0.0,
444 proj: 1.0,
445 });
446 }
447}