PocketMine-MP 5.15.1 git-5ef247620a7c6301a849b54e5ef1009217729fc8
BlockTransaction.php
1<?php
2
3/*
4 *
5 * ____ _ _ __ __ _ __ __ ____
6 * | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
7 * | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
8 * | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
9 * |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
10 *
11 * This program is free software: you can redistribute it and/or modify
12 * it under the terms of the GNU Lesser General Public License as published by
13 * the Free Software Foundation, either version 3 of the License, or
14 * (at your option) any later version.
15 *
16 * @author PocketMine Team
17 * @link http://www.pocketmine.net/
18 *
19 *
20 */
21
22declare(strict_types=1);
23
24namespace pocketmine\world;
25
29
32 private array $blocks = [];
33
38 private array $validators = [];
39
40 public function __construct(private ChunkManager $world){
41 $this->addValidator(static function(ChunkManager $world, int $x, int $y, int $z) : bool{
42 return $world->isInWorld($x, $y, $z);
43 });
44 }
45
51 public function addBlock(Vector3 $pos, Block $state) : self{
52 return $this->addBlockAt($pos->getFloorX(), $pos->getFloorY(), $pos->getFloorZ(), $state);
53 }
54
60 public function addBlockAt(int $x, int $y, int $z, Block $state) : self{
61 $this->blocks[$x][$y][$z] = $state;
62 return $this;
63 }
64
69 public function fetchBlock(Vector3 $pos) : Block{
70 return $this->fetchBlockAt($pos->getFloorX(), $pos->getFloorY(), $pos->getFloorZ());
71 }
72
76 public function fetchBlockAt(int $x, int $y, int $z) : Block{
77 return $this->blocks[$x][$y][$z] ?? $this->world->getBlockAt($x, $y, $z);
78 }
79
86 public function apply() : bool{
87 foreach($this->getBlocks() as [$x, $y, $z, $_]){
88 foreach($this->validators as $validator){
89 if(!$validator($this->world, $x, $y, $z)){
90 return false;
91 }
92 }
93 }
94 $changedBlocks = 0;
95 foreach($this->getBlocks() as [$x, $y, $z, $block]){
96 $oldBlock = $this->world->getBlockAt($x, $y, $z);
97 if(!$oldBlock->isSameState($block)){
98 $this->world->setBlockAt($x, $y, $z, $block);
99 $changedBlocks++;
100 }
101 }
102 return $changedBlocks !== 0;
103 }
104
109 public function getBlocks() : \Generator{
110 foreach($this->blocks as $x => $yLine){
111 foreach($yLine as $y => $zLine){
112 foreach($zLine as $z => $block){
113 yield [$x, $y, $z, $block];
114 }
115 }
116 }
117 }
118
126 public function addValidator(\Closure $validator) : void{
127 Utils::validateCallableSignature([$this, 'dummyValidator'], $validator);
128 $this->validators[] = $validator;
129 }
130
137 public function dummyValidator(ChunkManager $world, int $x, int $y, int $z) : bool{
138 return true;
139 }
140}
addBlock(Vector3 $pos, Block $state)
addBlockAt(int $x, int $y, int $z, Block $state)
dummyValidator(ChunkManager $world, int $x, int $y, int $z)
fetchBlockAt(int $x, int $y, int $z)
isInWorld(int $x, int $y, int $z)