Skip to main content

lensbench_core/
surface.rs

1//! 面のデータ(OpticStudio のレンズデータエディタの 1 行に当たる)。
2//!
3//! 種類ごとの値は種類の枝 [`Form`] の中に、曲率・円錐係数・非球面の係数のような共通の値は面に持つ。共通の値の
4//! 種類ごとの意味(`asph` が何の係数かなど)は形の見方 [`Surface::shape`]([`crate::shape`])と働きの見方
5//! [`Surface::action`]([`crate::action`])で分ける。形・働きに依る計算はこの 2 つを通す
6
7pub use crate::form::{Form, JONES_IDENTITY};
8pub use crate::material::Material;
9
10#[derive(
11    Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize, schemars::JsonSchema,
12)]
13pub enum SurfType {
14    Standard,
15    EvenAsph,
16    CoordBrk,
17    Jones,
18    Paraxial,
19    /// トロイダル面: YZ 面の曲線(c・k・asph を y で)を Y 軸に平行な軸の周りに回した面。
20    /// x 方向の曲率は `cx`(回転半径の逆数、0 なら円柱面)
21    Toroidal,
22    /// Zernike Standard Sag(基準の面 c・k・asph + Noll の順の Zernike の項、[`crate::freeform`])
23    ZernikeStd,
24    /// Zernike Fringe Sag(Fringe の順の 37 項まで)
25    ZernikeFringe,
26    /// Grid Sag(基準の面 + 格子の補間)
27    GridSag,
28    /// Fresnel(OpticStudio の FRESNELS): 交点は頂点の平面、屈折は偶数次非球面(c・k・asph)の傾きで
29    Fresnel,
30    /// Cylinder Fresnel(CFRESNEL): 交点は基板(c・k・asph、y だけの関数)、屈折は [`CylFresnel`] の面(y だけ)の傾きで
31    CylFresnel,
32    /// Binary Optic 2(BINARY_2): 形は偶数次非球面、位相 [`Binary2`] で光路長と方向が変わる
33    Binary2,
34    /// Gradium(GRINSUR8): 形は標準面、面の後ろは軸方向の屈折率分布 [`crate::grin`]
35    Gradium,
36    /// Gradient 9(GRINSUR9): 形は標準面 + x tan α + y tan β、面の後ろは径方向の屈折率分布
37    Gradient9,
38    /// Odd Asphere(ODDASPHE): 標準面(c・k)+ Σ β_i r^i(i = 1..8、`asph` に β_1..β_8)
39    OddAsph,
40    /// Tilted(TILTSURF): 平面 z = x tan α + y tan β(`asph` に tan α・tan β)。局所座標は傾けない
41    TiltSurf,
42    /// Irregular(IRREGULA): 偏心・傾けた標準面(c・k)に Zs ρ⁴ + Za ρ_y² + Zc ρ² ρ_y(ρ は半直径で正規化、
43    /// 角度で回した座標)。`asph` に [偏心 x, 偏心 y, 傾き x°, 傾き y°, Zs, Za, Zc, 角度°]([`crate::freeform`])
44    Irregular,
45    /// 利用者定義の面([`crate::usersurf`]): 形は頂点の平面、曲げ方と位相は登録のモデル(`Surface::user`)
46    User,
47    /// 利用者定義の形の面([`crate::usershape`]): 形は二次曲面(c・k)+登録のモデルの矢高(`Surface::user_shape`)、
48    /// 働きはふつうの屈折・反射
49    UserShape,
50}
51
52/// Binary 2 の位相 Φ = order · Σ coef[i] ρ^{2(i+1)}(ρ = r / norm、係数の単位は rad)
53#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
54pub struct Binary2 {
55    /// 回折次数 M
56    pub order: f64,
57    /// 正規化半径
58    pub norm: f64,
59    pub coef: Vec<f64>,
60}
61
62impl Binary2 {
63    /// 位相 [rad] と (∂Φ/∂x, ∂Φ/∂y)
64    pub fn phase(&self, x: f64, y: f64) -> (f64, f64, f64) {
65        let inv = 1.0 / (self.norm * self.norm);
66        let p2 = (x * x + y * y) * inv;
67        // Σ a_i p^i と d/dp
68        let (mut f, mut df, mut pw) = (0.0, 0.0, 1.0);
69        for (i, &a) in self.coef.iter().enumerate() {
70            let e = (i + 1) as f64;
71            df += a * e * pw;
72            pw *= p2;
73            f += a * pw;
74        }
75        let g = self.order * df * 2.0 * inv;
76        (self.order * f, g * x, g * y)
77    }
78}
79
80/// Cylinder Fresnel の屈折に使う面: z = c y² / (1 + √(1 − (1 + k) c² y²)) + Σ coef[i] y^{2(i+1)}
81#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
82pub struct CylFresnel {
83    pub c: f64,
84    pub k: f64,
85    pub coef: Vec<f64>,
86}
87
88/// 傾き・偏心(dx dy tx ty tz [deg])と順序(0: 偏心→X→Y→Z、1: Z→Y→X→偏心)
89#[derive(
90    Debug, Clone, Copy, PartialEq, serde::Serialize, serde::Deserialize, schemars::JsonSchema,
91)]
92pub struct Tilt {
93    pub d: [f64; 5],
94    pub order: u8,
95}
96
97#[derive(
98    Debug, Clone, Copy, PartialEq, serde::Serialize, serde::Deserialize, schemars::JsonSchema,
99)]
100pub enum After {
101    None,
102    /// 「前」の変換を戻す
103    Reverse,
104    Tilt(Tilt),
105}
106
107#[derive(
108    Debug, Clone, Copy, PartialEq, serde::Serialize, serde::Deserialize, schemars::JsonSchema,
109)]
110pub enum Aperture {
111    None,
112    /// 最小・最大半径、偏心 x y
113    Circular {
114        min: f64,
115        max: f64,
116        dx: f64,
117        dy: f64,
118    },
119    /// x・y の半幅、偏心
120    Rect {
121        hx: f64,
122        hy: f64,
123        dx: f64,
124        dy: f64,
125    },
126    /// 自動の半径(既定では切らない)
127    Floating {
128        semi: f64,
129    },
130    /// 楕円(x・y の半軸、偏心)
131    Ellipse {
132        hx: f64,
133        hy: f64,
134        dx: f64,
135        dy: f64,
136    },
137    /// 円形遮蔽(最小〜最大半径の間を遮る)
138    Obsc {
139        min: f64,
140        max: f64,
141        dx: f64,
142        dy: f64,
143    },
144    /// スパイダー(.zmx の SPID): 中心(偏心 dx dy)から外へ無限に伸びる幅 width(全幅)の腕 arms 本を遮る。
145    /// 腕は 360° を等分し、最初の腕は +x の向き
146    Spider {
147        width: f64,
148        arms: u32,
149        dx: f64,
150        dy: f64,
151    },
152}
153
154/// 面の値(処方)。`==` は値の比較(NaN は等しくない、−0 と 0 は等しい)
155#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
156pub struct Surface {
157    /// 面の種類と、種類ごとの値([`Form`])。serde では面の表の中に平たく(`typ`・`cb` など)
158    #[serde(flatten)]
159    pub form: Form,
160    pub ignore: bool,
161    /// 次の面までの厚さ [mm](物体面は無限遠なら inf)
162    pub t: f64,
163    pub comment: String,
164    /// 面の後ろの媒質(鏡・座標ブレークの媒質なしも)
165    pub mat: Material,
166    pub coat: String,
167    pub stop: bool,
168    /// 半直径 [mm]。`semi_auto` なら光線から求めた値([`crate::System::update_semi`])
169    pub semi: f64,
170    /// 半直径を光線から求める(OpticStudio の Automatic、.zmx の DIAM … 0、系ファイルの "semi": "auto")
171    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
172    pub semi_auto: bool,
173    pub c: f64,
174    pub k: f64,
175    pub before: Option<Tilt>,
176    pub after: After,
177    pub ap: Aperture,
178    /// 媒質の屈折率のずれ(全波長に足す)。[`crate::param`] で変える
179    pub dn: f64,
180    /// 媒質の分散の相対変化: n = n0(λ) + dn + disp·(n0(λ) − n0(主波長))
181    pub disp: f64,
182    /// ガラスの d 線の屈折率のずれ(OpticStudio の TIND)。ガラスの nd・vd・ΔPgF のモデルガラスの式で、nd を
183    /// このぶん変えた差を波長ごとに n0(λ) に足す(ガラスかモデルガラスの面だけ。dn・disp はその後にかける)
184    #[serde(default, skip_serializing_if = "is_zero")]
185    pub dnd: f64,
186    /// ガラスのアッベ数のずれ(OpticStudio の TABB)。[`Surface::dnd`] と同じくモデルガラスの式の差を足す
187    #[serde(default, skip_serializing_if = "is_zero")]
188    pub dvd: f64,
189    /// 屈折面での反射(ゴーストの経路、lensbench-analysis の ghost)。材料を鏡にして立て、光線は鏡として曲げ、
190    /// 偏光の係数は入射側の媒質と反対側の媒質 [`Reflect::mat`] の境界(膜込み)の反射にする
191    pub reflect: Option<Reflect>,
192    /// Jones 面([`SurfType::Jones`])を波長ごとに作る偏光子・波長板。あれば偏光の追跡は `jones` でなく
193    /// これを各波長で使う(`jones` は設計波長 `wl0` の値で、.zmx の JONESMAT に書く)
194    #[serde(default, skip_serializing_if = "Option::is_none")]
195    pub retarder: Option<Retarder>,
196    /// 複屈折材の板の入口・出口(OpticStudio の Birefringent In / Out)。形は標準面のまま
197    #[serde(default, skip_serializing_if = "Option::is_none")]
198    pub bire: Option<Bire>,
199    /// 面の熱膨張係数 [1e-6/°C](OpticStudio のレンズデータの TCE の列、.zmx の TCED。空気の面の機構の膨張に使う値で、
200    /// 光線追跡には効かない。硝材の面の TCE はカタログの値)
201    #[serde(default, skip_serializing_if = "is_zero")]
202    pub tce: f64,
203    /// 固定した機械半径(OpticStudio の Mech Semi-Dia、.zmx の MEMA の固定)。None は自動。玉の半径
204    /// ([`System::lens_radius`](crate::system::System::lens_radius))はガラスでつながる面の、これとクリア半径 + チップゾーンの最大
205    /// (自動より小さい値は使わない。OpticStudio 26.1 と同じ)。光線追跡には効かない
206    #[serde(default, skip_serializing_if = "Option::is_none")]
207    pub mech_semi: Option<f64>,
208    /// 座標の戻り(OpticStudio の Coordinate Return、座標ブレークだけ): 座標ブレークの傾き・偏心(と厚さ)を、前の面 surf の
209    /// 座標系に戻るように求める([`crate::coord_return`])
210    #[serde(default, skip_serializing_if = "Option::is_none")]
211    pub coord_return: Option<crate::coord_return::CoordReturn>,
212    /// チップゾーン(OpticStudio の Chip Zone、.zmx の OEMA): 面の形をクリア半径からこの幅だけ外へ延ばし、その外を平らにする。
213    /// 光線追跡には効かない
214    #[serde(default, skip_serializing_if = "is_zero")]
215    pub chip_zone: f64,
216}
217
218fn is_zero(x: &f64) -> bool {
219    *x == 0.0
220}
221
222/// 偏光子・波長板の Jones 行列の元: 軸(`axis_deg`、x から y へ)の向きの振幅透過 `tx`、直交する向き `ty`、
223/// 軸の向きを速い軸とする遅延 φ = 2π·(`order` + `retardance`)·`wl0`/λ(ゼロ次は order 0)。
224/// 行列は R(−θ)·diag(tx·e^{+iφ/2}, ty·e^{−iφ/2})·R(θ)(遅い軸が位相 −。OpticStudio の伝播の位相 e^{−i2πnd/λ}・
225/// 厚さのある結晶板([`Bire`])と同じ向き)。
226/// `plates` があれば(複屈折材の板)遅延は板ごとの Δn(λ)·d/λ で、行列は板の行列の積(光の通る順)
227#[derive(serde::Serialize, serde::Deserialize, schemars::JsonSchema, Debug, Clone, PartialEq)]
228pub struct Retarder {
229    pub axis_deg: f64,
230    pub tx: f64,
231    pub ty: f64,
232    /// 設計波長での遅延 [波長](λ/4 板は 0.25、偏光子は 0)
233    pub retardance: f64,
234    /// 多次の波長板の整数の次数(遅延は order + retardance 波長)
235    pub order: u32,
236    /// 設計波長 [µm]
237    pub wl0: f64,
238    /// 複屈折材の板(空なら理想の遅延 order + retardance)
239    #[serde(default, skip_serializing_if = "Vec::is_empty")]
240    pub plates: Vec<Plate>,
241}
242
243/// 波長板の複屈折材の板 1 枚: 常光の屈折率はガラス `material`、異常光は `material`-E(OpticStudio の
244/// 複屈折材の名前の約束)。板の光学軸は板の面内で、速い軸の向きは `axis_deg`(波長板の `axis_deg` からの角度)。
245/// 遅延は φ(λ) = 2π·s·(ne − no)(λ)·d/λ(s は設計波長での ne − no の符号で、設計波長で速い軸が `axis_deg` になる)。
246/// 斜めに入る光での遅延の変化は見ない(垂直入射の値)
247#[derive(serde::Serialize, serde::Deserialize, schemars::JsonSchema, Debug, Clone, PartialEq)]
248pub struct Plate {
249    pub material: String,
250    /// 厚さ [mm]
251    pub thickness: f64,
252    pub axis_deg: f64,
253    /// 常光・異常光のガラス([`Retarder::resolve`] で引く)
254    #[serde(default)]
255    pub o: Option<crate::glass::Glass>,
256    #[serde(default)]
257    pub e: Option<crate::glass::Glass>,
258}
259
260impl Plate {
261    /// 波長 `wl` [µm] の ne − no(ガラスを引いていなければ 0)
262    pub fn dn(&self, wl: f64) -> f64 {
263        match (&self.o, &self.e) {
264            (Some(o), Some(e)) => e.n_cat(wl) - o.n_cat(wl),
265            _ => 0.0,
266        }
267    }
268}
269
270/// 軸 `axis_deg` の向きの振幅 a、直交する向き b の Jones 行列
271fn axis_matrix(
272    a: num_complex::Complex64,
273    b: num_complex::Complex64,
274    axis_deg: f64,
275) -> [num_complex::Complex64; 4] {
276    let (s, c) = axis_deg.to_radians().sin_cos();
277    // R(θ) = [[c, s], [−s, c]] で軸の座標へ、diag(a, b)、R(−θ) で戻す
278    [
279        a * c * c + b * s * s,
280        (a - b) * c * s,
281        (a - b) * c * s,
282        a * s * s + b * c * c,
283    ]
284}
285
286fn mul2(
287    m: &[num_complex::Complex64; 4],
288    n: &[num_complex::Complex64; 4],
289) -> [num_complex::Complex64; 4] {
290    [
291        m[0] * n[0] + m[1] * n[2],
292        m[0] * n[1] + m[1] * n[3],
293        m[2] * n[0] + m[3] * n[2],
294        m[2] * n[1] + m[3] * n[3],
295    ]
296}
297
298impl Retarder {
299    /// 板の常光・異常光のガラスを `glasses` から引く。厚さ 0 の板(1 枚だけのとき)は、設計波長の遅延
300    /// order + retardance から厚さを決める
301    pub fn resolve(
302        &mut self,
303        glasses: &std::collections::HashMap<String, crate::glass::Glass>,
304    ) -> crate::Result<()> {
305        let n = self.plates.len();
306        for p in &mut self.plates {
307            let ename = format!("{}-E", p.material);
308            let (Some(o), Some(e)) = (glasses.get(&p.material), glasses.get(&ename)) else {
309                return Err(format!(
310                    "birefringent material {}: the ordinary glass {} or extraordinary glass {ename} is not in the catalogs",
311                    p.material, p.material
312                ).into());
313            };
314            p.o = Some(o.clone());
315            p.e = Some(e.clone());
316            let dn = p.dn(self.wl0);
317            if !(dn.is_finite() && dn != 0.0) {
318                return Err(format!(
319                    "ne − no of birefringent material {} at the design wavelength {} µm is {dn}",
320                    p.material, self.wl0
321                )
322                .into());
323            }
324            if p.thickness == 0.0 {
325                if n != 1 {
326                    return Err(
327                        "write a thickness for each plate of a waveplate with 2 or more plates"
328                            .into(),
329                    );
330                }
331                // d [mm] = (order + retardance)·λ0 / |Δn(λ0)|
332                p.thickness = (self.order as f64 + self.retardance) * self.wl0 * 1e-3 / dn.abs();
333            }
334            if !(p.thickness > 0.0 && p.thickness.is_finite()) {
335                return Err(format!(
336                    "birefringent material {} plate thickness {}",
337                    p.material, p.thickness
338                )
339                .into());
340            }
341        }
342        Ok(())
343    }
344
345    /// 設計波長での板ごとの遅延 [波長](速い軸から見た遅い軸の遅れ)
346    pub fn plate_retardance(&self, wl: f64) -> Vec<f64> {
347        self.plates
348            .iter()
349            .map(|p| p.dn(self.wl0).signum() * p.dn(wl) * p.thickness * 1e3 / wl)
350            .collect()
351    }
352
353    /// 波長 `wl` [µm] の Jones 行列 [A, B, C, D](Ex' = A·Ex + B·Ey、Ey' = C·Ex + D·Ey)
354    pub fn jones_at(&self, wl: f64) -> [num_complex::Complex64; 4] {
355        use num_complex::Complex64 as C;
356        if !self.plates.is_empty() {
357            let tau = 2.0 * std::f64::consts::PI;
358            let mut m = axis_matrix(C::new(self.tx, 0.0), C::new(self.ty, 0.0), self.axis_deg);
359            for (p, r) in self.plates.iter().zip(self.plate_retardance(wl)) {
360                let q = axis_matrix(
361                    C::from_polar(1.0, tau * r / 2.0),
362                    C::from_polar(1.0, -tau * r / 2.0),
363                    self.axis_deg + p.axis_deg,
364                );
365                m = mul2(&q, &m);
366            }
367            return m;
368        }
369        let phi = if self.retardance == 0.0 && self.order == 0 {
370            0.0
371        } else {
372            2.0 * std::f64::consts::PI * (self.order as f64 + self.retardance) * self.wl0 / wl
373        };
374        axis_matrix(
375            C::from_polar(self.tx, phi / 2.0),
376            C::from_polar(self.ty, -phi / 2.0),
377            self.axis_deg,
378        )
379    }
380    /// 波長 `wl` の行列を面の `jones`([Ar, Ai, Br, Bi, Cr, Ci, Dr, Di])の並びで
381    pub fn jones8(&self, wl: f64) -> [f64; 8] {
382        let m = self.jones_at(wl);
383        [
384            m[0].re, m[0].im, m[1].re, m[1].im, m[2].re, m[2].im, m[3].re, m[3].im,
385        ]
386    }
387}
388
389/// 複屈折材の板(OpticStudio の Birefringent In / Out の組)。入口の面の後の媒質(`mat`)が常光の材料、
390/// `mat`-E が異常光の材料。Mode 0・2 は光線が常光の道を進み(屈折率 no)、出口の面で、板の中の光線の向き k と
391/// 結晶軸 a から決まる異常光の成分(a の k に垂直な向き)に、常光の成分に対して
392/// exp(−i·2π·(n(θ) − no)·L/λ) の位相を付ける(OpticStudio の Mode 2、波長板モード)。
393/// n(θ) = 1/√(cos²θ/no² + sin²θ/ne²)、θ は k と a の角、L は板の中の光線の長さ。Mode 0 は常光の成分だけを通す。
394/// Mode 1・3 は光線が異常光の道を進む(入口・出口で波面法線の向きの屈折率 n(θ) で屈折し、板の中は
395/// エネルギーの向きへ walk-off して進み、光路長は異常光で数える)。Mode 1 は異常光の成分だけを通し、Mode 3 は
396/// 常光の成分に異常光に対する位相を付ける([`crate::trace`] の uniaxial)
397#[derive(serde::Serialize, serde::Deserialize, schemars::JsonSchema, Debug, Clone, PartialEq)]
398pub enum Bire {
399    In {
400        /// 0: 常光の成分だけ、1: 異常光の道で異常光の成分だけ、2: 常光の道で両方の位相(波長板)、
401        /// 3: 異常光の道で両方の位相
402        mode: u8,
403        /// 結晶軸の向き(入口の面の局所座標、規格化しなくてよい)
404        axis: [f64; 3],
405        /// 異常光の屈折率(波長ごと)
406        #[serde(default)]
407        ne: Vec<f64>,
408    },
409    Out,
410}
411
412impl Bire {
413    /// 異常光の材料の名前(OpticStudio の約束)
414    pub fn e_name(mat: &str) -> String {
415        format!("{}-E", mat.trim())
416    }
417}
418
419/// 屈折面での反射の、反対側(光が入らない側)の媒質
420#[derive(serde::Serialize, serde::Deserialize, schemars::JsonSchema, Debug, Clone, PartialEq)]
421pub struct Reflect {
422    /// 媒質の名前(空気は "AIR")
423    pub mat: String,
424    /// 屈折率(波長ごと)
425    pub n: Vec<f64>,
426}
427
428impl Default for Surface {
429    fn default() -> Self {
430        Surface {
431            form: Form::Standard,
432            ignore: false,
433            t: 0.0,
434            comment: String::new(),
435            mat: Material::Air,
436            coat: String::new(),
437            stop: false,
438            semi: 0.0,
439            semi_auto: false,
440            c: 0.0,
441            k: 0.0,
442            before: None,
443            after: After::None,
444            ap: Aperture::None,
445            dn: 0.0,
446            disp: 0.0,
447            dnd: 0.0,
448            dvd: 0.0,
449            reflect: None,
450            retarder: None,
451            bire: None,
452            tce: 0.0,
453            mech_semi: None,
454            coord_return: None,
455            chip_zone: 0.0,
456        }
457    }
458}
459
460/// 面ごとに、前後で媒質が変わる面か(玉の縁でける浮動開口を付ける面。.zmx の読込・プロジェクトの展開で同じ規則)。
461/// ガラスと空気・別のガラスの境(ガラスの名前は大文字小文字を区別しない)は true、空気どうし・同じガラスどうしは false。
462/// 座標ブレーク(媒質を持たない面)は false で、後ろの媒質は前のまま(OpticStudio 2026 R1.01 の読込の実測と同じ)。
463/// 鏡は前の媒質がガラスなら true(裏面鏡)
464pub fn medium_edges(surfaces: &[Surface]) -> Vec<bool> {
465    let same = |a: &Material, b: &Material| match (a, b) {
466        (Material::Glass(x), Material::Glass(y)) => x.eq_ignore_ascii_case(y),
467        _ => a == b,
468    };
469    let mut before = Material::Air;
470    let mut out = Vec::with_capacity(surfaces.len());
471    for (k, d) in surfaces.iter().enumerate() {
472        let after = match &d.mat {
473            Material::Mirror | Material::Inherit => before.clone(),
474            m => m.clone(),
475        };
476        out.push(
477            k > 0
478                && match &d.mat {
479                    Material::Mirror => !before.is_air(),
480                    Material::Inherit => false,
481                    _ => !same(&before, &after),
482                },
483        );
484        before = after;
485    }
486    out
487}
488
489impl Surface {
490    /// 鏡(材料が [`Material::Mirror`])
491    pub fn is_mirror(&self) -> bool {
492        self.mat.is_mirror()
493    }
494
495    pub fn has_asph(&self) -> bool {
496        self.asph().iter().any(|&a| a != 0.0)
497    }
498}