Skip to main content

lensbench_sdk/
lib.rs

1//! lensbench の拡張の SDK: 外のクレートが依存するのはこのクレート 1 つ。
2//!
3//! 外のクレートは足すもの(プラグイン・解析・検出器・利用者定義の面・光源・材料・カタログの形式・膜のカタログ・誤りの文の訳、GUI の見せ方、
4//! Python の関数)を [`Extensions`] 1 つにまとめる関数を持ち、自分の exe・wheel の入口でそれを渡す:
5//!
6//! ```ignore
7//! fn main() -> std::process::ExitCode {
8//!     lensbench_sdk::cli::main(my_ext::extensions())
9//! }
10//! ```
11//!
12//! GUI は [`gui::main`](feature `gui`)、Python の拡張モジュールは [`py::module`](feature `py`)、Web 版は
13//! [`web`](feature `web` と、画面用は `gui`、計算の Web Worker 用は `web-worker`)。
14//!
15//! **約束の型** はこのクレートが再輸出するものだけ(下のモジュール)。各クレートのほかの pub は中の都合で変わる。
16//! 0.x の間はマイナー版で約束の型を壊してよく、壊す変更は CHANGELOG の「拡張の約束」に書く。外は git のタグか
17//! rev で参照する。pyo3・egui は境を越える型なので、外は [`py::pyo3`]・[`gui::egui`] だけを使い、自分の Cargo.toml に
18//! 直接の依存を書かない(版がずれると型が合わない)。
19
20pub use lensbench_core::{Error, Result};
21pub use lensbench_engine::Extensions;
22// 解析の設定・結果の型に使う(derive は `#[serde(crate = "lensbench_sdk::serde")]`・
23// `#[schemars(crate = "lensbench_sdk::schemars")]` を付ける)
24pub use schemars;
25pub use serde;
26pub use serde_json;
27
28/// 検出器・解析のプラグイン(名前つきの配列を受けて返す)
29pub mod plugin {
30    /// 中断を頼まれていれば `Error::Cancelled`(重い解析のループで呼ぶ)
31    pub use lensbench_core::par::check_cancel;
32    pub use lensbench_core::plugin::{
33        Array, ArrayReader, Arrays, Config, ConfigReader, Context, Data, Instance, Kind, Linear,
34        OutputSpec, ParamSpec, ParamType, Plugin, Registry, Spec, Value,
35    };
36}
37
38/// 解析(CLI のサブコマンド・serve の analyze・GUI の解析)
39pub mod analysis {
40    pub use lensbench_analysis::{Analysis, Cx, Meta, Param, ParamTy, Saved, Source, Variant};
41}
42
43/// 系(読むだけ)と、プロジェクトからの展開
44pub mod system {
45    pub use lensbench_core::param::Param;
46    pub use lensbench_core::System;
47    pub use lensbench_project::{expand, BlockAt, Env, ExpandError, ExpandOpts, Project};
48}
49
50/// 追跡の要求と結果
51pub mod trace {
52    pub use lensbench_analysis::raygrid::RayGrid;
53    pub use lensbench_core::system::{
54        Cols, FieldSel, Launch, ObjSpec, PolIn, PolTrace, RayBuf, RecSel, Trace, TraceOpts,
55    };
56    pub use lensbench_core::trace::{RayCounts, RayOut, RayStatus};
57}
58
59/// 利用者定義の面のモデル
60pub mod surface {
61    /// Zernike の多項式(Standard は Noll の順で OpticStudio と同じ正規化、Fringe の順は正規化なし)。
62    /// `ZernSag::new(fringe, 半径, 係数, 外挿)`・`term(j, x, y)`・`max_terms(fringe)`
63    pub use lensbench_core::freeform::ZernSag;
64    pub use lensbench_core::usersurf::{check_flip, Flip, SurfaceInstance, SurfaceModel};
65}
66
67/// 利用者定義の形のモデル(面の種類 USERSHAPE: 二次曲面に足す矢高と勾配。追跡・grad・偏光・膜・反転は本体が受け持つ)
68pub mod shape {
69    pub use lensbench_core::usershape::{check_shape, ShapeInstance, ShapeModel};
70}
71
72/// 利用者定義の光源(設定から光線の始点・方向・重みを作る。追跡は `trace::Launch::Rays`、物体の座標系から大域へは
73/// `System::source_rays`)
74pub mod source {
75    pub use lensbench_core::usersource::{check_source, SourceInstance, SourceModel, SourceRays};
76}
77
78/// 利用者定義の材料(名前つきのカタログの単位で足し、AGF のカタログと同じに名前で引く)
79pub mod material {
80    pub use lensbench_core::usermaterial::{check_material, MaterialModel};
81}
82
83/// 膜のカタログ: 膜のファイル形式(拡張子ごとの読み手)と、名前つきの膜の一覧。膜の中身は層の並びとその材料・TABLE・
84/// 特性行列のモデル・実測表・係数を計算で返す膜(`CoatingModel`)。同じ名前の膜の引く順は `lensbench_core::usercoating` の文書
85pub mod coating {
86    pub use lensbench_core::coating::{
87        parse_measured, parse_models, CoatModel, CoatingFile, Layer, Measured, Table, C64,
88    };
89    pub use lensbench_core::usercoating::{
90        check_coating_model, check_coatings, CoatCoefs, CoatInput, CoatPath, CoatingModel,
91        CoatingSet, CoatingSource,
92    };
93}
94
95/// レンズカタログの形式
96pub mod catalog {
97    pub use lensbench_core::catalog::{CatalogLens, LensCatalogSource};
98}
99
100/// プロジェクトの検出器のブロック
101pub mod detector {
102    pub use lensbench_project::detectors::DetectorKind;
103}
104
105/// 足し忘れの検査: GUI の見せ方の無い解析、検出器の欄の無い検出器(feature `gui` のとき)、反転の約束を守らない
106/// 利用者定義の面のモデル、約束(有限・勾配と微分が差分と合う)を守らない利用者定義の形のモデル、約束(有限・重みが 0 以上・同じ設定で同じ光線)を守らない光源のモデル、
107/// 約束を守らない・同じカタログに同じ名前のある材料のモデル(同梱のガラスのカタログと同じ名前の材料のカタログは、
108/// 表を作れない誤りとして挙がる)、約束を守らない膜の一覧(2 つの一覧の同じ名前の膜は、表を作れない誤りとして挙がる)。見つけたものの説明を返す(空なら問題なし)。雛形と exe の試験で呼ぶ
109pub fn check(ext: &Extensions) -> Vec<String> {
110    let mut out = Vec::new();
111    let table = match ext.ext() {
112        Ok(t) => t,
113        Err(e) => return vec![e.to_string()],
114    };
115    #[cfg(feature = "gui")]
116    {
117        for a in ext.analysis_names() {
118            if !lensbench_gui::ext::has_analysis(&table, a) {
119                out.push(format!(
120                    "analysis {a} has no GUI presentation (gui_analysis)"
121                ));
122            }
123        }
124        for d in ext.detector_kinds() {
125            if !lensbench_gui::ext::has_detector(&table, d.name) {
126                out.push(format!(
127                    "detector {} has no GUI fields (gui_detector)",
128                    d.name
129                ));
130            }
131        }
132    }
133    #[cfg(not(feature = "gui"))]
134    let _ = &table;
135    for m in ext.surface_models() {
136        if let Some(c) = m.example_config() {
137            if let Err(e) = lensbench_core::usersurf::check_flip(m.as_ref(), &c) {
138                out.push(format!("surface model {}: {e}", m.name()));
139            }
140        }
141    }
142    for m in ext.shape_models() {
143        if let Some(c) = m.example_config() {
144            let r = m.example_radius();
145            if let Err(e) = lensbench_core::usershape::check_shape(m.as_ref(), &c, r) {
146                out.push(format!("shape model {}: {e}", m.name()));
147            }
148        }
149    }
150    for m in ext.source_models() {
151        if let Some(c) = m.example_config() {
152            if let Err(e) = lensbench_core::usersource::check_source(m.as_ref(), &c) {
153                out.push(format!("source model {}: {e}", m.name()));
154            }
155        }
156    }
157    for (cat, ms) in ext.material_catalogs() {
158        let mut seen = std::collections::BTreeSet::new();
159        for m in ms {
160            if !seen.insert(m.name().to_string()) {
161                out.push(format!(
162                    "material catalog {cat}: {} is added twice",
163                    m.name()
164                ));
165            }
166            if let Err(e) = lensbench_core::usermaterial::check_material(m.as_ref()) {
167                out.push(format!("material catalog {cat}: {e}"));
168            }
169        }
170    }
171    for (cat, set) in ext.coating_catalogs() {
172        if let Err(e) = lensbench_core::usercoating::check_coatings(set) {
173            out.push(format!("coating catalog {cat}: {e}"));
174        }
175    }
176    out
177}
178
179/// CLI の入口(feature `cli`)
180#[cfg(feature = "cli")]
181pub mod cli {
182    /// 拡張を入れて CLI を動かす
183    pub fn main(ext: crate::Extensions) -> std::process::ExitCode {
184        lensbench_cli::main_with(ext)
185    }
186}
187
188/// GUI の入口と見せ方(feature `gui`)
189#[cfg(feature = "gui")]
190pub mod gui {
191    pub use egui;
192    pub use lensbench_gui::ext::{
193        fig, Analysis, Detector, Figure, FigureParams, GuiExtensions, ObjectArg,
194    };
195
196    /// 拡張を入れて GUI を起動する
197    #[cfg(not(target_arch = "wasm32"))]
198    pub fn main(ext: crate::Extensions) -> std::process::ExitCode {
199        lensbench_gui::main_with(ext)
200    }
201}
202
203/// Python の拡張モジュールの入口と関数の足し方(feature `py`)
204#[cfg(feature = "py")]
205pub mod py {
206    pub use lensbench::ext::{
207        arrays_to_py, system_method, ModuleFn, NativeTask, NativeTaskFrom, PyExtensions, PyPlugin,
208        PySystem,
209    };
210    pub use pyo3;
211
212    /// 拡張を入れ、同梱の関数・クラスと拡張の分をモジュールに足す(拡張モジュールの `#[pymodule]` から呼ぶ)
213    pub fn module(
214        m: &pyo3::Bound<'_, pyo3::types::PyModule>,
215        ext: crate::Extensions,
216    ) -> pyo3::PyResult<()> {
217        lensbench::ext::module_with(m, ext)
218    }
219}
220
221/// Web 版の入口(feature `web`。画面用は `gui` も、計算の Web Worker 用は `web-worker`・`web-threads`)。
222///
223/// 外の wasm のクレート(`crate-type = ["cdylib", "rlib"]`)は、`#[wasm_bindgen(start)]` の関数で拡張を入れ
224/// ([`crate::Extensions::install`])、要れば [`set_extra`] で同梱のファイルを足す。JS の口とページは公開の
225/// Web 版のまま。組み立ては公開のリポジトリの `scripts/build_web.sh` に `CRATE`・`MANIFEST` を渡す
226/// (docs/rust.md の「拡張の約束」)。
227#[cfg(feature = "web")]
228pub mod web {
229    pub use lensbench_web::{set_extra, Extra};
230    #[cfg(target_arch = "wasm32")]
231    pub use wasm_bindgen;
232}
233
234#[cfg(test)]
235mod tests {
236    use super::*;
237
238    /// 同梱の利用者定義の面(反転の約束を守る)は検査を通る。組み込みと同じ名前の検出器は表を作れずに挙がる
239    #[test]
240    fn check_passes_a_good_model_and_reports_errors() {
241        let m = lensbench_core::ext::current()
242            .surface_model("ideal_mapping")
243            .unwrap();
244        let ok = Extensions::named("t").surface_model(m);
245        assert!(check(&ok).is_empty(), "{:?}", check(&ok));
246        let bad = lensbench_project::BUILTIN_BLOCKS[0];
247        let e = Extensions::named("t").detector(detector::DetectorKind {
248            name: bad,
249            doc: "",
250            check: |_| Ok(()),
251            schema: None,
252        });
253        assert_eq!(check(&e).len(), 1);
254        // 同梱のガラスのカタログと同じ名前の材料のカタログは表を作れない(大文字小文字は問わない)
255        let e = Extensions::named("t").material_catalog("schott", Vec::new());
256        let c = check(&e);
257        assert!(
258            c.len() == 1 && c[0].contains("has the name of a built-in glass catalog"),
259            "{c:?}"
260        );
261        assert!(e.ext().is_err());
262    }
263
264    /// GUI の見せ方の無い検出器を挙げ、足せば挙げない
265    #[cfg(feature = "gui")]
266    #[test]
267    fn check_reports_a_detector_without_gui_fields() {
268        use gui::GuiExtensions;
269        let k = detector::DetectorKind {
270            name: "sdk-test-detector",
271            doc: "",
272            check: |_| Ok(()),
273            schema: None,
274        };
275        let e = Extensions::named("t").detector(k);
276        assert_eq!(
277            check(&e),
278            ["detector sdk-test-detector has no GUI fields (gui_detector)"]
279        );
280        let e = e.gui_detector(gui::Detector::new(
281            "sdk-test-detector",
282            gui::ObjectArg::new("", "", Vec::new),
283        ));
284        assert!(check(&e).is_empty());
285    }
286}