1use std::rc::Rc;
17
18use lensbench_core::math::{
19 add, col, mm, mtv, mv, rot, scale, sub, transpose, xyz_angles, I3, M3, V3,
20};
21use lensbench_core::surface::{Aperture, Material, Reflect, Surface, Tilt};
22use lensbench_core::system::{apply_cb, step_frame};
23use schemars::JsonSchema;
24use serde::{Deserialize, Serialize};
25
26use crate::{Block, Ctx, OffMode, Place};
27
28#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default, JsonSchema)]
30#[serde(rename_all = "snake_case")]
31pub enum SplitForm {
32 #[default]
34 Cube,
35 Plate,
37 Ideal,
39}
40
41#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default, JsonSchema)]
43#[serde(rename_all = "snake_case")]
44pub enum SplitFace {
45 #[default]
46 Front,
47 Back,
48}
49
50#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default, JsonSchema)]
52#[serde(rename_all = "snake_case")]
53pub enum Arm {
54 #[default]
55 T,
56 R,
57}
58
59#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, JsonSchema)]
61pub struct PbsSpec {
62 #[serde(default = "one_f")]
63 pub tp: f64,
64 #[serde(default)]
65 pub ts: f64,
66}
67
68fn one_f() -> f64 {
69 1.0
70}
71
72pub(crate) fn default_angle() -> [f64; 2] {
73 [45.0, 0.0]
74}
75
76#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
78pub struct SplitterSpec {
79 #[serde(default)]
80 pub form: SplitForm,
81 #[serde(default)]
83 pub size: f64,
84 #[serde(default)]
86 pub thickness: f64,
87 #[serde(default)]
89 pub glass: String,
90 #[serde(default)]
92 pub semi: f64,
93 #[serde(default)]
95 pub wedge: [f64; 2],
96 #[serde(default)]
98 pub split_face: SplitFace,
99 #[serde(default = "default_angle")]
101 pub angle: [f64; 2],
102 #[serde(default, skip_serializing_if = "Option::is_none")]
104 pub ratio: Option<f64>,
105 #[serde(default, skip_serializing_if = "String::is_empty")]
107 pub coat: String,
108 #[serde(default, skip_serializing_if = "Option::is_none")]
110 pub pbs: Option<PbsSpec>,
111 #[serde(default, skip_serializing_if = "String::is_empty")]
113 pub ar: String,
114 #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
116 pub faces: std::collections::BTreeMap<String, String>,
117 #[serde(default)]
119 pub arm: Arm,
120 #[serde(default, skip_serializing_if = "Vec::is_empty")]
122 pub t: Vec<Block>,
123 #[serde(default, skip_serializing_if = "Vec::is_empty")]
125 pub r: Vec<Block>,
126 #[serde(default, skip_serializing_if = "Vec::is_empty")]
128 pub d: Vec<Block>,
129}
130
131pub(crate) const A: usize = 0;
132pub(crate) const B: usize = 1;
133const TPAIR: [usize; 4] = [1, 0, 3, 2];
134const RPAIR: [usize; 4] = [2, 3, 0, 1];
135const Y180: M3 = [[-1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, -1.0]];
137const MAX_PASSES: usize = 64;
138
139enum Act {
141 T(String),
143 R(String),
145}
146
147struct Face {
149 o: V3,
150 r: M3,
151 ap: Aperture,
152 coat: String,
153 semi: f64,
154}
155
156impl SplitterSpec {
157 pub(crate) fn branch(&self, port: usize) -> &[Block] {
158 match port {
159 1 => &self.t,
160 2 => &self.r,
161 3 => &self.d,
162 _ => &[],
163 }
164 }
165 pub(crate) fn has_branches(&self) -> bool {
166 !(self.t.is_empty() && self.r.is_empty() && self.d.is_empty())
167 }
168
169 fn split_coat(&self) -> lensbench_core::Result<String> {
171 let n = self.ratio.is_some() as u8 + !self.coat.is_empty() as u8 + self.pbs.is_some() as u8;
172 if n > 1 {
173 return Err("exactly one of ratio, coat and pbs".into());
174 }
175 if let Some(p) = &self.pbs {
176 return Ok(format!("I.s={},p={}", p.ts, p.tp));
177 }
178 if !self.coat.is_empty() {
179 return Ok(self.coat.clone());
180 }
181 let t = self.ratio.unwrap_or(0.5);
182 Ok(format!("I.s={t},p={t}"))
183 }
184
185 fn face_coat(&self, name: &str) -> String {
186 self.faces
187 .get(name)
188 .cloned()
189 .unwrap_or_else(|| self.ar.clone())
190 }
191
192 fn tilt(&self) -> M3 {
194 mm(&rot(0, self.angle[0]), &rot(1, self.angle[1]))
195 }
196
197 pub(crate) fn length(&self) -> f64 {
199 match self.form {
200 SplitForm::Cube => self.size,
201 SplitForm::Plate => self.thickness,
202 SplitForm::Ideal => 0.0,
203 }
204 }
205
206 pub(crate) fn check(&self, id: &str) -> lensbench_core::Result<()> {
207 let e = |m: &str| Err(lensbench_core::Error::Invalid(format!("BS {id}: {m}")));
208 if id.is_empty() {
209 return Err("a BS (splitter) needs an id".into());
210 }
211 self.split_coat().map_err(|m| format!("BS {id}: {m}"))?;
212 if let Some(t) = self.ratio {
213 if !(0.0..=1.0).contains(&t) {
214 return e("ratio must be 0 to 1");
215 }
216 }
217 if let Some(p) = &self.pbs {
218 if !(0.0..=1.0).contains(&p.tp) || !(0.0..=1.0).contains(&p.ts) {
219 return e("pbs tp and ts must be 0 to 1");
220 }
221 }
222 let names: &[&str] = match self.form {
223 SplitForm::Cube => &["a", "b", "c", "d"],
224 SplitForm::Plate => match self.split_face {
225 SplitFace::Front => &["back"],
226 SplitFace::Back => &["front"],
227 },
228 SplitForm::Ideal => &[],
229 };
230 if let Some(k) = self.faces.keys().find(|k| !names.contains(&k.as_str())) {
231 return e(&format!(
232 "no {k} in faces (faces that can take a coating: {})",
233 if names.is_empty() {
234 "none".to_string()
235 } else {
236 names.join(", ")
237 }
238 ));
239 }
240 match self.form {
241 SplitForm::Cube => {
242 let [tx, ty] = self.angle;
243 let ok = (tx.abs() == 45.0 && ty == 0.0) || (ty.abs() == 45.0 && tx == 0.0);
244 if !ok {
245 return e("cube angle must be [±45, 0] or [0, ±45]");
246 }
247 if self.size.is_nan() || self.size <= 0.0 {
248 return e("a cube needs size (the edge length)");
249 }
250 if self.glass.is_empty() {
251 return e("a cube needs glass");
252 }
253 }
254 SplitForm::Plate => {
255 if self.thickness.is_nan() || self.thickness <= 0.0 {
256 return e("a plate needs thickness");
257 }
258 if self.glass.is_empty() {
259 return e("a plate needs glass");
260 }
261 }
262 SplitForm::Ideal => {}
263 }
264 Ok(())
265 }
266
267 fn fold(&self) -> M3 {
270 mm(
271 &self.tilt(),
272 &mm(&rot(1, self.angle[1]), &rot(0, self.angle[0])),
273 )
274 }
275
276 fn dirs(&self) -> (V3, V3) {
278 let n = col(&self.tilt(), 2);
279 let ez = [0.0, 0.0, 1.0];
280 (n, sub(ez, scale(n, 2.0 * n[2])))
281 }
282
283 fn faces(&self) -> Vec<Face> {
284 let r = self.tilt();
285 let r2 = self.fold();
286 let (n, dc) = self.dirs();
287 match self.form {
288 SplitForm::Cube => {
289 let a = self.size;
290 let h = 0.5 * a;
291 let c = [0.0, 0.0, h];
292 let sq = Aperture::Rect {
293 hx: h,
294 hy: h,
295 dx: 0.0,
296 dy: 0.0,
297 };
298 let semi = h * std::f64::consts::SQRT_2;
299 let f = |o: V3, r: M3, name: &str| Face {
300 o,
301 r,
302 ap: sq,
303 coat: self.face_coat(name),
304 semi,
305 };
306 let (hx, hy) = if self.angle[0] != 0.0 {
307 (h, semi)
308 } else {
309 (semi, h)
310 };
311 vec![
312 f([0.0; 3], I3, "a"),
313 f([0.0, 0.0, a], I3, "b"),
314 f(add(c, scale(dc, h)), r2, "c"),
315 f(add(c, scale(dc, -h)), r2, "d"),
316 Face {
317 o: c,
318 r,
319 ap: Aperture::Rect {
320 hx,
321 hy,
322 dx: 0.0,
323 dy: 0.0,
324 },
325 coat: String::new(),
326 semi: hx.max(hy),
327 },
328 ]
329 }
330 SplitForm::Plate => {
331 let ap = if self.semi > 0.0 {
332 Aperture::Circular {
333 min: 0.0,
334 max: self.semi,
335 dx: 0.0,
336 dy: 0.0,
337 }
338 } else {
339 Aperture::None
340 };
341 let rk = mm(&mm(&r, &rot(0, self.wedge[0])), &rot(1, self.wedge[1]));
342 vec![
343 Face {
344 o: [0.0; 3],
345 r,
346 ap,
347 coat: self.face_coat("front"),
348 semi: self.semi,
349 },
350 Face {
351 o: scale(n, self.thickness),
352 r: rk,
353 ap,
354 coat: self.face_coat("back"),
355 semi: self.semi,
356 },
357 ]
358 }
359 SplitForm::Ideal => vec![Face {
360 o: [0.0; 3],
361 r,
362 ap: if self.semi > 0.0 {
363 Aperture::Circular {
364 min: 0.0,
365 max: self.semi,
366 dx: 0.0,
367 dy: 0.0,
368 }
369 } else {
370 Aperture::None
371 },
372 coat: String::new(),
373 semi: self.semi,
374 }],
375 }
376 }
377
378 fn split_index(&self) -> usize {
380 match (self.form, self.split_face) {
381 (SplitForm::Cube, _) => 4,
382 (SplitForm::Plate, SplitFace::Front) => 0,
383 (SplitForm::Plate, SplitFace::Back) => 1,
384 (SplitForm::Ideal, _) => 0,
385 }
386 }
387
388 fn seq(&self, p: usize, t: bool) -> (Vec<(usize, Act)>, usize) {
390 let out = if t { TPAIR[p] } else { RPAIR[p] };
391 let g = || self.glass.clone();
392 let air = || "AIR".to_string();
393 let v = match self.form {
394 SplitForm::Cube => vec![
395 (p, Act::T(g())),
396 (4, if t { Act::T(g()) } else { Act::R(g()) }),
397 (out, Act::T(air())),
398 ],
399 SplitForm::Ideal => vec![(0, if t { Act::T(air()) } else { Act::R(air()) })],
400 SplitForm::Plate => {
401 let front_side = p == 0 || p == 2;
403 let (s, o) = match self.split_face {
404 SplitFace::Front => (0, 1),
405 SplitFace::Back => (1, 0),
406 };
407 let on_split_side = front_side == (s == 0);
409 if on_split_side {
410 if t {
411 vec![(s, Act::T(g())), (o, Act::T(air()))]
412 } else {
413 vec![(s, Act::R(g()))]
414 }
415 } else if t {
416 vec![(o, Act::T(g())), (s, Act::T(air()))]
417 } else {
418 vec![(o, Act::T(g())), (s, Act::R(air())), (o, Act::T(air()))]
419 }
420 }
421 };
422 (v, out)
423 }
424
425 fn port(&self, p: usize) -> (V3, M3) {
427 let r2 = self.fold();
428 let (n, dc) = self.dirs();
429 let (oc, od) = match self.form {
430 SplitForm::Cube => {
431 let h = 0.5 * self.size;
432 let c = [0.0, 0.0, h];
433 (add(c, scale(dc, h)), add(c, scale(dc, -h)))
434 }
435 SplitForm::Plate => {
436 let v = match self.split_face {
437 SplitFace::Front => [0.0; 3],
438 SplitFace::Back => scale(n, self.thickness),
439 };
440 (v, v)
441 }
442 SplitForm::Ideal => ([0.0; 3], [0.0; 3]),
443 };
444 match p {
445 0 => ([0.0; 3], Y180),
446 1 => ([0.0, 0.0, self.length()], I3),
447 2 => (oc, mm(&r2, &Y180)),
448 _ => (od, r2),
449 }
450 }
451}
452
453#[derive(Clone)]
455pub(crate) struct SplitInfo {
456 s: (V3, M3),
458 fwd: usize,
460 off: bool,
461 parent: Rc<Vec<Block>>,
463 pidx: usize,
464 plevel: Level,
465 spec: Rc<SplitterSpec>,
466 id: String,
467}
468
469#[derive(Clone, Debug)]
471pub(crate) enum Level {
472 Other,
474 Branch { key: String, port: usize },
476}
477
478#[derive(Default)]
480pub(crate) struct SplitState {
481 pub path: Vec<bool>,
482 pub pos: usize,
483 pub strict: bool,
484 pub info: std::collections::HashMap<String, SplitInfo>,
485 pub levels: Vec<Level>,
486 pub stopped: bool,
488 pub done: bool,
490 pub passes: usize,
491 pub need: bool,
493 pub loose: bool,
495}
496
497pub(crate) fn parse_path(s: &str) -> lensbench_core::Result<Vec<bool>> {
499 s.chars()
500 .filter(|c| !c.is_whitespace())
501 .map(|c| match c {
502 'T' | 't' => Ok(true),
503 'R' | 'r' => Ok(false),
504 _ => Err(format!("path {s}: letters must be T or R").into()),
505 })
506 .collect()
507}
508
509impl<'a, 'b> Ctx<'a, 'b> {
510 fn split_key(&self, id: &str) -> String {
511 let mut k = String::new();
512 for l in &self.loading[self.outer..] {
513 if let Some(it) = &l.item {
514 k.push_str(&format!("{}#{it}/", l.file.display()));
515 }
516 }
517 k.push_str(id);
518 k
519 }
520
521 fn letter(&mut self, arm: Arm) -> lensbench_core::Result<bool> {
522 let st = &mut self.split;
523 st.passes += 1;
524 if st.passes > MAX_PASSES {
525 return Err(format!(
526 "the BS is passed more than {MAX_PASSES} times (the path keeps coming back)"
527 )
528 .into());
529 }
530 if st.pos < st.path.len() {
531 st.pos += 1;
532 return Ok(st.path[st.pos - 1]);
533 }
534 if st.strict {
535 st.need = true;
537 return Err("the BS path has too few letters".into());
538 }
539 Ok(arm == Arm::T)
540 }
541
542 fn current_frame(&self) -> (V3, M3) {
544 let (mut o, mut r) = ([0.0; 3], I3);
545 for d in &self.sf {
546 (_, (o, r)) = step_frame(o, r, d);
547 }
548 (o, r)
549 }
550
551 fn goto(&mut self, ot: V3, rt: M3) {
553 if self.sf.is_empty() {
554 self.put(crate::cb([0.0; 5], 0, 0.0));
555 }
556 let (o, r) = self.current_frame();
557 let dv = mtv(&r, sub(ot, o));
558 let ang = xyz_angles(&mm(&transpose(&r), &rt));
559 let snap = |v: f64, eps: f64| if v.abs() < eps { 0.0 } else { v };
560 let dn = mtv(&rt, sub(ot, o));
563 let turn = ang.iter().any(|a| a.abs() >= 1e-10);
564 if turn && dn[0].abs() < 1e-12 && dn[1].abs() < 1e-12 && dn[2].abs() >= 1e-12 {
565 let d = [
566 0.0,
567 0.0,
568 snap(ang[0], 1e-10),
569 snap(ang[1], 1e-10),
570 snap(ang[2], 1e-10),
571 ];
572 self.put(crate::cb(d, 0, dn[2]));
573 return;
574 }
575 let d = [
576 snap(dv[0], 1e-12),
577 snap(dv[1], 1e-12),
578 snap(ang[0], 1e-10),
579 snap(ang[1], 1e-10),
580 snap(ang[2], 1e-10),
581 ];
582 self.sf.last_mut().expect("non-empty surfaces").t += snap(dv[2], 1e-12);
583 if d.iter().any(|&v| v != 0.0) {
584 self.put(crate::cb(d, 0, 0.0));
585 }
586 }
587
588 fn split_pass(&mut self, key: &str, p: usize, t: bool) -> lensbench_core::Result<usize> {
590 let info = self.split.info[key].clone();
591 let sp = &info.spec;
592 let faces = sp.faces();
593 let coat = sp.split_coat()?;
594 let si = sp.split_index();
595 let (so, sr) = info.s;
596 let (v, out) = sp.seq(p, t);
597 for (k, act) in v {
598 let f = &faces[k];
599 self.goto(add(so, mv(&sr, f.o)), mm(&sr, &f.r));
600 let c = if k == si {
601 coat.clone()
602 } else {
603 f.coat.clone()
604 };
605 let mut s = Surface {
606 ap: f.ap,
607 semi: f.semi,
608 coat: c,
609 comment: format!("{} {}", info.id, if k == si { "split" } else { "face" }),
610 ..Default::default()
611 };
612 match act {
613 Act::T(m) => s.mat = Material::parse(&m),
614 Act::R(m) => {
615 s.mat = Material::Mirror;
616 s.reflect = Some(Reflect {
617 mat: m,
618 n: Vec::new(),
619 });
620 self.parity = -self.parity;
621 }
622 }
623 self.put(s);
624 }
625 let (po, pr) = sp.port(out);
626 let pr = if self.parity < 0.0 {
627 mm(&pr, &Y180)
628 } else {
629 pr
630 };
631 self.goto(add(so, mv(&sr, po)), mm(&sr, &pr));
632 Ok(out)
633 }
634
635 fn traverse_branch(&mut self, key: &str, port: usize) -> lensbench_core::Result<()> {
637 let spec = self.split.info[key].spec.clone();
638 let bl = spec.branch(port);
639 self.split.levels.push(Level::Branch {
640 key: key.to_string(),
641 port,
642 });
643 let mut r = Ok(());
644 for (i, x) in bl.iter().enumerate() {
645 if self.split.done {
646 break;
647 }
648 r = self.block(x, bl, i);
649 if r.is_err() {
650 break;
651 }
652 }
653 self.split.levels.pop();
654 r?;
655 self.split.done = true;
656 Ok(())
657 }
658
659 pub(crate) fn splitter_forward(
661 &mut self,
662 id: &str,
663 spec: &SplitterSpec,
664 place: &Place,
665 siblings: &[Block],
666 idx: usize,
667 ) -> lensbench_core::Result<()> {
668 spec.check(id)?;
669 if spec.has_branches() && idx + 1 < siblings.len() {
670 return Err(format!(
671 "BS {id}: no block can go after a BS with branches (t, r, d); write it in the branch"
672 ).into());
673 }
674 let key = self.split_key(id);
675 let level = self.split.levels.last().cloned().unwrap_or(Level::Other);
676 if self.sf.is_empty() {
677 self.put(crate::cb([0.0; 5], 0, 0.0));
678 }
679 let (o, r) = self.current_frame();
680 let r = if self.parity < 0.0 { mm(&r, &Y180) } else { r };
681 let [dx, dy] = place.decenter;
682 let [tx, ty, tz] = place.tilt;
683 let s = apply_cb(
684 o,
685 r,
686 &Tilt {
687 d: [dx, dy, tx, ty, tz],
688 order: 0,
689 },
690 );
691 self.split.info.insert(
692 key.clone(),
693 SplitInfo {
694 s,
695 fwd: B,
696 off: !place.on,
697 parent: Rc::new(siblings.to_vec()),
698 pidx: idx,
699 plevel: level,
700 spec: Rc::new(spec.clone()),
701 id: id.to_string(),
702 },
703 );
704 if !place.on {
705 if place.off == OffMode::Air {
706 self.gap(spec.length());
707 }
708 if spec.has_branches() {
709 self.traverse_branch(&key, B)?;
710 }
711 return Ok(());
712 }
713 let t = self.letter(spec.arm)?;
714 let start = self.sf.len();
715 let out = self.split_pass(&key, A, t)?;
716 self.tag_split(id, start);
717 if spec.has_branches() {
718 self.traverse_branch(&key, out)?;
719 } else {
720 self.split
721 .info
722 .get_mut(&key)
723 .expect("entry inserted above")
724 .fwd = out;
725 }
726 Ok(())
727 }
728
729 pub(crate) fn splitter_back(&mut self, id: &str) -> lensbench_core::Result<()> {
731 let key = self.split_key(id);
732 let Some(info) = self.split.info.get(&key).cloned() else {
733 return Err(format!("BS {id}: not passed on the way out").into());
734 };
735 if info.off {
736 if info.spec.length() != 0.0 && self.split_off_air(&info) {
737 self.gap(info.spec.length());
738 }
739 return Ok(());
740 }
741 let t = self.letter(info.spec.arm)?;
742 let start = self.sf.len();
743 let out = self.split_pass(&key, info.fwd, t)?;
744 self.tag_split(id, start);
745 if out != A {
746 self.split.stopped = true;
747 self.split.loose = true;
748 }
749 Ok(())
750 }
751
752 fn tag_split(&mut self, id: &str, start: usize) {
756 if id.is_empty() {
757 return;
758 }
759 for o in &mut self.map[start..] {
760 if !o.blocks.iter().any(|b| b == id) {
761 o.blocks.push(id.to_string());
762 }
763 }
764 }
765
766 fn split_off_air(&self, info: &SplitInfo) -> bool {
767 match &info.parent[info.pidx] {
768 Block::Splitter { place, .. } => place.off == OffMode::Air,
769 _ => false,
770 }
771 }
772
773 pub(crate) fn return_at(&mut self, level: Level) -> lensbench_core::Result<()> {
775 let Level::Branch { key, port } = level else {
776 return Ok(());
777 };
778 let info = self.split.info[&key].clone();
779 if info.off {
780 if self.split_off_air(&info) {
781 self.gap(info.spec.length());
782 }
783 } else {
784 let t = self.letter(info.spec.arm)?;
785 let start = self.sf.len();
786 let out = self.split_pass(&key, port, t)?;
787 self.tag_split(&info.id, start);
788 if out != A {
789 if !info.spec.branch(out).is_empty() {
790 self.traverse_branch(&key, out)?;
791 }
792 self.split.stopped = true;
793 return Ok(());
794 }
795 }
796 for x in info.parent[..info.pidx].iter().rev() {
797 self.back_block(x)?;
798 if self.split.stopped {
799 return Ok(());
800 }
801 }
802 self.return_at(info.plevel.clone())
803 }
804}
805
806pub fn paths(p: &crate::Project, env: &crate::Env) -> lensbench_core::Result<Vec<String>> {
811 paths_cached(p, env, &crate::SourceCache::default())
812}
813
814pub fn paths_cached(
816 p: &crate::Project,
817 env: &crate::Env,
818 cache: &crate::SourceCache,
819) -> lensbench_core::Result<Vec<String>> {
820 let mut out = Vec::new();
821 let mut todo = vec![String::new()];
822 while let Some(q) = todo.pop() {
823 match crate::expand::expand_inner(p, env, Some(&q), true, Some(cache), &[])
824 .map_err(crate::ExpandError::into_error)
825 {
826 Ok(crate::expand::Walk::Done(_) | crate::expand::Walk::Walked) => out.push(q),
827 Ok(crate::expand::Walk::Need) => {
828 if out.len() + todo.len() > 1024 {
829 return Err("more than 1024 paths".into());
830 }
831 todo.push(format!("{q}R"));
832 todo.push(format!("{q}T"));
833 }
834 Err(e) => {
835 return Err(if q.is_empty() {
836 e
837 } else {
838 format!("path {q}: {e}").into()
839 })
840 }
841 }
842 }
843 if out == [""] {
844 out.clear();
845 }
846 out.sort_by(|a, b| a.len().cmp(&b.len()).then(b.cmp(a)));
847 Ok(out)
848}