use crate::paint::RenderProfile;
use super::render_tree::LineNode;
use super::{ArrowStyle, LineRenderType, StrokeDash};
pub(crate) fn raster_line_geometry(
line: &LineNode,
matrix: [f64; 6],
profile: RenderProfile,
paint_width: f64,
) -> (f64, f64, f64, f64, f64) {
let original = (line.x1, line.y1, line.x2, line.y2, paint_width);
let style = &line.style;
if !matches!(profile, RenderProfile::Print | RenderProfile::HighQuality)
|| style.line_type != LineRenderType::Single
|| style.compound_component
|| style.dash != StrokeDash::Solid
|| style.start_arrow != ArrowStyle::None
|| style.end_arrow != ArrowStyle::None
|| style.shadow.is_some()
|| !paint_width.is_finite()
|| paint_width <= 0.0
|| !style.width.is_finite()
|| style.width <= 0.0
|| ![line.x1, line.y1, line.x2, line.y2]
.into_iter()
.chain(matrix)
.all(f64::is_finite)
{
return original;
}
let [a, b, c, d, e, f] = matrix;
if !((b == 0.0 && c == 0.0) || (a == 0.0 && d == 0.0)) {
return original;
}
let determinant = a * d - b * c;
if !determinant.is_finite() || determinant == 0.0 {
return original;
}
let (dx, dy) = (line.x2 - line.x1, line.y2 - line.y1);
let (nx, ny) = if dx != 0.0 && dy == 0.0 {
(0.0, 1.0)
} else if dx == 0.0 && dy != 0.0 {
(1.0, 0.0)
} else {
return original;
};
let normal_scale = (a * nx + c * ny).hypot(b * nx + d * ny);
let device_width = paint_width * normal_scale;
if !(0.0..1.0).contains(&device_width) || device_width == 0.0 {
return original;
}
let raster_width = 1.0 / normal_scale;
if !raster_width.is_finite() || raster_width <= 0.0 {
return original;
}
let (px, py) = (a * line.x1 + c * line.y1 + e, b * line.x1 + d * line.y1 + f);
let (ex, ey) = (a * dx + c * dy, b * dx + d * dy);
if ![px, py, ex, ey].into_iter().all(f64::is_finite) {
return original;
}
if style.preserve_fractional_position {
return (line.x1, line.y1, line.x2, line.y2, raster_width);
}
let (shift_x, shift_y) = if ex != 0.0 && ey == 0.0 {
(0.0, py.floor() + 0.5 - py)
} else if ex == 0.0 && ey != 0.0 {
(px.floor() + 0.5 - px, 0.0)
} else {
return original;
};
let local_x = (d * shift_x - c * shift_y) / determinant;
let local_y = (-b * shift_x + a * shift_y) / determinant;
let adjusted = (
line.x1 + local_x,
line.y1 + local_y,
line.x2 + local_x,
line.y2 + local_y,
raster_width,
);
if [adjusted.0, adjusted.1, adjusted.2, adjusted.3]
.into_iter()
.all(f64::is_finite)
{
adjusted
} else {
original
}
}
pub(crate) fn minimum_width([a, b, c, d]: [f64; 4]) -> Option<f64> {
if ![a, b, c, d].iter().all(|value| value.is_finite()) {
return None;
}
let determinant = a * d - b * c;
if !determinant.is_finite() || determinant == 0.0 {
return None;
}
let unit = (d.hypot(b) / determinant.abs()).min(c.hypot(a) / determinant.abs());
(unit.is_finite() && unit > 0.0).then_some(unit)
}
pub(crate) fn width(source: f64, minimum: Option<f64>) -> f64 {
minimum.map_or(source, |minimum| source.max(minimum))
}