def test_pack_sequential_width(self): # AAAAAAAA # BBBBBBB # CCCCCC # DDDDD # EEEE # FFF # GG # H boxes = [Box(i, 1) for i in range(1, 9)] # AAAAAAAA # BBBBBBBH # CCCCCCGG # DDDDDFFF # EEEE packing = [ (0, 0, Box(8, 1)), (0, 1, Box(7, 1)), (7, 1, Box(1, 1)), (0, 2, Box(6, 1)), (6, 2, Box(2, 1)), (0, 3, Box(5, 1)), (5, 3, Box(3, 1)), (0, 4, Box(4, 1)), ] (_, _, actual) = pack_boxes(boxes, 8) self.assert_(check_no_overlap(actual)) self.assertEqual(actual, packing)
def test_random_no_overlap(self): # Not having overlap is an important invariant we need to maintain. # This just checks it. for _ in xrange(3): boxes = [Box(random.randrange(1, 40), random.randrange(1, 40)) for _ in xrange(100)] (_, _, actual) = pack_boxes(boxes) self.assert_(check_no_overlap(actual))
def test_pack_sequence_height_width(self): # A # B # B # C # C # C # DD # EE # EE # FF # FF # FF # GGG # HHH # HHH # III # III # III boxes = [Box(i, j) for i in range(1, 4) for j in range(1, 4)] # III # III # III # FFC # FFC # FFC # HHH # HHH # EEB # EEB # GGG # DDA packing = [ (0, 0, Box(3, 3)), (0, 3, Box(2, 3)), (2, 3, Box(1, 3)), (0, 6, Box(3, 2)), (0, 8, Box(2, 2)), (2, 8, Box(1, 2)), (0, 10, Box(3, 1)), (0, 11, Box(2, 1)), (2, 11, Box(1, 1)), ] (_, _, actual) = pack_boxes(boxes, 3) self.assert_(check_no_overlap(actual)) self.assertEqual(actual, packing)
def test_pack_easy(self): # AA # B # C boxes = [ Box(2, 1), Box(1, 1), Box(1, 1), ] # AA # BC packing = [ (0, 0, Box(2, 1)), (0, 1, Box(1, 1)), (1, 1, Box(1, 1)), ] (_, _, actual) = pack_boxes(boxes, 2) self.assert_(check_no_overlap(actual)) self.assertEqual(actual, packing)
def minify(self): import Image # If this fails, you need the Python Imaging Library. boxes = [ImageBox(Image.open(path), path) for path in self.full_path_files] # Pick a max_width so that the sprite is squarish and a multiple of 16, # and so no image is too wide to fit. total_area = sum(box.width * box.height for box in boxes) width = max(max(box.width for box in boxes), (int(math.sqrt(total_area)) // 16 + 1) * 16) (_, height, packing) = pack_boxes(boxes, width) sprite = Image.new( mode='RGBA', size=(width, height), color=(0,0,0,0)) for (left, top, box) in packing: # This is a bit of magic to make the transparencies work. To # preserve transparency, we pass the image so it can take its # alpha channel mask or something. However, if the image has no # alpha channels, then it fails, we we have to check if the # image is RGBA here. img = box.image sprite.paste(img, (left, top)) sprite.save(self.bundle_path, "PNG") self._optimize_output() self.generate_css(packing)
def test_pack_single(self): boxes = [Box(1, 1)] packing = [(0, 0, Box(1, 1))] (_, _, actual) = pack_boxes(boxes, 1) self.assert_(check_no_overlap(actual)) self.assertEqual(actual, packing)