1use crate::collision_detection::CDEConfig;
2use crate::entities::Item;
3use crate::entities::{Container, InferiorQualityZone, N_QUALITIES};
4use crate::geometry::geo_enums::RotationRange;
5use crate::geometry::primitives::{Point, Rect, SPolygon};
6use crate::geometry::shape_modification::{ShapeModifyConfig, ShapeModifyMode};
7use crate::geometry::short_edges::remove_short_edges;
8use crate::geometry::{AllowedOrientations, OriginalShape};
9use crate::geometry::{DTransformation, Transformation};
10use crate::io::ext_repr::{ExtContainer, ExtItem, ExtRotation, ExtSPolygon, ExtShape};
11use anyhow::{Result, bail, ensure};
12use itertools::Itertools;
13use log::{debug, warn};
14use std::fmt::Display;
15use std::sync::Arc;
16
17#[derive(Clone, Debug, Copy)]
20pub struct Importer {
21 pub shape_modify_config: ShapeModifyConfig,
22 pub cde_config: CDEConfig,
23}
24
25impl Importer {
26 #[must_use]
32 pub fn new(
33 cde_config: CDEConfig,
34 simplify_tolerance: Option<f32>,
35 narrow_concavity_cutoff: Option<(f32, f32)>,
36 ) -> Importer {
37 Importer {
38 shape_modify_config: ShapeModifyConfig {
39 offset: None,
40 simplify_tolerance,
41 narrow_concavity_cutoff,
42 },
43 cde_config,
44 }
45 }
46
47 pub fn with_min_item_separation(mut self, separation: f32) -> Result<Self> {
50 ensure!(
51 separation.is_finite() && separation >= 0.0,
52 "min_item_separation must be finite and nonnegative"
53 );
54 self.shape_modify_config.offset = (separation > 0.0).then_some(separation / 2.0);
55 Ok(self)
56 }
57
58 pub fn import_item(&self, ext_item: &ExtItem, idx: usize) -> Result<Arc<Item>> {
60 debug!("[IMPORT] starting item {:?}", ext_item.id);
61
62 let original_shape = {
63 let shape = match &ext_item.shape {
64 ExtShape::Rectangle {
65 x_min,
66 y_min,
67 width,
68 height,
69 } => import_rectangle(*x_min, *y_min, *width, *height)?,
70 ExtShape::SimplePolygon(esp) => {
71 import_described_polygon(esp, format_args!("item {}", ext_item.id))?
72 }
73 ExtShape::Polygon(ep) => {
74 ensure!(
75 ep.inner.is_empty(),
76 "item {} has unsupported holes",
77 ext_item.id
78 );
79 import_described_polygon(&ep.outer, format_args!("item {}", ext_item.id))?
80 }
81 ExtShape::MultiPolygon(_) => {
82 bail!("No support for multipolygons yet")
83 }
84 };
85 OriginalShape {
86 pre_transform: centering_transformation(&shape),
87 shape,
88 modify_mode: ShapeModifyMode::Inflate,
89 modify_config: self.shape_modify_config,
90 }
91 };
92
93 let base_quality = ext_item.min_quality;
94
95 let rotations = import_rotation(&ext_item.orientation.rotation)?;
96 let axes = normalized_radians(&ext_item.orientation.reflection_axes, 180.0)?;
97 let allowed_orientations = AllowedOrientations::new(rotations, axes)?;
98
99 Item::new(
100 idx,
101 ext_item.id,
102 original_shape,
103 allowed_orientations,
104 base_quality,
105 self.cde_config.item_surrogate_config,
106 )
107 .map(Arc::new)
108 }
109
110 pub fn import_container(&self, ext_cont: &ExtContainer) -> Result<Container> {
113 ensure!(
114 ext_cont.zones.iter().all(|zone| zone.quality < N_QUALITIES),
115 "Quality zones must have quality below {N_QUALITIES}"
116 );
117
118 let original_outer = {
119 let outer = match &ext_cont.shape {
120 ExtShape::Rectangle {
121 x_min,
122 y_min,
123 width,
124 height,
125 } => import_rectangle(*x_min, *y_min, *width, *height)?,
126 ExtShape::SimplePolygon(esp) => {
127 import_described_polygon(esp, format_args!("container {}", ext_cont.id))?
128 }
129 ExtShape::Polygon(ep) => {
130 import_described_polygon(&ep.outer, format_args!("container {}", ext_cont.id))?
131 }
132 ExtShape::MultiPolygon(_) => {
133 bail!("No support for multipolygon shapes yet")
134 }
135 };
136 OriginalShape {
137 shape: outer,
138 pre_transform: DTransformation::empty(),
139 modify_mode: ShapeModifyMode::Deflate,
140 modify_config: self.shape_modify_config,
141 }
142 };
143
144 let holes = match &ext_cont.shape {
145 ExtShape::SimplePolygon(_) | ExtShape::Rectangle { .. } => vec![],
146 ExtShape::Polygon(jp) => {
147 let json_holes = &jp.inner;
148 json_holes
149 .iter()
150 .enumerate()
151 .map(|(i, hole)| {
152 import_described_polygon(
153 hole,
154 format_args!("hole {i} of container {}", ext_cont.id),
155 )
156 })
157 .collect::<Result<Vec<SPolygon>>>()?
158 }
159 ExtShape::MultiPolygon(_) => {
160 bail!("No support for multipolygon shapes yet")
161 }
162 };
163
164 let mut shapes_inferior_qzones = (0..N_QUALITIES)
165 .map(|q| {
166 ext_cont
167 .zones
168 .iter()
169 .enumerate()
170 .filter(|(_, zone)| zone.quality == q)
171 .map(|(i, zone)| match &zone.shape {
172 ExtShape::Rectangle {
173 x_min,
174 y_min,
175 width,
176 height,
177 } => import_rectangle(*x_min, *y_min, *width, *height),
178 ExtShape::SimplePolygon(esp) => import_described_polygon(
179 esp,
180 format_args!("quality zone {i} of container {}", ext_cont.id),
181 ),
182 ExtShape::Polygon(_) => {
183 bail!("Quality zones require rectangles or simple polygons")
184 }
185 ExtShape::MultiPolygon(_) => {
186 bail!("Quality zones do not support multipolygons")
187 }
188 })
189 .collect::<Result<Vec<SPolygon>>>()
190 })
191 .collect::<Result<Vec<Vec<SPolygon>>>>()?;
192
193 shapes_inferior_qzones[0].extend(holes);
195
196 let quality_zones = shapes_inferior_qzones
198 .into_iter()
199 .enumerate()
200 .map(|(q, zone_shapes)| {
201 let original_shapes = zone_shapes
202 .into_iter()
203 .map(|s| OriginalShape {
204 shape: s,
205 pre_transform: DTransformation::empty(),
206 modify_mode: ShapeModifyMode::Inflate,
207 modify_config: self.shape_modify_config,
208 })
209 .collect_vec();
210 InferiorQualityZone::new(q, original_shapes, self.cde_config.item_surrogate_config)
211 })
212 .collect::<Result<Vec<InferiorQualityZone>>>()?;
213
214 Container::new(original_outer, quality_zones, self.cde_config)
215 }
216}
217
218#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
219fn import_rotation(rotation: &ExtRotation) -> Result<RotationRange> {
220 const MAX_ANGLES: usize = 65_536;
221 let mut angles = match rotation {
222 ExtRotation::Continuous {} => return Ok(RotationRange::Continuous),
223 ExtRotation::Discrete { angles } => {
224 ensure!(
225 !angles.is_empty() && angles.len() <= MAX_ANGLES,
226 "discrete rotation requires 1..=65536 angles"
227 );
228 ensure!(
229 angles.iter().all(|angle| angle.is_finite()),
230 "rotation angles must be finite"
231 );
232 angles
233 .iter()
234 .map(|angle| angle.rem_euclid(360.0) % 360.0)
235 .collect::<Vec<_>>()
236 }
237 ExtRotation::Stepped { step } => {
238 ensure!(
239 step.is_finite() && *step > 0.0 && *step <= 360.0,
240 "rotation step must be finite and in (0, 360]"
241 );
242 let step = f64::from(*step);
243 let count = (360.0 / step).round();
244 ensure!(
245 count <= 65_536.0
246 && (count * step - 360.0).abs() <= 360.0 * f64::from(f32::EPSILON),
247 "rotation step must divide 360 into at most 65536 angles"
248 );
249 (0..count as u32)
250 .map(|i| (f64::from(i) * 360.0 / count) as f32)
251 .collect()
252 }
253 };
254 angles.sort_by(f32::total_cmp);
255 angles.dedup();
256 if angles == [0.0] {
257 Ok(RotationRange::None)
258 } else {
259 Ok(RotationRange::Discrete(
260 angles.into_iter().map(f32::to_radians).collect(),
261 ))
262 }
263}
264
265fn normalized_radians(angles: &[f32], period: f32) -> Result<Vec<f32>> {
267 ensure!(
268 angles.len() <= AllowedOrientations::MAX_ANGLES,
269 "orientation angle list exceeds the count limit"
270 );
271 ensure!(
272 angles.iter().all(|a| a.is_finite()),
273 "orientation angles must be finite"
274 );
275 Ok(angles
276 .iter()
277 .map(|a| (a.rem_euclid(period) % period).to_radians())
278 .collect())
279}
280
281fn import_rectangle(x_min: f32, y_min: f32, width: f32, height: f32) -> Result<SPolygon> {
284 let rect = Rect::try_new(x_min, y_min, x_min + width, y_min + height)?;
285 SPolygon::try_from(rect)
286}
287
288pub fn import_simple_polygon(sp: &ExtSPolygon) -> Result<SPolygon> {
289 import_described_polygon(sp, "simple polygon")
290}
291
292fn import_described_polygon(sp: &ExtSPolygon, shape: impl Display) -> Result<SPolygon> {
294 let mut points = sp.0.iter().map(|(x, y)| Point(*x, *y)).collect_vec();
295 if points.len() > 1 && points[0] == points[points.len() - 1] {
297 points.pop();
298 }
299 let removal = remove_short_edges(&mut points);
301 if !removal.removed.is_empty() {
302 warn!("[IMPORT] {shape}: {removal}");
303 }
304 SPolygon::new(points)
305}
306
307#[must_use]
309pub fn centering_transformation(shape: &SPolygon) -> DTransformation {
310 let Point(cx, cy) = shape.centroid();
311 DTransformation::new(0.0, (-cx, -cy))
312}
313
314#[must_use]
319pub fn ext_to_int_transformation(
320 ext_transf: &DTransformation,
321 pre_transf: &DTransformation,
322) -> DTransformation {
323 Transformation::empty()
327 .transform(&pre_transf.compose().inverse())
328 .transform_from_decomposed(ext_transf)
329 .decompose()
330}