1use lensbench_core::{Error, Result, System};
7use lensbench_export::d2::{self, ColorBy, Plane};
8use lensbench_export::mesh;
9use lensbench_export::scene::{self, Fan};
10
11pub const RAYS: (usize, usize) = (1, 200);
13pub const WIDTH: (u32, u32) = (100, 20000);
15pub const SEGMENTS: (usize, usize) = (4, 1024);
17pub const RINGS: (usize, usize) = (1, 256);
19
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
22pub enum View {
23 #[default]
24 #[serde(rename = "yz")]
25 YZ,
26 #[serde(rename = "xz")]
27 XZ,
28 #[serde(rename = "3d")]
29 D3,
30}
31
32impl std::str::FromStr for View {
33 type Err = String;
34 fn from_str(s: &str) -> std::result::Result<View, String> {
35 match s.to_ascii_lowercase().as_str() {
36 "3d" => Ok(View::D3),
37 x => match x.parse::<Plane>()? {
38 Plane::YZ => Ok(View::YZ),
39 Plane::XZ => Ok(View::XZ),
40 },
41 }
42 }
43}
44
45impl View {
46 pub fn plane(self) -> Plane {
48 match self {
49 View::XZ => Plane::XZ,
50 _ => Plane::YZ,
51 }
52 }
53}
54
55#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
57#[serde(rename_all = "snake_case")]
58pub enum Pick {
59 All,
60 List(Vec<usize>),
61}
62
63impl std::str::FromStr for Pick {
64 type Err = String;
65 fn from_str(s: &str) -> std::result::Result<Pick, String> {
67 if s.trim().eq_ignore_ascii_case("all") {
68 return Ok(Pick::All);
69 }
70 s.split(',')
71 .map(|t| t.trim().parse().map_err(|_| format!("number {t}")))
72 .collect::<std::result::Result<_, _>>()
73 .map(Pick::List)
74 }
75}
76
77#[derive(Debug, Clone, Default, PartialEq)]
79pub struct RaySel {
80 pub fields: Option<Pick>,
82 pub waves: Option<Pick>,
84 pub fan: Option<Fan>,
86 pub rays: Option<usize>,
88 pub first: Option<usize>,
89 pub last: Option<usize>,
90 pub unfold: bool,
92}
93
94fn index0(v: &Option<Pick>, n: usize, what: &str) -> Result<Option<Vec<usize>>> {
95 v.as_ref()
96 .map(|v| match v {
97 Pick::All => Ok((0..n).collect()),
98 Pick::List(v) => v
99 .iter()
100 .map(|&k| {
101 if k >= 1 && k <= n {
102 Ok(k - 1)
103 } else {
104 Err(Error::Invalid(format!("no {what} {k} (1 to {n})")))
105 }
106 })
107 .collect(),
108 })
109 .transpose()
110}
111
112impl RaySel {
113 pub fn options(&self, s: &System, view: View) -> Result<scene::Options> {
115 if self.unfold && view == View::D3 {
116 return Err(Error::Invalid(
117 "unfold is only for 2D (plane yz or xz)".into(),
118 ));
119 }
120 let fan = self.fan.unwrap_or(match view {
121 View::D3 => Fan::Ring,
122 View::XZ => Fan::X,
123 View::YZ => Fan::Y,
124 });
125 let n0 = if fan == Fan::Ring { 12 } else { 7 };
126 Ok(scene::Options {
127 fields: index0(&self.fields, s.fields.len(), "field")?,
128 waves: index0(&self.waves, s.wavelengths.len(), "wavelength")?,
129 fan,
130 rays: self.rays.unwrap_or(n0).clamp(RAYS.0, RAYS.1),
131 first: self.first,
132 last: self.last,
133 unfold: self.unfold,
134 })
135 }
136}
137
138#[derive(Clone)]
140pub struct Draw {
141 pub plane: Plane,
143 pub color: Option<ColorBy>,
145 pub width: Option<u32>,
147 pub segments: Option<usize>,
149 pub rings: Option<usize>,
151 pub tube: Option<f64>,
153 pub mech_detail: Option<lensbench_export::detail::Details>,
155}
156
157impl Default for Draw {
158 fn default() -> Draw {
159 Draw {
160 plane: Plane::YZ,
161 color: None,
162 width: None,
163 segments: None,
164 rings: None,
165 tube: None,
166 mech_detail: None,
167 }
168 }
169}
170
171impl Draw {
172 pub fn color(&self, overlay: bool) -> ColorBy {
174 self.color.unwrap_or(if overlay {
175 ColorBy::Config
176 } else {
177 ColorBy::Field
178 })
179 }
180
181 pub fn options(&self, overlay: bool) -> Result<(d2::Options2D, mesh::Options3D)> {
183 if let Some(t) = self.tube {
184 if !(t > 0.0 && t.is_finite()) {
185 return Err(Error::Invalid("tube must be a positive number [mm]".into()));
186 }
187 }
188 let (a, b) = (d2::Options2D::default(), mesh::Options3D::default());
189 let color = self.color(overlay);
190 let segments = self
191 .segments
192 .unwrap_or(a.segments)
193 .clamp(SEGMENTS.0, SEGMENTS.1);
194 Ok((
195 d2::Options2D {
196 plane: self.plane,
197 color,
198 width: self.width.unwrap_or(a.width).clamp(WIDTH.0, WIDTH.1),
199 segments,
200 },
201 mesh::Options3D {
202 segments,
203 rings: self.rings.unwrap_or(b.rings).clamp(RINGS.0, RINGS.1),
204 tube: self.tube,
205 color,
206 mech_detail: self.mech_detail.clone(),
207 },
208 ))
209 }
210}
211
212pub fn offset(v: &[f64]) -> Result<[f64; 3]> {
214 match v {
215 [a, b, c] => Ok([*a, *b, *c]),
216 _ => Err(Error::Invalid("offset takes 3 values dx,dy,dz".into())),
217 }
218}
219
220#[cfg(test)]
221mod tests {
222 use super::*;
223
224 #[test]
225 fn defaults_follow_the_view() {
226 let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
227 let opt = lensbench_formats::zmx::LoadOptions {
228 catalog_dirs: vec![root.join("tests/glass")],
229 ..Default::default()
230 };
231 let s = lensbench_formats::zmx::load_with(&root.join("tests/refs/A0/system.zmx"), &opt)
232 .unwrap();
233 let r = RaySel::default();
234 assert_eq!(r.options(&s, View::YZ).unwrap().fan, Fan::Y);
235 assert_eq!(r.options(&s, View::XZ).unwrap().fan, Fan::X);
236 let o = r.options(&s, View::D3).unwrap();
237 assert_eq!((o.fan, o.rays), (Fan::Ring, 12));
238 let r = RaySel {
239 fields: Some(Pick::List(vec![9])),
240 ..Default::default()
241 };
242 assert!(r.options(&s, View::YZ).is_err());
243 let r = RaySel {
244 unfold: true,
245 rays: Some(1000),
246 ..Default::default()
247 };
248 assert!(r.options(&s, View::D3).is_err());
249 assert_eq!(r.options(&s, View::YZ).unwrap().rays, RAYS.1);
250 let d = Draw::default();
251 assert_eq!(d.color(true), ColorBy::Config);
252 let (a, b) = d.options(false).unwrap();
253 assert_eq!((a.width, b.rings), (1600, 16));
254 assert!(offset(&[1.0, 2.0]).is_err());
255 }
256}