Skip to main content

lensbench_core/
usersurf.rs

1//! 利用者が定義する面の口。
2//!
3//! 面の形は頂点の平面(z = 0、理想レンズと同じ)に限り、光線の曲げ方と光路長(位相)だけを利用者が決める。
4//! [`SurfaceModel`] を実装して拡張の表([`crate::ext::Ext::add_surface_model`])に足し、面の種類 [`crate::surface::SurfType::User`] の面に
5//! `user = {"model": 名前, "config": {…}}`([`UserSurf`])を与える。設定は検出器・解析のプラグインと同じ
6//! 数・文字列・数の並びの小さな辞書([`crate::plugin::Config`])。
7//!
8//! 約束:
9//! - [`SurfaceInstance::deflect`] は面の局所座標の交点(z = 0)と単位の入射方向から、単位の出射方向と
10//!   OPD に足す光路長 [mm](理想レンズの位相と同じ扱い。幾何的な光路長 `opl` には入れない)を返す。
11//!   状態を持たず、どのスレッドから呼んでもよい。光線を落とすときは None(その面で err)
12//! - 近軸の追跡(EFL・瞳・近軸像面)には [`SurfaceInstance::paraxial_power`](1 / 焦点距離)を使う
13//! - 偏光の追跡では、電場を方向の変化と同じ最小の回転で回す(振幅は変えない。理想レンズと同じ)。
14//!   [`SurfaceInstance::jones`] を返すモデルは、その後に位置ごとの Jones 行列をかける(基底は Jones 面と同じ、
15//!   [`crate::trace::apply_jones`])
16//! - dOPL/dp([`crate::fermat`])・着地点の微分([`crate::landing`])は、この面を通る光線では未対応(誤り)
17//! - .zmx には書けない(系ファイル・プロジェクトには書ける)。前後の媒質は空気に限る(理想レンズと同じ)
18//!
19//! 同梱のモデル `ideal_mapping`([`IdealMapping`])は、画角 θ → 像高 h の関係を与える理想レンズ。
20
21use std::sync::Arc;
22
23use crate::math::{dot, norm, sub, V3};
24use crate::plugin::{Config, ConfigReader, ParamSpec, ParamType, Value};
25use crate::{invalid, Result};
26
27/// 利用者定義の面のモデル(設定から [`SurfaceInstance`] を作る)
28pub trait SurfaceModel: Send + Sync {
29    /// 登録の名前
30    fn name(&self) -> &str;
31    /// 1 行の説明
32    fn doc(&self) -> String {
33        String::new()
34    }
35    /// 設定の項目(GUI の欄・一覧用)
36    fn params(&self) -> Vec<ParamSpec> {
37        Vec::new()
38    }
39    /// 設定を確かめて面を作る
40    fn prepare(&self, config: &Config) -> Result<Arc<dyn SurfaceInstance>>;
41    /// 試しの設定(拡張の検査で [`check_flip`] に渡す)。既定は [`SurfaceModel::params`] の既定値を並べたもの
42    /// (既定値の無い項目があれば None。そのときは自分で返す)
43    fn example_config(&self) -> Option<Config> {
44        self.params()
45            .into_iter()
46            .map(|p| Some((p.name, p.default?)))
47            .collect()
48    }
49    /// 面を裏返した面の設定(鏡の後に置く・玉を反転するときに使う)。None は「対応しない」で、そのとき鏡の後や
50    /// 反転では誤りになる(既定)。
51    ///
52    /// 約束([`check_flip`] で確かめられる):
53    /// - 2 回裏返すと元の設定に戻る(`flip(flip(c, how), how) == c`)
54    /// - 裏返した面の [`SurfaceInstance::deflect`] は元の面を映したものと一致する: 映す行列 M([`Flip::Z`] は
55    ///   z → −z、[`Flip::X`] は x → −x)で、裏返した面の deflect(p, k) の方向は M · (元の deflect(M p, M k) の方向)、
56    ///   OPD に足す光路長は同じ
57    /// - [`SurfaceInstance::paraxial_power`] は同じ(近軸の屈折力は理想レンズの焦点距離と同じく光の向きによらない)
58    fn flip(&self, config: &Config, how: Flip) -> Result<Option<Config>> {
59        let _ = (config, how);
60        Ok(None)
61    }
62}
63
64/// 面の裏返し方([`SurfaceModel::flip`])
65#[derive(Debug, Clone, Copy, PartialEq, Eq)]
66#[non_exhaustive]
67pub enum Flip {
68    /// z → −z(x・y はそのまま)。鏡の後の座標で面を書くとき
69    Z,
70    /// x → −x。[`Flip::Z`] と合わせて y 軸のまわりに 180° 回した向き(玉の反転)
71    X,
72}
73
74impl Flip {
75    fn apply(self, v: V3) -> V3 {
76        match self {
77            Flip::Z => [v[0], v[1], -v[2]],
78            Flip::X => [-v[0], v[1], v[2]],
79        }
80    }
81
82    fn label(self) -> &'static str {
83        match self {
84            Flip::Z => "z",
85            Flip::X => "x",
86        }
87    }
88}
89
90/// モデルの [`SurfaceModel::flip`] が約束を守るかを確かめる(拡張の試験から呼ぶ): 対応する裏返し方ごとに、2 回で
91/// 元の設定に戻ること、裏返した面の deflect が元の面を映したものと合うこと(数本の光線、両方の向き)、近軸の
92/// 屈折力が同じこと。どの裏返し方にも対応しないモデルは何も確かめずに Ok
93pub fn check_flip(model: &dyn SurfaceModel, config: &Config) -> Result<()> {
94    let name = model.name();
95    let base = model.prepare(config)?;
96    for how in [Flip::Z, Flip::X] {
97        let Some(c1) = model.flip(config, how)? else {
98            continue;
99        };
100        let h = how.label();
101        let back = model.flip(&c1, how)?;
102        if back.as_ref() != Some(config) {
103            invalid!(
104                "user-defined surface model {name}: flipping twice in {h} does not give the original config"
105            );
106        }
107        let fl = model.prepare(&c1)?;
108        let tol = 1e-12;
109        if (fl.paraxial_power() - base.paraxial_power()).abs()
110            > tol * (1.0 + base.paraxial_power().abs())
111        {
112            invalid!(
113                "user-defined surface model {name}: the paraxial power changes when flipped in {h}"
114            );
115        }
116        for &(px, py) in &[(0.0, 0.0), (1.0, 0.0), (0.0, -2.0), (1.5, 0.7)] {
117            for &(kx, ky, kz) in &[
118                (0.0, 0.0, 1.0),
119                (0.1, -0.05, 1.0),
120                (-0.2, 0.15, 1.0),
121                (0.05, 0.1, -1.0),
122            ] {
123                let k = crate::math::normalize([kx, ky, kz]);
124                let p = [px, py, 0.0];
125                let a = base.deflect(how.apply(p), how.apply(k), 1.0, 1.0, 0.55);
126                let b = fl.deflect(p, k, 1.0, 1.0, 0.55);
127                let ok = match (a, b) {
128                    (None, None) => true,
129                    (Some((ka, oa)), Some((kb, ob))) => {
130                        let ka = how.apply(ka);
131                        (0..3).all(|i| (ka[i] - kb[i]).abs() <= tol)
132                            && (oa - ob).abs() <= tol * (1.0 + oa.abs())
133                    }
134                    _ => false,
135                };
136                if !ok {
137                    invalid!(
138                        "user-defined surface model {name}: the surface flipped in {h} does not deflect the ray at ({px}, {py}) in direction ({kx}, {ky}, {kz}) as the mirror image"
139                    );
140                }
141            }
142            // Jones: z は同じ点で同じ行列、x は映した点の行列の B・C の符号を替えたもの
143            let q = how.apply([px, py, 0.0]);
144            let ja = base.jones(q[0], q[1], 0.55).map(|m| match how {
145                Flip::X => [m[0], -m[1], -m[2], m[3]],
146                Flip::Z => m,
147            });
148            let jb = fl.jones(px, py, 0.55);
149            let ok = match (ja, jb) {
150                (None, None) => true,
151                (Some(a), Some(b)) => {
152                    (0..4).all(|i| (a[i] - b[i]).norm() <= tol * (1.0 + a[i].norm()))
153                }
154                _ => false,
155            };
156            if !ok {
157                invalid!(
158                    "user-defined surface model {name}: the Jones matrix of the surface flipped in {h} at ({px}, {py}) is not the mirror image"
159                );
160            }
161        }
162    }
163    Ok(())
164}
165
166/// 設定の決まった利用者定義の面
167pub trait SurfaceInstance: Send + Sync {
168    /// 局所座標の交点 `p`(z = 0)・単位の入射方向 `k`(k[2] の符号が進む向き)・前後の屈折率・波長 [µm] から、
169    /// 単位の出射方向と OPD に足す光路長 [mm]。None で光線を落とす
170    fn deflect(&self, p: V3, k: V3, n_in: f64, n_out: f64, wl_um: f64) -> Option<(V3, f64)>;
171    /// 近軸の屈折力 1 / f [1/mm](近軸の追跡で使う。0 なら素通し)
172    fn paraxial_power(&self) -> f64 {
173        0.0
174    }
175    /// 局所座標の交点 (x, y) と波長 [µm] での Jones 行列 [A, B, C, D](Ex' = A·Ex + B·Ey、Ey' = C·Ex + D·Ey。基底は
176    /// Jones 面と同じく、局所の ±z を出射の向きへ移す最小の回転で運んだ x・y)。None は Jones なし(既定)。頂点
177    /// (0, 0)・0.55 µm で None を返すモデルは Jones を持たないとみなす。裏返した面([`SurfaceModel::flip`])の Jones は、
178    /// z では同じ点で同じ行列、x では映した点 (−x, y) の行列の B・C の符号を替えたもの([`check_flip`] が確かめる)
179    fn jones(&self, x: f64, y: f64, wl_um: f64) -> Option<[crate::coating::C64; 4]> {
180        let _ = (x, y, wl_um);
181        None
182    }
183}
184
185/// 面に付ける利用者定義の面(モデルの名前・設定と、準備した面)。系ファイルには名前と設定だけを書き、
186/// 読むときに登録から作り直す
187#[derive(Clone, serde::Serialize, serde::Deserialize)]
188#[serde(try_from = "UserSurfSpec", into = "UserSurfSpec")]
189pub struct UserSurf {
190    pub model: String,
191    pub config: Config,
192    inst: Arc<dyn SurfaceInstance>,
193}
194
195/// [`UserSurf`] の書き出しの形
196#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
197pub(crate) struct UserSurfSpec {
198    /// モデルの名前(同梱は ideal_mapping)
199    pub model: String,
200    /// 設定(数・文字列・数の並び)
201    #[serde(default)]
202    pub config: Config,
203}
204
205impl TryFrom<UserSurfSpec> for UserSurf {
206    type Error = crate::Error;
207    fn try_from(s: UserSurfSpec) -> Result<Self> {
208        UserSurf::new(&s.model, s.config)
209    }
210}
211
212impl From<UserSurf> for UserSurfSpec {
213    fn from(u: UserSurf) -> Self {
214        UserSurfSpec {
215            model: u.model,
216            config: u.config,
217        }
218    }
219}
220
221impl schemars::JsonSchema for UserSurf {
222    fn schema_name() -> std::borrow::Cow<'static, str> {
223        UserSurfSpec::schema_name()
224    }
225    fn json_schema(g: &mut schemars::SchemaGenerator) -> schemars::Schema {
226        UserSurfSpec::json_schema(g)
227    }
228}
229
230impl std::fmt::Debug for UserSurf {
231    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
232        f.debug_struct("UserSurf")
233            .field("model", &self.model)
234            .field("config", &self.config)
235            .finish()
236    }
237}
238
239impl PartialEq for UserSurf {
240    fn eq(&self, o: &Self) -> bool {
241        self.model == o.model && self.config == o.config
242    }
243}
244
245impl UserSurf {
246    /// 今の拡張の表([`crate::ext::current`])のモデル `model` を設定 `config` で準備する
247    pub fn new(model: &str, config: Config) -> Result<UserSurf> {
248        let m = crate::ext::current().surface_model(model)?;
249        let inst = m.prepare(&config)?;
250        Ok(UserSurf {
251            model: model.to_string(),
252            config,
253            inst,
254        })
255    }
256
257    pub fn instance(&self) -> &dyn SurfaceInstance {
258        self.inst.as_ref()
259    }
260
261    /// 準備した面(偏光の準備で Jones を持つ面を写すため)
262    pub(crate) fn instance_arc(&self) -> Arc<dyn SurfaceInstance> {
263        self.inst.clone()
264    }
265
266    /// 裏返した面([`SurfaceModel::flip`])。モデルが対応しなければ誤り
267    pub fn flipped(&self, how: Flip) -> Result<UserSurf> {
268        let m = crate::ext::current().surface_model(&self.model)?;
269        match m.flip(&self.config, how)? {
270            Some(c) => UserSurf::new(&self.model, c),
271            None => {
272                let (model, h) = (&self.model, how.label());
273                crate::notimpl!("the user-defined surface model {model} can't be flipped in {h} (it has no flip)")
274            }
275        }
276    }
277}
278
279// ---------------------------------------------------------------------------------------------------------------
280// 同梱: 画角 → 像高を与える理想レンズ
281
282/// 画角 θ → 像高 h の関係を与える理想レンズ(焦点距離 f の薄肉、頂点の平面)。
283///
284/// 入射方向 k の光線(θ = 光軸からの角、方位は k の xy の向き)は、焦点面(レンズから f)の点
285/// P = (h(θ)·方位, f) に集まる。出射方向は交点から P への向き、OPD に足す光路長は
286/// sign(f)·(|P| − |P − r| − k·r)(平行光の波面から P までの光路長を一定にする。同じ方向の光線はどれも P で
287/// 無収差)。`tan`(h = f tan θ)は理想レンズ(`PARAXIAL`、物体が無限遠)とビット同じ。
288///
289/// 物体は無限遠を想定する(有限の物体でも光線の方向ごとに上の式で曲げる。`tan` 以外では有限の物点の像は
290/// 無収差にならない)。
291///
292/// 設定: `f`(焦点距離 [mm]、必須、0 以外)、`mapping`(`tan`・`theta`(f θ、等距離射影)・`sin`(f sin θ、正射影)・
293/// `equisolid`(2 f sin(θ/2)、等立体角)・`stereographic`(2 f tan(θ/2)、立体射影)・`poly`・`table`、既定 `tan`)、
294/// `coef`(poly: h = f (θ + c₁ θ³ + c₂ θ⁵ + …) の c₁, c₂, …)、`theta_deg`・`height`(table: θ [deg](0 から増える)と
295/// h [mm] の表、区分 3 次エルミート(PCHIP)で補間、範囲の外は光線を落とす)。
296pub(crate) struct IdealMapping;
297
298#[derive(Debug, Clone)]
299enum Mapping {
300    Tan,
301    Theta,
302    Sin,
303    Equisolid,
304    Stereo,
305    Poly(Vec<f64>),
306    Table(Pchip),
307}
308
309/// 単調な区分 3 次エルミート(Fritsch–Carlson)
310#[derive(Debug, Clone)]
311struct Pchip {
312    x: Vec<f64>,
313    y: Vec<f64>,
314    d: Vec<f64>,
315}
316
317impl Pchip {
318    fn new(x: Vec<f64>, y: Vec<f64>) -> Result<Pchip> {
319        let n = x.len();
320        if n < 2 || y.len() != n {
321            invalid!("the table theta_deg and height need 2 or more points of the same length");
322        }
323        if x.windows(2).any(|w| !(w[1] > w[0])) || !x.iter().chain(&y).all(|v| v.is_finite()) {
324            invalid!("the table theta_deg must be ascending finite values");
325        }
326        let h: Vec<f64> = x.windows(2).map(|w| w[1] - w[0]).collect();
327        let s: Vec<f64> = (0..n - 1).map(|i| (y[i + 1] - y[i]) / h[i]).collect();
328        let mut d = vec![0.0; n];
329        if n == 2 {
330            d = vec![s[0]; 2];
331        } else {
332            for i in 1..n - 1 {
333                d[i] = if s[i - 1] * s[i] <= 0.0 {
334                    0.0
335                } else {
336                    let (w1, w2) = (2.0 * h[i] + h[i - 1], h[i] + 2.0 * h[i - 1]);
337                    (w1 + w2) / (w1 / s[i - 1] + w2 / s[i])
338                };
339            }
340            let end = |h0: f64, h1: f64, s0: f64, s1: f64| {
341                let e = ((2.0 * h0 + h1) * s0 - h0 * s1) / (h0 + h1);
342                if e * s0 <= 0.0 {
343                    0.0
344                } else if s0 * s1 <= 0.0 && e.abs() > 3.0 * s0.abs() {
345                    3.0 * s0
346                } else {
347                    e
348                }
349            };
350            d[0] = end(h[0], h[1], s[0], s[1]);
351            d[n - 1] = end(h[n - 2], h[n - 3], s[n - 2], s[n - 3]);
352        }
353        Ok(Pchip { x, y, d })
354    }
355
356    fn eval(&self, t: f64) -> Option<f64> {
357        let n = self.x.len();
358        if !(t >= self.x[0] && t <= self.x[n - 1]) {
359            return None;
360        }
361        let i = match self.x.partition_point(|&v| v <= t) {
362            0 => 0,
363            k => (k - 1).min(n - 2),
364        };
365        let h = self.x[i + 1] - self.x[i];
366        let u = (t - self.x[i]) / h;
367        let (u2, u3) = (u * u, u * u * u);
368        Some(
369            (2.0 * u3 - 3.0 * u2 + 1.0) * self.y[i]
370                + (u3 - 2.0 * u2 + u) * h * self.d[i]
371                + (-2.0 * u3 + 3.0 * u2) * self.y[i + 1]
372                + (u3 - u2) * h * self.d[i + 1],
373        )
374    }
375}
376
377/// 設定の決まった [`IdealMapping`]
378#[derive(Debug, Clone)]
379pub(crate) struct IdealMappingInst {
380    f: f64,
381    map: Mapping,
382}
383
384impl IdealMappingInst {
385    /// 画角 θ [rad] の像高 [mm](表の範囲の外は None)
386    pub(crate) fn height(&self, th: f64) -> Option<f64> {
387        let f = self.f;
388        Some(match &self.map {
389            Mapping::Tan => f * th.tan(),
390            Mapping::Theta => f * th,
391            Mapping::Sin => f * th.sin(),
392            Mapping::Equisolid => 2.0 * f * (th / 2.0).sin(),
393            Mapping::Stereo => 2.0 * f * (th / 2.0).tan(),
394            Mapping::Poly(c) => {
395                let t2 = th * th;
396                let (mut s, mut p) = (th, th);
397                for a in c {
398                    p *= t2;
399                    s += a * p;
400                }
401                f * s
402            }
403            Mapping::Table(t) => t.eval(th.to_degrees())?,
404        })
405    }
406
407    /// h′(0) [mm/rad](近軸の焦点距離)
408    fn slope0(&self) -> f64 {
409        match &self.map {
410            Mapping::Table(t) => t.d[0].to_degrees(),
411            _ => self.f,
412        }
413    }
414}
415
416impl SurfaceModel for IdealMapping {
417    fn name(&self) -> &str {
418        "ideal_mapping"
419    }
420
421    fn doc(&self) -> String {
422        "Ideal lens given by the field angle θ → image height h relation (f tan θ, f θ, f sin θ, equisolid, stereographic, polynomial, table)".into()
423    }
424
425    fn params(&self) -> Vec<ParamSpec> {
426        let ch = [
427            "tan",
428            "theta",
429            "sin",
430            "equisolid",
431            "stereographic",
432            "poly",
433            "table",
434        ];
435        vec![
436            ParamSpec::new(
437                "f",
438                ParamType::Num,
439                None,
440                "mm",
441                "Focal length (nonzero, required)",
442            ),
443            ParamSpec::new(
444                "mapping",
445                ParamType::Choice(ch.iter().map(|s| s.to_string()).collect()),
446                Some(Value::Str("tan".into())),
447                "",
448                "Field angle → image height relation",
449            ),
450            ParamSpec::new(
451                "coef",
452                ParamType::Nums { len: None },
453                None,
454                "",
455                "poly: c₁, c₂, … of h = f (θ + c₁ θ³ + c₂ θ⁵ + …)",
456            ),
457            ParamSpec::new(
458                "theta_deg",
459                ParamType::Nums { len: None },
460                None,
461                "deg",
462                "table: field angles (increasing from 0)",
463            ),
464            ParamSpec::new(
465                "height",
466                ParamType::Nums { len: None },
467                None,
468                "mm",
469                "table: image heights",
470            ),
471        ]
472    }
473
474    /// 回転対称で、光の向き(k の z の符号)によらない曲げ方なので、どちらに裏返しても同じ設定
475    fn flip(&self, config: &Config, _how: Flip) -> Result<Option<Config>> {
476        Ok(Some(config.clone()))
477    }
478
479    fn prepare(&self, config: &Config) -> Result<Arc<dyn SurfaceInstance>> {
480        let mut r = ConfigReader::new(config);
481        let f = r.num("f", f64::NAN)?;
482        if !f.is_finite() || f == 0.0 {
483            invalid!("ideal_mapping f must be finite and not 0 ({f})");
484        }
485        let kind = r.str("mapping", "tan")?;
486        let coef = r.nums("coef")?;
487        let th = r.nums("theta_deg")?;
488        let hh = r.nums("height")?;
489        r.finish()?;
490        let unused = |what: &str, v: bool| -> Result<()> {
491            if v {
492                invalid!("ideal_mapping {what} is not used with mapping = {kind}");
493            }
494            Ok(())
495        };
496        unused("coef", coef.is_some() && kind != "poly")?;
497        unused(
498            "theta_deg・height",
499            (th.is_some() || hh.is_some()) && kind != "table",
500        )?;
501        let map = match kind.as_str() {
502            "tan" => Mapping::Tan,
503            "theta" => Mapping::Theta,
504            "sin" => Mapping::Sin,
505            "equisolid" => Mapping::Equisolid,
506            "stereographic" => Mapping::Stereo,
507            "poly" => Mapping::Poly(coef.unwrap_or_default()),
508            "table" => {
509                let (Some(t), Some(h)) = (th, hh) else {
510                    invalid!("mapping = table needs theta_deg and height");
511                };
512                if t[0] != 0.0 || h[0] != 0.0 {
513                    invalid!(
514                        "the table must start at θ = 0, h = 0 ({} deg, {} mm)",
515                        t[0],
516                        h[0]
517                    );
518                }
519                let p = Pchip::new(t, h)?;
520                if !(p.d[0] != 0.0) || p.d[0].signum() != f.signum() {
521                    invalid!(
522                        "the table slope at θ = 0 ({} mm/deg) must be non-zero with the same sign as f",
523                        p.d[0]
524                    );
525                }
526                Mapping::Table(p)
527            }
528            k => invalid!(
529                "mapping must be tan, theta, sin, equisolid, stereographic, poly or table ({k})"
530            ),
531        };
532        Ok(Arc::new(IdealMappingInst { f, map }))
533    }
534}
535
536impl SurfaceInstance for IdealMappingInst {
537    fn deflect(&self, pl: V3, kl: V3, _n_in: f64, _n_out: f64, _wl: f64) -> Option<(V3, f64)> {
538        let f = self.f;
539        if let Mapping::Tan = self.map {
540            // 理想レンズ(物体が無限遠)の式そのもの(ビット同じ)
541            return Some(crate::trace::paraxial(f, pl, kl, f64::INFINITY));
542        }
543        let sz = kl[2].signum();
544        let t = [kl[0] / kl[2].abs(), kl[1] / kl[2].abs()];
545        let r = [pl[0], pl[1], 0.0];
546        // 焦点面の像点 P = (h(θ)·方位, f)。h(θ)/tan θ(θ → 0 は h′(0))を t にかける
547        let tt = t[0].hypot(t[1]);
548        let g = if tt > 1e-12 {
549            self.height(tt.atan())? / tt
550        } else {
551            self.slope0()
552        };
553        let ff = [g * t[0], g * t[1], f];
554        if !ff.iter().all(|v| v.is_finite()) {
555            return None;
556        }
557        let d = [(ff[0] - r[0]) / f, (ff[1] - r[1]) / f];
558        let nn = (1.0 + d[0] * d[0] + d[1] * d[1]).sqrt();
559        let k2 = [d[0] / nn, d[1] / nn, sz / nn];
560        // 入ってくる平行光の面内の位相は実際の方向の k·r(光が −z へ進むときも x・y の成分はそのまま)
561        let kin = [kl[0], kl[1], kl[2].abs()];
562        Some((k2, f.signum() * (norm(ff) - norm(sub(ff, r)) - dot(kin, r))))
563    }
564
565    fn paraxial_power(&self) -> f64 {
566        1.0 / self.slope0()
567    }
568}
569
570#[cfg(test)]
571mod tests {
572    use super::*;
573
574    fn cfg(kv: &[(&str, Value)]) -> Config {
575        kv.iter().map(|(k, v)| (k.to_string(), v.clone())).collect()
576    }
577
578    /// x の向きに光を曲げる面(裏返しの試験用)。`flip` は「x について裏返すと曲げる向きが逆」を設定で表す。
579    /// `wrong` なら設定をそのまま返す(約束を破る)
580    struct Prism {
581        wrong: bool,
582        flips: bool,
583    }
584    struct PrismInst(f64);
585    impl SurfaceInstance for PrismInst {
586        fn deflect(&self, _p: V3, k: V3, _: f64, _: f64, _: f64) -> Option<(V3, f64)> {
587            let t = [k[0] / k[2].abs() + self.0, k[1] / k[2].abs()];
588            let n = (1.0 + t[0] * t[0] + t[1] * t[1]).sqrt();
589            Some(([t[0] / n, t[1] / n, k[2].signum() / n], 0.0))
590        }
591    }
592    impl SurfaceModel for Prism {
593        fn name(&self) -> &str {
594            "lbtest_prism"
595        }
596        fn prepare(&self, config: &Config) -> Result<Arc<dyn SurfaceInstance>> {
597            Ok(Arc::new(PrismInst(
598                ConfigReader::new(config).num("a", 0.0)?,
599            )))
600        }
601        fn flip(&self, config: &Config, how: Flip) -> Result<Option<Config>> {
602            if !self.flips {
603                return Ok(None);
604            }
605            let a = ConfigReader::new(config).num("a", 0.0)?;
606            let a = if how == Flip::X && !self.wrong { -a } else { a };
607            Ok(Some(cfg(&[("a", Value::Num(a))])))
608        }
609    }
610
611    /// 裏返しの約束: 同梱の ideal_mapping は守る。曲げる向きを映さないモデルは check_flip で見つかる。
612    /// flip の無いモデルの面は裏返すと誤り(面とモデルの名前つき)
613    #[test]
614    fn flips_follow_the_contract() {
615        for m in ["tan", "theta", "sin"] {
616            let c = cfg(&[("f", Value::Num(-40.0)), ("mapping", Value::Str(m.into()))]);
617            check_flip(&IdealMapping, &c).unwrap();
618        }
619        let c = cfg(&[("a", Value::Num(0.1))]);
620        check_flip(
621            &Prism {
622                wrong: false,
623                flips: true,
624            },
625            &c,
626        )
627        .unwrap();
628        let e = check_flip(
629            &Prism {
630                wrong: true,
631                flips: true,
632            },
633            &c,
634        )
635        .unwrap_err();
636        assert!(e.to_string().contains("flipped in x"), "{e}");
637        check_flip(
638            &Prism {
639                wrong: false,
640                flips: false,
641            },
642            &c,
643        )
644        .unwrap();
645        let mut ext = crate::ext::Ext::default();
646        ext.add_surface_model(Arc::new(Prism {
647            wrong: false,
648            flips: false,
649        }));
650        crate::ext::with(Arc::new(ext), || {
651            let u = UserSurf::new("lbtest_prism", c.clone()).unwrap();
652            let e = u.flipped(Flip::Z).unwrap_err();
653            assert!(
654                e.to_string().contains("lbtest_prism can't be flipped in z"),
655                "{e}"
656            );
657            let mut s = crate::surface::Surface::default();
658            s.set_type(crate::surface::SurfType::User);
659            *s.user_mut().unwrap() = Some(u.clone());
660            let before = s.clone();
661            assert!(s.flip_z().is_err());
662            assert_eq!(s, before);
663        });
664    }
665
666    #[test]
667    fn tan_matches_the_paraxial_lens() {
668        let u = UserSurf::new("ideal_mapping", cfg(&[("f", Value::Num(50.0))])).unwrap();
669        for (p, k) in [
670            ([1.0, -2.0, 0.0], [0.1, 0.05, 1.0]),
671            ([0.0, 3.0, 0.0], [0.0, -0.3, 1.0]),
672            ([2.0, 0.5, 0.0], [-0.2, 0.1, -1.0]),
673        ] {
674            let k = crate::math::normalize(k);
675            let (k2, dl) = u.instance().deflect(p, k, 1.0, 1.0, 0.5).unwrap();
676            let (k3, dl3) = crate::trace::paraxial(50.0, p, k, f64::INFINITY);
677            assert_eq!((k2, dl), (k3, dl3));
678        }
679    }
680
681    #[test]
682    fn rays_of_one_direction_meet_at_h_theta_with_equal_path() {
683        for (m, h) in [
684            ("theta", 50.0 * 0.3),
685            ("sin", 50.0 * 0.3f64.sin()),
686            ("equisolid", 100.0 * 0.15f64.sin()),
687            ("stereographic", 100.0 * 0.15f64.tan()),
688        ] {
689            let u = UserSurf::new(
690                "ideal_mapping",
691                cfg(&[("f", Value::Num(50.0)), ("mapping", Value::Str(m.into()))]),
692            )
693            .unwrap();
694            let th: f64 = 0.3;
695            let k = [0.0, th.sin(), th.cos()];
696            let mut lens = Vec::new();
697            for y in [-5.0, -1.0, 0.0, 2.0, 4.0] {
698                for x in [-3.0, 0.0, 1.5] {
699                    let p = [x, y, 0.0];
700                    let (k2, dl) = u.instance().deflect(p, k, 1.0, 1.0, 0.5).unwrap();
701                    // 焦点面 z = 50 での位置
702                    let s = 50.0 / k2[2];
703                    let q = [x + s * k2[0], y + s * k2[1]];
704                    assert!(
705                        q[0].abs() < 1e-9 && (q[1] - h).abs() < 1e-9,
706                        "{m}: {q:?} {h}"
707                    );
708                    // 平行光の波面(原点を通る)から P までの光路長 + 位相が一定
709                    lens.push(dot(k, p) + s + dl);
710                }
711            }
712            let (lo, hi) = lens
713                .iter()
714                .fold((f64::MAX, f64::MIN), |a, &v| (a.0.min(v), a.1.max(v)));
715            assert!(hi - lo < 1e-9, "{m}: {lo} {hi}");
716        }
717    }
718
719    #[test]
720    fn poly_table_and_errors() {
721        let poly = UserSurf::new(
722            "ideal_mapping",
723            cfg(&[
724                ("f", Value::Num(20.0)),
725                ("mapping", Value::Str("poly".into())),
726                ("coef", Value::Nums(vec![-0.1, 0.01])),
727            ]),
728        )
729        .unwrap();
730        let th = 0.4f64;
731        let (k2, _) = poly
732            .instance()
733            .deflect([0.0; 3], [0.0, th.sin(), th.cos()], 1.0, 1.0, 0.5)
734            .unwrap();
735        let want = 20.0 * (th - 0.1 * th.powi(3) + 0.01 * th.powi(5));
736        assert!((20.0 * k2[1] / k2[2] - want).abs() < 1e-12);
737        assert!((poly.instance().paraxial_power() - 1.0 / 20.0).abs() < 1e-15);
738        // 表: f θ を表で与えると theta と同じ(PCHIP は直線を正確に再現)
739        let deg: Vec<f64> = (0..=8).map(|i| 10.0 * i as f64).collect();
740        let hs: Vec<f64> = deg.iter().map(|d| 20.0 * d.to_radians()).collect();
741        let tab = UserSurf::new(
742            "ideal_mapping",
743            cfg(&[
744                ("f", Value::Num(20.0)),
745                ("mapping", Value::Str("table".into())),
746                ("theta_deg", Value::Nums(deg)),
747                ("height", Value::Nums(hs)),
748            ]),
749        )
750        .unwrap();
751        let th_ = UserSurf::new(
752            "ideal_mapping",
753            cfg(&[
754                ("f", Value::Num(20.0)),
755                ("mapping", Value::Str("theta".into())),
756            ]),
757        )
758        .unwrap();
759        let k = [0.0, 0.5f64.sin(), 0.5f64.cos()];
760        let a = tab
761            .instance()
762            .deflect([0.3, 1.0, 0.0], k, 1.0, 1.0, 0.5)
763            .unwrap();
764        let b = th_
765            .instance()
766            .deflect([0.3, 1.0, 0.0], k, 1.0, 1.0, 0.5)
767            .unwrap();
768        assert!((a.0[1] - b.0[1]).abs() < 1e-12 && (a.1 - b.1).abs() < 1e-12);
769        assert!((tab.instance().paraxial_power() - 1.0 / 20.0).abs() < 1e-12);
770        // 表の外(85°)は光線を落とす
771        let far = [0.0, 85f64.to_radians().sin(), 85f64.to_radians().cos()];
772        assert!(tab
773            .instance()
774            .deflect([0.0; 3], far, 1.0, 1.0, 0.5)
775            .is_none());
776        for c in [
777            cfg(&[]),
778            cfg(&[("f", Value::Num(0.0))]),
779            cfg(&[("f", Value::Num(1.0)), ("mapping", Value::Str("x".into()))]),
780            cfg(&[("f", Value::Num(1.0)), ("coef", Value::Nums(vec![1.0]))]),
781            cfg(&[
782                ("f", Value::Num(1.0)),
783                ("mapping", Value::Str("table".into())),
784                ("theta_deg", Value::Nums(vec![1.0, 2.0])),
785                ("height", Value::Nums(vec![0.0, 1.0])),
786            ]),
787            cfg(&[("f", Value::Num(1.0)), ("g", Value::Num(1.0))]),
788        ] {
789            assert!(UserSurf::new("ideal_mapping", c.clone()).is_err(), "{c:?}");
790        }
791        assert!(UserSurf::new("none", cfg(&[])).is_err());
792    }
793}