Skip to main content

lensbench_project/
sysfile.rs

1//! 系ファイル: 順次の面の列の系([`System`])を保存・読込する lensbench 独自の JSON。
2//!
3//! ```json
4//! {"format": "lensbench-system", "format_version": 2, "lensbench": "0.1.0",
5//!  "hash": "sha256:…", "coatings": ["膜の表.json"], "system": { … }}
6//! ```
7//!
8//! - `system` は処方(利用者が書いた値だけ、[`crate::sysfile_v2::Prescription`])。形は core の内部の構造体と
9//!   切り離して決めてある。読み直した系の追跡は元の系とビット一致する(屈折率・自動の半直径・ピックアップ・ソルブは
10//!   読んだ後に求める)。
11//! - ガラスは名前だけを書き、`system.catalogs` に使ったカタログの名前とファイルの SHA-256 を残す。読むときは
12//!   カタログをフォルダから探して今のカタログの値で追い、hash が違えば注意を返す。
13//! - JSON に書けない数(無限遠の物体距離の inf、NaN)は `{"$f": "inf"}`・`{"$f": "-inf"}`・`{"$f": "nan"}`。
14//!   実数の欄は整数の書き方でも読め、誤りには欄の道が付く([`crate::lenient`])。
15//! - `hash` は `system` の部分(キーを名前の順にした空白なしの JSON)の SHA-256。解析の結果に刻んで、後から同じ系か確かめる。
16//!   読むときに合わなければ(手で直したなど)注意を返す。
17//! - `coatings` は膜の実測表・モデルのファイル(相対パスは系ファイルのフォルダから)。系の `coating_file` は系の中。
18//! - 版 1(core の System の serde をそのまま書いた形)は読まない(0.5 までの lensbench で開いて保存し直すと版 2 になる)。
19
20use lensbench_core::System;
21use serde_json::{Map, Value};
22use sha2::{Digest, Sha256};
23use std::path::{Path, PathBuf};
24
25/// 系ファイルの `format` の値
26pub const FORMAT: &str = "lensbench-system";
27/// 書く版(読めるのはこの版だけ)
28pub const FORMAT_VERSION: u64 = 2;
29
30/// 系ファイルの中身(系以外)
31#[derive(Debug, Clone, Default, PartialEq)]
32pub struct Meta {
33    /// 書いた lensbench の版
34    pub lensbench: String,
35    /// 系の hash("sha256:…")
36    pub hash: String,
37    /// 膜の実測表・モデルのファイル
38    pub coatings: Vec<PathBuf>,
39}
40
41/// JSON の文字列が系ファイルか(`format` を見る)
42pub fn is_system_json(txt: &str) -> bool {
43    // 先頭だけ見て決めずに、きちんと読む(大きな系でも 1 回読むだけ)
44    match serde_json::from_str::<Value>(txt) {
45        Ok(Value::Object(m)) => m.get("format").and_then(Value::as_str) == Some(FORMAT),
46        _ => false,
47    }
48}
49
50/// ファイルが系ファイルか(拡張子 .json で、`format` が系ファイル)
51pub fn is_system_file(path: &Path) -> bool {
52    if !path
53        .extension()
54        .is_some_and(|x| x.eq_ignore_ascii_case("json"))
55    {
56        return false;
57    }
58    lensbench_core::vfs::read_to_string(path).is_ok_and(|t| is_system_json(&t))
59}
60
61pub(crate) fn to_json(v: ciborium::value::Value) -> lensbench_core::Result<Value> {
62    use ciborium::value::Value as C;
63    Ok(match v {
64        C::Null => Value::Null,
65        C::Bool(b) => Value::Bool(b),
66        C::Integer(i) => {
67            let i: i128 = i.into();
68            if let Ok(u) = u64::try_from(i) {
69                Value::from(u)
70            } else if let Ok(s) = i64::try_from(i) {
71                Value::from(s)
72            } else {
73                return Err(format!("integer {i} is too large").into());
74            }
75        }
76        C::Float(f) => {
77            if f.is_finite() {
78                Value::from(f)
79            } else {
80                let s = if f.is_nan() {
81                    "nan"
82                } else if f > 0.0 {
83                    "inf"
84                } else {
85                    "-inf"
86                };
87                let mut m = Map::new();
88                m.insert("$f".into(), Value::from(s));
89                Value::Object(m)
90            }
91        }
92        C::Text(s) => Value::String(s),
93        C::Array(a) => Value::Array(a.into_iter().map(to_json).collect::<Result<_, _>>()?),
94        C::Map(m) => {
95            let mut o = Map::new();
96            for (k, v) in m {
97                let C::Text(k) = k else {
98                    return Err(format!("a table key is not a string ({k:?})").into());
99                };
100                o.insert(k, to_json(v)?);
101            }
102            Value::Object(o)
103        }
104        C::Tag(_, v) => to_json(*v)?,
105        C::Bytes(_) => return Err("bytes can't be written".into()),
106        _ => return Err("a value that can't be written".into()),
107    })
108}
109
110pub(crate) fn from_json(v: Value) -> lensbench_core::Result<ciborium::value::Value> {
111    use ciborium::value::Value as C;
112    Ok(match v {
113        Value::Null => C::Null,
114        Value::Bool(b) => C::Bool(b),
115        Value::Number(n) => {
116            if let Some(u) = n.as_u64() {
117                C::Integer(u.into())
118            } else if let Some(i) = n.as_i64() {
119                C::Integer(i.into())
120            } else {
121                C::Float(n.as_f64().ok_or("number")?)
122            }
123        }
124        Value::String(s) => C::Text(s),
125        Value::Array(a) => C::Array(a.into_iter().map(from_json).collect::<Result<_, _>>()?),
126        Value::Object(m) => {
127            if m.len() == 1 {
128                if let Some(Value::String(s)) = m.get("$f") {
129                    return Ok(C::Float(match s.as_str() {
130                        "inf" => f64::INFINITY,
131                        "-inf" => f64::NEG_INFINITY,
132                        "nan" => f64::NAN,
133                        _ => return Err(format!("number {{\"$f\": {s:?}}}").into()),
134                    }));
135                }
136            }
137            C::Map(
138                m.into_iter()
139                    .map(|(k, v)| Ok((C::Text(k), from_json(v)?)))
140                    .collect::<lensbench_core::Result<_>>()?,
141            )
142        }
143    })
144}
145
146/// core の System の serde をそのまま JSON にした値(ガラスの表は名前の順)。系どうしを比べる([`crate::same_system`])のに使う
147pub(crate) fn internal_value(s: &System) -> lensbench_core::Result<Value> {
148    let c =
149        ciborium::value::Value::serialized(s).map_err(|e| format!("writing the system: {e}"))?;
150    let mut v = to_json(c)?;
151    if let Some(Value::Object(g)) = v.get_mut("glasses") {
152        let mut items: Vec<(String, Value)> = std::mem::take(g).into_iter().collect();
153        items.sort_by(|a, b| a.0.cmp(&b.0));
154        g.extend(items);
155    }
156    Ok(v)
157}
158
159/// 系ファイルの `system` の JSON の値(処方)
160fn system_value(s: &System) -> lensbench_core::Result<Value> {
161    let p = crate::sysfile_v2::write::prescription(s)?;
162    let c =
163        ciborium::value::Value::serialized(&p).map_err(|e| format!("writing the system: {e}"))?;
164    to_json(c)
165}
166
167/// 系のガラスの元のカタログのファイル(このプロセスで読んだ AGF・既定のフォルダから、系のガラスと値が同じもの)。
168/// 系ファイルの JSON を別のプロセスに渡すとき(Python の pickle)に、そのフォルダを glass_dirs に渡す
169pub fn catalog_files(s: &System) -> Vec<PathBuf> {
170    crate::sysfile_v2::catalogs::files(s)
171}
172
173/// キーを名前の順に並べ、空白なしで書いた JSON(serde_json の preserve_order の有無によらず同じ)
174fn canonical(v: &Value, out: &mut String) {
175    match v {
176        Value::Object(m) => {
177            let mut keys: Vec<&String> = m.keys().collect();
178            keys.sort();
179            out.push('{');
180            for (i, k) in keys.into_iter().enumerate() {
181                if i > 0 {
182                    out.push(',');
183                }
184                out.push_str(&serde_json::to_string(k).expect("JSON"));
185                out.push(':');
186                canonical(&m[k], out);
187            }
188            out.push('}');
189        }
190        Value::Array(a) => {
191            out.push('[');
192            for (i, x) in a.iter().enumerate() {
193                if i > 0 {
194                    out.push(',');
195                }
196                canonical(x, out);
197            }
198            out.push(']');
199        }
200        x => out.push_str(&serde_json::to_string(x).expect("JSON")),
201    }
202}
203
204pub fn hash_value(v: &Value) -> String {
205    let mut txt = String::new();
206    canonical(v, &mut txt);
207    let d = Sha256::digest(txt.as_bytes());
208    let hex: String = d.iter().map(|b| format!("{b:02x}")).collect();
209    format!("sha256:{hex}")
210}
211
212/// 系の hash("sha256:…"、系ファイルの `hash` と同じ)。同じ系なら同じ値
213pub fn system_hash(s: &System) -> lensbench_core::Result<String> {
214    Ok(hash_value(&system_value(s)?))
215}
216
217/// 系を系ファイルの JSON(整形した文字列)にする
218pub fn to_string(s: &System, coatings: &[PathBuf]) -> lensbench_core::Result<String> {
219    let sv = system_value(s)?;
220    let hash = hash_value(&sv);
221    let mut o = Map::new();
222    o.insert("$schema".into(), Value::from(crate::schema::url("system")));
223    o.insert("format".into(), Value::from(FORMAT));
224    o.insert("format_version".into(), Value::from(FORMAT_VERSION));
225    o.insert("lensbench".into(), Value::from(lensbench_core::VERSION));
226    o.insert("hash".into(), Value::from(hash));
227    o.insert(
228        "coatings".into(),
229        Value::Array(
230            coatings
231                .iter()
232                .map(|p| Value::from(p.to_string_lossy().to_string()))
233                .collect(),
234        ),
235    );
236    o.insert("system".into(), sv);
237    // キーは名前の順(serde_json の preserve_order の有無によらず同じ文字列)
238    Ok(crate::schema::to_text(&Value::Object(o)))
239}
240
241/// 系ファイルの JSON を読む(ガラスのカタログは既定のフォルダとこのプロセスで読んだ AGF から探す)。
242/// 返すのは (系, 中身, 注意)。注意は hash が合わない・カタログが保存時と違うなど
243pub fn from_str(txt: &str) -> lensbench_core::Result<(System, Meta, Vec<String>)> {
244    from_str_with(txt, &[])
245}
246
247/// [`from_str`] で、ガラスのカタログをフォルダ glass_dirs から先に探す(その後に既定のフォルダ・このプロセスで
248/// 読んだ AGF)
249pub fn from_str_with(
250    txt: &str,
251    glass_dirs: &[PathBuf],
252) -> lensbench_core::Result<(System, Meta, Vec<String>)> {
253    let v: Value = serde_json::from_str(txt).map_err(|e| format!("system file: {e}"))?;
254    let Value::Object(mut o) = v else {
255        return Err("system file: not a JSON object".into());
256    };
257    if o.get("format").and_then(Value::as_str) != Some(FORMAT) {
258        return Err(format!("system file: format is not {FORMAT}").into());
259    }
260    let ver = o
261        .get("format_version")
262        .and_then(Value::as_u64)
263        .ok_or("system file: no format_version")?;
264    if ver > FORMAT_VERSION {
265        return Err(format!(
266            "system file: version {ver} can't be read (up to {FORMAT_VERSION}; update lensbench)"
267        )
268        .into());
269    }
270    if ver < FORMAT_VERSION {
271        return Err(format!(
272            "system file: version {ver} is no longer read (open and save it with lensbench 0.5 to make version {FORMAT_VERSION})"
273        )
274        .into());
275    }
276    let sv = o.remove("system").ok_or("system file: no system")?;
277    let mut warn = Vec::new();
278    let hash_now = hash_value(&sv);
279    let hash = o
280        .get("hash")
281        .and_then(Value::as_str)
282        .unwrap_or("")
283        .to_string();
284    let c = from_json(sv).map_err(|e| format!("system file: {e}"))?;
285    let p: crate::sysfile_v2::Prescription =
286        crate::lenient::decode(c, "system").map_err(|e| format!("system file: {e}"))?;
287    let dirs = lensbench_core::glass::catalog_dirs(glass_dirs);
288    let (mut g, notes) =
289        crate::sysfile_v2::catalogs::load(&p.catalogs, &dirs).map_err(|e| e.at("system file"))?;
290    warn.extend(notes);
291    // 名前@カタログ のガラス(同じ名前の別のガラスと分けた名前)は、そのカタログから引く
292    let named = p.surfaces.iter().filter_map(|r| match &r.medium {
293        Some(crate::sysfile_v2::Medium::Glass(m)) if m.contains('@') => Some(m.as_str()),
294        _ => None,
295    });
296    lensbench_core::glass::resolve_qualified(&mut g, named, &dirs);
297    let sys = crate::sysfile_v2::read::system(p, std::sync::Arc::new(g))
298        .map_err(|e| format!("system file: {e}"))?;
299    check(&sys)?;
300    // hash は読み直した系から作り直したものとも比べる(数の書き方の違いでは値が変わる)
301    let hash_sys = system_hash(&sys)?;
302    if !hash.is_empty() && hash != hash_now && hash != hash_sys {
303        warn.push(format!(
304            "the hash of the system file doesn't match its content (edited after writing? recorded {hash}, now {hash_sys})"
305        ));
306    }
307    let coatings = match o.get("coatings") {
308        None | Some(Value::Null) => Vec::new(),
309        Some(Value::Array(a)) => a
310            .iter()
311            .map(|x| {
312                x.as_str()
313                    .map(PathBuf::from)
314                    .ok_or_else(|| "system file: coatings must be a list of strings".to_string())
315            })
316            .collect::<Result<_, _>>()?,
317        Some(_) => return Err("system file: coatings must be a list of strings".into()),
318    };
319    let meta = Meta {
320        lensbench: o
321            .get("lensbench")
322            .and_then(Value::as_str)
323            .unwrap_or("")
324            .to_string(),
325        hash: hash_sys,
326        coatings,
327    };
328    Ok((sys, meta, warn))
329}
330
331/// 壊れた・手で直した系で追跡が panic しないよう、配列の長さと系の約束を確かめる
332pub fn check(sys: &System) -> lensbench_core::Result<()> {
333    let nw = sys.wavelengths.len();
334    if nw == 0 || sys.weights.len() != nw || sys.primary >= nw {
335        return Err(
336            "system file: the numbers of wavelengths, weights and primary don't match".into(),
337        );
338    }
339    check_refs(sys)?;
340    Ok(sys.check().map_err(|e| format!("system file: {e}"))?)
341}
342
343/// ピックアップ・ソルブ・マクロ・玉と群・大域座標の基準が範囲の中の面を指すか
344pub(crate) fn check_refs(sys: &lensbench_core::Prescription) -> lensbench_core::Result<()> {
345    let ns = sys.surfaces.len();
346    for p in &sys.pickups {
347        if p.src >= ns || p.dst >= ns {
348            return Err(format!("system file: pickup surfaces ({} → {})", p.src, p.dst).into());
349        }
350    }
351    for q in &sys.solves {
352        if q.surf >= ns || q.kind.other_surface().is_some_and(|f| f >= ns) {
353            return Err(format!("system file: solve surface {}", q.surf).into());
354        }
355        if let lensbench_core::solves::SolveKind::MacroCurv { index: i }
356        | lensbench_core::solves::SolveKind::MacroThick { index: i } = q.kind
357        {
358            if i as usize >= sys.macros.len() {
359                return Err(format!("system file: no macro {i} for surface {}", q.surf).into());
360            }
361        }
362    }
363    for q in &sys.macro_parms {
364        if q.surf >= ns || q.id as usize >= sys.macros.len() {
365            return Err(format!("system file: macro solve (surface {})", q.surf).into());
366        }
367    }
368    for u in &sys.units {
369        if u.spans.iter().any(|s| s[0] > s[1] || s[1] >= ns) {
370            return Err(format!("system file: range of lens or group {}", u.name).into());
371        }
372    }
373    if sys.glrs >= ns {
374        return Err(format!(
375            "system file: global coordinate reference surface {}",
376            sys.glrs
377        )
378        .into());
379    }
380    Ok(())
381}
382
383/// 系ファイルに書く(coatings は書いたとおりに残す)
384pub fn save(path: &Path, s: &System, coatings: &[PathBuf]) -> lensbench_core::Result<()> {
385    let txt = to_string(s, coatings)?;
386    lensbench_core::vfs::write_atomic(path, txt)
387        .map_err(lensbench_core::Error::io_at(path.display()))
388}
389
390/// 系を系ファイルに書くときの注意([`save`]・[`to_string`] の後に表に出す): 系のガラスと値が同じカタログのファイルが
391/// 見つからず、`catalogs` に hash を書けないカタログ(読むときに値を確かめられない)
392pub fn save_notes(s: &System) -> Vec<String> {
393    crate::sysfile_v2::catalogs::unverified(s)
394}
395
396/// 系ファイルを読む。coatings の相対パスはファイルのフォルダからにする。ガラスのカタログはファイルのフォルダ・
397/// 既定のフォルダ・このプロセスで読んだ AGF から探す
398pub fn load(path: &Path) -> lensbench_core::Result<(System, Meta, Vec<String>)> {
399    load_with(path, &[])
400}
401
402/// [`load`] で、ガラスのカタログをフォルダ glass_dirs から先に探す
403pub fn load_with(
404    path: &Path,
405    glass_dirs: &[PathBuf],
406) -> lensbench_core::Result<(System, Meta, Vec<String>)> {
407    let txt = lensbench_core::vfs::read_to_string(path)
408        .map_err(lensbench_core::Error::io_at(path.display()))?;
409    load_text_with(path, &txt, glass_dirs)
410}
411
412/// [`load_with`] で、ファイル path の中身 txt をもう読んであるとき(読み直さない)
413pub fn load_text_with(
414    path: &Path,
415    txt: &str,
416    glass_dirs: &[PathBuf],
417) -> lensbench_core::Result<(System, Meta, Vec<String>)> {
418    // "a.json" の parent は "" なので、カタログは "." から探す
419    let base = path
420        .parent()
421        .filter(|p| !p.as_os_str().is_empty())
422        .unwrap_or(Path::new("."));
423    let mut dirs = glass_dirs.to_vec();
424    dirs.push(base.to_path_buf());
425    let (s, mut m, w) = from_str_with(txt, &dirs).map_err(|e| e.at(path.display()))?;
426    for c in m.coatings.iter_mut() {
427        if c.is_relative() {
428            *c = base.join(&*c);
429        }
430    }
431    Ok((s, m, w))
432}