use crate::{
EditorSession,
material::GEAR_PRESETS,
retarget::{
CrownShift, apply_with_anchors,
check::{CheckInputs, check_retarget},
plan::build_plan_from,
validity::ValidityStatus,
view::resolved_material_from_selection,
},
};
use indicatrix::optics::{LightingPreset, materials::GemMaterial};
use indicatrix_cut_core::{
Design, Edit, FreshDesignSpec, MaterialSelection, PreformSpec, RemapRounding, ResolvedMaterial,
templates::{TEMPLATES, TemplateSpec},
};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TemplateCard {
pub name: String,
pub shape: String,
pub description: String,
pub ready: bool,
}
#[must_use]
pub fn template_cards() -> Vec<TemplateCard> {
let mut cards = vec![TemplateCard {
name: "Empty".to_string(),
shape: "Blank design".to_string(),
description: "No starting tiers -- author the schedule from scratch.".to_string(),
ready: true,
}];
for spec in indicatrix_cut_core::templates::TEMPLATES {
cards.push(TemplateCard {
name: spec.name.to_string(),
shape: spec.shape.to_string(),
description: spec.description.to_string(),
ready: true,
});
}
cards
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GalleryGroup {
Blank,
Shapes,
Variants,
}
impl GalleryGroup {
#[must_use]
pub const fn title(self) -> &'static str {
match self {
Self::Blank => "Blank",
Self::Shapes => "Shapes",
Self::Variants => "Round variants and teaching designs",
}
}
#[must_use]
pub const fn code(self) -> i32 {
match self {
Self::Blank => 0,
Self::Shapes => 1,
Self::Variants => 2,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct GalleryCard {
pub template_index: i32,
pub group: GalleryGroup,
pub slot: usize,
pub name: String,
pub shape: String,
pub description: String,
pub design_ri: Option<f64>,
pub default_material: Option<String>,
pub allowed_gears: Vec<i32>,
}
impl GalleryCard {
#[must_use]
pub fn designed_for(&self) -> String {
match (&self.default_material, self.design_ri) {
(Some(material), Some(ri)) => format!("Designed for {material} (n {ri:.3})"),
_ => String::new(),
}
}
}
#[must_use]
pub fn template_spec(template_index: i32) -> Option<&'static TemplateSpec> {
template_index
.checked_sub(1)
.and_then(|position| usize::try_from(position).ok())
.and_then(|position| TEMPLATES.get(position))
}
fn session_index(position: usize) -> i32 {
i32::try_from(position).map_or(i32::MAX, |p| p.saturating_add(1))
}
#[must_use]
pub fn gallery_cards() -> Vec<GalleryCard> {
let card_of =
|position: usize, spec: &TemplateSpec, group: GalleryGroup, slot: usize| GalleryCard {
template_index: session_index(position),
group,
slot,
name: spec.name.to_string(),
shape: spec.shape.to_string(),
description: spec.description.to_string(),
design_ri: Some(spec.design_ri),
default_material: Some(spec.default_material.to_string()),
allowed_gears: spec.allowed_gears_among(&GEAR_PRESETS),
};
let mut cards = Vec::with_capacity(TEMPLATES.len() + 1);
for (group, featured) in [
(GalleryGroup::Shapes, true),
(GalleryGroup::Variants, false),
] {
let mut slot = 0;
for (position, spec) in TEMPLATES.iter().enumerate() {
if spec.featured == featured {
cards.push(card_of(position, spec, group, slot));
slot += 1;
}
}
}
cards.push(GalleryCard {
template_index: 0,
group: GalleryGroup::Blank,
slot: 0,
name: "Empty".to_string(),
shape: "Blank design".to_string(),
description: "No starting tiers -- author the schedule from scratch.".to_string(),
design_ri: None,
default_material: None,
allowed_gears: GEAR_PRESETS.to_vec(),
});
cards
}
#[must_use]
pub fn gallery_design(template_index: i32) -> Design {
let spec = template_spec(template_index).map_or_else(
|| FreshDesignSpec {
gear_teeth: 96,
symmetry_order: 8,
mirror: true,
material: MaterialSelection::none(),
preform: PreformSpec::cylinder(96, 1.5, 1.0, 1.5),
},
|template| template.fresh_spec(template.default_material_selection()),
);
EditorSession::from_template(spec, template_index).design
}
pub const RI_TOLERANCE: f64 = 0.02;
#[must_use]
pub const fn adaptation_needed(design_ri: f64, material_n_d: f64) -> bool {
(design_ri - material_n_d).abs() > RI_TOLERANCE
}
#[derive(Debug, Clone, PartialEq)]
pub enum AngleAdaptation {
NotNeeded,
Adapted {
n_from: f64,
n_to: f64,
headline: String,
},
KeptTemplateAngles {
n_from: f64,
n_to: f64,
reason: String,
},
}
impl AngleAdaptation {
#[must_use]
pub fn message(&self) -> Option<String> {
match self {
Self::NotNeeded => None,
Self::Adapted {
n_from,
n_to,
headline,
} => Some(format!(
"Pavilion angles adapted from n {n_from:.3} to n {n_to:.3}; the crown is as \
authored. {headline}"
)),
Self::KeptTemplateAngles {
n_from,
n_to,
reason,
} => Some(format!(
"Kept the template's angles: adapting the pavilion from n {n_from:.3} to \
n {n_to:.3} would not leave a valid stone ({reason}). Use Retarget to adapt \
the angles later."
)),
}
}
#[must_use]
pub const fn adapted(&self) -> bool {
matches!(self, Self::Adapted { .. })
}
}
pub fn settle_adaptation(
n_from: f64,
n_to: f64,
attempt: impl FnOnce() -> Result<String, String>,
) -> AngleAdaptation {
if !adaptation_needed(n_from, n_to) {
return AngleAdaptation::NotNeeded;
}
match attempt() {
Ok(headline) => AngleAdaptation::Adapted {
n_from,
n_to,
headline,
},
Err(reason) => AngleAdaptation::KeptTemplateAngles {
n_from,
n_to,
reason,
},
}
}
#[must_use]
pub fn material_note(spec: &TemplateSpec, chosen_label: &str, chosen_n_d: f64) -> String {
let designed = format!(
"Designed for {} (n {:.3}).",
spec.default_material, spec.design_ri
);
if adaptation_needed(spec.design_ri, chosen_n_d) {
format!(
"{designed} {chosen_label} has n {chosen_n_d:.3}, so the pavilion angles are adapted \
when the design is created (the crown stays as authored) -- if the adapted stone \
stays valid; otherwise the template's angles are kept and you are told."
)
} else {
format!("{designed} {chosen_label} has n {chosen_n_d:.3}: the angles are used as authored.")
}
}
#[derive(Debug, Clone)]
pub struct NewDesignChoice {
pub template_index: i32,
pub gear_teeth: i32,
pub material: MaterialSelection,
pub girdle_diameter_mm: Option<f64>,
pub custom_materials: Vec<GemMaterial>,
}
pub struct CreatedDesign {
pub session: EditorSession,
pub adaptation: AngleAdaptation,
}
fn adapt_angles(
design: &mut Design,
n_from: f64,
target: &ResolvedMaterial,
) -> Result<String, String> {
let plan = build_plan_from(design, n_from, target, CrownShift::default());
if plan.is_empty() {
return Err("none of the template's angles move".to_string());
}
let check = check_retarget(&CheckInputs {
girdle: None,
design,
plan: &plan,
current_gem: None,
lighting: LightingPreset::RingLights,
});
if check.validity.status != ValidityStatus::Valid {
return Err(check.validity.headline());
}
let edit = apply_with_anchors(design, &plan.proposal(), &check.anchors);
design
.apply_edit(edit)
.map(|_inverse| ())
.map_err(|error| format!("the angles could not be applied: {error}"))?;
Ok(check.validity.headline())
}
fn target_material(design: &Design, custom: &[GemMaterial]) -> ResolvedMaterial {
let mut selection = design.material.clone();
if selection.name.is_none() && selection.refractive_index_override.is_none() {
selection.refractive_index_override = Some(design.effective_refractive_index_with(custom));
}
resolved_material_from_selection(&selection, custom)
}
pub fn create_from_template(choice: &NewDesignChoice) -> Result<CreatedDesign, String> {
let spec = template_spec(choice.template_index).ok_or_else(|| {
format!(
"There is no template number {} to start from.",
choice.template_index
)
})?;
if !spec.allows_gear(choice.gear_teeth) {
return Err(format!(
"{} cannot be cut on a {}-tooth gear: its facets would not land on whole teeth \
symmetrically. Pick one of the offered gears.",
spec.name, choice.gear_teeth
));
}
let mut session = EditorSession::from_template(
spec.fresh_spec(choice.material.clone()),
choice.template_index,
);
if choice.gear_teeth != spec.gear_teeth {
session
.design
.apply_edit(Edit::Batch(vec![
Edit::RemapIndices {
from_gear: spec.gear_teeth,
to_gear: choice.gear_teeth,
rounding: RemapRounding::Nearest,
},
Edit::SetSchedule {
gear_teeth: choice.gear_teeth,
symmetry_order: spec.symmetry_order,
mirror: spec.mirror,
},
]))
.map(|_inverse| ())
.map_err(|error| {
format!(
"Could not remap {} to {} teeth: {error}",
spec.name, choice.gear_teeth
)
})?;
}
session.design.girdle_diameter_mm = choice
.girdle_diameter_mm
.filter(|mm| mm.is_finite() && *mm > 0.0);
let target = target_material(&session.design, &choice.custom_materials);
let adaptation = settle_adaptation(spec.design_ri, target.n_d, || {
adapt_angles(&mut session.design, spec.design_ri, &target)
});
Ok(CreatedDesign {
session,
adaptation,
})
}
#[cfg(test)]
mod tests;