lensbench_project/
beams.rs1use lensbench_core::error::{code, Error};
4use schemars::JsonSchema;
5use serde::{Deserialize, Serialize};
6
7use crate::Project;
8
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
11#[serde(rename_all = "lowercase")]
12pub enum BeamRole {
13 Sample,
15 Reference,
17 Stray,
19}
20
21#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
24#[serde(deny_unknown_fields)]
25pub struct Beam {
26 pub name: String,
28 #[serde(default, skip_serializing_if = "Option::is_none")]
30 pub path: Option<String>,
31 #[serde(default, skip_serializing_if = "Option::is_none")]
33 pub state: Option<String>,
34 #[serde(default, skip_serializing_if = "Option::is_none")]
36 pub role: Option<BeamRole>,
37 #[serde(default, skip_serializing_if = "Option::is_none")]
41 pub turn: Option<crate::edit_spec::BlockFace>,
42 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
44 pub off: bool,
45}
46
47impl Project {
48 pub fn check_beams(&self) -> lensbench_core::Result<()> {
50 for (i, b) in self.beams.iter().enumerate() {
51 let name = &b.name;
52 if name.trim().is_empty() {
53 return Err(format!("beam {}: the name is empty", i + 1).into());
54 }
55 if ["0", "ref", "reference"].contains(&name.trim().to_ascii_lowercase().as_str()) {
56 return Err(format!(
57 "beam {name}: 0, ref and reference mean the reference sphere in interference (use another name)"
58 )
59 .into());
60 }
61 if self.beams[..i].iter().any(|c| c.name == *name) {
62 return Err(format!("two or more beams named {name}").into());
63 }
64 if self.states.iter().any(|s| s.name == *name) {
65 return Err(format!("beam {name}: a state has the same name").into());
66 }
67 if let Some(st) = &b.state {
68 if !self.states.iter().any(|s| s.name == *st) {
69 return Err(Error::Invalid(format!("beam {name}: no state {st}"))
70 .with_code(code::STATE_NOT_FOUND));
71 }
72 }
73 if let Some(path) = &b.path {
74 crate::splitter::parse_path(path).map_err(|e| format!("beam {name}: {e}"))?;
75 }
76 if let Some(t) = &b.turn {
77 if t.back || t.coordbrk {
78 return Err(format!(
79 "beam {name}: turn takes a surface on the way out (not back or coordbrk)"
80 )
81 .into());
82 }
83 if t.block.is_empty() {
84 return Err(format!("beam {name}: turn needs a block id").into());
85 }
86 }
87 }
88 Ok(())
89 }
90
91 pub fn beam_names(&self) -> Vec<&str> {
93 self.beams.iter().map(|b| b.name.as_str()).collect()
94 }
95
96 pub fn beam(&self, name: &str) -> Option<&Beam> {
98 self.beams.iter().find(|b| b.name == name)
99 }
100
101 pub fn beam_takes_path(&self, name: &str, path_given: bool) -> lensbench_core::Result<()> {
103 if path_given && self.beam(name).is_some_and(|b| b.path.is_some()) {
104 return Err(Error::Invalid(format!(
105 "beam {name} has its own path, so another path can't be given"
106 ))
107 .with_code(code::BAD_ARGUMENT));
108 }
109 Ok(())
110 }
111
112 pub fn with_state_and_path(
114 &self,
115 name: &str,
116 path_given: bool,
117 ) -> lensbench_core::Result<Project> {
118 self.beam_takes_path(name, path_given)?;
119 self.with_state(name)
120 }
121}
122
123pub fn face_var(name: &str) -> Option<(&str, usize, &str)> {
126 let (block, rest) = name.trim().split_once(':')?;
127 let (k, kind) = rest.split_once('.')?;
128 let k = k.trim().parse().ok()?;
129 let block = block.trim();
130 (!block.is_empty() && !kind.trim().is_empty()).then_some((block, k, kind.trim()))
131}
132
133pub fn face_surfaces(
136 s: &lensbench_core::System,
137 spans: &[crate::BlockSpans],
138 block: &str,
139 surface: usize,
140) -> lensbench_core::Result<Vec<usize>> {
141 let Some(b) = spans.iter().find(|b| b.id == block) else {
142 return Ok(Vec::new());
143 };
144 let faces = |r: &[usize; 2]| -> Vec<usize> {
145 (r[0]..=r[1].min(s.surfaces.len().saturating_sub(1)))
146 .filter(|&j| !s.surfaces[j].is_coord_break())
147 .collect()
148 };
149 let mut out = Vec::new();
150 for r in &b.forward {
151 let f = faces(r);
152 let Some(&j) = f.get(surface) else {
153 return Err(format!("block {block} surface {surface} ({} surfaces)", f.len()).into());
154 };
155 out.push(j);
156 }
157 for r in &b.back {
158 let f = faces(r);
159 if let Some(k) = f.len().checked_sub(surface + 1) {
161 out.push(f[k]);
162 }
163 }
164 Ok(out)
165}