15141
|
1 |
use integral_geometry::{Rect, Size};
|
15207
|
2 |
use itertools::Itertools;
|
|
3 |
use std::{
|
|
4 |
cmp::{max, min, Ordering},
|
|
5 |
ops::Index,
|
|
6 |
};
|
15141
|
7 |
|
|
8 |
#[derive(PartialEq, Eq, PartialOrd, Ord, Clone)]
|
|
9 |
struct Fit {
|
|
10 |
short_side: u32,
|
|
11 |
long_side: u32,
|
|
12 |
}
|
|
13 |
|
|
14 |
impl Fit {
|
|
15 |
fn new() -> Self {
|
|
16 |
Self {
|
|
17 |
short_side: u32::max_value(),
|
|
18 |
long_side: u32::max_value(),
|
|
19 |
}
|
|
20 |
}
|
|
21 |
|
|
22 |
fn measure(container: Size, size: Size) -> Option<Self> {
|
|
23 |
if container.contains(size) {
|
|
24 |
let x_leftover = container.width - size.width;
|
|
25 |
let y_leftover = container.height - size.height;
|
|
26 |
Some(Self {
|
|
27 |
short_side: min(x_leftover, y_leftover) as u32,
|
|
28 |
long_side: max(x_leftover, y_leftover) as u32,
|
|
29 |
})
|
|
30 |
} else {
|
|
31 |
None
|
|
32 |
}
|
|
33 |
}
|
|
34 |
}
|
|
35 |
|
|
36 |
#[derive(PartialEq, Eq)]
|
|
37 |
pub struct UsedSpace {
|
|
38 |
used_area: usize,
|
|
39 |
total_area: usize,
|
|
40 |
}
|
|
41 |
|
|
42 |
impl UsedSpace {
|
|
43 |
const fn new(used_area: usize, total_area: usize) -> Self {
|
|
44 |
Self {
|
|
45 |
used_area,
|
|
46 |
total_area,
|
|
47 |
}
|
|
48 |
}
|
|
49 |
|
|
50 |
const fn used(&self) -> usize {
|
|
51 |
self.used_area
|
|
52 |
}
|
|
53 |
|
|
54 |
const fn total(&self) -> usize {
|
|
55 |
self.total_area
|
|
56 |
}
|
15207
|
57 |
|
|
58 |
const fn free(&self) -> usize {
|
|
59 |
self.total_area - self.used_area
|
|
60 |
}
|
15141
|
61 |
}
|
|
62 |
|
|
63 |
impl std::fmt::Debug for UsedSpace {
|
|
64 |
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
|
|
65 |
write!(
|
|
66 |
f,
|
|
67 |
"{:.2}%",
|
15211
|
68 |
self.used() as f32 / self.total() as f32 * 100.0
|
15141
|
69 |
)?;
|
|
70 |
Ok(())
|
|
71 |
}
|
|
72 |
}
|
|
73 |
|
15207
|
74 |
pub struct Atlas<T> {
|
15141
|
75 |
size: Size,
|
|
76 |
free_rects: Vec<Rect>,
|
15207
|
77 |
used_rects: Vec<(Rect, T)>,
|
15141
|
78 |
splits: Vec<Rect>,
|
|
79 |
}
|
|
80 |
|
15207
|
81 |
impl<T: Copy> Atlas<T> {
|
15141
|
82 |
pub fn new(size: Size) -> Self {
|
|
83 |
Self {
|
|
84 |
size,
|
|
85 |
free_rects: vec![Rect::at_origin(size)],
|
|
86 |
used_rects: vec![],
|
|
87 |
splits: vec![],
|
|
88 |
}
|
|
89 |
}
|
|
90 |
|
|
91 |
pub fn size(&self) -> Size {
|
|
92 |
self.size
|
|
93 |
}
|
|
94 |
|
|
95 |
pub fn used_space(&self) -> UsedSpace {
|
15207
|
96 |
let used = self.used_rects.iter().map(|(r, _)| r.size().area()).sum();
|
15141
|
97 |
UsedSpace::new(used, self.size.area())
|
|
98 |
}
|
|
99 |
|
|
100 |
fn find_position(&self, size: Size) -> Option<(Rect, Fit)> {
|
|
101 |
let mut best_rect = Rect::EMPTY;
|
|
102 |
let mut best_fit = Fit::new();
|
|
103 |
|
|
104 |
for rect in &self.free_rects {
|
|
105 |
if let Some(fit) = Fit::measure(rect.size(), size) {
|
|
106 |
if fit < best_fit {
|
|
107 |
best_fit = fit;
|
|
108 |
best_rect = Rect::from_size(rect.top_left(), size);
|
|
109 |
}
|
|
110 |
}
|
|
111 |
|
|
112 |
if let Some(fit) = Fit::measure(rect.size(), size.transpose()) {
|
|
113 |
if fit < best_fit {
|
|
114 |
best_fit = fit;
|
|
115 |
best_rect = Rect::from_size(rect.top_left(), size.transpose());
|
|
116 |
}
|
|
117 |
}
|
|
118 |
}
|
|
119 |
|
|
120 |
if best_rect == Rect::EMPTY {
|
|
121 |
None
|
|
122 |
} else {
|
|
123 |
Some((best_rect, best_fit))
|
|
124 |
}
|
|
125 |
}
|
|
126 |
|
15207
|
127 |
fn split_insert(&mut self, rect: Rect, value: T) {
|
15141
|
128 |
let mut splits = std::mem::replace(&mut self.splits, vec![]);
|
|
129 |
let mut buffer = [Rect::EMPTY; 4];
|
|
130 |
|
|
131 |
for i in (0..self.free_rects.len()).rev() {
|
|
132 |
if let Some(count) = split_rect(self.free_rects[i], rect, &mut splits, &mut buffer) {
|
|
133 |
self.free_rects.swap_remove(i as usize);
|
|
134 |
splits.extend_from_slice(&buffer[0..count]);
|
|
135 |
}
|
|
136 |
}
|
|
137 |
|
|
138 |
filter_swap_remove(&mut splits, |s| {
|
|
139 |
self.free_rects.iter().any(|r| r.contains_rect(s))
|
|
140 |
});
|
|
141 |
self.free_rects.extend(splits.drain(..));
|
|
142 |
std::mem::replace(&mut self.splits, splits);
|
|
143 |
|
15207
|
144 |
self.used_rects.push((rect, value));
|
15141
|
145 |
}
|
|
146 |
|
15207
|
147 |
pub fn insert(&mut self, size: Size, value: T) -> Option<Rect> {
|
15141
|
148 |
let (rect, _) = self.find_position(size)?;
|
15207
|
149 |
self.split_insert(rect, value);
|
15141
|
150 |
Some(rect)
|
|
151 |
}
|
|
152 |
|
15207
|
153 |
pub fn insert_set<Iter>(&mut self, sizes: Iter) -> Vec<(Rect, T)>
|
15141
|
154 |
where
|
15207
|
155 |
Iter: Iterator<Item = (Size, T)>,
|
15141
|
156 |
{
|
|
157 |
let mut sizes: Vec<_> = sizes.collect();
|
15207
|
158 |
let mut result = Vec::with_capacity(sizes.len());
|
15141
|
159 |
|
15207
|
160 |
while let Some((index, (rect, _), value)) = sizes
|
15141
|
161 |
.iter()
|
|
162 |
.enumerate()
|
15207
|
163 |
.filter_map(|(i, (s, v))| self.find_position(*s).map(|res| (i, res, v)))
|
|
164 |
.min_by_key(|(_, (_, fit), _)| fit.clone())
|
15141
|
165 |
{
|
15207
|
166 |
self.split_insert(rect, *value);
|
15141
|
167 |
|
15207
|
168 |
result.push((rect, *value));
|
15141
|
169 |
sizes.swap_remove(index);
|
|
170 |
}
|
|
171 |
result
|
|
172 |
}
|
|
173 |
|
|
174 |
pub fn reset(&mut self) {
|
|
175 |
self.free_rects.clear();
|
|
176 |
self.used_rects.clear();
|
|
177 |
self.free_rects.push(Rect::at_origin(self.size));
|
|
178 |
}
|
|
179 |
}
|
|
180 |
|
15207
|
181 |
pub type SpriteIndex = u32;
|
|
182 |
pub type SpriteLocation = (u32, Rect);
|
|
183 |
|
15141
|
184 |
pub struct AtlasCollection {
|
15207
|
185 |
next_index: SpriteIndex,
|
15141
|
186 |
texture_size: Size,
|
15207
|
187 |
atlases: Vec<Atlas<SpriteIndex>>,
|
|
188 |
rects: Vec<SpriteLocation>,
|
15141
|
189 |
}
|
|
190 |
|
|
191 |
impl AtlasCollection {
|
|
192 |
pub fn new(texture_size: Size) -> Self {
|
|
193 |
Self {
|
15207
|
194 |
next_index: 0,
|
15141
|
195 |
texture_size,
|
|
196 |
atlases: vec![],
|
15207
|
197 |
rects: vec![],
|
15141
|
198 |
}
|
|
199 |
}
|
|
200 |
|
|
201 |
fn repack(&mut self, size: Size) -> bool {
|
15207
|
202 |
for (atlas_index, atlas) in self.atlases.iter_mut().enumerate() {
|
|
203 |
if atlas.used_space().free() >= size.area() {
|
|
204 |
let mut temp_atlas = Atlas::new(atlas.size());
|
|
205 |
let sizes = atlas
|
|
206 |
.used_rects
|
|
207 |
.iter()
|
|
208 |
.map(|(r, v)| (r.size(), *v))
|
|
209 |
.chain(std::iter::once((size, self.next_index)));
|
|
210 |
let inserts = temp_atlas.insert_set(sizes);
|
|
211 |
if inserts.len() > atlas.used_rects.len() {
|
|
212 |
self.rects.push((0, Rect::EMPTY));
|
|
213 |
for (rect, index) in inserts {
|
|
214 |
self.rects[index as usize] = (atlas_index as u32, rect);
|
|
215 |
}
|
|
216 |
std::mem::swap(atlas, &mut temp_atlas);
|
|
217 |
return true;
|
|
218 |
}
|
15141
|
219 |
}
|
|
220 |
}
|
|
221 |
false
|
|
222 |
}
|
|
223 |
|
15207
|
224 |
#[inline]
|
|
225 |
fn consume_index(&mut self) -> Option<SpriteIndex> {
|
|
226 |
let result = Some(self.next_index);
|
|
227 |
self.next_index += 1;
|
|
228 |
result
|
|
229 |
}
|
|
230 |
|
|
231 |
pub fn insert_sprite(&mut self, size: Size) -> Option<SpriteIndex> {
|
15141
|
232 |
if !self.texture_size.contains(size) {
|
15207
|
233 |
None
|
15141
|
234 |
} else {
|
15207
|
235 |
let index = self.next_index;
|
|
236 |
if let Some(index_rect) = self
|
|
237 |
.atlases
|
|
238 |
.iter_mut()
|
|
239 |
.enumerate()
|
|
240 |
.find_map(|(i, a)| a.insert(size, index).map(|r| (i as u32, r)))
|
|
241 |
{
|
|
242 |
self.rects.push(index_rect);
|
15141
|
243 |
} else if !self.repack(size) {
|
|
244 |
let mut atlas = Atlas::new(self.texture_size);
|
15207
|
245 |
let rect = atlas.insert(size, index)?;
|
15141
|
246 |
self.atlases.push(atlas);
|
15207
|
247 |
self.rects.push(((self.atlases.len() - 1) as u32, rect))
|
15141
|
248 |
}
|
15207
|
249 |
self.consume_index()
|
15141
|
250 |
}
|
|
251 |
}
|
15211
|
252 |
|
15307
|
253 |
pub fn get_rect(&self, index: SpriteIndex) -> Option<(u32, Rect)> {
|
|
254 |
self.rects.get(index as usize).cloned()
|
|
255 |
}
|
|
256 |
|
15211
|
257 |
pub fn used_space(&self) -> String {
|
|
258 |
self.atlases
|
|
259 |
.iter()
|
|
260 |
.enumerate()
|
|
261 |
.map(|(i, a)| format!("{}: {:?}", i, a.used_space()))
|
|
262 |
.join("\n")
|
|
263 |
}
|
15141
|
264 |
}
|
|
265 |
|
15207
|
266 |
impl Index<SpriteIndex> for AtlasCollection {
|
|
267 |
type Output = SpriteLocation;
|
|
268 |
|
|
269 |
#[inline]
|
|
270 |
fn index(&self, index: SpriteIndex) -> &Self::Output {
|
|
271 |
&self.rects[index as usize]
|
|
272 |
}
|
|
273 |
}
|
|
274 |
|
15141
|
275 |
#[inline]
|
|
276 |
fn filter_swap_remove<T, F>(vec: &mut Vec<T>, predicate: F)
|
|
277 |
where
|
|
278 |
F: Fn(&T) -> bool,
|
|
279 |
{
|
|
280 |
let mut i = 0;
|
|
281 |
while i < vec.len() {
|
|
282 |
if predicate(&vec[i]) {
|
|
283 |
vec.swap_remove(i);
|
|
284 |
} else {
|
|
285 |
i += 1;
|
|
286 |
}
|
|
287 |
}
|
|
288 |
}
|
|
289 |
|
|
290 |
#[inline]
|
|
291 |
fn prune_push(
|
|
292 |
previous_splits: &mut Vec<Rect>,
|
|
293 |
buffer: &mut [Rect; 4],
|
|
294 |
buffer_size: &mut usize,
|
|
295 |
rect: Rect,
|
|
296 |
) {
|
|
297 |
if !previous_splits.iter().any(|r| r.contains_rect(&rect)) {
|
|
298 |
filter_swap_remove(previous_splits, |s| rect.contains_rect(s));
|
|
299 |
buffer[*buffer_size] = rect;
|
|
300 |
*buffer_size += 1;
|
|
301 |
}
|
|
302 |
}
|
|
303 |
|
|
304 |
fn split_rect(
|
|
305 |
free_rect: Rect,
|
|
306 |
rect: Rect,
|
|
307 |
previous_splits: &mut Vec<Rect>,
|
|
308 |
buffer: &mut [Rect; 4],
|
|
309 |
) -> Option<usize> {
|
|
310 |
let mut buffer_size = 0usize;
|
|
311 |
let split = free_rect.intersects(&rect);
|
|
312 |
if split {
|
|
313 |
if rect.left() > free_rect.left() {
|
|
314 |
let trim = free_rect.right() - rect.left() + 1;
|
|
315 |
prune_push(
|
|
316 |
previous_splits,
|
|
317 |
buffer,
|
|
318 |
&mut buffer_size,
|
|
319 |
free_rect.with_margins(0, -trim, 0, 0),
|
|
320 |
);
|
|
321 |
}
|
|
322 |
if rect.right() < free_rect.right() {
|
|
323 |
let trim = rect.right() - free_rect.left() + 1;
|
|
324 |
prune_push(
|
|
325 |
previous_splits,
|
|
326 |
buffer,
|
|
327 |
&mut buffer_size,
|
|
328 |
free_rect.with_margins(-trim, 0, 0, 0),
|
|
329 |
);
|
|
330 |
}
|
|
331 |
if rect.top() > free_rect.top() {
|
|
332 |
let trim = free_rect.bottom() - rect.top() + 1;
|
|
333 |
prune_push(
|
|
334 |
previous_splits,
|
|
335 |
buffer,
|
|
336 |
&mut buffer_size,
|
|
337 |
free_rect.with_margins(0, 0, 0, -trim),
|
|
338 |
);;
|
|
339 |
}
|
|
340 |
if rect.bottom() < free_rect.bottom() {
|
|
341 |
let trim = rect.bottom() - free_rect.top() + 1;
|
|
342 |
prune_push(
|
|
343 |
previous_splits,
|
|
344 |
buffer,
|
|
345 |
&mut buffer_size,
|
|
346 |
free_rect.with_margins(0, 0, -trim, 0),
|
|
347 |
);;
|
|
348 |
}
|
|
349 |
}
|
|
350 |
if split {
|
|
351 |
Some(buffer_size)
|
|
352 |
} else {
|
|
353 |
None
|
|
354 |
}
|
|
355 |
}
|
|
356 |
|
|
357 |
#[cfg(test)]
|
|
358 |
mod tests {
|
|
359 |
use super::Atlas;
|
|
360 |
use integral_geometry::{Rect, Size};
|
|
361 |
use itertools::Itertools as _;
|
|
362 |
use proptest::prelude::*;
|
|
363 |
|
|
364 |
#[test]
|
|
365 |
fn insert() {
|
|
366 |
let atlas_size = Size::square(16);
|
|
367 |
let mut atlas = Atlas::new(atlas_size);
|
|
368 |
|
15207
|
369 |
assert_eq!(None, atlas.insert(Size::square(20), ()));
|
15141
|
370 |
|
|
371 |
let rect_size = Size::new(11, 3);
|
15207
|
372 |
let rect = atlas.insert(rect_size, ()).unwrap();
|
15141
|
373 |
|
|
374 |
assert_eq!(rect, Rect::at_origin(rect_size));
|
|
375 |
assert_eq!(2, atlas.free_rects.len());
|
|
376 |
}
|
|
377 |
|
|
378 |
#[derive(Debug, Clone)]
|
|
379 |
struct TestRect(Size);
|
|
380 |
struct TestRectParameters(Size);
|
|
381 |
|
|
382 |
impl Default for TestRectParameters {
|
|
383 |
fn default() -> Self {
|
|
384 |
Self(Size::square(64))
|
|
385 |
}
|
|
386 |
}
|
|
387 |
|
|
388 |
impl Arbitrary for TestRect {
|
|
389 |
type Parameters = TestRectParameters;
|
|
390 |
|
|
391 |
fn arbitrary_with(args: Self::Parameters) -> Self::Strategy {
|
|
392 |
(1..=args.0.width, 1..=args.0.height)
|
|
393 |
.prop_map(|(w, h)| TestRect(Size::new(w, h)))
|
|
394 |
.boxed()
|
|
395 |
}
|
|
396 |
|
|
397 |
type Strategy = BoxedStrategy<TestRect>;
|
|
398 |
}
|
|
399 |
|
|
400 |
trait HasSize {
|
|
401 |
fn size(&self) -> Size;
|
|
402 |
}
|
|
403 |
|
|
404 |
impl HasSize for TestRect {
|
|
405 |
fn size(&self) -> Size {
|
|
406 |
self.0
|
|
407 |
}
|
|
408 |
}
|
|
409 |
|
|
410 |
impl HasSize for Rect {
|
|
411 |
fn size(&self) -> Size {
|
|
412 |
self.size()
|
|
413 |
}
|
|
414 |
}
|
|
415 |
|
15207
|
416 |
impl HasSize for (Rect, ()) {
|
|
417 |
fn size(&self) -> Size {
|
|
418 |
self.0.size()
|
|
419 |
}
|
|
420 |
}
|
|
421 |
|
15141
|
422 |
fn sum_area<S: HasSize>(items: &[S]) -> usize {
|
|
423 |
items.iter().map(|s| s.size().area()).sum()
|
|
424 |
}
|
|
425 |
|
|
426 |
proptest! {
|
|
427 |
#[test]
|
|
428 |
fn prop_insert(rects in Vec::<TestRect>::arbitrary()) {
|
|
429 |
let container = Rect::at_origin(Size::square(2048));
|
|
430 |
let mut atlas = Atlas::new(container.size());
|
15207
|
431 |
let inserted: Vec<_> = rects.iter().filter_map(|TestRect(size)| atlas.insert(*size, ())).collect();
|
15141
|
432 |
|
|
433 |
let mut inserted_pairs = inserted.iter().cartesian_product(inserted.iter());
|
|
434 |
|
|
435 |
assert!(inserted.iter().all(|r| container.contains_rect(r)));
|
|
436 |
assert!(inserted_pairs.all(|(r1, r2)| r1 == r2 || r1 != r2 && !r1.intersects(r2)));
|
|
437 |
|
|
438 |
assert_eq!(inserted.len(), rects.len());
|
|
439 |
assert_eq!(sum_area(&inserted), sum_area(&rects));
|
|
440 |
}
|
|
441 |
}
|
|
442 |
|
|
443 |
proptest! {
|
|
444 |
#[test]
|
|
445 |
fn prop_insert_set(rects in Vec::<TestRect>::arbitrary()) {
|
|
446 |
let container = Rect::at_origin(Size::square(2048));
|
|
447 |
let mut atlas = Atlas::new(container.size());
|
|
448 |
let mut set_atlas = Atlas::new(container.size());
|
|
449 |
|
15207
|
450 |
let inserted: Vec<_> = rects.iter().filter_map(|TestRect(size)| atlas.insert(*size, ())).collect();
|
|
451 |
let set_inserted: Vec<_> = set_atlas.insert_set(rects.iter().map(|TestRect(size)| (*size, ())));
|
15141
|
452 |
|
|
453 |
let mut set_inserted_pairs = set_inserted.iter().cartesian_product(set_inserted.iter());
|
|
454 |
|
15207
|
455 |
assert!(set_inserted_pairs.all(|((r1, _), (r2, _))| r1 == r2 || r1 != r2 && !r1.intersects(r2)));
|
15141
|
456 |
assert!(set_atlas.used_space().used() <= atlas.used_space().used());
|
|
457 |
|
|
458 |
assert_eq!(sum_area(&set_inserted), sum_area(&inserted));
|
|
459 |
}
|
|
460 |
}
|
|
461 |
}
|