Skip to main content

lensbench_project/
zmx_wrap.rs

1//! .zmx の系を、.zmx を 1 つの zmx ブロックとして取り込むプロジェクトに書き換える(GUI が .zmx を組合せとして
2//! 開くため)。作り直した系が元の系と同じかは [`same_system`] で確かめる
3
4use super::*;
5use serde_json::json;
6
7/// [`zmx_project`] の zmx ブロックの id(GLRS をブロックの面で書くとき)
8pub const ZMX_ID: &str = "zmx";
9
10/// .zmx(`path`)の構成ごとの系 cfgs(cfgs[k - 1] が構成 k)の設定と、`path` をまるごと取り込む zmx ブロック 1 つの
11/// プロジェクト。系 1 つで多重構成の表があれば、表から構成ごとの系を作る。構成が 2 つ以上なら、本体は構成 1 で、
12/// 構成ごとに状態「Config k」を足す(zmx ブロックの config と、構成で変わる系の値)。
13/// 書いた形が読めなければ誤り
14pub fn zmx_project(cfgs: &[System], path: &str) -> lensbench_core::Result<Value> {
15    let from_table: Vec<System>;
16    let cfgs = match cfgs {
17        [] => return Err("no system".into()),
18        [s] => match s.configs().map(|c| c.n) {
19            Some(n) => {
20                from_table = (1..=n)
21                    .map(|k| s.config(k))
22                    .collect::<lensbench_core::Result<_>>()?;
23                &from_table[..]
24            }
25            None => {
26                let mut p = settings(s, path)?;
27                set_catalogs(&mut p, std::slice::from_ref(s));
28                checked(&p)?;
29                return Ok(p);
30            }
31        },
32        _ => cfgs,
33    };
34    let mut p = settings(&cfgs[0], path)?;
35    p["blocks"][0]["id"] = json!(ZMX_ID);
36    let mut states = Vec::new();
37    for (i, s) in cfgs.iter().enumerate() {
38        let q = settings(s, path)?;
39        let (Some(a), Some(b)) = (p.as_object(), q.as_object()) else {
40            unreachable!("settings write an object");
41        };
42        let mut project = serde_json::Map::new();
43        for (key, v) in b {
44            if key != "blocks" && a.get(key) != Some(v) {
45                project.insert(key.clone(), v.clone());
46            }
47        }
48        // 構成 1 にあって構成 k で省いた値は既定に戻す
49        for key in a.keys().filter(|key| !b.contains_key(*key)) {
50            let d = match key.as_str() {
51                "telecentric" => json!(false),
52                "floating_clip" => json!(true),
53                "mech_clip" => json!(true),
54                "apodization" => json!("uniform"),
55                "ropd" => json!(2),
56                "aim_pupil" => json!({}),
57                "input_pol" => json!({}),
58                "glass_template" => {
59                    serde_json::to_value(lensbench_core::system::GlassTemplate::default())
60                        .unwrap_or_default()
61                }
62                "environment" => {
63                    json!({ "temperature_c": 20.0, "pressure_atm": 1.0, "adjust_index": false })
64                }
65                _ => Value::Null,
66            };
67            project.insert(key.clone(), d);
68        }
69        let k = i + 1;
70        states.push(json!({
71            "name": format!("Config {k}"),
72            "set": { ZMX_ID: { "config": k } },
73            "project": project,
74        }));
75    }
76    p["states"] = json!(states);
77    set_catalogs(&mut p, cfgs);
78    // 書いた形を読めるか、状態を当てられるか
79    let pj = checked(&p)?;
80    for st in pj.state_names() {
81        pj.with_state(st)?;
82    }
83    Ok(p)
84}
85
86/// 系 s の設定と zmx ブロック 1 つのプロジェクト(多重構成の表は見ない)
87pub(crate) fn settings(s: &System, path: &str) -> lensbench_core::Result<Value> {
88    let ap = match s.aperture.0 {
89        ApertureKind::Epd => "epd",
90        ApertureKind::FNum => "fnum",
91        ApertureKind::Na => "na",
92        ApertureKind::Float => "float",
93        ApertureKind::Pwfn => "pwfn",
94        ApertureKind::Cone => "cone",
95    };
96    let ft = match s.field_type {
97        FieldType::Angle => "angle",
98        FieldType::ObjH => "object_height",
99        FieldType::ParH => "paraxial_image_height",
100        FieldType::RealH => "real_image_height",
101        FieldType::Solve(_) => "solve",
102    };
103    let mut fields = json!({
104        "type": ft,
105        "points": s.fields.iter().map(|f| [f.x, f.y]).collect::<Vec<_>>(),
106        "weights": s.fields.iter().map(|f| f.w).collect::<Vec<_>>(),
107    });
108    // 条件の面は系の面の番号(.zmx をまるごと取り込むので、展開した系でも同じ番号)
109    if let FieldType::Solve(c) = s.field_type {
110        fields["solve"] = match c {
111            FieldCond::Position { surf } => {
112                json!({ "cond": "position", "surface": surf.to_string() })
113            }
114            FieldCond::DirSum { s1, s2 } => {
115                json!({ "cond": "dir_sum", "s1": s1.to_string(), "s2": s2.to_string() })
116            }
117            FieldCond::DirDiff { s1, s2 } => {
118                json!({ "cond": "dir_diff", "s1": s1.to_string(), "s2": s2.to_string() })
119            }
120        };
121    }
122    if s.field_norm == FieldNorm::Rect {
123        fields["norm"] = json!("rect");
124    }
125    let vig: Vec<[f64; 5]> = s
126        .fields
127        .iter()
128        .map(|f| [f.vdx, f.vdy, f.vcx, f.vcy, f.van])
129        .collect();
130    if vig.iter().flatten().any(|&x| x != 0.0) {
131        fields["vignetting"] = json!(vig);
132    }
133    let mut p = json!({
134        "name": s.name,
135        "wavelengths": s.wavelengths.iter().zip(&s.weights)
136            .map(|(um, w)| json!({ "um": um, "weight": w }))
137            .collect::<Vec<_>>(),
138        "primary": s.primary + 1,
139        "aperture": { "type": ap, "value": s.aperture.1 },
140        "fields": fields,
141        "aiming": match s.aiming {
142            Aiming::Off => "off",
143            Aiming::Paraxial => "paraxial",
144            Aiming::Real => "real",
145        },
146        "blocks": [{ "type": "zmx", "path": path }],
147    });
148    let t0 = s.surfaces.first().map_or(f64::INFINITY, |o| o.t);
149    if t0.is_finite() {
150        p["object_distance"] = json!(t0);
151    }
152    if s.telecentric {
153        p["telecentric"] = json!(true);
154    }
155    if s.afocal {
156        p["afocal"] = json!(s.afocal_unit.code().to_ascii_lowercase());
157    }
158    if !s.floating_clip {
159        p["floating_clip"] = json!(false);
160    }
161    if !s.mech_clip {
162        p["mech_clip"] = json!(false);
163    }
164    if s.apodization != lensbench_core::pupil::Apodization::Uniform {
165        p["apodization"] = serde_json::to_value(s.apodization).map_err(|e| e.to_string())?;
166    }
167    if s.ropd != 2 {
168        p["ropd"] = json!(s.ropd);
169    }
170    if !s.glass_template.is_default() {
171        p["glass_template"] = serde_json::to_value(s.glass_template).map_err(|e| e.to_string())?;
172    }
173    if !s.input_pol.is_default() {
174        p["input_pol"] = serde_json::to_value(s.input_pol).map_err(|e| e.to_string())?;
175    }
176    if !s.aim_pupil.is_default() {
177        p["aim_pupil"] = serde_json::to_value(s.aim_pupil).map_err(|e| e.to_string())?;
178    }
179    // GLRS はブロックの面で書く(前に要素を足しても同じ面を指す)。ブロックの面は座標ブレークを数えないので、
180    // 座標ブレーク・物体面・像面は系の面の番号のまま
181    let image = s.surfaces.len().saturating_sub(1);
182    let cb = |j: usize| s.surfaces[j].is_coord_break();
183    if (1..image).contains(&s.glrs) && !cb(s.glrs) {
184        p["blocks"][0]["id"] = json!(ZMX_ID);
185        let k = (1..s.glrs).filter(|&j| !cb(j)).count();
186        p["glrs"] = json!({ "block": ZMX_ID, "surface": k });
187    } else if s.glrs != 1 {
188        p["glrs"] = json!(s.glrs);
189    }
190    if s.temperature != 20.0 || s.pressure != 1.0 || s.adjust_index {
191        p["environment"] = json!({
192            "temperature_c": s.temperature,
193            "pressure_atm": s.pressure,
194            "adjust_index": s.adjust_index,
195        });
196    }
197    // 物体面の形・開口・物体空間の媒質(平面で開口なし・空気なら書かない。厚さは object_distance、コメントは zmx
198    // ブロックが持ち越す)
199    if let Some(obj) = s.surfaces.first() {
200        let mut r = crate::sysfile_v2::write::surface_row(obj, false)?;
201        r.semi = None;
202        r.stop = false;
203        r.object = false;
204        r.t = 0.0;
205        r.comment.clear();
206        if r != crate::sysfile_v2::Row::default() {
207            p["object"] = serde_json::to_value(&r).map_err(|e| e.to_string())?;
208        }
209    }
210    // 像面の形・傾き(平面で傾きなしなら書かない。半直径は描画にだけ使うので書かない。像面の後ろは無いので厚さも書かない)
211    if let Some(img) = s.surfaces.last().filter(|_| image > 0) {
212        let mut r = crate::sysfile_v2::write::surface_row(img, false)?;
213        r.semi = None;
214        r.stop = false;
215        r.t = 0.0;
216        // 浮動開口の半径は面の半直径に付いてくるので、半直径を書かない像面では値を書く
217        if let (
218            Some(crate::sysfile_v2::Aperture::Floating { semi: v @ None }),
219            lensbench_core::surface::Aperture::Floating { semi },
220        ) = (r.aperture.as_mut(), img.ap)
221        {
222            *v = Some(semi);
223        }
224        if r != crate::sysfile_v2::Row::default() {
225            p["image"] = serde_json::to_value(&r).map_err(|e| e.to_string())?;
226        }
227    }
228    Ok(p)
229}
230
231/// 2 つの系が同じか。名前・読込の注意・ガラスの表(屈折率は面ごとに比べる)・玉の表と、物体面・像面の半直径
232/// (描画にだけ使う)は見ない。自動の半直径は光線から求めた値なので 1e-9 mm まで。違えば最初のいくつかの違い
233pub fn same_system(a: &System, b: &System) -> lensbench_core::Result<()> {
234    let va = comparable(a)?;
235    let vb = comparable(b)?;
236    let mut out = Vec::new();
237    diff(&va, &vb, &mut String::new(), &mut out);
238    if out.is_empty() {
239        Ok(())
240    } else {
241        out.truncate(5);
242        Err(lensbench_core::Error::Invalid(out.join("; ")))
243    }
244}
245
246fn comparable(s: &System) -> lensbench_core::Result<Value> {
247    let mut v = sysfile::internal_value(s)?;
248    let m = v.as_object_mut().ok_or("system is not an object")?;
249    for k in ["name", "import_notes", "glasses", "units", "configs"] {
250        m.remove(k);
251    }
252    // 物体面・像面の半直径は描画にだけ使うので、そのピックアップも見ない
253    let last = s.surfaces.len().saturating_sub(1);
254    if let Some(Value::Array(ps)) = m.get_mut("pickups") {
255        ps.retain(|q| {
256            let dst = q["dst"].as_u64().map(|d| d as usize);
257            !(q["what"] == "Semi" && (dst == Some(0) || dst == Some(last)))
258        });
259        if ps.is_empty() {
260            m.remove("pickups");
261        }
262    }
263    // 面の後の媒質の屈折率(同じ名前のガラスを別のカタログから引いたら違う。ガラスの表そのものは比べない)
264    let n: Vec<&[f64]> = (0..s.surfaces.len()).map(|j| s.n(j)).collect();
265    m.insert("media_n".into(), json!(n));
266    // 無限遠系でなければ無限遠系の単位は使わない
267    if m.get("afocal") != Some(&Value::Bool(true)) {
268        m.remove("afocal_unit");
269    }
270    // ZPL マクロのソルブ・OPD のソルブの値は光線から繰り返して求めた値(解く順で最後の桁が変わる)なので、その面の値は 10 桁まで
271    let solved_by_macro: Vec<usize> = s
272        .macro_parms
273        .iter()
274        .map(|q| q.surf)
275        .chain(s.solves.iter().filter_map(|q| {
276            matches!(
277                q.kind,
278                lensbench_core::solves::SolveKind::MacroCurv { .. }
279                    | lensbench_core::solves::SolveKind::MacroThick { .. }
280                    | lensbench_core::solves::SolveKind::Opd { .. }
281            )
282            .then_some(q.surf)
283        }))
284        .collect();
285    fn round10(v: &mut Value) {
286        match v {
287            Value::Number(n) if n.is_f64() => {
288                if let Some(x) = n.as_f64().filter(|x| x.is_finite()) {
289                    let r: f64 = format!("{x:.9e}").parse().unwrap_or(x);
290                    // ±0 と 1e-15 ほどの差は 0
291                    *v = json!(if r.abs() < 1e-12 { 0.0 } else { r });
292                }
293            }
294            Value::Array(a) => a.iter_mut().for_each(round10),
295            Value::Object(o) => o.values_mut().for_each(round10),
296            _ => {}
297        }
298    }
299    if let Some(Value::Array(sf)) = m.get_mut("surfaces") {
300        for &k in &solved_by_macro {
301            if let Some(x) = sf.get_mut(k) {
302                round10(x);
303            }
304        }
305        let last = sf.len().saturating_sub(1);
306        for (i, x) in sf.iter_mut().enumerate() {
307            let Some(o) = x.as_object_mut() else { continue };
308            if i == 0 || i == last {
309                o.remove("semi");
310                o.remove("semi_auto");
311            } else if o.get("semi_auto") == Some(&Value::Bool(true)) {
312                if let Some(r) = o.get("semi").and_then(Value::as_f64) {
313                    o.insert("semi".into(), json!((r * 1e9).round() / 1e9));
314                }
315            }
316        }
317    }
318    Ok(v)
319}
320
321fn diff(a: &Value, b: &Value, path: &mut String, out: &mut Vec<String>) {
322    match (a, b) {
323        (Value::Object(x), Value::Object(y)) => {
324            for k in x.keys().chain(y.keys().filter(|k| !x.contains_key(*k))) {
325                let n = path.len();
326                path.push('/');
327                path.push_str(k);
328                match (x.get(k), y.get(k)) {
329                    (Some(u), Some(w)) => diff(u, w, path, out),
330                    _ => out.push(format!("{path} on one side only")),
331                }
332                path.truncate(n);
333            }
334        }
335        (Value::Array(x), Value::Array(y)) if x.len() == y.len() => {
336            for (i, (u, w)) in x.iter().zip(y).enumerate() {
337                let n = path.len();
338                path.push_str(&format!("/{i}"));
339                diff(u, w, path, out);
340                path.truncate(n);
341            }
342        }
343        _ if a != b => out.push(format!("{path}: {a} vs {b}")),
344        _ => {}
345    }
346}
347
348/// 書いたプロジェクトを読み直す。読めなければ null の欄(有限でない値は JSON で null になる)の場所を理由に足す
349pub(crate) fn checked(p: &Value) -> lensbench_core::Result<Project> {
350    fn nulls(v: &Value, at: &str, out: &mut Vec<String>) {
351        match v {
352            Value::Null => out.push(at.to_string()),
353            Value::Array(a) => a
354                .iter()
355                .enumerate()
356                .for_each(|(i, x)| nulls(x, &format!("{at}/{i}"), out)),
357            Value::Object(o) => o
358                .iter()
359                .for_each(|(k, x)| nulls(x, &format!("{at}/{k}"), out)),
360            _ => {}
361        }
362    }
363    Project::from_json(&p.to_string()).map_err(|e| {
364        let mut at = Vec::new();
365        nulls(p, "", &mut at);
366        if at.is_empty() {
367            e
368        } else {
369            e.map_message(|e| format!("{e} (null at {})", at.join(", ")))
370        }
371    })
372}
373
374/// 構成のガラスを引くカタログ(.zmx の GCAT で引いたものと同じガラスになる並び)を `glass_catalogs` に書く。
375/// 既定の並びでは、同じ名前のガラスを別のカタログから引くことがある
376pub(crate) fn set_catalogs(p: &mut Value, cfgs: &[System]) {
377    let mut names: Vec<String> = Vec::new();
378    for s in cfgs {
379        for n in crate::sysfile_v2::catalogs::names(s) {
380            if !names.contains(&n) {
381                names.push(n);
382            }
383        }
384    }
385    if !names.is_empty() && names != crate::defaults::default_catalogs() {
386        p["glass_catalogs"] = json!(names);
387    }
388}