Passed
Pull Request — master (#452)
by
unknown
05:07 queued 03:31
created

VolumePacker   A

Complexity

Total Complexity 30

Size/Duplication

Total Lines 222
Duplicated Lines 0 %

Test Coverage

Coverage 87.5%

Importance

Changes 58
Bugs 2 Features 0
Metric Value
eloc 87
c 58
b 2
f 0
dl 0
loc 222
ccs 77
cts 88
cp 0.875
rs 10
wmc 30

11 Methods

Rating   Name   Duplication   Size   Complexity  
A setSinglePassMode() 0 7 2
B packRotation() 0 40 6
A beStrictAboutItemOrdering() 0 4 1
A getPackedItemList() 0 10 3
A __construct() 0 11 1
A getCurrentPackedDepth() 0 8 2
A pack() 0 30 6
A setLogger() 0 4 1
A correctLayerRotation() 0 17 4
A packAcrossWidthOnly() 0 3 1
A stabiliseLayers() 0 9 3
1
<?php
2
/**
3
 * Box packing (3D bin packing, knapsack problem).
4
 *
5
 * @author Doug Wright
6
 */
7
declare(strict_types=1);
8
9
namespace DVDoug\BoxPacker;
10
11
use Psr\Log\LoggerAwareInterface;
12
use Psr\Log\LoggerInterface;
13
use Psr\Log\NullLogger;
14
15
use function array_map;
16
use function count;
17
use function max;
18
use function reset;
19
use function usort;
20
21
/**
22
 * Actual packer.
23
 */
24
class VolumePacker implements LoggerAwareInterface
25
{
26
    protected LoggerInterface $logger;
27
28
    protected ItemList $items;
29
30
    protected bool $singlePassMode = false;
31
32
    protected bool $packAcrossWidthOnly = false;
33
34
    private readonly LayerPacker $layerPacker;
35
36
    protected bool $beStrictAboutItemOrdering = false;
37
38
    private readonly bool $hasConstrainedItems;
39
40
    private readonly bool $hasNoRotationItems;
41
42 84
    public function __construct(protected Box $box, ItemList $items)
43
    {
44 84
        $this->items = clone $items;
45
46 84
        $this->logger = new NullLogger();
47
48 84
        $this->hasConstrainedItems = $items->hasConstrainedItems();
0 ignored issues
show
Bug introduced by
The property hasConstrainedItems is declared read-only in DVDoug\BoxPacker\VolumePacker.
Loading history...
49 84
        $this->hasNoRotationItems = $items->hasNoRotationItems();
0 ignored issues
show
Bug introduced by
The property hasNoRotationItems is declared read-only in DVDoug\BoxPacker\VolumePacker.
Loading history...
50
51 84
        $this->layerPacker = new LayerPacker($this->box);
0 ignored issues
show
Bug introduced by
The property layerPacker is declared read-only in DVDoug\BoxPacker\VolumePacker.
Loading history...
52 84
        $this->layerPacker->setLogger($this->logger);
53
    }
54
55
    /**
56
     * Sets a logger.
57
     */
58 24
    public function setLogger(LoggerInterface $logger): void
59
    {
60 24
        $this->logger = $logger;
61 24
        $this->layerPacker->setLogger($logger);
62
    }
63
64
    public function packAcrossWidthOnly(): void
65
    {
66
        $this->packAcrossWidthOnly = true;
67
    }
68
69 24
    public function beStrictAboutItemOrdering(bool $beStrict): void
70
    {
71 24
        $this->beStrictAboutItemOrdering = $beStrict;
72 24
        $this->layerPacker->beStrictAboutItemOrdering($beStrict);
73
    }
74
75
    /**
76
     * @internal
77
     */
78 4
    public function setSinglePassMode(bool $singlePassMode): void
79
    {
80 4
        $this->singlePassMode = $singlePassMode;
81 4
        if ($singlePassMode) {
82 4
            $this->packAcrossWidthOnly = true;
83
        }
84 4
        $this->layerPacker->setSinglePassMode($singlePassMode);
85
    }
86
87
    /**
88
     * Pack as many items as possible into specific given box.
89
     *
90
     * @return PackedBox packed box
91
     */
92 84
    public function pack(): PackedBox
93
    {
94 84
        $this->logger->debug("[EVALUATING BOX] {$this->box->getReference()}", ['box' => $this->box]);
95
96 84
        $rotationsToTest = [false];
97 84
        if (!$this->packAcrossWidthOnly && !$this->hasNoRotationItems) {
98 84
            $rotationsToTest[] = true;
99
        }
100
101 84
        $boxPermutations = [];
102 84
        foreach ($rotationsToTest as $rotation) {
103 84
            if ($rotation) {
104 16
                $boxWidth = $this->box->getInnerLength();
105 16
                $boxLength = $this->box->getInnerWidth();
106
            } else {
107 84
                $boxWidth = $this->box->getInnerWidth();
108 84
                $boxLength = $this->box->getInnerLength();
109
            }
110
111 84
            $boxPermutation = $this->packRotation($boxWidth, $boxLength);
112 84
            if ($boxPermutation->getItems()->count() === $this->items->count()) {
113 72
                return $boxPermutation;
114
            }
115
116 18
            $boxPermutations[] = $boxPermutation;
117
        }
118
119 18
        usort($boxPermutations, static fn (PackedBox $a, PackedBox $b) => $b->getVolumeUtilisation() <=> $a->getVolumeUtilisation());
120
121 18
        return reset($boxPermutations);
122
    }
123
124
    /**
125
     * Pack as many items as possible into specific given box.
126
     *
127
     * @return PackedBox packed box
128
     */
129 84
    private function packRotation(int $boxWidth, int $boxLength): PackedBox
130
    {
131 84
        $this->logger->debug("[EVALUATING ROTATION] {$this->box->getReference()}", ['width' => $boxWidth, 'length' => $boxLength]);
132
133 84
        $layers = [];
134 84
        $items = clone $this->items;
135
136 84
        while ($items->count() > 0) {
137 84
            $layerStartDepth = self::getCurrentPackedDepth($layers);
138 84
            $packedItemList = $this->getPackedItemList($layers);
139
140
            // do a preliminary layer pack to get the depth used
141 84
            $preliminaryItems = clone $items;
142 84
            $preliminaryLayer = $this->layerPacker->packLayer($preliminaryItems, clone $packedItemList, 0, 0, $layerStartDepth, $boxWidth, $boxLength, $this->box->getInnerDepth() - $layerStartDepth, 0, true);
143 84
            if (count($preliminaryLayer->getItems()) === 0) {
144 14
                break;
145
            }
146
147 82
            if ($preliminaryLayer->getDepth() === $preliminaryLayer->getItems()[0]->getDepth()) { // preliminary === final
148 80
                $layers[] = $preliminaryLayer;
149 80
                $items = $preliminaryItems;
150
            } else { // redo with now-known-depth so that we can stack to that height from the first item
151 4
                $layers[] = $this->layerPacker->packLayer($items, $packedItemList, 0, 0, $layerStartDepth, $boxWidth, $boxLength, $this->box->getInnerDepth() - $layerStartDepth, $preliminaryLayer->getDepth(), true);
152
            }
153
        }
154
155 84
        if (!$this->singlePassMode && $layers) {
156 82
            $layers = $this->stabiliseLayers($layers);
157
158
            // having packed layers, there may be tall, narrow gaps at the ends that can be utilised
159 82
            $maxLayerWidth = max(array_map(static fn (PackedLayer $layer) => $layer->getEndX(), $layers));
160 82
            $layers[] = $this->layerPacker->packLayer($items, $this->getPackedItemList($layers), $maxLayerWidth, 0, 0, $boxWidth, $boxLength, $this->box->getInnerDepth(), $this->box->getInnerDepth(), false);
161
162 82
            $maxLayerLength = max(array_map(static fn (PackedLayer $layer) => $layer->getEndY(), $layers));
163 82
            $layers[] = $this->layerPacker->packLayer($items, $this->getPackedItemList($layers), 0, $maxLayerLength, 0, $boxWidth, $boxLength, $this->box->getInnerDepth(), $this->box->getInnerDepth(), false);
164
        }
165
166 84
        $layers = $this->correctLayerRotation($layers, $boxWidth);
167
168 84
        return new PackedBox($this->box, $this->getPackedItemList($layers));
169
    }
170
171
    /**
172
     * During packing, it is quite possible that layers have been created that aren't physically stable
173
     * i.e. they overhang the ones below.
174
     *
175
     * This function reorders them so that the ones with the greatest surface area are placed at the bottom
176
     *
177
     * @param  PackedLayer[] $oldLayers
178
     * @return PackedLayer[]
179
     */
180 82
    private function stabiliseLayers(array $oldLayers): array
181
    {
182 82
        if ($this->hasConstrainedItems || $this->beStrictAboutItemOrdering) { // constraints include position, so cannot change
183
            return $oldLayers;
184
        }
185
186 82
        $stabiliser = new LayerStabiliser();
0 ignored issues
show
Bug introduced by
The type DVDoug\BoxPacker\LayerStabiliser was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
187
188 82
        return $stabiliser->stabilise($oldLayers);
189
    }
190
191
    /**
192
     * Swap back width/length of the packed items to match orientation of the box if needed.
193
     *
194
     * @param PackedLayer[] $oldLayers
195
     *
196
     * @return PackedLayer[]
197
     */
198 84
    private function correctLayerRotation(array $oldLayers, int $boxWidth): array
199
    {
200 84
        if ($this->box->getInnerWidth() === $boxWidth) {
201 84
            return $oldLayers;
202
        }
203
204
        $newLayers = [];
205
        foreach ($oldLayers as $originalLayer) {
206
            $newLayer = new PackedLayer();
207
            foreach ($originalLayer->getItems() as $item) {
208
                $packedItem = new PackedItem($item->getItem(), $item->getY(), $item->getX(), $item->getZ(), $item->getLength(), $item->getWidth(), $item->getDepth());
209
                $newLayer->insert($packedItem);
210
            }
211
            $newLayers[] = $newLayer;
212
        }
213
214
        return $newLayers;
215
    }
216
217
    /**
218
     * Generate a single list of items packed.
219
     * @param PackedLayer[] $layers
220
     */
221 84
    private function getPackedItemList(array $layers): PackedItemList
0 ignored issues
show
Bug introduced by
The type DVDoug\BoxPacker\PackedItemList was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
222
    {
223 84
        $packedItemList = new PackedItemList();
224 84
        foreach ($layers as $layer) {
225 82
            foreach ($layer->getItems() as $packedItem) {
226 82
                $packedItemList->insert($packedItem);
227
            }
228
        }
229
230 84
        return $packedItemList;
231
    }
232
233
    /**
234
     * Return the current packed depth.
235
     *
236
     * @param PackedLayer[] $layers
237
     */
238 84
    private static function getCurrentPackedDepth(array $layers): int
239
    {
240 84
        $depth = 0;
241 84
        foreach ($layers as $layer) {
242 54
            $depth += $layer->getDepth();
243
        }
244
245 84
        return $depth;
246
    }
247
}
248