| 1 | import unittest |
| 2 | |
| 3 | from pyglet.image import atlas |
| 4 | |
| 5 | __noninteractive = True |
| 6 | |
| 7 | |
| 8 | class Rect: |
| 9 | def __init__(self, x1, y1, x2, y2): |
| 10 | self.x1 = x1 |
| 11 | self.y1 = y1 |
| 12 | self.x2 = x2 |
| 13 | self.y2 = y2 |
| 14 | |
| 15 | def __repr__(self): |
| 16 | return 'Rect(%d, %d to %d, %d)' % ( |
| 17 | self.x1, self.y1, self.x2, self.y2) |
| 18 | |
| 19 | def intersects(self, other): |
| 20 | return self.x2 > other.x1 and self.x1 < other.x2 and \ |
| 21 | self.y2 > other.y1 and self.y1 < other.y2 |
| 22 | |
| 23 | |
| 24 | class AllocatorEnvironment: |
| 25 | def __init__(self, test_case, width, height): |
| 26 | self.test_case = test_case |
| 27 | self.rectes = [] |
| 28 | self.allocator = atlas.Allocator(width, height) |
| 29 | |
| 30 | def check(self, test_case): |
| 31 | for i, rect in enumerate(self.rectes): |
| 32 | test_case.assertTrue(0 <= rect.x1 < self.allocator.width) |
| 33 | test_case.assertTrue(0 <= rect.x2 <= self.allocator.width) |
| 34 | test_case.assertTrue(0 <= rect.y1 < self.allocator.height) |
| 35 | test_case.assertTrue(0 <= rect.y2 <= self.allocator.height) |
| 36 | for other in self.rectes[i + 1:]: |
| 37 | test_case.assertFalse(rect.intersects(other)) |
| 38 | |
| 39 | def add(self, width, height): |
| 40 | x, y = self.allocator.alloc(width, height) |
| 41 | self.rectes.append(Rect(x, y, x + width, y + height)) |
| 42 | self.check(self.test_case) |
| 43 | |
| 44 | def add_fail(self, width, height): |
| 45 | self.test_case.assertRaises(atlas.AllocatorException, |
| 46 | self.allocator.alloc, width, height) |
| 47 | |
| 48 | |
| 49 | class TestPack(unittest.TestCase): |
| 50 | def test_over_x(self): |
| 51 | env = AllocatorEnvironment(self, 3, 3) |
| 52 | env.add_fail(3, 4) |
| 53 | |
| 54 | def test_over_y(self): |
| 55 | env = AllocatorEnvironment(self, 3, 3) |
| 56 | env.add_fail(4, 3) |
| 57 | |
| 58 | def test_1(self): |
| 59 | env = AllocatorEnvironment(self, 4, 4) |
| 60 | for i in range(16): |
| 61 | env.add(1, 1) |
| 62 | env.add_fail(1, 1) |
| 63 | |
| 64 | def test_2(self): |
| 65 | env = AllocatorEnvironment(self, 3, 3) |
| 66 | env.add(2, 2) |
| 67 | for i in range(4): |
| 68 | env.add(1, 1) |
| 69 | |
| 70 | def test_3(self): |
| 71 | env = AllocatorEnvironment(self, 3, 3) |
| 72 | env.add(3, 3) |
| 73 | env.add_fail(1, 1) |
| 74 | |
| 75 | def test_4(self): |
| 76 | env = AllocatorEnvironment(self, 5, 4) |
| 77 | for i in range(4): |
| 78 | env.add(2, 2) |
| 79 | env.add_fail(2, 1) |
| 80 | env.add(1, 2) |
| 81 | env.add(1, 2) |
| 82 | env.add_fail(1, 1) |
| 83 | |
| 84 | def test_5(self): |
| 85 | env = AllocatorEnvironment(self, 4, 4) |
| 86 | env.add(3, 2) |
| 87 | env.add(4, 2) |
| 88 | env.add(1, 2) |
| 89 | env.add_fail(1, 1) |
| 90 | |
| 91 | |
| 92 | if __name__ == '__main__': |
| 93 | unittest.main() |