summaryrefslogtreecommitdiff
path: root/assetFactory/texturePacker.cpp
blob: 31c9a0e6ecbfa1f8821705c56d19230487e31ef1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include "texturePacker.h"
#include <algorithm>
#include <cstdio>
#include <numeric>
#include <ostream>
#include <set>

TexturePacker::TexturePacker(std::vector<Image> in) : inputImages {std::move(in)}
{
	std::sort(inputImages.rbegin(), inputImages.rend(), [](const auto & a, const auto & b) {
		return area(a) < area(b);
	});
}

TexturePacker::Result
TexturePacker::pack() const
{
	return pack(minSize());
}

TexturePacker::Result
TexturePacker::pack(Size size) const
{
	using Spaces = std::set<Space>;
	Spaces spaces {{{}, size}};

	Positions result;
	for (const auto & image : inputImages) {
		if (const auto spaceItr = std::find_if(spaces.begin(), spaces.end(),
					[image](const Space & s) {
						return image.x <= s.size.x && image.y <= s.size.y;
					});
				spaceItr != spaces.end()) {
			auto space = *spaceItr;
			result.push_back(space.position);
			spaces.erase(spaceItr);
			if (space.size.x > image.x) {
				spaces.emplace(Position {space.position.x + image.x, space.position.y},
						Size {space.size.x - image.x, image.y});
			}
			if (space.size.y > image.y) {
				spaces.emplace(Position {space.position.x, space.position.y + image.y},
						Size {space.size.x, space.size.y - image.y});
			}
		}
		else {
			if (size.x < size.y) {
				return pack({size.x * 2, size.y});
			}
			else {
				return pack({size.x, size.y * 2});
			}
		}
	}

	return {result, size};
}

TexturePacker::Size
TexturePacker::minSize() const
{
	return std::accumulate(inputImages.begin(), inputImages.end(), Size {1}, [](Size size, const Image & i) {
		while (size.x < i.x) {
			size.x *= 2;
		}
		while (size.y < i.y) {
			size.y *= 2;
		}
		return size;
	});
}

decltype(TexturePacker::Size::x)
TexturePacker::area(const Size & size)
{
	return size.x * size.y;
}