use geometry::Point;
use glam::Vec2;
use mln_math::deg2radf;
use mln_style_types::SymbolPlacementType;
use mln_text::PositionedIcon;
use mln_text::glyph::Shaping;
use mln_tile_id::geometry_tile_data::{GeometryCoordinate, GeometryCoordinates};
use mln_util::Padding;
use mln_util::grid_index::{BBox, BCircle};
use crate::geometry::anchor::Anchor;
use crate::geometry::feature_index::IndexedSubfeature;
use crate::util::pool::PoolRange;
fn dist(a: GeometryCoordinate, b: GeometryCoordinate) -> f32 {
let dx = f64::from(i32::from(b.x) - i32::from(a.x));
let dy = f64::from(i32::from(b.y) - i32::from(a.y));
(dx * dx + dy * dy).sqrt() as f32
}
fn min4(values: [f32; 4]) -> f32 {
let mut smallest = values[0];
for value in &values[1..] {
if *value < smallest {
smallest = *value;
}
}
smallest
}
fn max4(values: [f32; 4]) -> f32 {
let mut largest = values[0];
for value in &values[1..] {
if largest < *value {
largest = *value;
}
}
largest
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) enum ProjectedCollisionBoxType {
#[default]
Unknown,
Box,
Circle,
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub(crate) struct ProjectedCollisionBox {
geometry: ProjectedCollisionBoxGeometry,
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
enum ProjectedCollisionBoxGeometry {
#[default]
Unknown,
Box(BBox),
Circle(BCircle),
}
impl ProjectedCollisionBox {
#[must_use]
pub(crate) fn new_box(x1: f32, y1: f32, x2: f32, y2: f32) -> Self {
ProjectedCollisionBox {
geometry: ProjectedCollisionBoxGeometry::Box(BBox::new(Point::new(x1, y1), Point::new(x2, y2))),
}
}
#[must_use]
pub(crate) fn new_circle(x: f32, y: f32, r: f32) -> Self {
ProjectedCollisionBox { geometry: ProjectedCollisionBoxGeometry::Circle(BCircle::new(Point::new(x, y), r)) }
}
#[must_use]
pub(crate) fn box_(&self) -> &BBox {
match &self.geometry {
ProjectedCollisionBoxGeometry::Box(b) => b,
_ => panic!("ProjectedCollisionBox::box: not a box"),
}
}
#[must_use]
pub(crate) fn circle(&self) -> &BCircle {
match &self.geometry {
ProjectedCollisionBoxGeometry::Circle(c) => c,
_ => panic!("ProjectedCollisionBox::circle: not a circle"),
}
}
#[must_use]
pub(crate) fn type_(&self) -> ProjectedCollisionBoxType {
match self.geometry {
ProjectedCollisionBoxGeometry::Unknown => ProjectedCollisionBoxType::Unknown,
ProjectedCollisionBoxGeometry::Box(_) => ProjectedCollisionBoxType::Box,
ProjectedCollisionBoxGeometry::Circle(_) => ProjectedCollisionBoxType::Circle,
}
}
#[must_use]
pub(crate) fn is_circle(&self) -> bool {
self.type_() == ProjectedCollisionBoxType::Circle
}
#[must_use]
pub(crate) fn is_box(&self) -> bool {
self.type_() == ProjectedCollisionBoxType::Box
}
}
#[derive(Clone, Copy, Debug, PartialEq, mln_wire::Wire)]
pub(crate) struct CollisionBox {
pub(crate) anchor: Vec2,
pub(crate) x1: f32,
pub(crate) y1: f32,
pub(crate) x2: f32,
pub(crate) y2: f32,
pub(crate) signed_distance_from_anchor: f32,
}
impl CollisionBox {
#[must_use]
pub(crate) fn new(anchor: Vec2, x1: f32, y1: f32, x2: f32, y2: f32, signed_distance_from_anchor: f32) -> Self {
CollisionBox { anchor, x1, y1, x2, y2, signed_distance_from_anchor }
}
}
#[derive(Clone, Debug, mln_wire::Wire)]
pub(crate) struct CollisionFeature {
pub(crate) boxes: PoolRange,
pub(crate) indexed_feature: IndexedSubfeature,
pub(crate) along_line: bool,
}
impl CollisionFeature {
#[expect(
clippy::too_many_arguments,
reason = "the line, anchor and shaped text, and the box scale, padding, placement, feature, overscaling and rotation of its boxes"
)]
#[must_use]
pub(crate) fn new_text(
line: &GeometryCoordinates,
anchor: &Anchor,
shaped_text: &Shaping,
box_scale: f32,
padding: f32,
placement: SymbolPlacementType,
indexed_feature: &IndexedSubfeature,
overscaling: f32,
rotate: f32,
boxes: &mut Vec<CollisionBox>,
) -> Self {
let mut feature = CollisionFeature {
boxes: PoolRange::at_end(boxes),
indexed_feature: indexed_feature.clone(),
along_line: placement != SymbolPlacementType::Point,
};
feature.initialize(
boxes,
line,
anchor,
shaped_text.top,
shaped_text.bottom,
shaped_text.left,
shaped_text.right,
None,
box_scale,
&Padding::uniform(padding),
overscaling,
rotate,
);
feature
}
#[expect(
clippy::too_many_arguments,
reason = "the line, anchor and shaped icon, the box scale, padding, feature and rotation, and the pool"
)]
#[must_use]
pub(crate) fn new_icon(
line: &GeometryCoordinates,
anchor: &Anchor,
shaped_icon: Option<&PositionedIcon>,
box_scale: f32,
padding: &Padding,
indexed_feature: &IndexedSubfeature,
rotate: f32,
boxes: &mut Vec<CollisionBox>,
) -> Self {
let mut feature = CollisionFeature {
boxes: PoolRange::at_end(boxes),
indexed_feature: indexed_feature.clone(),
along_line: false,
};
if let Some(shaped_icon) = shaped_icon {
let image = shaped_icon.image();
let mut icon = shaped_icon.clone();
if image.content.is_some() && (image.text_fit_width.is_some() || image.text_fit_height.is_some()) {
icon = shaped_icon.apply_text_fit();
}
feature.initialize(
boxes,
line,
anchor,
icon.top(),
icon.bottom(),
icon.left(),
icon.right(),
Some(shaped_icon.collision_padding()),
box_scale,
padding,
1.0,
rotate,
);
} else {
feature.initialize(boxes, line, anchor, 0.0, 0.0, 0.0, 0.0, None, box_scale, padding, 1.0, rotate);
}
feature
}
#[expect(
clippy::too_many_arguments,
reason = "the pool, line, anchor and box edges, and the paddings, scales and rotation of the boxes"
)]
fn initialize(
&mut self,
boxes: &mut Vec<CollisionBox>,
line: &GeometryCoordinates,
anchor: &Anchor,
top: f32,
bottom: f32,
left: f32,
right: f32,
collision_padding: Option<&Padding>,
box_scale: f32,
padding: &Padding,
overscaling: f32,
rotate: f32,
) {
if top == 0.0 && bottom == 0.0 && left == 0.0 && right == 0.0 {
return;
}
let mut y1 = top * box_scale - padding.top;
let mut y2 = bottom * box_scale + padding.bottom;
let mut x1 = left * box_scale - padding.left;
let mut x2 = right * box_scale + padding.right;
if let Some(collision_padding) = collision_padding {
x1 -= collision_padding.left * box_scale;
y1 -= collision_padding.top * box_scale;
x2 += collision_padding.right * box_scale;
y2 += collision_padding.bottom * box_scale;
}
if self.along_line {
let mut height = y2 - y1;
let length = x2 - x1;
if height <= 0.0 {
return;
}
let min_height = 10.0f32 * box_scale;
height = if min_height < height { height } else { min_height };
let mut anchor_point = GeometryCoordinate::new(anchor.point.x as i16, anchor.point.y as i16);
self.bboxify_label(
boxes,
line,
&mut anchor_point,
anchor.segment.unwrap_or(0),
length,
height,
overscaling,
);
} else if rotate != 0.0 {
let rotate_radians = deg2radf(rotate);
let rotation = Vec2::from_angle(rotate_radians);
let tl = rotation.rotate(Vec2::new(x1, y1));
let tr = rotation.rotate(Vec2::new(x2, y1));
let bl = rotation.rotate(Vec2::new(x1, y2));
let br = rotation.rotate(Vec2::new(x2, y2));
let x_min = min4([tl.x, tr.x, bl.x, br.x]);
let x_max = max4([tl.x, tr.x, bl.x, br.x]);
let y_min = min4([tl.y, tr.y, bl.y, br.y]);
let y_max = max4([tl.y, tr.y, bl.y, br.y]);
self.boxes.push(boxes, CollisionBox::new(anchor.point, x_min, y_min, x_max, y_max, 0.0));
} else {
self.boxes.push(boxes, CollisionBox::new(anchor.point, x1, y1, x2, y2, 0.0));
}
}
#[expect(
clippy::too_many_arguments,
reason = "the pool, the line and the anchor on it, and the label's length, box size and overscaling"
)]
fn bboxify_label(
&mut self,
boxes: &mut Vec<CollisionBox>,
line: &GeometryCoordinates,
anchor_point: &mut GeometryCoordinate,
segment: usize,
label_length: f32,
box_size: f32,
overscaling: f32,
) {
let step = box_size / 2.0;
let n_boxes = ((label_length / step).floor() as i32).max(1);
let overscaling_padding_factor: f64 = 1.0 + 0.4 * f64::from(overscaling).log2();
let n_pitch_padding_boxes = (f64::from(n_boxes) * overscaling_padding_factor / 2.0).floor() as i32;
let first_box_offset = -box_size / 2.0;
let p = anchor_point;
let mut index: usize = segment + 1;
let mut anchor_distance = first_box_offset;
let label_start_distance = -label_length / 2.0;
let padding_start_distance = label_start_distance - label_length / 8.0;
loop {
if index == 0 {
if anchor_distance > label_start_distance {
return;
}
index = 0;
break;
}
index -= 1;
anchor_distance -= dist(line[index], *p);
*p = line[index];
if anchor_distance <= padding_start_distance {
break;
}
}
let mut segment_length = dist(line[index], line[index + 1]);
for i in -n_pitch_padding_boxes..n_boxes + n_pitch_padding_boxes {
let box_offset = i as f32 * step;
let mut box_distance_to_anchor = label_start_distance + box_offset;
if box_offset < 0.0 {
box_distance_to_anchor += box_offset;
}
if box_offset > label_length {
box_distance_to_anchor += box_offset - label_length;
}
if box_distance_to_anchor < anchor_distance {
continue;
}
while anchor_distance + segment_length < box_distance_to_anchor {
anchor_distance += segment_length;
index += 1;
if index + 1 >= line.len() {
return;
}
segment_length = dist(line[index], line[index + 1]);
}
let segment_box_distance = box_distance_to_anchor - anchor_distance;
let p0 = &line[index];
let p1 = &line[index + 1];
let box_anchor = Vec2::new(
f32::from(p0.x) + segment_box_distance / segment_length * (i32::from(p1.x) - i32::from(p0.x)) as f32,
f32::from(p0.y) + segment_box_distance / segment_length * (i32::from(p1.y) - i32::from(p0.y)) as f32,
);
let padded_anchor_distance = if (box_distance_to_anchor - first_box_offset).abs() < step {
0.0f32
} else {
(box_distance_to_anchor - first_box_offset) * 0.8f32
};
self.boxes.push(
boxes,
CollisionBox::new(
box_anchor,
-box_size / 2.0,
-box_size / 2.0,
box_size / 2.0,
box_size / 2.0,
padded_anchor_distance,
),
);
}
}
}