use crate::sweep::TiltAverages;
use indicatrix::{
color::metrics::{
AxisProfile, GemOpticalMetrics, SweepProgress, evaluate_all_axes_profiles_stepped_geom,
evaluate_gem_optical_metrics_geom,
},
geometry::{GpuFacetPlane, StoneGeometry},
optics::{materials::GemMaterial, raytracer::EnvironmentSource},
};
use std::f32::consts::FRAC_PI_2;
pub const BRILLIANCE_NOISE_POINTS: f32 = 2.0;
pub const WINDOWING_NOISE_POINTS: f32 = 2.0;
pub const EXTINCTION_NOISE_POINTS: f32 = 2.0;
pub const SCINTILLATION_NOISE_POINTS: f32 = 3.0;
pub const FIRE_NOISE_RELATIVE: f32 = 0.05;
pub const FIRE_NOISE_FLOOR: f32 = 0.5;
pub const TILT_NOISE_POINTS: f32 = 1.0;
pub const DEFAULT_SUBJECT: &str = "The after design";
const TABLE_UP_PITCH_RAD: f32 = FRAC_PI_2;
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct OpticalFigures {
pub brilliance_pct: f32,
pub windowing_pct: f32,
pub extinction_pct: f32,
pub fire_index: f32,
pub scintillation_pct: f32,
}
impl From<GemOpticalMetrics> for OpticalFigures {
fn from(metrics: GemOpticalMetrics) -> Self {
Self {
brilliance_pct: metrics.brilliance_pct,
windowing_pct: metrics.windowing_pct,
extinction_pct: metrics.extinction_pct,
fire_index: metrics.fire_index,
scintillation_pct: metrics.scintillation_pct,
}
}
}
#[must_use]
pub fn measure_table_up(
planes: &[GpuFacetPlane],
material: &GemMaterial,
environment: EnvironmentSource<'_>,
) -> OpticalFigures {
measure_table_up_geom(StoneGeometry::planes_only(planes), material, environment)
}
#[must_use]
pub fn measure_table_up_geom(
geom: StoneGeometry<'_>,
material: &GemMaterial,
environment: EnvironmentSource<'_>,
) -> OpticalFigures {
evaluate_gem_optical_metrics_geom(geom, material, 0.0, TABLE_UP_PITCH_RAD, environment).into()
}
#[must_use]
pub fn measure_tilt_average(
planes: &[GpuFacetPlane],
material: &GemMaterial,
environment: EnvironmentSource<'_>,
step: &mut dyn FnMut(SweepProgress) -> bool,
) -> Option<TiltAverages> {
measure_tilt_average_geom(
StoneGeometry::planes_only(planes),
material,
environment,
step,
)
}
#[must_use]
pub fn measure_tilt_average_geom(
geom: StoneGeometry<'_>,
material: &GemMaterial,
environment: EnvironmentSource<'_>,
step: &mut dyn FnMut(SweepProgress) -> bool,
) -> Option<TiltAverages> {
evaluate_all_axes_profiles_stepped_geom(geom, material, environment, step)
.map(|axes| average_axis_profiles(&axes))
}
#[must_use]
pub fn average_axis_profiles(axes: &[AxisProfile]) -> TiltAverages {
let mut brilliance = 0.0_f64;
let mut windowing = 0.0_f64;
let mut extinction = 0.0_f64;
let mut samples = 0_u32;
for axis in axes {
for ((b, w), e) in axis
.brilliance
.iter()
.zip(&axis.windowing)
.zip(&axis.extinction)
{
brilliance += f64::from(*b);
windowing += f64::from(*w);
extinction += f64::from(*e);
samples += 1;
}
}
let samples = f64::from(samples.max(1));
TiltAverages {
brilliance_pct: (brilliance / samples) as f32,
windowing_pct: (windowing / samples) as f32,
extinction_pct: (extinction / samples) as f32,
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DeltaMetric {
Brilliance,
Windowing,
Extinction,
Fire,
Scintillation,
}
impl DeltaMetric {
pub const ALL: [Self; 5] = [
Self::Brilliance,
Self::Windowing,
Self::Extinction,
Self::Fire,
Self::Scintillation,
];
#[must_use]
pub const fn label(self) -> &'static str {
match self {
Self::Brilliance => "Brilliance",
Self::Windowing => "Windowing",
Self::Extinction => "Extinction",
Self::Fire => "Fire",
Self::Scintillation => "Scintillation",
}
}
#[must_use]
pub const fn tilt_label(self) -> &'static str {
match self {
Self::Brilliance => "Tilt brilliance",
Self::Windowing => "Tilt windowing",
Self::Extinction => "Tilt extinction",
Self::Fire => "Tilt fire",
Self::Scintillation => "Tilt scintillation",
}
}
#[must_use]
pub const fn higher_is_better(self) -> bool {
!matches!(self, Self::Windowing | Self::Extinction)
}
#[must_use]
pub const fn is_main(self) -> bool {
matches!(self, Self::Brilliance | Self::Windowing | Self::Extinction)
}
#[must_use]
pub const fn value(self, figures: &OpticalFigures) -> f32 {
match self {
Self::Brilliance => figures.brilliance_pct,
Self::Windowing => figures.windowing_pct,
Self::Extinction => figures.extinction_pct,
Self::Fire => figures.fire_index,
Self::Scintillation => figures.scintillation_pct,
}
}
const fn noise_points(self) -> f32 {
match self {
Self::Brilliance => BRILLIANCE_NOISE_POINTS,
Self::Windowing => WINDOWING_NOISE_POINTS,
Self::Extinction => EXTINCTION_NOISE_POINTS,
Self::Scintillation => SCINTILLATION_NOISE_POINTS,
Self::Fire => FIRE_NOISE_FLOOR,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Tone {
Same,
Better,
Worse,
}
impl Tone {
#[must_use]
pub const fn word(self) -> &'static str {
match self {
Self::Same => "same",
Self::Better => "better",
Self::Worse => "worse",
}
}
#[must_use]
pub const fn code(self) -> i32 {
match self {
Self::Same => 0,
Self::Better => 1,
Self::Worse => 2,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct MetricChange {
pub metric: DeltaMetric,
pub change: f32,
pub tone: Tone,
}
#[must_use]
pub fn judge(metric: DeltaMetric, before: f32, after: f32, tilt: bool) -> Option<MetricChange> {
if !before.is_finite() || !after.is_finite() {
return None;
}
let difference = after - before;
let (threshold, change) = if metric == DeltaMetric::Fire {
let relative = FIRE_NOISE_RELATIVE * before;
(
relative.max(FIRE_NOISE_FLOOR),
difference / before.max(FIRE_NOISE_FLOOR) * 100.0,
)
} else if tilt {
(TILT_NOISE_POINTS, difference)
} else {
(metric.noise_points(), difference)
};
let tone = if difference.abs() <= threshold {
Tone::Same
} else if (difference > 0.0) == metric.higher_is_better() {
Tone::Better
} else {
Tone::Worse
};
Some(MetricChange {
metric,
change,
tone,
})
}
#[must_use]
pub fn describe_metric_deltas(
before: &OpticalFigures,
after: &OpticalFigures,
tilt: Option<(&TiltAverages, &TiltAverages)>,
) -> Vec<String> {
describe_metric_deltas_for(DEFAULT_SUBJECT, before, after, tilt)
}
#[must_use]
pub fn describe_metric_deltas_for(
subject: &str,
before: &OpticalFigures,
after: &OpticalFigures,
tilt: Option<(&TiltAverages, &TiltAverages)>,
) -> Vec<String> {
let judged: Vec<MetricChange> = DeltaMetric::ALL
.iter()
.filter_map(|&metric| judge(metric, metric.value(before), metric.value(after), false))
.collect();
let mut lines = table_up_lines(subject, &judged);
if let Some((tilt_before, tilt_after)) = tilt {
lines.push(tilt_line(subject, tilt_before, tilt_after));
}
lines
}
fn table_up_lines(subject: &str, judged: &[MetricChange]) -> Vec<String> {
if judged.is_empty() {
return vec!["The optical figures could not be compared.".to_owned()];
}
let changed: Vec<&MetricChange> = judged
.iter()
.filter(|change| change.tone != Tone::Same)
.collect();
if changed.is_empty() {
return vec!["No clear optical difference.".to_owned()];
}
let phrases = |main: bool| -> Vec<String> {
changed
.iter()
.filter(|change| change.metric.is_main() == main)
.map(|&&change| direction_phrase(change, false))
.collect()
};
let (main, other) = (phrases(true), phrases(false));
let mut lines = Vec::new();
if !main.is_empty() {
lines.push(format!("{subject} {}.", join_list(&main)));
}
if !other.is_empty() {
let lead = if lines.is_empty() { subject } else { "It also" };
lines.push(format!("{lead} {}.", join_list(&other)));
}
let same: Vec<&str> = judged
.iter()
.filter(|change| change.tone == Tone::Same)
.map(|change| change.metric.label())
.collect();
lines.extend(same_line(&same));
lines
}
fn tilt_line(subject: &str, before: &TiltAverages, after: &TiltAverages) -> String {
let pairs = [
(
DeltaMetric::Brilliance,
before.brilliance_pct,
after.brilliance_pct,
),
(
DeltaMetric::Windowing,
before.windowing_pct,
after.windowing_pct,
),
(
DeltaMetric::Extinction,
before.extinction_pct,
after.extinction_pct,
),
];
let phrases: Vec<String> = pairs
.iter()
.filter_map(|&(metric, was, now)| judge(metric, was, now, true))
.filter(|change| change.tone != Tone::Same)
.map(|change| direction_phrase(change, true))
.collect();
if phrases.is_empty() {
"Averaged over all tilts, there is no clear difference.".to_owned()
} else {
format!(
"Averaged over all tilts, {} {}.",
lower_first(subject),
join_list(&phrases)
)
}
}
fn direction_phrase(change: MetricChange, tilt: bool) -> String {
let more = change.change > 0.0;
let words = match (change.metric, tilt, more) {
(DeltaMetric::Brilliance, false, true) => "is brighter face-up",
(DeltaMetric::Brilliance, false, false) => "is less bright face-up",
(DeltaMetric::Brilliance, true, true) => "returns more light",
(DeltaMetric::Brilliance, true, false) => "returns less light",
(DeltaMetric::Windowing, _, true) => "shows more windowing",
(DeltaMetric::Windowing, _, false) => "shows less windowing",
(DeltaMetric::Extinction, _, true) => "has more extinction",
(DeltaMetric::Extinction, _, false) => "has less extinction",
(DeltaMetric::Fire, _, true) => "shows more fire",
(DeltaMetric::Fire, _, false) => "shows less fire",
(DeltaMetric::Scintillation, _, true) => "sparkles more",
(DeltaMetric::Scintillation, _, false) => "sparkles less",
};
format!("{words} ({:+.0} %)", change.change)
}
fn same_line(labels: &[&str]) -> Option<String> {
let (first, rest) = labels.split_first()?;
let mut names = vec![(*first).to_owned()];
names.extend(rest.iter().map(|label| label.to_lowercase()));
let verb = if names.len() == 1 { "is" } else { "are" };
Some(format!("{} {verb} about the same.", join_list(&names)))
}
fn join_list(items: &[String]) -> String {
match items {
[] => String::new(),
[only] => only.clone(),
[init @ .., last] => format!("{} and {last}", init.join(", ")),
}
}
fn lower_first(text: &str) -> String {
let mut chars = text.chars();
chars.next().map_or_else(String::new, |first| {
first.to_lowercase().chain(chars).collect()
})
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MetricRow {
pub label: &'static str,
pub before: String,
pub after: String,
pub change: String,
pub tone: Tone,
}
#[must_use]
pub fn metric_rows(
before: &OpticalFigures,
after: &OpticalFigures,
tilt: Option<(&TiltAverages, &TiltAverages)>,
) -> Vec<MetricRow> {
let mut rows: Vec<MetricRow> = DeltaMetric::ALL
.iter()
.map(|&metric| {
row(
metric.label(),
metric,
metric.value(before),
metric.value(after),
false,
)
})
.collect();
if let Some((tilt_before, tilt_after)) = tilt {
let pairs = [
(
DeltaMetric::Brilliance,
tilt_before.brilliance_pct,
tilt_after.brilliance_pct,
),
(
DeltaMetric::Windowing,
tilt_before.windowing_pct,
tilt_after.windowing_pct,
),
(
DeltaMetric::Extinction,
tilt_before.extinction_pct,
tilt_after.extinction_pct,
),
];
rows.extend(
pairs
.iter()
.map(|&(metric, was, now)| row(metric.tilt_label(), metric, was, now, true)),
);
}
rows
}
const NOT_AVAILABLE: &str = "n/a";
fn row(label: &'static str, metric: DeltaMetric, before: f32, after: f32, tilt: bool) -> MetricRow {
let judged = judge(metric, before, after, tilt);
let change = judged.map_or_else(
|| NOT_AVAILABLE.to_owned(),
|judged| {
if metric == DeltaMetric::Fire {
format!("{} %", signed(judged.change, 0))
} else {
format!("{} %", signed(judged.change, 1))
}
},
);
MetricRow {
label,
before: figure_text(metric, before),
after: figure_text(metric, after),
change,
tone: judged.map_or(Tone::Same, |judged| judged.tone),
}
}
fn figure_text(metric: DeltaMetric, value: f32) -> String {
if !value.is_finite() {
NOT_AVAILABLE.to_owned()
} else if metric == DeltaMetric::Fire {
format!("{value:.1}")
} else {
format!("{value:.1} %")
}
}
fn signed(value: f32, decimals: usize) -> String {
let text = format!("{value:+.decimals$}");
if text[1..].chars().all(|c| c == '0' || c == '.') {
text[1..].to_owned()
} else {
text
}
}
#[cfg(test)]
mod tests;