Skip to main content

lensbench_engine/
layout.rs

1//! レイアウトの描き方の設定(CLI の `layout` と serve の `layout`・`layout_export` で共通)
2//!
3//! 光線の選び方([`RaySel`])と書き出しの形([`Draw`])の既定値・範囲はここだけに書く。CLI は旗から、serve は params
4//! の JSON からこの型を作り、同じ関数で場面と書き出しの設定にする。
5
6use lensbench_core::{Error, Result, System};
7use lensbench_export::d2::{self, ColorBy, Plane};
8use lensbench_export::mesh;
9use lensbench_export::scene::{self, Fan};
10
11/// 光線の本数の範囲
12pub const RAYS: (usize, usize) = (1, 200);
13/// PNG の幅の範囲 [px]
14pub const WIDTH: (u32, u32) = (100, 20000);
15/// 周の分割の範囲
16pub const SEGMENTS: (usize, usize) = (4, 1024);
17/// 半径の分割の範囲
18pub const RINGS: (usize, usize) = (1, 256);
19
20/// 見る面: 断面図(yz・xz)か 3D
21#[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    /// 断面図の面(3D なら yz)
47    pub fn plane(self) -> Plane {
48        match self {
49            View::XZ => Plane::XZ,
50            _ => Plane::YZ,
51        }
52    }
53}
54
55/// 視野・波長の選び方: 全部か、番号(1 始まり)の並び
56#[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    /// "all" か、カンマ区切りの番号
66    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/// 描く光線の選び方
78#[derive(Debug, Clone, Default, PartialEq)]
79pub struct RaySel {
80    /// 視野(None で全視野)
81    pub fields: Option<Pick>,
82    /// 波長(None で主波長だけ)
83    pub waves: Option<Pick>,
84    /// 光線の並び(None で 3D は円周、xz 面は x の扇、ほかは y の扇)
85    pub fan: Option<Fan>,
86    /// 光線の本数(None で円周は 12、ほかは 7)
87    pub rays: Option<usize>,
88    pub first: Option<usize>,
89    pub last: Option<usize>,
90    /// 光路に沿って展開する(2D だけ)
91    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    /// 系 s を view で描く場面の設定
114    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/// 書き出しの形
139#[derive(Clone)]
140pub struct Draw {
141    /// 2D の面(3D の書き出しでは使わない)
142    pub plane: Plane,
143    /// 光線の色分け(None で重ね描きなら構成ごと、ほかは視野ごと)
144    pub color: Option<ColorBy>,
145    /// PNG の幅(None で既定)
146    pub width: Option<u32>,
147    /// 周の分割(None で既定)
148    pub segments: Option<usize>,
149    /// 半径の分割(None で既定)
150    pub rings: Option<usize>,
151    /// 光線の管の半径 [mm]
152    pub tube: Option<f64>,
153    /// 機構部品を取った STEP の詳しい形(None で簡易外形)
154    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    /// 色分け(overlay は構成を重ね描きするか)
173    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    /// 2D・3D の書き出しの設定
182    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
212/// 構成ごとのずらし dx,dy,dz(3 つでなければ誤り)
213pub 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}