use indicatrix::{
geometry::meet_solver::{MeetConstraint, SolvedTier},
optics::materials::GemMaterial,
};
use indicatrix_cut_core::{
Design, MaterialSelection, ObjectiveWeights, OptimizeOutcome, free_tier_indices,
optimize::SearchStage,
};
use std::collections::BTreeSet;
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct OptimizeResultLine {
pub label: String,
pub before: String,
pub after: String,
pub direction: i32,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct OptimizeChangeLine {
pub tier_number: String,
pub name: String,
pub from_angle: String,
pub to_angle: String,
pub delta: String,
}
#[must_use]
fn after_with_delta(before: f32, after: f32, higher_is_better: bool, unit: &str) -> (String, i32) {
let delta = after - before;
let direction = if delta.abs() < f32::EPSILON {
0
} else if (higher_is_better && delta > 0.0) || (!higher_is_better && delta < 0.0) {
1
} else {
-1
};
let verdict = match direction {
1 => "better",
-1 => "worse",
_ => "unchanged",
};
(
format!("{after:.2}{unit} ({delta:+.2}{unit}, {verdict})"),
direction,
)
}
#[must_use]
pub fn optimize_result_rows(outcome: &OptimizeOutcome) -> Vec<OptimizeResultLine> {
vec![
metric_row(
"Windowing",
outcome.before.windowing_pct,
outcome.after.windowing_pct,
false,
"%",
),
metric_row(
"Extinction",
outcome.before.extinction_pct,
outcome.after.extinction_pct,
false,
"%",
),
metric_row(
"Tilt brilliance",
outcome.before.tilt_brilliance_pct,
outcome.after.tilt_brilliance_pct,
true,
"%",
),
metric_row(
"Yield loss",
outcome.before_yield_loss_pct,
outcome.after_yield_loss_pct,
false,
"%",
),
metric_row(
"Blended score",
outcome.before_score,
outcome.after_score,
false,
"",
),
]
}
fn metric_row(
label: &str,
before: f32,
after: f32,
higher_is_better: bool,
unit: &str,
) -> OptimizeResultLine {
let (after_text, direction) = after_with_delta(before, after, higher_is_better, unit);
OptimizeResultLine {
label: label.to_string(),
before: format!("{before:.2}{unit}"),
after: after_text,
direction,
}
}
#[must_use]
pub fn optimize_status_text(outcome: &OptimizeOutcome) -> String {
let cancelled_note = if outcome.cancelled {
" (cancelled -- showing the best partial result found before the checkpoint \
fired)"
} else {
""
};
let polish_note = if outcome.polish_evaluations > 0 {
format!(
" (polish: +{:.2} in {} evaluation(s))",
outcome.polish_improvement, outcome.polish_evaluations
)
} else {
String::new()
};
if outcome.changes.is_empty() {
format!(
"Optimize found no improving move in {} evaluation(s) -- this design's \
free tiers were already at (or very near) a local optimum for these \
weights.{cancelled_note}{polish_note}",
outcome.evaluations
)
} else {
format!(
"Optimize changed {} tier(s) in {} evaluation(s).{cancelled_note}{polish_note}",
outcome.changes.len(),
outcome.evaluations
)
}
}
#[must_use]
pub fn build_optimize_preview_design(design: &Design, outcome: &OptimizeOutcome) -> Design {
let mut preview = design.clone();
for change in &outcome.changes {
if let Some(tier) = preview.tiers.get_mut(change.index) {
tier.angle_deg = change.to_deg;
}
}
preview
}
pub fn parse_optimize_weights(
windowing: &str,
extinction: &str,
tilt_brilliance: &str,
yield_weight: f32,
) -> Result<ObjectiveWeights, String> {
fn parse_weight(label: &str, text: &str) -> Result<f32, String> {
let value: f32 = text
.trim()
.parse()
.map_err(|_| format!("{label} weight must be a number."))?;
if !value.is_finite() || value < 0.0 {
return Err(format!(
"{label} weight must be a non-negative, finite number."
));
}
Ok(value)
}
Ok(ObjectiveWeights {
windowing: parse_weight("Windowing", windowing)?,
extinction: parse_weight("Extinction", extinction)?,
tilt_brilliance: parse_weight("Tilt brilliance", tilt_brilliance)?,
yield_weight,
})
}
#[must_use]
pub fn tier_name_for_row(design: &Design, tier_index: usize) -> String {
design
.tiers
.get(tier_index)
.map(|tier| tier.name.clone())
.unwrap_or_default()
}
#[must_use]
pub fn optimize_change_rows(outcome: &OptimizeOutcome, design: &Design) -> Vec<OptimizeChangeLine> {
outcome
.changes
.iter()
.map(|change| OptimizeChangeLine {
tier_number: format!("#{}", change.index + 1),
name: tier_name_for_row(design, change.index),
from_angle: format!("{:.2}\u{b0}", change.from_deg),
to_angle: format!("{:.2}\u{b0}", change.to_deg),
delta: format!("{:+.2}\u{b0}", change.to_deg - change.from_deg),
})
.collect()
}
#[must_use]
pub fn facet_count_from_solved(design: &Design, solved: &[SolvedTier]) -> usize {
design
.planes_from_solved(solved)
.len()
.saturating_sub(design.preform.planes_offset(design.preform_y_offset).len())
}
#[must_use]
pub fn default_optimize_material_ri(
design: &Design,
selection: &mut MaterialSelection,
custom: &[GemMaterial],
) -> Option<f64> {
if selection.name.is_some() || selection.refractive_index_override.is_some() {
return None;
}
let n_d = design.effective_refractive_index_with(custom);
selection.refractive_index_override = Some(n_d);
Some(n_d)
}
#[must_use]
pub fn pin_non_selected_free_tiers(
design: &Design,
solved: &[SolvedTier],
keep_free: &BTreeSet<usize>,
) -> Design {
let mut restricted = design.clone();
for index in free_tier_indices(design) {
if keep_free.contains(&index) {
continue;
}
let Some(mast) = solved.get(index).map(|s| s.mast) else {
continue;
};
if let Some(tier) = restricted.tiers.get_mut(index) {
tier.constraint = MeetConstraint::ScaleReference(mast);
}
}
restricted
}
#[must_use]
pub fn optimize_start_status(defaulted_ri: Option<f64>) -> String {
defaulted_ri.map_or_else(
|| "Optimizing... 0 evaluations, 0.0s elapsed".to_string(),
|n_d| {
format!(
"Optimizing (no material set -- scored for n_d={n_d:.4})... 0 \
evaluations, 0.0s elapsed"
)
},
)
}
#[must_use]
pub fn optimize_progress_status(
stage: SearchStage,
evaluations: usize,
max_evaluations: usize,
elapsed_secs: f32,
) -> String {
match stage {
SearchStage::BaselineFull => {
format!(
"Optimizing... scoring the starting point at full fidelity, {elapsed_secs:.1}s elapsed"
)
}
SearchStage::Coordinate => format!(
"Optimizing... {evaluations} of ~{max_evaluations} evaluations, {elapsed_secs:.1}s elapsed"
),
SearchStage::Polish => format!(
"Optimizing (polish)... {evaluations} of ~{max_evaluations} evaluations, {elapsed_secs:.1}s elapsed"
),
SearchStage::FinalFull => {
format!("Optimizing... scoring the result at full fidelity, {elapsed_secs:.1}s elapsed")
}
}
}
#[must_use]
pub fn optimize_hint(design: &Design, max_evaluations: usize) -> (bool, String) {
let free = free_tier_indices(design);
if free.is_empty() {
(
false,
"Every tier is currently pinned as a scale reference -- a freshly \
imported design starts this way, and that is correct, not broken. \
Optimize has nothing free to move until you adopt at least one tier's \
real meet constraint (the tier list's Adopt action) or author one by \
hand."
.to_string(),
)
} else {
(
true,
format!(
"Coordinate search over {} free tier angle(s), scored on windowing, \
extinction, and tilt brilliance under a FIXED canonical light pose \
(not necessarily the light you see in the viewport right now -- drag \
the light and these figures can disagree with the trace/HUD until you \
re-run Optimize). Roughly 7 ms per evaluation on a small design, but \
up to several seconds each on a large, heavily meet-derived one (a \
{max_evaluations}-evaluation budget can then take minutes) -- plus two \
fixed full-fidelity scorings (one before, one after the search) that \
can each take over a second on their own, so even a fast run has some \
up-front and trailing wait beyond the quoted per-evaluation cost. Runs \
off the UI thread and can be cancelled.",
free.len()
),
)
}
}
#[cfg(test)]
mod tests;