-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSameMaterialPlacementStrategy.php
81 lines (69 loc) · 2.04 KB
/
SameMaterialPlacementStrategy.php
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
78
79
80
81
<?php
namespace Aternos\Plop\Placement;
use Aternos\Plop\Structure\Elements\Element;
use Aternos\Plop\Structure\Elements\ElementCollection;
class SameMaterialPlacementStrategy extends PlacementStrategy
{
protected ElementCollection $elements;
/**
* @param int $perTick
*/
public function __construct(public int $perTick = 1)
{
}
/**
* @inheritDoc
*/
public function getPlacements(): array
{
$resultElements = [];
$this->elements = ElementCollection::fromArray($this->getElements());
while ($start = $this->findStartingPoint()) {
$found = $this->propagate($start);
array_unshift($found, $start);
foreach ($found as $element) {
$resultElements[] = $element;
$this->elements->remove($element);
}
}
return $this->generatePlacements($resultElements, $this->perTick);
}
/**
* @param Element $start
* @param Element[] $found
* @return Element[]
*/
protected function propagate(Element $start, array $found = []): array
{
foreach ($this->elements->getAdjacentToElement($start, 1) as $element) {
if (in_array($element, $found)) {
continue;
}
if ($element->getName() === $start->getName()) {
$found[] = $element;
$found = $this->propagate($element, $found);
}
}
return $found;
}
/**
* @return Element|null
*/
protected function findStartingPoint(): ?Element
{
$minY = PHP_INT_MAX;
$lowest = [];
foreach ($this->elements->getAll() as $element) {
if ($element->getY() < $minY) {
$minY = $element->getY();
$lowest = [$element];
} elseif ($element->getY() === $minY) {
$lowest[] = $element;
}
}
if (count($lowest) === 0) {
return null;
}
return $lowest[array_rand($lowest)];
}
}