Skip to main content

lensbench_export/
lib.rs

1//! lensbench の書き出し: レイアウト(2D: SVG・PNG・DXF、3D: glTF・OBJ・STL・STEP)と追跡結果(CSV・JSON・npz)。
2//!
3//! レイアウトは [`scene::build`] で系から場面(玉の立体・鏡・面・光線)を作り、各形式の書き手に渡す。
4
5#![warn(unreachable_pub)]
6// 入力次第で panic しないように、ライブラリでは unwrap・panic を使わない。前に確かめた形は expect に理由を書く(試験は対象外)
7// 添字で回す数値計算のループはそのままにする
8#![allow(clippy::needless_range_loop)]
9
10pub mod d2;
11pub mod detail;
12pub mod image;
13pub mod mesh;
14pub mod scene;
15pub mod step;
16pub mod step_embed;
17pub mod table;
18
19use std::path::Path;
20
21/// 8 bit の色
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub struct Rgb(pub u8, pub u8, pub u8);
24
25impl Rgb {
26    pub fn hex(self) -> String {
27        format!("#{:02x}{:02x}{:02x}", self.0, self.1, self.2)
28    }
29    /// 白に寄せた薄い色(機構部品に切られた後ろの光線。`k` は元の色の割合)
30    pub fn faint(self, k: f64) -> Rgb {
31        let f = |v: u8| (v as f64 * k + 255.0 * (1.0 - k)).round().clamp(0.0, 255.0) as u8;
32        Rgb(f(self.0), f(self.1), f(self.2))
33    }
34    pub fn linear(self) -> [f32; 3] {
35        // sRGB → 線形(glTF の色は線形)
36        [self.0, self.1, self.2].map(|v| {
37            let c = v as f32 / 255.0;
38            if c <= 0.04045 {
39                c / 12.92
40            } else {
41                ((c + 0.055) / 1.055).powf(2.4)
42            }
43        })
44    }
45}
46
47/// 視野・波長の色(OpticStudio のレイアウトに近い並び: 青・緑・赤・…)
48pub fn palette(i: usize) -> Rgb {
49    const P: [Rgb; 12] = [
50        Rgb(0, 0, 255),
51        Rgb(0, 160, 0),
52        Rgb(220, 0, 0),
53        Rgb(230, 170, 0),
54        Rgb(200, 0, 200),
55        Rgb(0, 170, 190),
56        Rgb(110, 60, 0),
57        Rgb(110, 110, 110),
58        Rgb(0, 0, 120),
59        Rgb(0, 90, 0),
60        Rgb(120, 0, 0),
61        Rgb(255, 100, 0),
62    ];
63    P[i % P.len()]
64}
65
66/// レイアウトの書き出し形式(拡張子で決める)
67#[derive(Debug, Clone, Copy, PartialEq, Eq)]
68pub enum LayoutFormat {
69    Svg,
70    Png,
71    Dxf,
72    Gltf,
73    Glb,
74    Obj,
75    Stl,
76    Step,
77}
78
79impl LayoutFormat {
80    /// 2D の形式か(svg・png・dxf)
81    pub fn is_2d(self) -> bool {
82        matches!(
83            self,
84            LayoutFormat::Svg | LayoutFormat::Png | LayoutFormat::Dxf
85        )
86    }
87
88    pub fn from_path(p: &Path) -> Option<LayoutFormat> {
89        let e = p.extension()?.to_str()?.to_ascii_lowercase();
90        Some(match e.as_str() {
91            "svg" => LayoutFormat::Svg,
92            "png" => LayoutFormat::Png,
93            "dxf" => LayoutFormat::Dxf,
94            "gltf" => LayoutFormat::Gltf,
95            "glb" => LayoutFormat::Glb,
96            "obj" => LayoutFormat::Obj,
97            "stl" => LayoutFormat::Stl,
98            "step" | "stp" => LayoutFormat::Step,
99            _ => return None,
100        })
101    }
102}
103
104/// 書き出した結果([`write_layout`])
105#[derive(Debug, Clone)]
106pub struct Written {
107    pub format: LayoutFormat,
108    /// 利用者に見せる注意(STEP に写した品の長さを直せなかった実体など)
109    pub notes: Vec<String>,
110}
111
112/// 場面を書き出す(形式はファイルの拡張子で決める)
113pub fn write_layout(
114    path: &Path,
115    sc: &scene::Scene,
116    o2: &d2::Options2D,
117    o3: &mesh::Options3D,
118) -> lensbench_core::Result<Written> {
119    let f = LayoutFormat::from_path(path).ok_or_else(|| {
120        lensbench_core::Error::from(format!(
121            "{}: the extension must be svg, png, dxf, gltf, glb, obj, stl, step or stp",
122            path.display()
123        ))
124    })?;
125    // 中身を作ってから書く(wasm ではファイルの置き場へ、lensbench_core::vfs)
126    let mut w: Vec<u8> = Vec::new();
127    let mut notes = Vec::new();
128    let r = match f {
129        LayoutFormat::Svg => d2::write_svg(&mut w, sc, o2),
130        LayoutFormat::Png => d2::write_png(&mut w, sc, o2),
131        LayoutFormat::Dxf => d2::write_dxf(&mut w, sc, o2),
132        LayoutFormat::Gltf => mesh::write_gltf(&mut w, sc, o3, false),
133        LayoutFormat::Glb => mesh::write_gltf(&mut w, sc, o3, true),
134        LayoutFormat::Obj => mesh::write_obj(&mut w, sc, o3),
135        LayoutFormat::Stl => mesh::write_stl(&mut w, sc, o3),
136        LayoutFormat::Step => {
137            let os = step::OptionsStep {
138                mech_detail: o3.mech_detail.clone(),
139                ..Default::default()
140            };
141            step::write_step(&mut w, sc, &os).map(|rep| notes = rep.notes)
142        }
143    };
144    r.and_then(|_| lensbench_core::vfs::write(path, w))
145        .map_err(lensbench_core::Error::io_at(path.display()))?;
146    Ok(Written { format: f, notes })
147}