Skip to main content

lensbench_core/
usersource.rs

1//! 利用者定義の光源: 設定から光線の始点・方向・重みの並びを作る。
2//!
3//! 外のクレートは [`SourceModel`] を実装して拡張の表に名前で足し([`crate::ext::Ext::add_source_model`])、使う側は
4//! 名前と設定から [`SourceInstance`] を作って波長ごとに光線を受け取る。追跡は [`crate::system::Launch::Rays`] で
5//! 行う([`System::source_rays`] が物体の座標系から大域に直す)。
6//!
7//! 約束:
8//! - 光線は物体の座標系(有限物体は物体面、無限遠物体は面 1 の変換の前の座標系。[`System::object_frame`])で返す。
9//!   方向は規格化しなくてよい(長さ 0 は誤り)。重みは 0 以上の有限の数(相対的な強さ。足して 1 でなくてよい)
10//! - 同じ設定・波長なら同じ光線を返す(乱数を使うなら種を設定に持つ)
11//! - 設定が合わなければ [`crate::Error::Invalid`] を返す(panic しない)
12
13use crate::error::Result;
14use crate::math::V3;
15use crate::plugin::{Config, ParamSpec};
16use crate::{invalid, System};
17use std::sync::Arc;
18
19/// 光源のモデル
20pub trait SourceModel: Send + Sync {
21    /// 登録の名前
22    fn name(&self) -> &str;
23    /// 1 行の説明
24    fn doc(&self) -> String {
25        String::new()
26    }
27    /// 設定の項目(一覧用)
28    fn params(&self) -> Vec<ParamSpec> {
29        Vec::new()
30    }
31    /// 設定を確かめて光源を作る
32    fn prepare(&self, config: &Config) -> Result<Arc<dyn SourceInstance>>;
33    /// 試しの設定(拡張の検査で [`check_source`] に渡す)。既定は [`SourceModel::params`] の既定値を並べたもの
34    /// (既定値の無い項目があれば None。そのときは自分で返す)
35    fn example_config(&self) -> Option<Config> {
36        self.params()
37            .into_iter()
38            .map(|p| Some((p.name, p.default?)))
39            .collect()
40    }
41}
42
43/// 準備した光源
44pub trait SourceInstance: Send + Sync {
45    /// 波長 wl [µm] の光線(物体の座標系)
46    fn rays(&self, wl: f64) -> Result<SourceRays>;
47}
48
49/// 光源の光線: 始点・方向・重み(同じ長さ)
50#[derive(Debug, Clone, Default, PartialEq)]
51pub struct SourceRays {
52    pub p: Vec<V3>,
53    pub k: Vec<V3>,
54    pub w: Vec<f64>,
55}
56
57impl SourceRays {
58    /// 本数
59    pub fn len(&self) -> usize {
60        self.p.len()
61    }
62
63    pub fn is_empty(&self) -> bool {
64        self.p.is_empty()
65    }
66
67    /// 約束(長さがそろう・有限・方向が 0 でない・重みが 0 以上)を確かめる
68    pub fn check(&self) -> Result<()> {
69        let n = self.p.len();
70        if self.k.len() != n || self.w.len() != n {
71            invalid!(
72                "the source gave different numbers of starts, directions and weights ({n}, {} and {})",
73                self.k.len(),
74                self.w.len()
75            );
76        }
77        for i in 0..n {
78            let (p, k, w) = (self.p[i], self.k[i], self.w[i]);
79            if !p.iter().chain(&k).all(|x| x.is_finite()) || k == [0.0; 3] {
80                invalid!("ray {i} of the source has a start {p:?} or direction {k:?} that is not finite or is zero");
81            }
82            if !(w.is_finite() && w >= 0.0) {
83                invalid!(
84                    "ray {i} of the source has the weight {w} (must be finite and not negative)"
85                );
86            }
87        }
88        Ok(())
89    }
90}
91
92/// 光源のモデルの約束を確かめる: 設定 config で作れ、F・d・C 線の波長で約束どおりの光線を 1 本以上返し、2 回呼んで
93/// 同じ光線を返す(雛形・拡張の検査で呼ぶ)
94pub fn check_source(m: &dyn SourceModel, config: &Config) -> Result<()> {
95    let inst = m.prepare(config)?;
96    for wl in [0.4861327, 0.5875618, 0.6562725] {
97        let r = inst.rays(wl)?;
98        r.check()?;
99        if r.is_empty() {
100            invalid!("the source gave no rays at {wl} µm");
101        }
102        if inst.rays(wl)? != r {
103            invalid!("the source gave different rays for the same setting at {wl} µm");
104        }
105    }
106    Ok(())
107}
108
109impl System {
110    /// 光源 src の波長番号 w(0 始まり)の光線を大域座標に直したもの([`crate::system::Launch::Rays`] に渡せる)。
111    /// 約束を守らない光線は誤り
112    pub fn source_rays(&self, src: &dyn SourceInstance, w: usize) -> Result<SourceRays> {
113        let Some(&wl) = self.wavelengths.get(w) else {
114            invalid!(
115                "no wavelength {} (the system has {})",
116                w + 1,
117                self.wavelengths.len()
118            );
119        };
120        let mut r = src.rays(wl)?;
121        r.check()?;
122        let f = self.object_frame();
123        let mv = |v: V3| [0, 1, 2].map(|c| f.r[c][0] * v[0] + f.r[c][1] * v[1] + f.r[c][2] * v[2]);
124        for q in r.p.iter_mut() {
125            let g = mv(*q);
126            *q = [f.o[0] + g[0], f.o[1] + g[1], f.o[2] + g[2]];
127        }
128        for q in r.k.iter_mut() {
129            *q = mv(*q);
130        }
131        Ok(r)
132    }
133}