Skip to main content

lensbench_project/
back.rs

1//! 面からブロックへの逆変換(玉モードの玉・ユーザーカタログへの保存)
2
3use super::*;
4/// 玉(玉モードの要素)を、面を直接書いた玉のブロックにする(ほかのプロジェクトへ持ち出せる形)
5pub fn lens_to_block(e: &Element, id: &str) -> lensbench_core::Result<Block> {
6    if e.kind != Kind::Lens {
7        return Err("not a lens element".into());
8    }
9    let n = e.surfaces.len();
10    let mut v = Vec::new();
11    for (i, s) in e.surfaces.iter().enumerate() {
12        let last = i + 1 == n;
13        let mut q = surface_spec(s, last)
14            .map_err(|x| x.map_message(|e| format!("lens surface {}: {e}", i + 1)))?;
15        if q.coordbrk.is_some() || s.typ() == SurfType::Jones {
16            return Err(format!(
17                "lens surface {}: only standard, even asphere, Odd Asphere, toroidal and Fresnel surfaces can be saved",
18                i + 1
19            )
20            .into());
21        }
22        if last {
23            q.t = 0.0;
24        }
25        // カタログの玉は径が決まっているので固定(自動ならいまの値)
26        q.semi = Semi::Value(s.semi);
27        v.push(q);
28    }
29    Ok(Block::Lens {
30        id: id.to_string(),
31        source: LensSource::Surfaces { surfaces: v },
32        reversed: false,
33        stop: false,
34        place: Place::default(),
35        faces: FaceMods::default(),
36    })
37}
38
39/// 系の玉 k(1 始まり、玉だけを数える)をユーザーカタログの項目にする
40pub fn lens_item(s: &System, k: usize, description: &str) -> lensbench_core::Result<UserItem> {
41    let e = pick_lens(s, k)?;
42    let mut cats: Vec<String> = Vec::new();
43    for d in &e.surfaces {
44        if let Some(g) = d.mat.glass().and_then(|g| s.glasses.get(g)) {
45            if !g.catalog.is_empty() && !cats.contains(&g.catalog) {
46                cats.push(g.catalog.clone());
47            }
48        }
49    }
50    Ok(UserItem::optic(
51        description,
52        cats,
53        vec![lens_to_block(&e, "")?],
54    ))
55}
56
57/// プロジェクトのブロック id(入れ子も探す)をユーザーカタログの項目にする。
58/// .zmx の玉は面を直接書いた玉に、.zmx の取り込み・ユーザーカタログの参照のパスは絶対パスにする
59pub fn block_item(
60    p: &Project,
61    env: &Env,
62    id: &str,
63    description: &str,
64) -> lensbench_core::Result<UserItem> {
65    fn find<'x>(v: &'x [Block], id: &str, out: &mut Vec<&'x Block>) {
66        for b in v {
67            let bid = match b {
68                Block::Lens { id, .. }
69                | Block::Air { id, .. }
70                | Block::Stop { id, .. }
71                | Block::Mirror { id, .. }
72                | Block::Surfaces { id, .. }
73                | Block::Zmx { id, .. }
74                | Block::User { id, .. }
75                | Block::Detector(DetectorBlock { id, .. })
76                | Block::Splitter { id, .. }
77                | Block::Group { id, .. } => id,
78            };
79            if !id.is_empty() && bid == id {
80                out.push(b);
81            }
82            if let Block::Group { blocks, .. } = b {
83                find(blocks, id, out);
84            }
85            if let Block::Splitter { spec, .. } = b {
86                for l in [&spec.t, &spec.r, &spec.d] {
87                    find(l, id, out);
88                }
89            }
90        }
91    }
92    let mut hits = Vec::new();
93    find(&p.blocks, id, &mut hits);
94    let b = match hits.as_slice() {
95        [b] => (*b).clone(),
96        [] => {
97            return Err(lensbench_core::Error::Invalid(format!("no block {id}"))
98                .with_code(lensbench_core::error::code::BLOCK_NOT_FOUND))
99        }
100        _ => return Err(format!("two or more blocks with id {id}").into()),
101    };
102    let mut c = Ctx {
103        env,
104        cache: None,
105        base: env.base.clone(),
106        loading: Vec::new(),
107        outer: 0,
108        sf: Vec::new(),
109        map: Vec::new(),
110        noted: Vec::new(),
111        nflip: 0,
112        flip_err: None,
113        zpicks: Vec::new(),
114        lead: 0.0,
115        parity: 1.0,
116        glasses: Default::default(),
117        coats: HashMap::new(),
118        nstop: 0,
119        gaps: Vec::new(),
120        split: SplitState::default(),
121        turn: Default::default(),
122        media: HashMap::new(),
123        frames: Vec::new(),
124        zenv: Vec::new(),
125        nodes: HashMap::new(),
126        leaf: Vec::new(),
127        failed: None,
128        notes: Vec::new(),
129    };
130    let mut cats = p.glass_catalogs.clone();
131    let b = portable(&mut c, b, &mut cats)?;
132    if let Some(e) = c.flip_err.take() {
133        return Err(e);
134    }
135    Ok(UserItem::optic(description, cats, vec![b]))
136}
137
138/// プロジェクトの最上位の並びの、id `ids[0]` から `ids[last]` までのブロック(間の空気も含む)をユーザーカタログの
139/// 項目にする(GUI の組合せの要素・範囲の保存)。`ids` が 1 つなら [`block_item`] と同じ(入れ子も探す)。
140/// ブロックの面の表で変えた値([`FaceMods::surface_edits`])は中身に焼き込む: 変えた玉は展開した系の面を直接書いた玉にする
141/// (玉のほかのブロックの変更は焼き込めないので誤り)
142pub fn blocks_item(
143    p: &Project,
144    env: &Env,
145    ids: &[String],
146    description: &str,
147) -> lensbench_core::Result<UserItem> {
148    let (first, last) = match ids {
149        [] => return Err("no block id to save".into()),
150        [a] => (a, a),
151        [a, .., b] => (a, b),
152    };
153    // 範囲(最上位の並び)
154    let top = |id: &str| -> lensbench_core::Result<usize> {
155        let v: Vec<usize> = p
156            .blocks
157            .iter()
158            .enumerate()
159            .filter(|(_, b)| !id.is_empty() && block_id(b) == id)
160            .map(|(i, _)| i)
161            .collect();
162        match v.as_slice() {
163            [i] => Ok(*i),
164            [] => Err(format!("block {id} is not in the top-level list").into()),
165            _ => Err(format!("two or more blocks with id {id}").into()),
166        }
167    };
168    let mut item = if ids.len() == 1 {
169        block_item(p, env, first, description)?
170    } else {
171        let (i, j) = (top(first)?, top(last)?);
172        if i > j {
173            return Err(format!("{first} is after {last}").into());
174        }
175        let mut blocks = Vec::new();
176        let mut cats = Vec::new();
177        for b in &p.blocks[i..=j] {
178            let id = block_id(b);
179            if id.is_empty() {
180                // 空気・絞りなど id の無いブロックはそのまま
181                blocks.push(b.clone());
182                continue;
183            }
184            let it = block_item(p, env, id, "")?;
185            for c in &it.glass_catalogs {
186                if !cats.contains(c) {
187                    cats.push(c.clone());
188                }
189            }
190            blocks.extend(it.blocks().iter().cloned());
191        }
192        UserItem::optic(description, cats, blocks)
193    };
194    // 面の表の変更を焼き込む(操作は持ち出さない)
195    let mut edited = Vec::new();
196    if let Some(b) = item.blocks_mut() {
197        take_faces(b, &mut edited)?;
198    }
199    if edited.is_empty() {
200        return Ok(item);
201    }
202    let s = expand(p, env, &ExpandOpts::default())?.system;
203    for id in edited {
204        bake_lens(&s, &mut item, &id)?;
205    }
206    Ok(item)
207}
208
209/// 項目のブロックの面の上書き・操作を外し、上書きのあったブロックの id を集める
210fn take_faces(blocks: &mut [Block], edited: &mut Vec<String>) -> lensbench_core::Result<()> {
211    for b in blocks {
212        let id = block_id(b).to_string();
213        if let Some(f) = b.faces_mut() {
214            if !f.surface_edits.is_empty() {
215                if id.is_empty() {
216                    return Err(
217                        "a block without an id can't bake in values changed in the surface table"
218                            .into(),
219                    );
220                }
221                edited.push(id);
222            }
223            *f = FaceMods::default();
224        }
225        if let Block::Group { blocks, .. } = b {
226            take_faces(blocks, edited)?;
227        }
228    }
229    Ok(())
230}
231
232/// 展開した系 s の玉 id の面(面の表の変更を当てた後)で、項目の玉 id を面を直接書いた玉にする
233pub(crate) fn bake_lens(s: &System, item: &mut UserItem, id: &str) -> lensbench_core::Result<()> {
234    fn find<'x>(v: &'x mut [Block], id: &str) -> Option<&'x mut Block> {
235        for b in v {
236            if block_id(b) == id {
237                return Some(b);
238            }
239            if let Block::Group { blocks, .. } = b {
240                if let Some(x) = find(blocks, id) {
241                    return Some(x);
242                }
243            }
244        }
245        None
246    }
247    let nope = || {
248        format!(
249            "block {id}: only lenses can bake in values changed in the surface table (undo the changes on others before saving)"
250        )
251    };
252    let UserItem {
253        body,
254        glass_catalogs,
255        ..
256    } = item;
257    let b = match body {
258        ItemBody::Optic { blocks, .. } => find(blocks, id),
259        _ => None,
260    }
261    .ok_or_else(nope)?;
262    let Block::Lens {
263        reversed,
264        source,
265        place,
266        ..
267    } = b
268    else {
269        return Err(lensbench_core::Error::Invalid(nope()));
270    };
271    let u = s
272        .units
273        .iter()
274        .find(|u| u.name == id)
275        .ok_or_else(|| format!("the surfaces of block {id} are not in the system"))?;
276    let [a, z] = u.spans[0];
277    if s.surfaces[..a].iter().any(|x| x.is_mirror()) {
278        return Err(format!(
279            "block {id}: changes to a lens after a mirror can't be baked in (not supported)"
280        )
281        .into());
282    }
283    // 面の表の番号と同じく、座標ブレークを除いた面(偏心・傾きの座標ブレークは place のまま残る)
284    let faces: Vec<&Surface> = (a..=z)
285        .map(|j| &s.surfaces[j])
286        .filter(|x| !x.is_coord_break())
287        .collect();
288    let span_cbs = (a..=z).filter(|&j| s.surfaces[j].is_coord_break()).count();
289    let place_cbs = if place.moved() { 2 } else { 0 };
290    // 元の面の並び(面を直接書いた玉なら、中の座標ブレークはそのまま残す)
291    let orig: Option<Vec<SurfSpec>> = match &*source {
292        LensSource::Surfaces { surfaces } => Some(surfaces.clone()),
293        _ => None,
294    };
295    let inner_cbs = orig
296        .as_ref()
297        .map_or(0, |v| v.iter().filter(|q| q.coordbrk.is_some()).count());
298    if span_cbs != place_cbs + inner_cbs || (*reversed && inner_cbs > 0) {
299        return Err(format!(
300            "block {id}: changes to a lens with a coordinate break inside can't be baked in (not supported)"
301        ).into());
302    }
303    let n = faces.len();
304    let mut specs = Vec::with_capacity(n + inner_cbs);
305    let mut k = 0;
306    let take = |k: &mut usize| -> lensbench_core::Result<SurfSpec> {
307        let f = faces.get(*k).ok_or_else(|| {
308            format!("block {id}: the number of surfaces differs from the original lens")
309        })?;
310        *k += 1;
311        let mut q = surface_spec(f, *k == n).map_err(|e| format!("block {id} surface {k}: {e}"))?;
312        if *k == n {
313            q.t = 0.0;
314        }
315        Ok(q)
316    };
317    match &orig {
318        Some(v) if !*reversed => {
319            for q in v {
320                if q.coordbrk.is_some() {
321                    specs.push(q.clone());
322                } else {
323                    specs.push(take(&mut k)?);
324                }
325            }
326        }
327        _ => {
328            for _ in 0..n {
329                specs.push(take(&mut k)?);
330            }
331        }
332    }
333    if k != n {
334        return Err(
335            format!("block {id}: the number of surfaces differs from the original lens").into(),
336        );
337    }
338    for d in &faces {
339        if let Some(g) = d.mat.glass().and_then(|g| s.glasses.get(g)) {
340            if !g.catalog.is_empty() && !glass_catalogs.contains(&g.catalog) {
341                glass_catalogs.push(g.catalog.clone());
342            }
343        }
344    }
345    // 展開した系の面はもう反転の後の向き
346    *source = LensSource::Surfaces { surfaces: specs };
347    *reversed = false;
348    Ok(())
349}
350
351/// 面を前後反転できるか([`lensbench_core::elements::reversible`]。読めない面は false)。GUI が玉の反転を
352/// 出すかを決める
353pub fn spec_reversible(q: &SurfSpec) -> bool {
354    crate::expand::surf(q).is_ok_and(|s| lensbench_core::elements::reversible(&s))
355}
356
357/// 展開した系の面を、面を直接書いた玉の面([`SurfSpec`])に戻す。[`surf`] が作る面はすべて書け、
358/// `surface_spec` → `surf` で同じ面に戻る。欄で書けない面は行([`SurfSpec::row`])で書く。書けない値
359/// (面の前後の傾き・偏心、鏡、ゴーストの反射)は誤り
360pub fn surface_spec(f: &Surface, last: bool) -> lensbench_core::Result<SurfSpec> {
361    surface_fields(f, last).or_else(|e| row_spec(f, last).map_err(|_| e))
362}
363
364/// ほかの欄で書けない面を、システムファイル(版 2)の面の行で([`SurfSpec::row`])。鏡(ブロックの鏡で書く)・
365/// ゴーストの反射・座標ブレークは書かない。面の前後の傾き偏心は行に書く(その玉は裏返せず、復路も通れない)
366fn row_spec(f: &Surface, last: bool) -> lensbench_core::Result<SurfSpec> {
367    if f.is_mirror() || f.reflect.is_some() || f.typ() == SurfType::CoordBrk {
368        return Err("this surface can't be written as a row".into());
369    }
370    let mut r = crate::sysfile_v2::write::surface_row(f, false)?;
371    r.stop = false;
372    if last {
373        r.t = 0.0;
374        r.medium = None;
375        r.dn = 0.0;
376        r.disp = 0.0;
377        r.dnd = 0.0;
378        r.dvd = 0.0;
379    }
380    Ok(SurfSpec {
381        row: Some(Box::new(r)),
382        ..Default::default()
383    })
384}
385
386/// 玉の中の鏡(裏面鏡・プリズムの反射)を、玉の面の行([`SurfSpec::row`])に。厚さ(鏡の後の向きで、次の面まで)は書く。
387/// 絞りの印は書かない。座標ブレーク・ゴーストの反射は書けない
388pub fn lens_mirror_spec(f: &Surface) -> lensbench_core::Result<SurfSpec> {
389    if !f.is_mirror() || f.reflect.is_some() || f.typ() == SurfType::CoordBrk {
390        return Err("this surface can't be written as a mirror in a lens".into());
391    }
392    let mut r = crate::sysfile_v2::write::surface_row(f, false)?;
393    r.stop = false;
394    Ok(SurfSpec {
395        row: Some(Box::new(r)),
396        ..Default::default()
397    })
398}
399
400/// 鏡の面を、鏡のブロックの行([`Block::Mirror`] の row)に。厚さ・絞りの印は書かない。面の前後の傾き偏心
401/// (before・after)は行に書く。座標ブレーク・ゴーストの反射は書けない
402pub fn mirror_row(f: &Surface) -> lensbench_core::Result<crate::sysfile_v2::Row> {
403    if !f.is_mirror() || f.reflect.is_some() || f.typ() == SurfType::CoordBrk {
404        return Err("this surface can't be written as a mirror row".into());
405    }
406    let mut r = crate::sysfile_v2::write::surface_row(f, false)?;
407    r.stop = false;
408    r.t = 0.0;
409    Ok(r)
410}
411
412/// 面を SurfSpec の欄で(書けなければ誤り)
413fn surface_fields(f: &Surface, last: bool) -> lensbench_core::Result<SurfSpec> {
414    let shape = match f.typ() {
415        SurfType::Standard | SurfType::EvenAsph | SurfType::Jones | SurfType::CoordBrk => {
416            SurfShape::Standard
417        }
418        SurfType::OddAsph => SurfShape::OddAsph,
419        SurfType::Toroidal => SurfShape::Toroidal,
420        SurfType::Fresnel => SurfShape::Fresnel,
421        t => return Err(format!("surface type {:?} can't be written", t).into()),
422    };
423    if f.is_mirror() {
424        return Err("a mirror surface can't be written".into());
425    }
426    if f.dn != 0.0 || f.disp != 0.0 || f.dnd != 0.0 || f.dvd != 0.0 {
427        return Err("dn, disp and the glass nd and vd offsets can't be written".into());
428    }
429    if f.cx() != 0.0 && shape != SurfShape::Toroidal {
430        return Err("cx is only for a toroidal surface".into());
431    }
432    let aperture = match f.ap {
433        Aperture::None => None,
434        Aperture::Circular { min, max, dx, dy } => {
435            Some(SurfAperture::Circular { min, max, dx, dy })
436        }
437        Aperture::Rect { hx, hy, dx, dy } => Some(SurfAperture::Rect { hx, hy, dx, dy }),
438        Aperture::Ellipse { hx, hy, dx, dy } => Some(SurfAperture::Ellipse { hx, hy, dx, dy }),
439        Aperture::Obsc { min, max, dx, dy } => Some(SurfAperture::Obscuration { min, max, dx, dy }),
440        Aperture::Spider {
441            width,
442            arms,
443            dx,
444            dy,
445        } => Some(SurfAperture::Spider {
446            width,
447            arms,
448            dx,
449            dy,
450        }),
451        Aperture::Floating { .. } => Some(SurfAperture::Floating),
452    };
453    if f.typ() == SurfType::CoordBrk {
454        if f.before.is_some() || f.after != After::None {
455            return Err(
456                "tilts and decenters before or after a surface (before, after) can't be written"
457                    .into(),
458            );
459        }
460        return Ok(SurfSpec {
461            t: f.t,
462            semi: Semi::of(f),
463            coat: f.coat.clone(),
464            comment: f.comment.clone(),
465            coordbrk: Some(f.cb()),
466            order: f.cb_order(),
467            aperture,
468            ignore: f.ignore,
469            ..Default::default()
470        });
471    }
472    // 頂点のまわりの傾きだけで後で戻す面は tilt で書ける(tilt は tx → ty の順。順序 1 は tx・ty の片方が 0 のときだけ同じ)
473    let tilt =
474        match (&f.before, &f.after) {
475            (None, After::None) => None,
476            (Some(t), After::Reverse)
477                if t.d[0] == 0.0
478                    && t.d[1] == 0.0
479                    && t.d[4] == 0.0
480                    && (t.order == 0 || t.d[2] == 0.0 || t.d[3] == 0.0) =>
481            {
482                Some([t.d[2], t.d[3]])
483            }
484            _ => return Err(
485                "tilts and decenters before or after a surface (before, after) can't be written"
486                    .into(),
487            ),
488        };
489    let glass = if last {
490        None
491    } else {
492        match &f.mat {
493            Material::Air => None,
494            Material::Index(nd) => Some(format!("{nd}")),
495            m => Some(m.name()),
496        }
497    };
498    // 偏光子・波長板の面はその書き方で戻す
499    let (mut polarizer, mut waveplate) = (None, None);
500    if let (SurfType::Jones, Some(r)) = (f.typ(), &f.retarder) {
501        // tx = ty は波長板(遅延 0 でも設計波長を残す)、tx > ty の遅延なしは偏光子
502        if r.retardance == 0.0 && r.order == 0 && r.tx > r.ty {
503            let t = r.tx * r.tx;
504            polarizer = Some(PolarizerSpec {
505                axis_deg: r.axis_deg,
506                extinction_ratio: if r.ty == 0.0 {
507                    f64::INFINITY
508                } else {
509                    t / (r.ty * r.ty)
510                },
511                transmittance: t,
512            });
513        } else if r.tx == r.ty {
514            // 板は厚さを書いて戻す(1 枚で軸 0 は material の書き方)
515            let (material, thickness_mm, plates) = match r.plates.as_slice() {
516                [] => (None, None, Vec::new()),
517                [p] if p.axis_deg == 0.0 => {
518                    (Some(p.material.clone()), Some(p.thickness), Vec::new())
519                }
520                ps => (
521                    None,
522                    None,
523                    ps.iter()
524                        .map(|p| PlateSpec {
525                            material: p.material.clone(),
526                            thickness_mm: p.thickness,
527                            axis_deg: p.axis_deg,
528                        })
529                        .collect(),
530                ),
531            };
532            waveplate = Some(WaveplateSpec {
533                retardance: r.retardance,
534                wavelength_um: r.wl0,
535                axis_deg: r.axis_deg,
536                order: r.order,
537                transmittance: r.tx * r.tx,
538                material,
539                thickness_mm,
540                plates,
541            });
542        }
543    }
544    let jones = (f.typ() == SurfType::Jones && polarizer.is_none() && waveplate.is_none())
545        .then_some(f.jones());
546    Ok(SurfSpec {
547        radius: (f.c != 0.0).then(|| 1.0 / f.c),
548        conic: f.k,
549        asph: if matches!(f.typ(), SurfType::Standard | SurfType::Jones) {
550            Vec::new()
551        } else {
552            f.asph().to_vec()
553        },
554        shape,
555        radius_x: (f.cx() != 0.0).then(|| 1.0 / f.cx()),
556        t: f.t,
557        glass,
558        semi: Semi::of(f),
559        coat: f.coat.clone(),
560        comment: f.comment.clone(),
561        jones,
562        tilt,
563        polarizer,
564        waveplate,
565        aperture,
566        ignore: f.ignore,
567        birefringent: f.bire.as_ref().map(|b| match b {
568            lensbench_core::surface::Bire::In { mode, axis, .. } => BireSpec::In {
569                mode: *mode,
570                axis: *axis,
571            },
572            lensbench_core::surface::Bire::Out => BireSpec::Out,
573        }),
574        ..Default::default()
575    })
576}
577
578/// ブロックを持ち出せる形に(.zmx の玉は面に、パスは絶対パスに)
579pub(crate) fn portable(
580    c: &mut Ctx,
581    b: Block,
582    cats: &mut Vec<String>,
583) -> lensbench_core::Result<Block> {
584    let abs = |c: &Ctx, p: &str| -> String {
585        let q = c.base.join(p);
586        lensbench_core::vfs::canonicalize(&q)
587            .unwrap_or(q)
588            .to_string_lossy()
589            .into_owned()
590    };
591    Ok(match b {
592        Block::Lens {
593            id,
594            source: source @ LensSource::Zmx { .. },
595            reversed,
596            stop,
597            place,
598            faces,
599        } => {
600            let e = c.lens_element(&source)?;
601            for d in &e.surfaces {
602                if let Some(g) = d.mat.glass().and_then(|g| c.glasses.get(g)) {
603                    if !g.catalog.is_empty() && !cats.contains(&g.catalog) {
604                        cats.push(g.catalog.clone());
605                    }
606                }
607            }
608            let Block::Lens { source, .. } = lens_to_block(&e, &id)? else {
609                unreachable!()
610            };
611            Block::Lens {
612                id,
613                source,
614                reversed,
615                stop,
616                place,
617                faces,
618            }
619        }
620        Block::Zmx {
621            id,
622            path,
623            from,
624            to,
625            config,
626            stop,
627            state,
628            beam_path,
629            groups,
630            place,
631            faces,
632        } => Block::Zmx {
633            id,
634            path: abs(c, &path),
635            from,
636            to,
637            config,
638            stop,
639            state,
640            beam_path,
641            groups,
642            place,
643            faces,
644        },
645        Block::User {
646            id,
647            catalog,
648            item,
649            place,
650            faces,
651        } => Block::User {
652            id,
653            catalog: abs(c, &catalog),
654            item,
655            place,
656            faces,
657        },
658        Block::Group {
659            id,
660            name,
661            role,
662            shift,
663            blocks,
664            place,
665            faces,
666        } => Block::Group {
667            id,
668            name,
669            role,
670            shift,
671            blocks: blocks
672                .into_iter()
673                .map(|x| portable(c, x, cats))
674                .collect::<Result<_, _>>()?,
675            place,
676            faces,
677        },
678        Block::Splitter { id, spec, place } => {
679            let mut spec = spec;
680            for l in [&mut spec.t, &mut spec.r, &mut spec.d] {
681                *l = std::mem::take(l)
682                    .into_iter()
683                    .map(|x| portable(c, x, cats))
684                    .collect::<Result<_, _>>()?;
685            }
686            Block::Splitter { id, spec, place }
687        }
688        x => x,
689    })
690}