use super::{CrownShift, RetargetMode, RetargetProposal, RetargetRow, build_notes};
use crate::view_model::row_format::representative_crown_and_pavilion_angles_deg;
use indicatrix::{
geometry::meet_solver::{Block, classify_blocks},
optics::materials::GemMaterial,
};
use indicatrix_cut_core::{
Design, ResolvedMaterial, Risk, critical_angle_deg, crown_window_margin_deg,
crown_windowing_risk,
optics_hints::{
AngleGuard, MAX_RETARGET_ANGLE_DEG, MIN_RETARGET_ANGLE_DEG, guard_retargeted_angle_deg,
is_horizontal_angle_deg,
},
retarget_angle_deg, tier_margin_deg, windowing_risk,
};
const FLAT_TIERS_NOTE: &str =
"Flat facets (the table and the culet) keep their angle: a retarget never tilts them.";
const CROWN_ESTIMATE_NOTE: &str = "Crown margins marked est. are rough estimates. Each follows one ray down through the crown facet and onto the main pavilion facet on the same side of the stone, and nothing else, so read it as a guide, not a measurement.";
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ShiftedAngle {
pub raw_deg: f64,
pub angle_deg: f64,
pub guard: AngleGuard,
}
impl ShiftedAngle {
const fn held(angle_deg: f64) -> Self {
Self {
raw_deg: angle_deg,
angle_deg,
guard: AngleGuard::Within,
}
}
}
#[must_use]
pub fn pavilion_stretch(design: &Design, n_from: f64, n_to: f64) -> f64 {
let Some(magnitude) = representative_crown_and_pavilion_angles_deg(design).1 else {
return 1.0;
};
if n_from.to_bits() == n_to.to_bits() {
return 1.0;
}
let raw = retarget_angle_deg(-magnitude, n_from, n_to);
let (guarded, _) = guard_retargeted_angle_deg(-magnitude, raw);
if guarded.abs().to_bits() == magnitude.to_bits() {
return 1.0;
}
let before = magnitude.to_radians().tan();
let after = guarded.abs().to_radians().tan();
let stretch = after / before;
if before.is_finite() && before > 0.0 && stretch.is_finite() && stretch > 0.0 {
stretch
} else {
1.0
}
}
fn raw_crown_angle(old_angle: f64, n_from: f64, n_to: f64, crown: CrownShift, stretch: f64) -> f64 {
if crown.scale_by_ratio {
old_angle * critical_angle_deg(n_to) / critical_angle_deg(n_from)
} else if crown.follow_pavilion {
if stretch.to_bits() == 1.0_f64.to_bits() {
return old_angle;
}
let sign = if old_angle.is_sign_negative() {
-1.0
} else {
1.0
};
sign * (stretch * old_angle.abs().to_radians().tan())
.atan()
.to_degrees()
} else {
crown.fraction.mul_add(
critical_angle_deg(n_to) - critical_angle_deg(n_from),
old_angle,
)
}
}
#[must_use]
pub fn shift_angle(
old_angle: f64,
block: Block,
n_from: f64,
n_to: f64,
crown: CrownShift,
stretch: f64,
) -> ShiftedAngle {
if block == Block::Girdle || is_horizontal_angle_deg(old_angle) {
return ShiftedAngle::held(old_angle);
}
let raw_deg = if block == Block::Pavilion {
retarget_angle_deg(old_angle, n_from, n_to)
} else {
raw_crown_angle(old_angle, n_from, n_to, crown, stretch)
};
let (angle_deg, guard) = guard_retargeted_angle_deg(old_angle, raw_deg);
ShiftedAngle {
raw_deg,
angle_deg,
guard,
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct PlanRow {
pub tier_index: usize,
pub block: Block,
pub name: String,
pub old_angle: f64,
pub new_angle: f64,
pub moves: bool,
pub guard: AngleGuard,
pub margin_deg: Option<f64>,
pub risk: Option<Risk>,
pub margin_is_estimate: bool,
pub follows: Option<String>,
}
impl PlanRow {
#[must_use]
pub fn to_legacy(&self) -> RetargetRow {
RetargetRow {
tier_index: self.tier_index,
block: self.block,
name: self.name.clone(),
old_angle: self.old_angle,
new_angle: self.new_angle,
margin_deg: self.margin_deg.unwrap_or(0.0),
risk: self.risk.unwrap_or(Risk::Safe),
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct RetargetPlan {
pub rows: Vec<PlanRow>,
pub target: ResolvedMaterial,
pub n_from: f64,
pub n_to: f64,
pub crown: CrownShift,
pub stretch: f64,
pub notes: Vec<String>,
pub relation_error: Option<String>,
}
impl RetargetPlan {
#[must_use]
pub fn moving_count(&self) -> usize {
self.rows.iter().filter(|row| row.moves).count()
}
#[must_use]
pub fn moving_angles_at(&self, fraction: f64) -> Vec<(usize, f64)> {
self.rows
.iter()
.filter(|row| row.moves)
.map(|row| {
(
row.tier_index,
(row.new_angle - row.old_angle).mul_add(fraction, row.old_angle),
)
})
.collect()
}
#[must_use]
pub fn with_angles(&self, design: &Design, angles: &[(usize, f64)]) -> Self {
let mut rows = self.rows.clone();
for row in &mut rows {
if row.moves {
row.new_angle = angles
.iter()
.find(|&&(index, _)| index == row.tier_index)
.map_or(row.old_angle, |&(_, angle)| angle);
row.guard = AngleGuard::Within;
}
if row.moves || row.follows.is_some() {
row.margin_deg = None;
row.risk = None;
row.margin_is_estimate = false;
}
}
let relation_error = complete_rows(design, &mut rows, self.n_to);
let mut notes = build_notes(RetargetMode::Shift, self.n_from, self.n_to, self.crown, 1.0);
if rows.iter().any(|row| !row.moves && row.follows.is_none()) {
notes.push(FLAT_TIERS_NOTE.to_string());
}
push_crown_estimate_note(&mut notes, &rows);
notes.extend(relation_notes(
&rows,
&tier_display_names(design),
relation_error.as_deref(),
));
Self {
rows,
target: self.target.clone(),
n_from: self.n_from,
n_to: self.n_to,
crown: self.crown,
stretch: self.stretch,
notes,
relation_error,
}
}
#[must_use]
pub fn proposal(&self) -> RetargetProposal {
RetargetProposal {
rows: self
.rows
.iter()
.filter(|row| row.moves)
.map(PlanRow::to_legacy)
.collect(),
target: self.target.clone(),
notes: self.notes.clone(),
}
}
#[must_use]
pub fn moving_angles(&self) -> Vec<(usize, f64)> {
self.rows
.iter()
.filter(|row| row.moves)
.map(|row| (row.tier_index, row.new_angle))
.collect()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.rows.iter().all(|row| !row.moves)
}
}
#[must_use]
pub fn margin_and_risk(
block: Block,
angle_deg: f64,
n_to: f64,
pavilion_partner_deg: Option<f64>,
) -> Option<(f64, Risk, bool)> {
match block {
Block::Pavilion => Some((
tier_margin_deg(angle_deg, n_to),
windowing_risk(angle_deg, n_to),
false,
)),
Block::Crown => pavilion_partner_deg.map(|partner| {
(
crown_window_margin_deg(partner, angle_deg, n_to),
crown_windowing_risk(partner, angle_deg, n_to),
true,
)
}),
Block::Girdle => None,
}
}
#[must_use]
pub fn pavilion_partner_after(design: &Design, angles: &[(usize, f64)]) -> Option<f64> {
let mut candidate = design.clone();
for &(index, angle) in angles {
if let Some(tier) = candidate.tiers.get_mut(index) {
tier.angle_deg = angle;
}
}
representative_crown_and_pavilion_angles_deg(&candidate).1
}
fn fill_risks(design: &Design, rows: &mut [PlanRow], n_to: f64) {
let angles: Vec<(usize, f64)> = rows
.iter()
.map(|row| (row.tier_index, row.new_angle))
.collect();
let partner = pavilion_partner_after(design, &angles);
for row in rows
.iter_mut()
.filter(|row| row.moves || row.follows.is_some())
{
if let Some((margin, risk, estimate)) =
margin_and_risk(row.block, row.new_angle, n_to, partner)
{
row.margin_deg = Some(margin);
row.risk = Some(risk);
row.margin_is_estimate = estimate;
}
}
}
fn follow_relations(design: &Design, rows: &mut [PlanRow]) -> Option<String> {
if rows.iter().all(|row| row.follows.is_none()) {
return None;
}
let mut candidate = design.clone();
for row in rows.iter().filter(|row| row.follows.is_none()) {
if let Some(tier) = candidate.tiers.get_mut(row.tier_index) {
tier.angle_deg = row.new_angle;
}
}
match candidate.evaluate_relations() {
Ok(updates) => {
for (index, angle) in updates {
if let Some(row) = rows.iter_mut().find(|row| row.tier_index == index) {
row.new_angle = angle;
}
}
None
}
Err(error) => Some(error.to_string()),
}
}
fn complete_rows(design: &Design, rows: &mut [PlanRow], n_to: f64) -> Option<String> {
let relation_error = follow_relations(design, rows);
fill_risks(design, rows, n_to);
relation_error
}
#[must_use]
pub fn tier_display_names(design: &Design) -> Vec<String> {
let labels = indicatrix_cut_core::compute_tier_labels(&design.tiers);
design
.tiers
.iter()
.enumerate()
.map(|(index, tier)| {
if tier.name.trim().is_empty() || indicatrix_cut_core::is_legacy_123_abc(&tier.name) {
labels
.get(index)
.map_or_else(|| tier.name.clone(), |label| label.code.clone())
} else {
tier.name.clone()
}
})
.collect()
}
#[must_use]
pub fn tier_display_name(design: &Design, index: usize) -> String {
tier_display_names(design)
.into_iter()
.nth(index)
.unwrap_or_else(|| design.relation_label(index))
}
fn relation_notes(rows: &[PlanRow], names: &[String], relation_error: Option<&str>) -> Vec<String> {
let mut notes: Vec<String> = rows
.iter()
.filter_map(|row| {
row.follows.as_ref().map(|relation| {
let name = names.get(row.tier_index).unwrap_or(&row.name);
format!("{name} follows {relation}, so it moves with the tiers it reads.")
})
})
.collect();
if let Some(error) = relation_error {
notes.push(format!(
"A tier that follows a relation cannot follow it after this change: {}",
error.trim_end_matches('.')
));
}
notes
}
fn push_crown_estimate_note(notes: &mut Vec<String>, rows: &[PlanRow]) {
if rows.iter().any(|row| row.margin_is_estimate) {
notes.push(CROWN_ESTIMATE_NOTE.to_string());
}
}
fn guard_note(name: &str, old_angle: f64, shifted: &ShiftedAngle) -> Option<String> {
let held = shifted.angle_deg.abs();
match shifted.guard {
AngleGuard::Within => None,
AngleGuard::HeldAtMinimum => {
let sign = if old_angle.is_sign_negative() {
-1.0
} else {
1.0
};
if shifted.raw_deg * sign <= 0.0 {
Some(format!(
"{name}: the shift would tilt it past the horizontal, so it is held at {held:.2}\u{b0}."
))
} else {
Some(format!(
"{name}: the shift would make it flatter than {MIN_RETARGET_ANGLE_DEG:.0}\u{b0}, so it is held at {held:.2}\u{b0}."
))
}
}
AngleGuard::HeldAtMaximum => Some(format!(
"{name}: the shift would make it steeper than {MAX_RETARGET_ANGLE_DEG:.1}\u{b0}, so it is held at {held:.2}\u{b0}."
)),
}
}
#[must_use]
pub fn build_plan_from(
design: &Design,
n_from: f64,
target: &ResolvedMaterial,
crown: CrownShift,
) -> RetargetPlan {
let n_to = target.n_d;
let blocks = classify_blocks(&design.meet_tier_inputs());
let stretch = pavilion_stretch(design, n_from, n_to);
let mut notes = build_notes(RetargetMode::Shift, n_from, n_to, crown, stretch);
let names = tier_display_names(design);
let mut rows = Vec::new();
let mut any_flat = false;
for (index, tier) in design.tiers.iter().enumerate() {
let block = blocks[index];
if block == Block::Girdle {
continue;
}
let follows = design.relation_text(index);
let flat = is_horizontal_angle_deg(tier.angle_deg);
let shifted = if follows.is_some() {
ShiftedAngle::held(tier.angle_deg)
} else {
shift_angle(tier.angle_deg, block, n_from, n_to, crown, stretch)
};
any_flat |= flat;
if follows.is_none()
&& let Some(note) = guard_note(&names[index], tier.angle_deg, &shifted)
{
notes.push(note);
}
rows.push(PlanRow {
tier_index: index,
block,
name: tier.name.clone(),
old_angle: tier.angle_deg,
new_angle: shifted.angle_deg,
moves: follows.is_none() && !flat,
guard: shifted.guard,
margin_deg: None,
risk: None,
margin_is_estimate: false,
follows,
});
}
if any_flat {
notes.push(FLAT_TIERS_NOTE.to_string());
}
let relation_error = complete_rows(design, &mut rows, n_to);
push_crown_estimate_note(&mut notes, &rows);
notes.extend(relation_notes(&rows, &names, relation_error.as_deref()));
RetargetPlan {
rows,
target: target.clone(),
n_from,
n_to,
crown,
stretch,
notes,
relation_error,
}
}
#[must_use]
pub fn build_plan(
design: &Design,
target: &ResolvedMaterial,
crown: CrownShift,
custom_materials: &[GemMaterial],
) -> RetargetPlan {
build_plan_from(
design,
design.effective_refractive_index_with(custom_materials),
target,
crown,
)
}
#[must_use]
pub fn legacy_rows(
original: &Design,
entries: &[(usize, Block, f64)],
n_to: f64,
) -> Vec<RetargetRow> {
let angles: Vec<(usize, f64)> = entries
.iter()
.map(|&(index, _, angle)| (index, angle))
.collect();
let partner = pavilion_partner_after(original, &angles);
entries
.iter()
.map(|&(index, block, new_angle)| {
let (margin, risk, _) = margin_and_risk(block, new_angle, n_to, partner).unwrap_or((
0.0,
Risk::Safe,
false,
));
RetargetRow {
tier_index: index,
block,
name: original.tiers[index].name.clone(),
old_angle: original.tiers[index].angle_deg,
new_angle,
margin_deg: margin,
risk,
}
})
.collect()
}
#[cfg(test)]
mod guard_note_tests {
use super::*;
fn shifted(raw_deg: f64, angle_deg: f64, guard: AngleGuard) -> ShiftedAngle {
ShiftedAngle {
raw_deg,
angle_deg,
guard,
}
}
#[test]
fn a_pavilion_row_held_at_the_steep_limit_reads_the_held_angle_as_positive() {
let note = guard_note(
"P1",
-88.0,
&shifted(-92.0, -MAX_RETARGET_ANGLE_DEG, AngleGuard::HeldAtMaximum),
);
assert_eq!(
note.as_deref(),
Some(
"P1: the shift would make it steeper than 89.5\u{b0}, so it is held at 89.50\u{b0}."
)
);
}
#[test]
fn a_pavilion_row_held_at_the_flat_limit_reads_the_held_angle_as_positive() {
let flatter = guard_note(
"P1",
-3.0,
&shifted(-0.5, -MIN_RETARGET_ANGLE_DEG, AngleGuard::HeldAtMinimum),
);
assert_eq!(
flatter.as_deref(),
Some("P1: the shift would make it flatter than 1\u{b0}, so it is held at 1.00\u{b0}.")
);
let crossed = guard_note(
"P1",
-3.0,
&shifted(0.4, -MIN_RETARGET_ANGLE_DEG, AngleGuard::HeldAtMinimum),
);
assert_eq!(
crossed.as_deref(),
Some("P1: the shift would tilt it past the horizontal, so it is held at 1.00\u{b0}.")
);
}
#[test]
fn a_row_within_the_limits_has_no_note() {
assert_eq!(guard_note("P1", -40.0, &ShiftedAngle::held(-40.0)), None);
}
#[test]
fn display_names_turn_old_style_names_into_codes_and_keep_descriptive_ones() {
use indicatrix::geometry::meet_solver::MeetConstraint;
use indicatrix_cut_core::{ConstraintTier, PreformSpec, ScheduleMeta};
let tier = |name: &str, angle_deg: f64| ConstraintTier {
angle_deg,
name: name.to_string(),
indices: vec![0.0],
constraint: MeetConstraint::ScaleReference(0.5),
imported_meet: None,
original_notes: None,
detached: Vec::new(),
};
let design = Design::new(
PreformSpec::block(2.0, 1.0, 2.0),
ScheduleMeta::default(),
vec![
tier("Pavilion Main", -41.0),
tier("1", -38.0),
tier("", 32.0),
],
);
let names = tier_display_names(&design);
let labels = indicatrix_cut_core::compute_tier_labels(&design.tiers);
assert_eq!(names[0], "Pavilion Main", "a descriptive name stays");
assert_eq!(
names[1], labels[1].code,
"an old-style name becomes the code"
);
assert_eq!(names[2], labels[2].code, "an empty name becomes the code");
assert!(
names[1].starts_with('P') && names[2].starts_with('C'),
"{names:?}"
);
}
}