Completed
Push — master ( cd15bf...431713 )
by Doug
03:17
created

VolumePacker::findPossibleOrientations()   B

Complexity

Conditions 4
Paths 3

Size

Total Lines 23
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 23
ccs 15
cts 15
cp 1
rs 8.7972
cc 4
eloc 13
nc 3
nop 2
crap 4
1
<?php
2
/**
3
 * Box packing (3D bin packing, knapsack problem)
4
 * @package BoxPacker
5
 * @author Doug Wright
6
 */
7
namespace DVDoug\BoxPacker;
8
9
use Psr\Log\LoggerAwareInterface;
10
use Psr\Log\LoggerAwareTrait;
11
use Psr\Log\NullLogger;
12
13
/**
14
 * Actual packer
15
 * @author Doug Wright
16
 * @package BoxPacker
17
 */
18
class VolumePacker implements LoggerAwareInterface
19
{
20
    use LoggerAwareTrait;
21
22
    /**
23
     * Box to pack items into
24
     * @var Box
25
     */
26
    protected $box;
27
28
    /**
29
     * List of items to be packed
30
     * @var ItemList
31
     */
32
    protected $items;
33
34
    /**
35
     * Constructor
36
     */
37
    public function __construct(Box $box, ItemList $items)
38 26
    {
39
        $this->box = $box;
40 26
        $this->items = $items;
41 26
        $this->logger = new NullLogger();
42 26
    }
43 26
44
    /**
45
     * Pack as many items as possible into specific given box
46
     * @return PackedBox packed box
47
     */
48
    public function pack()
49 26
    {
50
        $this->logger->debug("[EVALUATING BOX] {$this->box->getReference()}");
51 26
52
        $packedItems = new ItemList;
53 26
        $depthLeft = $this->box->getInnerDepth();
54 26
        $remainingWeight = $this->box->getMaxWeight() - $this->box->getEmptyWeight();
55 26
        $widthLeft = $this->box->getInnerWidth();
56 26
        $lengthLeft = $this->box->getInnerLength();
57 26
58
        $layerWidth = $layerLength = $layerDepth = 0;
59 26
60
        $prevItem = null;
61 26
62
        while (!$this->items->isEmpty()) {
63 26
64
            $itemToPack = $this->items->extract();
65 26
66
            //skip items that are simply too heavy
67
            if ($itemToPack->getWeight() > $remainingWeight) {
68 26
                continue;
69 4
            }
70
71
            $this->logger->debug("evaluating item {$itemToPack->getDescription()}");
72 26
            $this->logger->debug("remaining width: {$widthLeft}, length: {$lengthLeft}, depth: {$depthLeft}");
73 26
            $this->logger->debug("layerWidth: {$layerWidth}, layerLength: {$layerLength}, layerDepth: {$layerDepth}");
74 26
75
            $nextItem = !$this->items->isEmpty() ? $this->items->top() : null;
76 26
            $orientatedItem = $this->findBestOrientation($itemToPack, $prevItem, $nextItem, $widthLeft, $lengthLeft, $depthLeft);
77 26
78
            if ($orientatedItem) {
79 26
80
                $packedItems->insert($orientatedItem->getItem());
81 26
                $remainingWeight -= $itemToPack->getWeight();
82 26
83
                $lengthLeft -= $orientatedItem->getLength();
84 26
                $layerLength += $orientatedItem->getLength();
85 26
                $layerWidth = max($orientatedItem->getWidth(), $layerWidth);
86 26
87
                $layerDepth = max($layerDepth, $orientatedItem->getDepth()); //greater than 0, items will always be less deep
88 26
89
                //allow items to be stacked in place within the same footprint up to current layerdepth
90
                $maxStackDepth = $layerDepth - $orientatedItem->getDepth();
91 26
                while (!$this->items->isEmpty() && $this->canStackItemInLayer($itemToPack, $this->items->top(), $maxStackDepth, $remainingWeight)) {
92 26
                    $remainingWeight -= $this->items->top()->getWeight();
93 1
                    $maxStackDepth -= $this->items->top()->getDepth(); // XXX no attempt at best fit
94 1
                    $packedItems->insert($this->items->extract());
95 1
                }
96 1
97
                $prevItem = $orientatedItem;
98 26
            } else {
99 26
100
                $prevItem = null;
101 23
102
                if ($widthLeft >= min($itemToPack->getWidth(), $itemToPack->getLength()) && $this->isLayerStarted($layerWidth, $layerLength, $layerDepth)) {
103 23
                    $this->logger->debug("No more fit in lengthwise, resetting for new row");
104 22
                    $lengthLeft += $layerLength;
105 22
                    $widthLeft -= $layerWidth;
106 22
                    $layerWidth = $layerLength = 0;
107 22
                    $this->items->insert($itemToPack);
108 22
                    continue;
109 22
                } elseif ($lengthLeft < min($itemToPack->getWidth(), $itemToPack->getLength()) || $layerDepth == 0) {
110 18
                    $this->logger->debug("doesn't fit on layer even when empty");
111 7
                    continue;
112 7
                }
113
114
                $widthLeft = $layerWidth ? min(floor($layerWidth * 1.1), $this->box->getInnerWidth()) : $this->box->getInnerWidth();
115 17
                $lengthLeft = $layerLength ? min(floor($layerLength * 1.1), $this->box->getInnerLength()) : $this->box->getInnerLength();
116 17
                $depthLeft -= $layerDepth;
117 17
118
                $layerWidth = $layerLength = $layerDepth = 0;
119 17
                $this->logger->debug("doesn't fit, so starting next vertical layer");
120 17
                $this->items->insert($itemToPack);
121 17
            }
122
        }
123 26
        $this->logger->debug("done with this box");
124 26
        return new PackedBox($this->box, $packedItems, $widthLeft, $lengthLeft, $depthLeft, $remainingWeight);
125 26
    }
126
127
    /**
128
     * Get the best orientation for an item
129
     * @param Item $item
130
     * @param OrientatedItem|null $prevItem
131
     * @param Item|null $nextItem
132
     * @param int $widthLeft
133
     * @param int $lengthLeft
134
     * @param int $depthLeft
135
     * @return OrientatedItem|false
136
     */
137
    protected function findBestOrientation(Item $item, OrientatedItem $prevItem = null, Item $nextItem = null, $widthLeft, $lengthLeft, $depthLeft) {
138
139
        $orientations = $this->findPossibleOrientations($item, $prevItem);
140
141
        $orientationFits = [];
142
143
        /** @var OrientatedItem $orientation */
144
        foreach ($orientations as $o => $orientation) {
145
            $orientationFit = min($widthLeft   - $orientation->getWidth(),
146
                                  $lengthLeft  - $orientation->getLength());
147
148
            if ($orientationFit >= 0 && $depthLeft - $orientation->getDepth() >= 0) {
149
                $orientationFits[$o] = $orientationFit;
150
            }
151
        }
152
153
        if ($orientationFits) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $orientationFits of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
154
155
            //special casing based on next item
156
            if (isset($orientationFits[0]) && $nextItem == $item && $lengthLeft >= 2 * $item->getLength()) {
157
                $this->logger->debug("not rotating based on next item");
158
                return $orientations[0];
159
            }
160 26
161
            asort($orientationFits);
162 26
            reset($orientationFits);
163
            $bestFit = key($orientationFits);
164
            $this->logger->debug("Using orientation #{$bestFit}");
165 26
            return $orientations[$bestFit];
166 9
        } else {
167 9
            return false;
168
        }
169
    }
