Skip to main content

lensbench_project/
expand_error.rs

1//! 展開の誤り([`ExpandError`])と、誤りの起きたブロック([`BlockAt`])、展開の注意([`Note`])
2
3use crate::{block_id, Block, NodePath, NodeStep};
4
5/// 展開の誤り: 誤りと、それが起きたプロジェクトのブロック(ブロックの中で起きたとき)
6#[derive(Debug, Clone, PartialEq)]
7pub struct ExpandError {
8    pub error: lensbench_core::Error,
9    pub block: Option<BlockAt>,
10}
11
12/// 誤りの起きたブロック: 木の中の位置と、表示の名前(各段の id、id の無いブロックは「#番号」、BS の腕は t・r・d)
13#[derive(Debug, Clone, PartialEq, Eq)]
14pub struct BlockAt {
15    pub node: NodePath,
16    pub name: String,
17}
18
19impl BlockAt {
20    pub(crate) fn new(blocks: &[Block], node: NodePath) -> BlockAt {
21        let mut parts = Vec::new();
22        let mut v = blocks;
23        for (k, st) in node.0.iter().enumerate() {
24            let (arm, i) = match *st {
25                NodeStep::Block(i) => (None, i),
26                NodeStep::Arm(a, i) => (Some(a), i),
27            };
28            if let Some(a) = arm {
29                parts.push(["t", "r", "d"][usize::from(a).min(2)].to_string());
30            }
31            let Some(b) = v.get(i) else { break };
32            let id = block_id(b);
33            parts.push(if id.is_empty() {
34                format!("#{}", i + 1)
35            } else {
36                id.to_string()
37            });
38            v = match (b, arm) {
39                (Block::Group { blocks, .. }, _) => blocks,
40                (Block::Splitter { spec, .. }, _) => match node.0.get(k + 1) {
41                    Some(NodeStep::Arm(0, _)) => &spec.t,
42                    Some(NodeStep::Arm(1, _)) => &spec.r,
43                    Some(NodeStep::Arm(_, _)) => &spec.d,
44                    _ => &[],
45                },
46                _ => &[],
47            };
48        }
49        BlockAt {
50            node,
51            name: parts.join("/"),
52        }
53    }
54}
55
56impl ExpandError {
57    /// 誤りの種類([`lensbench_core::Error::kind`])
58    pub fn kind(&self) -> &'static str {
59        self.error.kind()
60    }
61    /// 誤りの文(ブロックの名前は付けない。[`lensbench_core::Error::message`])
62    pub fn message(&self) -> Option<&str> {
63        self.error.message()
64    }
65    /// 誤りの符号([`lensbench_core::Error::code`])
66    pub fn code(&self) -> &'static str {
67        self.error.code()
68    }
69    /// ブロックの名前を前に付けた誤り(ブロックの外なら誤りそのもの)
70    pub fn into_error(self) -> lensbench_core::Error {
71        match self.block {
72            Some(b) => {
73                let at = b.name;
74                self.error.map_message(|e| format!("block {at}: {e}"))
75            }
76            None => self.error,
77        }
78    }
79}
80
81impl std::fmt::Display for ExpandError {
82    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
83        self.clone().into_error().fmt(f)
84    }
85}
86
87impl std::error::Error for ExpandError {}
88
89impl From<lensbench_core::Error> for ExpandError {
90    fn from(error: lensbench_core::Error) -> Self {
91        ExpandError { error, block: None }
92    }
93}
94
95impl From<ExpandError> for lensbench_core::Error {
96    fn from(e: ExpandError) -> Self {
97        e.into_error()
98    }
99}
100
101impl From<ExpandError> for String {
102    fn from(e: ExpandError) -> Self {
103        e.to_string()
104    }
105}
106
107/// 展開の注意([`crate::Expansion::notes`]): 展開で落とした・変えたもの
108#[derive(Debug, Clone, PartialEq, Eq)]
109pub struct Note {
110    pub kind: NoteKind,
111    /// 注意の元のブロック・群の id(ブロックに依らない注意・取り込んだ .zmx の注意は None)
112    pub block: Option<String>,
113    /// 注意の文(ブロックの名前・.zmx のパスも含む)
114    pub text: String,
115}
116
117/// 注意の種類
118#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
119#[non_exhaustive]
120pub enum NoteKind {
121    /// 取り込んだ .zmx のピックアップ・ソルブを展開で保てなかった・符号を値で選んだ、ソルブで値を求め直した
122    Pickup,
123    /// 取り込んだ .zmx の温度・気圧がプロジェクトと違う
124    Environment,
125    /// 取り込んだ .zmx の膜ファイルが前の .zmx と違う
126    Coating,
127    /// id のブロック・群を玉・群のパラメータにできなかった
128    Unit,
129    /// 面の操作(`surface_ops`)を当てなかった・当てた操作の注意
130    SurfaceOp,
131    /// 全体の基準の面(`glrs`)のブロックが無い
132    Glrs,
133    /// 機構部品を置かなかった・ねじが合わない
134    Mechanics,
135    /// 取り込んだ .zmx の物体空間の媒質がプロジェクト(`object` の `medium`)と違う。空気でない媒質で終わるブロックの後に
136    /// 別のブロックが続く(後のブロックはその媒質の中)
137    Medium,
138}
139
140impl Note {
141    pub fn new(kind: NoteKind, block: Option<String>, text: String) -> Note {
142        Note { kind, block, text }
143    }
144
145    pub(crate) fn all(kind: NoteKind, block: Option<String>, v: Vec<String>) -> Vec<Note> {
146        v.into_iter()
147            .map(|t| Note::new(kind, block.clone(), t))
148            .collect()
149    }
150}
151
152impl From<Note> for String {
153    fn from(n: Note) -> String {
154        n.text
155    }
156}
157
158impl std::fmt::Display for Note {
159    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
160        f.write_str(&self.text)
161    }
162}
163
164/// 空気でない媒質(液浸の .zmx の像空間など)で終わるブロックの後に別のブロックの面が続くときの注意。間に空気は
165/// 入らないので、後のブロックはその媒質の中に置かれる(物理のとおりに計算し、気づけるように知らせる)
166pub(crate) fn in_medium_notes(
167    s: &lensbench_core::system::System,
168    map: &[crate::SurfOrigin],
169) -> Vec<Note> {
170    let img = s.image();
171    // 座標ブレークを除いた面(物体面・像面も除く)
172    let faces: Vec<usize> = (1..img)
173        .filter(|&j| !s.surfaces[j].is_coord_break())
174        .collect();
175    let node = |j: usize| map.get(j).and_then(|o| o.face.as_ref()).map(|f| &f.node);
176    let name = |j: usize| {
177        map.get(j)
178            .and_then(|o| o.blocks.first().cloned())
179            .unwrap_or_else(|| format!("surface {j}"))
180    };
181    let mut out = Vec::new();
182    for w in faces.windows(2) {
183        let (a, b) = (w[0], w[1]);
184        let m = &s.surfaces[a].mat;
185        if !m.is_medium() || m.is_air() || node(a).is_none() || node(a) == node(b) {
186            continue;
187        }
188        let (na, nb) = (name(a), name(b));
189        out.push(Note::new(
190            NoteKind::Medium,
191            Some(nb.clone()),
192            format!(
193                "{a} ends in {m} (no air after it), so {b} sits in that medium",
194                a = na,
195                m = m.label(),
196                b = nb
197            ),
198        ));
199    }
200    out
201}