use f_office_paint::{Point, stroke};
use f_office_units::{Length, div_round_i128, saturated};
use crate::chart::LineForm;
use crate::params::{CHART_SMOOTH_END_PARTS, CHART_SMOOTH_INNER_PARTS, CHART_SMOOTH_REACH_PARTS};
pub(super) fn form_points(form: LineForm, points: Vec<Point>) -> Vec<Point> {
match form {
LineForm::Straight => points,
LineForm::Smooth => smooth_points(&points),
}
}
fn smooth_points(points: &[Point]) -> Vec<Point> {
let mut out: Vec<Point> = points.first().copied().into_iter().collect();
for controls in curves(points) {
out.extend(stroke::cubic_points(controls));
}
out
}
pub(super) fn curves(points: &[Point]) -> Vec<[Point; 4]> {
let last = points.len().saturating_sub(1);
let tangents: Vec<Point> = (0..points.len())
.map(|index| tangent(points, index, last))
.collect();
points
.windows(2)
.zip(tangents.windows(2))
.filter_map(|pair| match pair {
([start, end], [leaving, arriving]) => {
Some(curve((*start, *end), (*leaving, *arriving)))
}
_ => None,
})
.collect()
}
fn tangent(points: &[Point], index: usize, last: usize) -> Point {
let (before, after, parts) = if index == 0 {
(0, 1, CHART_SMOOTH_END_PARTS)
} else if index == last {
(index - 1, index, CHART_SMOOTH_END_PARTS)
} else {
(index - 1, index + 1, CHART_SMOOTH_INNER_PARTS)
};
match (points.get(before), points.get(after)) {
(Some(from), Some(to)) => Point {
x: (to.x - from.x).div_round(parts),
y: (to.y - from.y).div_round(parts),
},
_ => Point {
x: Length::ZERO,
y: Length::ZERO,
},
}
}
fn reach(step: Point) -> i128 {
let (x, y) = (i128::from(step.x.units()), i128::from(step.y.units()));
(x * x + y * y).isqrt()
}
fn curve((start, end): (Point, Point), (leaving, arriving): (Point, Point)) -> [Point; 4] {
let chord = reach(Point {
x: end.x - start.x,
y: end.y - start.y,
});
let longest = reach(leaving).max(reach(arriving)) * i128::from(CHART_SMOOTH_REACH_PARTS);
let (times, over) = if longest <= chord || longest == 0 {
(1, 1)
} else {
(chord, longest)
};
let scaled = |length: Length| {
Length::from_units(saturated(div_round_i128(
i128::from(length.units()) * times,
over,
)))
};
[
start,
Point {
x: start.x + scaled(leaving.x),
y: start.y + scaled(leaving.y),
},
Point {
x: end.x - scaled(arriving.x),
y: end.y - scaled(arriving.y),
},
end,
]
}