use indicatrix::geometry::{
GpuFacetPlane,
meet_solver::{
MeetConstraint, SolveControl, SolveError, SolveStrategy, SolvedTier, solve_meet_points,
},
};
use indicatrix_cut_core::{Design, DesignSolveError};
use std::{
sync::atomic::{AtomicBool, Ordering},
time::Duration,
};
pub const SYNC_SOLVE_PLANE_LIMIT: usize = 32;
pub const SYNC_SOLVE_TIME_LIMIT: Duration = Duration::from_millis(500);
pub const SYNC_SOLVE_MEET_TIER_LIMIT: usize = 8;
pub const AUTO_SOLVE_DEBOUNCE: Duration = Duration::from_millis(150);
pub const IDLE_REPLAN_DEBOUNCE: Duration = Duration::from_millis(400);
pub const SOLVING_TICK_INTERVAL: Duration = Duration::from_millis(250);
#[must_use]
pub fn should_solve_synchronously(plane_count: usize, last_solve: Option<Duration>) -> bool {
last_solve.map_or(plane_count <= SYNC_SOLVE_PLANE_LIMIT, |last| {
last <= SYNC_SOLVE_TIME_LIMIT
})
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SolveCostEstimate {
pub planes: usize,
pub meet_derived_tiers: usize,
pub has_tier_targets: bool,
}
impl SolveCostEstimate {
#[must_use]
pub fn of(design: &Design) -> Self {
Self {
planes: design.tiers.iter().map(|t| t.indices.len()).sum(),
meet_derived_tiers: design
.tiers
.iter()
.filter(|t| !matches!(t.constraint, MeetConstraint::ScaleReference(_)))
.count(),
has_tier_targets: !design.tier_targets.is_empty(),
}
}
}
#[must_use]
pub fn should_solve_synchronously_for(
cost: SolveCostEstimate,
last_solve: Option<Duration>,
) -> bool {
cost.planes <= SYNC_SOLVE_PLANE_LIMIT
&& cost.meet_derived_tiers <= SYNC_SOLVE_MEET_TIER_LIMIT
&& !cost.has_tier_targets
&& last_solve.is_none_or(|last| last <= SYNC_SOLVE_TIME_LIMIT)
}
#[must_use]
pub const fn should_schedule_auto_solve(last_solve: Option<Duration>, budget: Duration) -> bool {
if budget.is_zero() {
return false;
}
match last_solve {
Some(last) => last.as_millis() < budget.as_millis(),
None => true,
}
}
#[must_use]
pub fn auto_solve_off_note(last_solve: Duration) -> String {
format!(
"Auto-solve off for this design: last solve took {:.1}s.",
last_solve.as_secs_f32()
)
}
#[must_use]
pub fn solving_banner(tier_count: usize, elapsed: Duration) -> String {
format!(
"Solving... ({tier_count} tier{}) -- {:.1}s elapsed",
if tier_count == 1 { "" } else { "s" },
elapsed.as_secs_f32()
)
}
pub fn solve_cancellably(
design: &Design,
cancel: &AtomicBool,
) -> Result<Vec<SolvedTier>, DesignSolveError> {
match design.solve_with(&SolveControl::with_cancel(cancel)) {
Err(DesignSolveError::Solve(SolveError::TooManyPlanes { .. })) => {
if cancel.load(Ordering::Relaxed) {
return Err(DesignSolveError::Solve(SolveError::Cancelled));
}
Ok(solve_meet_points(
design.meta.gear_teeth_abs(),
&design.meet_tier_inputs(),
))
}
other => other,
}
}
#[must_use]
pub fn likely_hit_plane_cap(solved: &[SolvedTier]) -> bool {
solved
.iter()
.any(|t| matches!(t.strategy, SolveStrategy::Failed) && t.detail.contains("plane cap"))
}
#[must_use]
pub fn too_many_planes_message(design: &Design) -> Option<String> {
match design.solve_with(&SolveControl::default()) {
Err(DesignSolveError::Solve(SolveError::TooManyPlanes { planes, max })) => Some(format!(
"This design has {planes} facet planes; the solver supports up to {max} -- reduce \
symmetry or split the design."
)),
_ => None,
}
}
#[must_use]
pub fn design_to_gpu_planes_from_solved(
design: &Design,
solved: &[SolvedTier],
) -> Vec<GpuFacetPlane> {
design
.planes_from_solved(solved)
.into_iter()
.map(|(normal, offset)| GpuFacetPlane::new(normal.as_vec3(), -offset as f32))
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
use indicatrix_cut_core::{ConstraintTier, PreformSpec, ScheduleMeta};
#[test]
fn a_zero_budget_never_schedules_and_no_measurement_schedules_optimistically() {
assert!(!should_schedule_auto_solve(None, Duration::ZERO));
assert!(should_schedule_auto_solve(None, Duration::from_millis(1)));
assert!(should_schedule_auto_solve(
Some(Duration::from_millis(100)),
Duration::from_millis(200)
));
assert!(!should_schedule_auto_solve(
Some(Duration::from_millis(200)),
Duration::from_millis(200)
));
}
#[test]
fn a_measurement_beats_the_plane_count_estimate() {
assert!(should_solve_synchronously(SYNC_SOLVE_PLANE_LIMIT, None));
assert!(!should_solve_synchronously(
SYNC_SOLVE_PLANE_LIMIT + 1,
None
));
assert!(should_solve_synchronously(
10_000,
Some(SYNC_SOLVE_TIME_LIMIT)
));
assert!(!should_solve_synchronously(
1,
Some(SYNC_SOLVE_TIME_LIMIT + Duration::from_millis(1))
));
}
const SMALL: SolveCostEstimate = SolveCostEstimate {
planes: 4,
meet_derived_tiers: 2,
has_tier_targets: false,
};
#[test]
fn a_small_design_solves_inline_unless_its_last_solve_was_slow() {
assert!(should_solve_synchronously_for(SMALL, None));
assert!(should_solve_synchronously_for(
SMALL,
Some(SYNC_SOLVE_TIME_LIMIT)
));
assert!(!should_solve_synchronously_for(
SMALL,
Some(SYNC_SOLVE_TIME_LIMIT + Duration::from_millis(1))
));
}
#[test]
fn a_fast_measurement_never_admits_a_design_the_estimate_rules_out() {
let fast = Some(Duration::from_millis(1));
let too_many_planes = SolveCostEstimate {
planes: SYNC_SOLVE_PLANE_LIMIT + 1,
..SMALL
};
let too_many_meet_tiers = SolveCostEstimate {
meet_derived_tiers: SYNC_SOLVE_MEET_TIER_LIMIT + 1,
..SMALL
};
let targeted = SolveCostEstimate {
has_tier_targets: true,
..SMALL
};
for cost in [too_many_planes, too_many_meet_tiers, targeted] {
assert!(!should_solve_synchronously_for(cost, None), "{cost:?}");
assert!(!should_solve_synchronously_for(cost, fast), "{cost:?}");
}
}
#[test]
fn the_limits_themselves_are_still_inline() {
let at_limits = SolveCostEstimate {
planes: SYNC_SOLVE_PLANE_LIMIT,
meet_derived_tiers: SYNC_SOLVE_MEET_TIER_LIMIT,
has_tier_targets: false,
};
assert!(should_solve_synchronously_for(at_limits, None));
}
#[test]
fn the_estimate_counts_indices_and_only_the_non_anchored_tiers() {
let mut design = Design::new(
PreformSpec::block(2.0, 1.0, 2.0),
ScheduleMeta::standard_round_brilliant(),
ConstraintTier::standard_round_brilliant(),
);
let expected_planes: usize = design.tiers.iter().map(|t| t.indices.len()).sum();
let anchored = SolveCostEstimate::of(&design);
assert_eq!(anchored.planes, expected_planes);
assert!(anchored.planes > 0);
assert_eq!(
anchored.meet_derived_tiers, 0,
"every template tier is anchored"
);
assert!(!anchored.has_tier_targets);
design.tiers[0].constraint = MeetConstraint::MeetExisting;
design.tiers[1].constraint = MeetConstraint::MeetNamed(vec!["P1".to_string()]);
let mixed = SolveCostEstimate::of(&design);
assert_eq!(mixed.meet_derived_tiers, 2);
assert_eq!(
mixed.planes, expected_planes,
"a constraint change moves no plane"
);
}
#[test]
fn banners_read_as_sentences() {
assert_eq!(
solving_banner(1, Duration::from_millis(1300)),
"Solving... (1 tier) -- 1.3s elapsed"
);
assert_eq!(
solving_banner(3, Duration::ZERO),
"Solving... (3 tiers) -- 0.0s elapsed"
);
assert_eq!(
auto_solve_off_note(Duration::from_millis(2500)),
"Auto-solve off for this design: last solve took 2.5s."
);
}
#[test]
fn a_set_cancel_flag_cancels_before_any_work() {
let design = crate::EditorSession::fresh().design;
let cancel = AtomicBool::new(false);
assert!(solve_cancellably(&design, &cancel).is_ok());
assert!(!likely_hit_plane_cap(&[]));
assert_eq!(too_many_planes_message(&design), None);
}
}