170 26
171 26
    /**
172
     * Get the best orientation for an item
173
     * @param Item $item
174 26
     * @param OrientatedItem|null $prevItem
175 10
     * @return OrientatedItem[]
176 10
     */
177 10
    protected function findPossibleOrientations(Item $item, OrientatedItem $prevItem = null) {
178 10
179 10
        $orientations = [];
180
181
        //Special case items that are the same as what we just packed - keep orientation
182 26
        if ($prevItem && $prevItem->getItem() == $item) {
183
            $orientations[] = new OrientatedItem($item, $prevItem->getWidth(), $prevItem->getLength(), $prevItem->getDepth());
184
        } else {
185 26
186 26
            //simple 2D rotation
187 26
            $orientations[] = new OrientatedItem($item, $item->getWidth(), $item->getLength(), $item->getDepth());
188
            $orientations[] = new OrientatedItem($item, $item->getLength(), $item->getWidth(), $item->getDepth());
189 26
190 26
            //add 3D rotation if we're allowed
191 26
            if (!$item->getKeepFlat()) {
192 26
                $orientations[] = new OrientatedItem($item, $item->getWidth(), $item->getDepth(), $item->getLength());
193
                $orientations[] = new OrientatedItem($item, $item->getLength(), $item->getDepth(), $item->getWidth());
194 26
                $orientations[] = new OrientatedItem($item, $item->getDepth(), $item->getWidth(), $item->getLength());
195
                $orientations[] = new OrientatedItem($item, $item->getDepth(), $item->getLength(), $item->getWidth());
196
            }
197 26
        }
198 5
        return $orientations;
199 5
    }
200
201
    /**
202 26
     * Figure out if we can stack the next item vertically on top of this rather than side by side
203 26
     * Used when we've packed a tall item, and have just put a shorter one next to it
204 26
     * @param Item $item
205 26
     * @param Item $nextItem
206 26
     * @param $maxStackDepth
207
     * @param $remainingWeight
208 23
     * @return bool
209
     */
210
    protected function canStackItemInLayer(Item $item, Item $nextItem, $maxStackDepth, $remainingWeight)
211
    {
212
        return $nextItem->getDepth() <= $maxStackDepth &&
213
               $nextItem->getWeight() <= $remainingWeight &&
214
               $nextItem->getWidth() <= $item->getWidth() &&
215
               $nextItem->getLength() <= $item->getLength();
216
    }
217
218
    /**
219
     * @param $layerWidth
220
     * @param $layerLength
221 24
     * @param $layerDepth
222
     * @return bool
223 24
     */
224 24
    protected function isLayerStarted($layerWidth, $layerLength, $layerDepth) {
225 24
        return $layerWidth > 0 && $layerLength > 0 && $layerDepth > 0;
226 24
    }
227
}
228