mod candidate_apply;
mod plan;
mod ranges;
mod ranking;
pub use candidate_apply::{apply_candidate, build_candidate_preview_design, candidate_edits};
pub use plan::{
CUSTOM_PRESET_INDEX, DEFAULT_BUDGET, DEFAULT_CANDIDATES, DEFAULT_GIRDLE_FRACTION,
DEFAULT_STARTS, MAX_CANDIDATES, MAX_STARTS, RunForm, RunPlan, build_run_plan,
default_vary_anchored, estimate_run_seconds, estimate_text, fill_anchor_hinges,
format_duration, measure_anchor_hinges, measured_ms_per_evaluation, optimize_availability,
parse_budget, parse_seed, parse_starts, prepare_anchor_hinges, preset_description,
preset_labels, weights_for_preset,
};
pub use ranges::{
DEFAULT_RANGE_DEG, MIN_RANGE_ANGLE_DEG, RangeInput, RangeRow, default_range,
format_range_value, parse_range, range_bounds, range_rows, range_summary,
};
pub use ranking::{
CandidateLine, baseline_line, candidate_lines, candidate_outcome, optimize_run_status,
};
use crate::loading::{NumberExprError, eval_number};
use indicatrix::{
color::metrics::ToneIlluminant,
geometry::meet_solver::{MeetConstraint, SolvedTier},
optics::{LightingPreset, materials::GemMaterial},
};
use indicatrix_cut_core::{
Design, MaterialSelection, ObjectiveWeights, OptimizeCandidate, OptimizeOutcome,
OptimizeResult, ToneGoal, free_tier_indices,
optimize::{CANONICAL_LIGHT_PITCH, CANONICAL_LIGHT_YAW, SearchStage, StartProgress},
};
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,
}
fn direction_of(delta: f32, higher_is_better: bool) -> i32 {
if delta.abs() < f32::EPSILON {
0
} else if (higher_is_better && delta > 0.0) || (!higher_is_better && delta < 0.0) {
1
} else {
-1
}
}
#[must_use]
fn after_with_delta(before: f32, after: f32, higher_is_better: bool, unit: &str) -> (String, i32) {
let delta = after - before;
let direction = direction_of(delta, higher_is_better);
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 = cancelled_note(outcome);
let polish_note = polish_note(outcome);
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
)
}
}
const fn cancelled_note(outcome: &OptimizeOutcome) -> &'static str {
if outcome.cancelled {
" (cancelled -- showing the best partial result found before the checkpoint \
fired)"
} else {
""
}
}
fn polish_note(outcome: &OptimizeOutcome) -> String {
if outcome.polish_evaluations > 0 {
format!(
" (polish: +{:.2} in {} evaluation(s))",
outcome.polish_improvement, outcome.polish_evaluations
)
} else {
String::new()
}
}
#[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,
tone: f32,
) -> Result<ObjectiveWeights, String> {
fn parse_weight(label: &str, text: &str) -> Result<f32, String> {
let trimmed = text.trim();
let value: f32 = match trimmed.parse::<f32>() {
Ok(value) => value,
Err(_) => match eval_number(trimmed, None) {
Ok(value) => value as f32,
Err(NumberExprError::NotANumber) => {
return Err(format!("{label} weight must be a number."));
}
Err(NumberExprError::Invalid(reason)) => {
return Err(format!(
"{label} weight '{trimmed}' cannot be calculated: {reason}."
));
}
},
};
if !value.is_finite() || value < 0.0 {
return Err(format!(
"{label} weight must be a non-negative, finite number."
));
}
Ok(value)
}
if !tone.is_finite() {
return Err("Tone must be a number.".to_string());
}
Ok(ObjectiveWeights {
windowing: parse_weight("Windowing", windowing)?,
extinction: parse_weight("Extinction", extinction)?,
tilt_brilliance: parse_weight("Tilt brilliance", tilt_brilliance)?,
yield_weight,
tone_weight: tone.abs(),
tone_goal: if tone > 0.0 {
ToneGoal::Deeper
} else {
ToneGoal::Lighter
},
})
}
#[must_use]
pub fn signed_tone(weights: &ObjectiveWeights) -> f32 {
if weights.tone_weight <= 0.0 || !weights.tone_weight.is_finite() {
return 0.0;
}
match weights.tone_goal {
ToneGoal::Lighter => -weights.tone_weight,
ToneGoal::Deeper => weights.tone_weight,
}
}
#[must_use]
pub fn material_has_body_color(material: &GemMaterial) -> bool {
let tensor = &material.absorption;
let sets = [
Some(&tensor.o_ray),
Some(&tensor.e_ray),
tensor.beta_ray.as_ref(),
];
sets.into_iter()
.flatten()
.any(|bands| bands.iter().any(|band| band.peak > 0.0))
}
#[must_use]
pub fn tone_scale_note(
design: &Design,
material: &GemMaterial,
lighting: LightingPreset,
) -> String {
if !material_has_body_color(material) {
return "The material has no body colour, so the tone objective has nothing to work on. \
Pick a colour in Design settings."
.to_string();
}
let size = match design.girdle_diameter_mm {
Some(mm) if mm > 0.0 && mm.is_finite() => {
format!("Face-up colour is worked out for a {mm:.1} mm stone (Design settings)")
}
_ => "No stone size set: one model unit of path counts as one unit of colour strength, \
the swatch convention; set the girdle diameter in Design settings to size it"
.to_string(),
};
let environment = lighting.studio(1.0, CANONICAL_LIGHT_YAW, CANONICAL_LIGHT_PITCH);
let light = if ToneIlluminant::for_environment(environment).uses_preset_light() {
format!(", under {} (the Live Render's lighting).", lighting.label())
} else {
", in daylight (D65): the UV lamp has no visible white, so the tone uses daylight."
.to_string()
};
format!("{size}{light}")
}
#[must_use]
pub fn tone_lighting_label(lighting: LightingPreset) -> String {
let environment = lighting.studio(1.0, CANONICAL_LIGHT_YAW, CANONICAL_LIGHT_PITCH);
if ToneIlluminant::for_environment(environment).uses_preset_light() {
format!("under {}", lighting.label())
} else {
"in daylight (D65) -- UV lamp".to_string()
}
}
#[must_use]
pub fn tone_result_rows(
result: &OptimizeResult,
candidate: &OptimizeCandidate,
) -> Vec<OptimizeResultLine> {
let (Some(before), Some(after)) = (result.tone_before, candidate.tone) else {
return Vec::new();
};
let (lightness_judged, chroma_judged) = match result.tone_goal {
Some(ToneGoal::Lighter) => (Some(true), None),
Some(ToneGoal::Deeper) => (None, Some(true)),
None => (None, None),
};
vec![
tone_row(
"Face-up lightness L*",
before.l_star,
after.l_star,
lightness_judged,
),
tone_row(
"Face-up colour strength C*",
before.chroma,
after.chroma,
chroma_judged,
),
]
}
fn tone_row(
label: &str,
before: f32,
after: f32,
higher_is_better: Option<bool>,
) -> OptimizeResultLine {
higher_is_better.map_or_else(
|| OptimizeResultLine {
label: label.to_string(),
before: format!("{before:.2}"),
after: format!("{after:.2} ({:+.2})", after - before),
direction: 0,
},
|higher| metric_row(label, before, after, higher, ""),
)
}
#[must_use]
pub fn tier_name_for_row(design: &Design, tier_index: usize) -> String {
crate::retarget::plan::tier_display_names(design)
.into_iter()
.nth(tier_index)
.unwrap_or_default()
}
#[must_use]
pub fn optimize_change_rows(outcome: &OptimizeOutcome, design: &Design) -> Vec<OptimizeChangeLine> {
let names = crate::retarget::plan::tier_display_names(design);
outcome
.changes
.iter()
.map(|change| OptimizeChangeLine {
tier_number: format!("#{}", change.index + 1),
name: names.get(change.index).cloned().unwrap_or_default(),
from_angle: format!("{:.2}\u{b0}", change.from_deg.abs()),
to_angle: format!("{:.2}\u{b0}", change.to_deg.abs()),
delta: format!("{:+.2}\u{b0}", change.to_deg.abs() - change.from_deg.abs()),
})
.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,
start: Option<StartProgress>,
elapsed_secs: f32,
) -> String {
let which = start.map_or_else(String::new, |start| {
format!(
"start {} of {}, best {:.2}, ",
start.index + 1,
start.count,
start.best_fast_score
)
});
match stage {
SearchStage::BaselineFull => {
format!(
"Optimizing... scoring the starting point at full fidelity, {elapsed_secs:.1}s elapsed"
)
}
SearchStage::Coordinate => format!(
"Optimizing... {which}{evaluations} of ~{max_evaluations} evaluations, {elapsed_secs:.1}s elapsed"
),
SearchStage::Polish => format!(
"Optimizing (polish)... {which}{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")
}
SearchStage::Screening => start.map_or_else(
|| {
format!(
"Optimizing... screening starting points, {evaluations} drawn, {elapsed_secs:.1}s elapsed"
)
},
|start| {
format!(
"Optimizing... screening {evaluations} of {} starting points, {elapsed_secs:.1}s elapsed",
(4 * start.count.saturating_sub(1)).min(64)
)
},
),
}
}
#[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, and the face-up tone when a tone \
objective is chosen, 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. With \
several starts the search also tries other starting arrangements inside \
your angle ranges, shares the budget between them, and keeps the best; a \
design or budget too small to afford them uses one start. Runs \
off the UI thread and can be cancelled.",
free.len()
),
)
}
}
#[cfg(test)]
mod tests;