From 6dd8aae8c07b0e2ecad0c0b387342cca64776606 Mon Sep 17 00:00:00 2001 From: XenialDan Date: Fri, 25 Dec 2020 01:52:03 +0100 Subject: [PATCH 01/67] Added BlockPalette, BlockQuery, WeightedRandom Improves BlockStatesParser::fromString --- src/xenialdan/MagicWE2/API.php | 21 +-- .../BlockQueryAlreadyParsedException.php | 10 ++ .../MagicWE2/helper/BlockPalette.php | 80 ++++++++- src/xenialdan/MagicWE2/helper/BlockQuery.php | 65 +++++++ .../MagicWE2/helper/BlockStatesParser.php | 109 +++++------- .../MagicWE2/helper/WeightedRandom.php | 163 ++++++++++++++++++ 6 files changed, 366 insertions(+), 82 deletions(-) create mode 100644 src/xenialdan/MagicWE2/exception/BlockQueryAlreadyParsedException.php create mode 100644 src/xenialdan/MagicWE2/helper/BlockQuery.php create mode 100644 src/xenialdan/MagicWE2/helper/WeightedRandom.php diff --git a/src/xenialdan/MagicWE2/API.php b/src/xenialdan/MagicWE2/API.php index 0c325e18..0a067126 100644 --- a/src/xenialdan/MagicWE2/API.php +++ b/src/xenialdan/MagicWE2/API.php @@ -8,7 +8,6 @@ use InvalidArgumentException; use pocketmine\block\Block; use pocketmine\block\BlockFactory; -use pocketmine\block\UnknownBlock; use pocketmine\math\AxisAlignedBB; use pocketmine\math\Vector3; use pocketmine\nbt\tag\CompoundTag; @@ -24,9 +23,8 @@ use xenialdan\MagicWE2\clipboard\Clipboard; use xenialdan\MagicWE2\clipboard\SingleClipboard; use xenialdan\MagicWE2\exception\CalculationException; -use xenialdan\MagicWE2\exception\InvalidBlockStateException; use xenialdan\MagicWE2\exception\LimitExceededException; -use xenialdan\MagicWE2\helper\BlockStatesParser; +use xenialdan\MagicWE2\helper\BlockPalette; use xenialdan\MagicWE2\selection\Selection; use xenialdan\MagicWE2\selection\shape\Shape; use xenialdan\MagicWE2\session\Session; @@ -417,22 +415,13 @@ public static function hasFlag(int $flags, int $check): bool * @param string $fullstring * @param array $messages * @param bool $error - * @return Block[] - * @throws RuntimeException - * @throws InvalidArgumentException - * @throws InvalidBlockStateException + * @return BlockPalette */ - public static function blockParser(string $fullstring, array &$messages, bool &$error): array + public static function blockParser(string $fullstring, array &$messages, bool &$error): BlockPalette { BlockFactory::getInstance(); - $blocks = BlockStatesParser::getInstance()::fromString($fullstring, true); - foreach ($blocks as $block) { - if ($block instanceof UnknownBlock) { - $messages[] = TF::GOLD . $block . " is an unknown block"; - } - } - - return $blocks; + //$blocks = BlockStatesParser::getInstance()::fromString($fullstring, true); + return BlockPalette::fromString($fullstring); } /** diff --git a/src/xenialdan/MagicWE2/exception/BlockQueryAlreadyParsedException.php b/src/xenialdan/MagicWE2/exception/BlockQueryAlreadyParsedException.php new file mode 100644 index 00000000..54d4a5f0 --- /dev/null +++ b/src/xenialdan/MagicWE2/exception/BlockQueryAlreadyParsedException.php @@ -0,0 +1,10 @@ +name = $name; + $this->randomBlockQueries = new WeightedRandom(); + } + + /** + * @param string $blocksQuery + * @return static + * @throws InvalidArgumentException + * @throws BlockQueryAlreadyParsedException + */ + public static function fromString(string $blocksQuery): self + { + $palette = self::EMPTY(); + + $pregSplit = preg_split('/,(?![^\[]*])/', trim($blocksQuery), -1, PREG_SPLIT_NO_EMPTY); + if (!is_array($pregSplit)) throw new InvalidArgumentException("Regex matching failed"); + foreach ($pregSplit as $query) { + // How to code ugly 101: https://3v4l.org/2KfNW + preg_match_all('/([\w:]+)(?:\[([\w=,]*)])?/m', $query, $matches, PREG_SET_ORDER); + [$blockMatch, $extraMatch] = [$matches[0] ?? [], $matches[1] ?? []]; + $blockMatch += [null, null, null]; + $extraMatch += [null, null]; + [[$fullBlockQuery, $blockId, $blockStatesQuery], [$fullExtraQuery, $weight]] = [$blockMatch, $extraMatch]; + $palette->addBlockQuery((new BlockQuery($query, $fullBlockQuery, $blockId, $blockStatesQuery, $fullExtraQuery, $weight))->parse()); + } + $palette->randomBlockQueries->setup(); + + return $palette; + } + + public function addBlockQuery(BlockQuery $query) + { + $this->randomBlockQueries->add($query, $query->weight); + } + + //TODO addBlock + + /** + * @return Generator|Block + * @throws InvalidArgumentException + */ + public function blocks(int $amount = 1): Generator + { + if ($amount < 1) throw new InvalidArgumentException('$amount must be positive'); + $this->randomBlockQueries->setup();//TODO check if performance impact is too big (i.e when calling this method multiple times) + /** @var BlockFactory $blockFactory */ + $blockFactory = BlockFactory::getInstance(); + /** @var BlockQuery $blockQuery */ + foreach ($this->randomBlockQueries->generate($amount) as $blockQuery) { + yield $blockFactory->fromFullBlock($blockQuery->blockFullId);//TODO yield blockFullId and do not yield Block? + } + } + /** * @param Block[] $blocks * @return string @@ -31,9 +100,16 @@ public static function encode(array $blocks): string public static function decode(string $blocks): array { $e = []; + /** @var BlockFactory $blockFactory */ + $blockFactory = BlockFactory::getInstance(); foreach (json_decode($blocks, true, 512, JSON_THROW_ON_ERROR) as $block) - $e[] = BlockFactory::getInstance()->fromFullBlock($block); + $e[] = $blockFactory->fromFullBlock($block); return $e; } + public static function EMPTY(): self + { + return new self; + } + } \ No newline at end of file diff --git a/src/xenialdan/MagicWE2/helper/BlockQuery.php b/src/xenialdan/MagicWE2/helper/BlockQuery.php new file mode 100644 index 00000000..9da0de88 --- /dev/null +++ b/src/xenialdan/MagicWE2/helper/BlockQuery.php @@ -0,0 +1,65 @@ +query = $query; + $this->fullBlockQuery = $fullBlockQuery; + $this->blockId = $blockId; + $this->blockStatesQuery = $blockStatesQuery; + $this->fullExtraQuery = $fullExtraQuery; + $this->weight = (float)($weight ?? "100") / 100; + } + + public function parse(bool $update = true): self + { + //calling methods should check with hasBlock() before parse() + if (!$update && $this->hasBlock()) throw new BlockQueryAlreadyParsedException("FullBlockID is already parsed"); + /** @var BlockStatesParser $blockStatesParser */ + $blockStatesParser = BlockStatesParser::getInstance(); + $blockStatesParser::fromString($this);//this should already set the blockFullId because it is a reference + var_dump($this->hasBlock() ? "Has block, " . $this->blockFullId : "Does not have block"); + //TODO throw BlockQueryParsingFailedException if blockFullId was not set? `if(!$this->hasBlock())` + return $this; + } + + public function hasBlockStates(): bool + { + return $this->blockStatesQuery !== null; + } + + public function hasExtraQuery(): bool + { + return $this->blockStatesQuery !== null; + } + + public function hasBlock(): bool + { + return $this->blockFullId !== null; + } + +} \ No newline at end of file diff --git a/src/xenialdan/MagicWE2/helper/BlockStatesParser.php b/src/xenialdan/MagicWE2/helper/BlockStatesParser.php index a21737bc..59072f1c 100644 --- a/src/xenialdan/MagicWE2/helper/BlockStatesParser.php +++ b/src/xenialdan/MagicWE2/helper/BlockStatesParser.php @@ -12,7 +12,6 @@ use JsonException; use pocketmine\block\Block; use pocketmine\block\BlockFactory; -use pocketmine\block\BlockLegacyIds; use pocketmine\block\Door; use pocketmine\block\utils\BlockDataSerializer; use pocketmine\data\bedrock\LegacyBlockIdToStringIdMap; @@ -22,6 +21,7 @@ use pocketmine\nbt\tag\CompoundTag; use pocketmine\nbt\tag\IntTag; use pocketmine\nbt\tag\StringTag; +use pocketmine\nbt\UnexpectedTagTypeException; use pocketmine\network\mcpe\convert\R12ToCurrentBlockMapEntry; use pocketmine\network\mcpe\protocol\serializer\NetworkNbtSerializer; use pocketmine\network\mcpe\protocol\serializer\PacketSerializer; @@ -139,18 +139,20 @@ public static function getDoorRotationFlipMap(): array } /** - * @param string $namespacedSelectedBlockName + * @param BlockQuery $query * @param CompoundTag $states * @return Door * @throws InvalidArgumentException - * @throws InvalidBlockStateException - * @throws RuntimeException * @throws \pocketmine\block\utils\InvalidBlockStateException */ - private static function buildDoor(string $namespacedSelectedBlockName, CompoundTag $states): Door + private static function buildDoor(BlockQuery $query, CompoundTag $states): Door { + $query = clone $query;//TODO test, i don't want the original $query to be modified + $query->fullExtraQuery = null; + $query->fullBlockQuery = $query->blockId; + $query->blockStatesQuery = null; /** @var Door $door */ - $door = self::fromString($namespacedSelectedBlockName)[0]; + $door = self::fromString($query); $door->setOpen($states->getByte("open_bit") === 1); $door->setTop($states->getByte("upper_block_bit") === 1); $door->setHingeRight($states->getByte("door_hinge_bit") === 1); @@ -186,51 +188,33 @@ protected static function getDefaultStates(string $blockIdentifier): CompoundTag } /** - * @param string $query - * @param bool $multiple - * @return Block[] + * Parses a BlockQuery (acquired using BlockPalette::fromString()) to a block and sets the BlockQuery's blockFullId + * @param BlockQuery $query + * @return Block * @throws InvalidArgumentException - * @throws InvalidBlockStateException - * @throws RuntimeException */ - public static function fromString(string $query, bool $multiple = false): array + public static function fromString(BlockQuery $query): Block { - #if (!BlockFactory::isInit()) BlockFactory::init(); - $blocks = []; - if ($multiple) { - $pregSplit = preg_split('/,(?![^\[]*])/', trim($query), -1, PREG_SPLIT_NO_EMPTY); - if (!is_array($pregSplit)) throw new InvalidArgumentException("Regex matching failed"); - foreach ($pregSplit as $b) { - /** @noinspection SlowArrayOperationsInLoopInspection */ - $blocks = array_merge($blocks, self::fromString($b, false)); - } - return $blocks; - } - - $blockData = strtolower(str_replace("minecraft:", "", $query));//TODO try to keep namespace "minecraft:" to support custom blocks - $re = '/([\w:]+)(?:\[([\w=,]*)\])?/m'; - preg_match_all($re, $blockData, $matches, PREG_SET_ORDER, 0); - if (!isset($matches[0][1])) { - throw new InvalidArgumentException("Could not detect block id"); - } + $selectedBlockName = strtolower(str_replace("minecraft:", "", $query->blockId));//TODO try to keep namespace "minecraft:" to support custom blocks - $selectedBlockName = $matches[0][1]; - $namespacedSelectedBlockName = "minecraft:" . $selectedBlockName;//TODO try to keep namespace "minecraft:" to support custom blocks + $namespacedSelectedBlockName = strpos($query->blockId, "minecraft:") === false ? "minecraft:" . $selectedBlockName : $selectedBlockName; /** @var LegacyStringToItemParser $legacyStringToItemParser */ $legacyStringToItemParser = LegacyStringToItemParser::getInstance(); $block = $legacyStringToItemParser->parse($selectedBlockName)->getBlock(); - if (count($matches[0]) < 3) { - return [$block]; + //no states, just block + if (!$query->hasBlockStates()) { + $query->blockFullId = $block->getFullId(); + return $block; } + $defaultStatesNamedTag = self::getDefaultStates($namespacedSelectedBlockName); if (!$defaultStatesNamedTag instanceof CompoundTag) { throw new InvalidArgumentException("Could not find default block states for $namespacedSelectedBlockName"); } - $extraData = $matches[0][2] ?? ""; - $statesExploded = explode(",", $extraData); + $blockStatesQuery = $query->blockStatesQuery ?? ""; + $statesExploded = explode(",", $blockStatesQuery); $finalStatesList = clone $defaultStatesNamedTag; - #var_dump($statesExploded, $finalStatesList->toString()); - #$finalStatesList->setName("states"); + $availableAliases = [];//TODO map in init()! No need to recreate every time! EDIT 2k20: uhm what? @ my past self, why can't you explain properly?! foreach ($finalStatesList as $stateName => $state) { if (array_key_exists($stateName, self::$aliasMap)) { @@ -250,7 +234,11 @@ public static function fromString(string $query, bool $multiple = false): array //change blockstate alias to blockstate name $stateName = $availableAliases[$stateName] ?? $stateName; //TODO maybe validate wrong states here? i.e. stone[type=wrongtype] => Exception, "wrongtype" is invalid value - $tag = $finalStatesList->getTag($stateName); + try { + $tag = $finalStatesList->getTag($stateName); + } catch (UnexpectedTagTypeException $e) { + throw new InvalidBlockStateException("Default states for block '$query->blockId' do not contain Tag with name '$stateName'"); + } if ($tag === null) { throw new InvalidBlockStateException("Invalid state $stateName"); } @@ -269,47 +257,40 @@ public static function fromString(string $query, bool $multiple = false): array throw new InvalidBlockStateException("Unknown tag of type " . get_class($tag) . " detected"); } } - #var_dump($finalStatesList->toString()); - //print final list - //TODO remove. This crashes in AsyncTasks and is just for debug - #Loader::getInstance()->getLogger()->notice(self::printStates(new BlockStatesEntry($namespacedSelectedBlockName,$finalStatesList), false)); //return found block(s) - $blocks = []; //doors.. special blocks annoying -.- - $isDoor = strpos($namespacedSelectedBlockName, "_door") !== false; - if ($isDoor) { - return [self::buildDoor($namespacedSelectedBlockName, $finalStatesList)]; + if (strpos($query->blockId, "_door") !== false) { + $block = self::buildDoor($query, $finalStatesList); + $query->blockFullId = $block->getFullId(); + return $block; } - #var_dump((string)$finalStatesList); + /** @var Block[] $blocks */ + $blocks = []; foreach (self::$legacyStateMap[$namespacedSelectedBlockName] as $meta => $r12ToCurrentBlockMapEntry) { $clonedPrintedCompound = clone $r12ToCurrentBlockMapEntry->getBlockState()->getCompoundTag('states'); if ($clonedPrintedCompound->equals($finalStatesList)) { - #Server::getInstance()->getLogger()->notice("FOUND!"); /** @var BlockFactory $blockFactory */ $blockFactory = BlockFactory::getInstance(); $block = $blockFactory->get($block->getId(), $meta & 0xf); - #var_dump($oldNameAndMeta,$block); - #var_dump($block, $finalStatesList); $blocks[] = $block; - #Server::getInstance()->getLogger()->debug(TF::GREEN . "Found block: " . TF::GOLD . $block); - #Server::getInstance()->getLogger()->notice(self::printStates(new BlockStatesEntry($namespacedSelectedBlockName, $clonedPrintedCompound), true));//might cause loop lol } } - #if (empty($blocks)) return [Block::get(0)];//no block found //TODO r12 map only has blocks up to id 255. On 4.0.0, return Item::fromString()? - if (empty($blocks)) throw new InvalidArgumentException("No block $namespacedSelectedBlockName matching $query could be found");//no block found //TODO r12 map only has blocks up to id 255. On 4.0.0, return Item::fromString()? - if (count($blocks) === 1) return $blocks; + if (empty($blocks) && !$block instanceof Block) throw new InvalidArgumentException("No block $namespacedSelectedBlockName matching $query->query could be found");//no block found //TODO r12 map only has blocks up to id 255. On 4.0.0, return Item::fromString()? + if (count($blocks) === 1) { + $block = $blocks[0]; + $query->blockFullId = $block->getFullId(); + return $block; + } //"Hack" to get just one block if multiple results have been found. Most times this results in the default one (meta:0) $smallestMeta = PHP_INT_MAX; - $result = null; - foreach ($blocks as $block) { - if ($block->getMeta() < $smallestMeta) { - $smallestMeta = $block->getMeta(); - $result = $block; + foreach ($blocks as $blockFromStates) { + if ($blockFromStates->getMeta() < $smallestMeta) { + $smallestMeta = $blockFromStates->getMeta(); + $block = $blockFromStates; } } - #Loader::getInstance()->getLogger()->debug(TF::LIGHT_PURPLE . "Final block: " . TF::AQUA . $result); - /** @var Block $result */ - return [$result]; + $query->blockFullId = $block->getFullId(); + return $block; } public static function getStateByBlock(Block $block): ?BlockStatesEntry diff --git a/src/xenialdan/MagicWE2/helper/WeightedRandom.php b/src/xenialdan/MagicWE2/helper/WeightedRandom.php new file mode 100644 index 00000000..c6942969 --- /dev/null +++ b/src/xenialdan/MagicWE2/helper/WeightedRandom.php @@ -0,0 +1,163 @@ +probabilities[] = $weight; + $this->indexes[] = $value; + } + + final public function count(): int + { + return count($this->probabilities); + } + + private function normalize(): void + { + $sum = array_sum($this->probabilities); + foreach ($this->probabilities as &$weight) { + $weight /= $sum; + } + } + + final public function setup(): void + { + $probabilities_c = $this->count(); + if ($probabilities_c === 0) { + return; + } + + // Store the underlying generator. + $this->random = new Random(Binary::readLong(Binary::writeInt(mt_rand()) . Binary::writeInt(mt_rand()))); + $this->aliases = []; + + $this->normalize(); + + // Compute the average probability and cache it for later use. + $average = 1.0 / $probabilities_c; + + $probabilities = $this->probabilities; + + // Create two stacks to act as worklists as we populate the tables. + $small = new Deque(); + $small->allocate($probabilities_c); + $large = new Deque(); + $large->allocate($probabilities_c); + + // Populate the stacks with the input probabilities. + for ($i = 0; $i < $probabilities_c; ++$i) { + /** + * If the probability is below the average probability, then we add + * it to the small list; otherwise we add it to the large list. + */ + if ($probabilities[$i] >= $average) { + $large->push($i); + } else { + $small->push($i); + } + } + + /** + * As a note: in the mathematical specification of the algorithm, we + * will always exhaust the small list before the big list. However, + * due to floating point inaccuracies, this is not necessarily true. + * Consequently, this inner loop (which tries to pair small and large + * elements) will have to check that both lists aren't empty. + */ + while (!$small->isEmpty() && !$large->isEmpty()) { + /* Get the index of the small and the large probabilities. */ + $less = $small->pop(); + $more = $large->pop(); + + /** + * These probabilities have not yet been scaled up to be such that + * 1/n is given weight 1.0. We do this here instead. + */ + $this->probabilities[$less] = $probabilities[$less] * $probabilities_c; + $this->aliases[$less] = $more; + + /** + * Decrease the probability of the larger one by the appropriate + * amount. + */ + $probabilities[$more] = ($probabilities[$more] + $probabilities[$less]) - $average; + + /** + * If the new probability is less than the average, add it into the + * small list; otherwise add it to the large list. + */ + if ($probabilities[$more] >= 1.0 / $probabilities_c) { + $large->push($more); + } else { + $small->push($more); + } + } + + /** + * At this point, everything is in one list, which means that the + * remaining probabilities should all be 1/n. Based on this, set them + * appropriately. Due to numerical issues, we can't be sure which + * stack will hold the entries, so we empty both. + */ + while (!$small->isEmpty()) { + $this->probabilities[$small->pop()] = 1.0; + } + while (!$large->isEmpty()) { + $this->probabilities[$large->pop()] = 1.0; + } + } + + /** + * @param int $count + * @return Generator + */ + final public function generateIndexes(int $count): Generator + { + $probabilities_c = count($this->probabilities); + if ($probabilities_c > 0) { + while (--$count >= 0) { + $index = $this->random->nextBoundedInt($probabilities_c); + yield $this->random->nextFloat() <= $this->probabilities[$index] ? $index : $this->aliases[$index]; + } + } + } + + /** + * @param int $count + * @return Generator + */ + public function generate(int $count): Generator + { + foreach ($this->generateIndexes($count) as $index) { + yield $this->indexes[$index]; + } + } +} \ No newline at end of file From fb58e748503c3118e4df882b2675110d66b0ee26 Mon Sep 17 00:00:00 2001 From: XenialDan Date: Fri, 25 Dec 2020 06:25:10 +0100 Subject: [PATCH 02/67] switch out Block[] with BlockPalette --- src/xenialdan/MagicWE2/API.php | 31 ++++---- src/xenialdan/MagicWE2/EventListener.php | 2 +- src/xenialdan/MagicWE2/Loader.php | 1 + .../MagicWE2/commands/TestCommand.php | 17 +++-- .../MagicWE2/commands/args/BlocksArgument.php | 38 ++++++++++ .../commands/clipboard/Cut2Command.php | 12 +-- .../commands/clipboard/CutCommand.php | 5 +- .../commands/generation/CylinderCommand.php | 9 +-- .../commands/region/OverlayCommand.php | 7 +- .../commands/region/ReplaceCommand.php | 10 +-- .../MagicWE2/commands/region/SetCommand.php | 6 +- .../commands/selection/info/CountCommand.php | 46 +++++------ src/xenialdan/MagicWE2/event/MWEEditEvent.php | 2 +- .../MagicWE2/helper/BlockPalette.php | 45 ++++++++--- src/xenialdan/MagicWE2/helper/BlockQuery.php | 6 +- .../MagicWE2/helper/BlockStatesEntry.php | 23 +++--- .../MagicWE2/helper/BlockStatesParser.php | 13 ++-- .../MagicWE2/helper/StructureStore.php | 1 + .../MagicWE2/helper/WeightedRandom.php | 10 +++ .../MagicWE2/selection/Selection.php | 8 +- .../MagicWE2/selection/shape/Cone.php | 11 +-- .../MagicWE2/selection/shape/Cube.php | 13 ++-- .../MagicWE2/selection/shape/Cuboid.php | 13 ++-- .../MagicWE2/selection/shape/Custom.php | 5 +- .../MagicWE2/selection/shape/Cylinder.php | 13 ++-- .../MagicWE2/selection/shape/Ellipsoid.php | 31 ++++---- .../MagicWE2/selection/shape/Pyramid.php | 13 ++-- .../MagicWE2/selection/shape/Shape.php | 7 +- .../MagicWE2/selection/shape/Sphere.php | 9 ++- .../MagicWE2/task/AsyncActionTask.php | 33 ++++---- src/xenialdan/MagicWE2/task/AsyncCopyTask.php | 3 +- .../MagicWE2/task/AsyncCountTask.php | 67 ++++++++-------- src/xenialdan/MagicWE2/task/AsyncFillTask.php | 36 +++++---- .../MagicWE2/task/AsyncReplaceTask.php | 76 ++++++++++--------- .../MagicWE2/task/action/ClipboardAction.php | 2 +- .../MagicWE2/task/action/CountAction.php | 28 +++---- .../MagicWE2/task/action/CutAction.php | 32 ++++---- .../MagicWE2/task/action/FlipAction.php | 2 +- .../MagicWE2/task/action/RotateAction.php | 20 ++--- .../MagicWE2/task/action/SetBiomeAction.php | 28 +++---- .../MagicWE2/task/action/SetBlockAction.php | 48 ++++++------ .../MagicWE2/task/action/TaskAction.php | 26 +++---- .../MagicWE2/task/action/TestAction.php | 30 ++++---- .../MagicWE2/task/action/ThawAction.php | 27 +++---- src/xenialdan/MagicWE2/tool/Brush.php | 15 ++-- src/xenialdan/MagicWE2/tool/Flood.php | 7 +- 46 files changed, 489 insertions(+), 398 deletions(-) create mode 100644 src/xenialdan/MagicWE2/commands/args/BlocksArgument.php diff --git a/src/xenialdan/MagicWE2/API.php b/src/xenialdan/MagicWE2/API.php index 0a067126..f8b14a33 100644 --- a/src/xenialdan/MagicWE2/API.php +++ b/src/xenialdan/MagicWE2/API.php @@ -22,6 +22,7 @@ use RuntimeException; use xenialdan\MagicWE2\clipboard\Clipboard; use xenialdan\MagicWE2\clipboard\SingleClipboard; +use xenialdan\MagicWE2\exception\BlockQueryAlreadyParsedException; use xenialdan\MagicWE2\exception\CalculationException; use xenialdan\MagicWE2\exception\LimitExceededException; use xenialdan\MagicWE2\helper\BlockPalette; @@ -77,13 +78,13 @@ class API /** * @param Selection $selection * @param Session $session - * @param Block[] $newblocks + * @param BlockPalette $newblocks * @param int $flags * @return bool */ - public static function fillAsync(Selection $selection, Session $session, $newblocks = [], int $flags = self::FLAG_BASE): bool + public static function fillAsync(Selection $selection, Session $session, BlockPalette $newblocks, int $flags = self::FLAG_BASE): bool { - if (empty($newblocks)) { + if ($newblocks->empty()) { $session->sendMessage(TF::RED . "New blocks is empty!"); return false; } @@ -109,16 +110,16 @@ public static function fillAsync(Selection $selection, Session $session, $newblo /** * @param Selection $selection * @param Session $session - * @param Block[] $oldBlocks - * @param Block[] $newBlocks + * @param BlockPalette $oldBlocks + * @param BlockPalette $newBlocks * @param int $flags * @return bool */ - public static function replaceAsync(Selection $selection, Session $session, $oldBlocks = [], $newBlocks = [], int $flags = self::FLAG_BASE): bool + public static function replaceAsync(Selection $selection, Session $session, BlockPalette $oldBlocks, BlockPalette $newBlocks, int $flags = self::FLAG_BASE): bool { - if (empty($oldBlocks)) $session->sendMessage(TF::RED . "Old blocks is empty!"); - if (empty($newBlocks)) $session->sendMessage(TF::RED . "New blocks is empty!"); - if (empty($oldBlocks) || empty($newBlocks)) return false; + if ($oldBlocks->empty()) $session->sendMessage(TF::RED . "Old blocks is empty!"); + if ($newBlocks->empty()) $session->sendMessage(TF::RED . "New blocks is empty!"); + if ($oldBlocks->empty() || $newBlocks->empty()) return false; try { $limit = Loader::getInstance()->getConfig()->get("limit", -1); if ($limit !== -1 && $selection->getShape()->getTotalCount() > $limit) { @@ -240,11 +241,11 @@ private static function getAABBTouchedChunksTemp(ChunkManager $manager, AxisAlig /** * @param Selection $selection * @param Session $session - * @param Block[] $filterBlocks + * @param BlockPalette $filterBlocks * @param int $flags * @return bool */ - public static function countAsync(Selection $selection, Session $session, array $filterBlocks, int $flags = self::FLAG_BASE): bool + public static function countAsync(Selection $selection, Session $session, BlockPalette $filterBlocks, int $flags = self::FLAG_BASE): bool { try { $limit = Loader::getInstance()->getConfig()->get("limit", -1); @@ -278,7 +279,7 @@ public static function setBiomeAsync(Selection $selection, Session $session, int /** @var Player $player */ $session->getBossBar()->showTo([$player]); } - Server::getInstance()->getAsyncPool()->submitTask(new AsyncActionTask($session->getUUID(), $selection, new SetBiomeAction($biomeId), $selection->getShape()->getTouchedChunks($selection->getWorld()))); + Server::getInstance()->getAsyncPool()->submitTask(new AsyncActionTask($session->getUUID(), $selection, new SetBiomeAction($biomeId), $selection->getShape()->getTouchedChunks($selection->getWorld()), BlockPalette::CREATE(), BlockPalette::CREATE())); } catch (Exception $e) { $session->sendMessage($e->getMessage()); Loader::getInstance()->getLogger()->logException($e); @@ -312,7 +313,7 @@ public static function createBrush(Block $target, Brush $brush, Session $session /** @var TaskAction $action */ $action = new $actionClass(...array_values($brush->properties->actionProperties)); $action->prefix = "Brush"; - Server::getInstance()->getAsyncPool()->submitTask(new AsyncActionTask($session->getUUID(), $selection, $action, $selection->getShape()->getTouchedChunks($selection->getWorld()), $brush->properties->blocks, $brush->properties->filter)); + Server::getInstance()->getAsyncPool()->submitTask(new AsyncActionTask($session->getUUID(), $selection, $action, $selection->getShape()->getTouchedChunks($selection->getWorld()), BlockPalette::fromString($brush->properties->blocks), BlockPalette::fromString($brush->properties->filter))); } /** @@ -416,11 +417,13 @@ public static function hasFlag(int $flags, int $check): bool * @param array $messages * @param bool $error * @return BlockPalette + * @throws InvalidArgumentException + * @throws BlockQueryAlreadyParsedException + * @deprecated Use BlockPalette::fromString() */ public static function blockParser(string $fullstring, array &$messages, bool &$error): BlockPalette { BlockFactory::getInstance(); - //$blocks = BlockStatesParser::getInstance()::fromString($fullstring, true); return BlockPalette::fromString($fullstring); } diff --git a/src/xenialdan/MagicWE2/EventListener.php b/src/xenialdan/MagicWE2/EventListener.php index 81c8220e..2e5e9846 100644 --- a/src/xenialdan/MagicWE2/EventListener.php +++ b/src/xenialdan/MagicWE2/EventListener.php @@ -337,7 +337,7 @@ public function onDropItem(PlayerDropItemEvent $event): void public function onSelectionChange(MWESelectionChangeEvent $event): void { Loader::getInstance()->getLogger()->debug("Called " . $event->getEventName()); - if (($session = $event->getSession()) instanceof UserSession && ($player = $event->getPlayer()) !== null) { + if (($session = $event->getSession()) instanceof UserSession && $event->getPlayer() !== null) { /** @var UserSession $session */ $session->sidebar->handleScoreboard($session); } diff --git a/src/xenialdan/MagicWE2/Loader.php b/src/xenialdan/MagicWE2/Loader.php index 09ed6912..608e22b1 100644 --- a/src/xenialdan/MagicWE2/Loader.php +++ b/src/xenialdan/MagicWE2/Loader.php @@ -174,6 +174,7 @@ public function onLoad(): void $blockstateparserInstance->setAliasMap(json_decode($fileGetContents, true, 512, JSON_THROW_ON_ERROR)); #StructureStore::getInstance(); + $blockstateparserInstance::runTests();//TODO REMOVE, DEBUG!!!!!!! } /** diff --git a/src/xenialdan/MagicWE2/commands/TestCommand.php b/src/xenialdan/MagicWE2/commands/TestCommand.php index 78cb1e7a..8c76455b 100644 --- a/src/xenialdan/MagicWE2/commands/TestCommand.php +++ b/src/xenialdan/MagicWE2/commands/TestCommand.php @@ -12,6 +12,7 @@ use pocketmine\Server; use pocketmine\utils\TextFormat as TF; use xenialdan\MagicWE2\exception\SessionException; +use xenialdan\MagicWE2\helper\BlockPalette; use xenialdan\MagicWE2\helper\SessionHelper; use xenialdan\MagicWE2\Loader; use xenialdan\MagicWE2\selection\Selection; @@ -55,8 +56,8 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo $selection, new TestAction(), $selection->getShape()->getTouchedChunks($selection->getWorld()), - "minecraft:snow_block", - "minecraft:tnt" + BlockPalette::fromString("minecraft:snow_block"), + BlockPalette::fromString("minecraft:tnt") ) ); $selection = new Selection($pluginSession->getUUID(), Server::getInstance()->getWorldManager()->getDefaultWorld(), 0, 0, 0, 1, 1, 1); @@ -66,8 +67,8 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo $selection, new TestAction(), $selection->getShape()->getTouchedChunks($selection->getWorld()), - "minecraft:snow_block", - "minecraft:tnt" + BlockPalette::fromString("minecraft:snow_block"), + BlockPalette::fromString("minecraft:tnt") ) ); $selection = new Selection($pluginSession->getUUID(), Server::getInstance()->getWorldManager()->getDefaultWorld(), 0, 0, 0, 2, 2, 2); @@ -77,8 +78,8 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo $selection, new TestAction(), $selection->getShape()->getTouchedChunks($selection->getWorld()), - "minecraft:snow_block", - "minecraft:tnt" + BlockPalette::fromString("minecraft:snow_block"), + BlockPalette::fromString("minecraft:tnt") ) ); $selection = new Selection($pluginSession->getUUID(), Server::getInstance()->getWorldManager()->getDefaultWorld(), 0, 0, 0, 1, 2, 3); @@ -88,8 +89,8 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo $selection, new TestAction(), $selection->getShape()->getTouchedChunks($selection->getWorld()), - "minecraft:snow_block", - "minecraft:tnt" + BlockPalette::fromString("minecraft:snow_block"), + BlockPalette::fromString("minecraft:tnt") ) ); } catch (Exception $error) { diff --git a/src/xenialdan/MagicWE2/commands/args/BlocksArgument.php b/src/xenialdan/MagicWE2/commands/args/BlocksArgument.php new file mode 100644 index 00000000..cb7ec85d --- /dev/null +++ b/src/xenialdan/MagicWE2/commands/args/BlocksArgument.php @@ -0,0 +1,38 @@ +registerArgument(0, new TextArgument("flags", true)); $this->setPermission("we.command.clipboard.cut"); } @@ -74,12 +76,12 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo $action->setClipboardVector($offset); Server::getInstance()->getAsyncPool()->submitTask( new AsyncActionTask( - $session->getUUID(), - $selection, - $action, + $session->getUUID(), + $selection, + $action, $selection->getShape()->getTouchedChunks($selection->getWorld()), - "air",//TODO option - "" + BlockPalette::fromString("air"),//TODO option + BlockPalette::CREATE() ) ); } catch (Exception $error) { diff --git a/src/xenialdan/MagicWE2/commands/clipboard/CutCommand.php b/src/xenialdan/MagicWE2/commands/clipboard/CutCommand.php index 6885430f..769daffe 100644 --- a/src/xenialdan/MagicWE2/commands/clipboard/CutCommand.php +++ b/src/xenialdan/MagicWE2/commands/clipboard/CutCommand.php @@ -9,14 +9,13 @@ use CortexPE\Commando\exception\ArgumentOrderException; use Exception; use InvalidArgumentException; -use pocketmine\block\BlockFactory; -use pocketmine\block\BlockLegacyIds; use pocketmine\command\CommandSender; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; use xenialdan\MagicWE2\API; use xenialdan\MagicWE2\exception\SelectionException; use xenialdan\MagicWE2\exception\SessionException; +use xenialdan\MagicWE2\helper\BlockPalette; use xenialdan\MagicWE2\helper\SessionHelper; use xenialdan\MagicWE2\Loader; @@ -72,7 +71,7 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo //TODO Temp hack - add cutAsync - Update 9th Feb. 2020 LEAVE THAT ALONE! IT WORKS, DO NOT TOUCH IT! $flags = $hasFlags ? API::flagParser(explode(" ", (string)$args["flags"])) : API::FLAG_BASE; API::copyAsync($selection, $session, $flags); - API::fillAsync($selection, $session, [BlockFactory::getInstance()->get(BlockLegacyIds::AIR, 0)], $flags); + API::fillAsync($selection, $session, BlockPalette::fromString("air"), $flags); } catch (Exception $error) { $sender->sendMessage(Loader::PREFIX . TF::RED . $lang->translateString('error.command-error')); $sender->sendMessage(Loader::PREFIX . TF::RED . $error->getMessage()); diff --git a/src/xenialdan/MagicWE2/commands/generation/CylinderCommand.php b/src/xenialdan/MagicWE2/commands/generation/CylinderCommand.php index 12000f11..1b6ed008 100644 --- a/src/xenialdan/MagicWE2/commands/generation/CylinderCommand.php +++ b/src/xenialdan/MagicWE2/commands/generation/CylinderCommand.php @@ -5,7 +5,6 @@ namespace xenialdan\MagicWE2\commands\generation; use CortexPE\Commando\args\IntegerArgument; -use CortexPE\Commando\args\RawStringArgument; use CortexPE\Commando\args\TextArgument; use CortexPE\Commando\BaseCommand; use CortexPE\Commando\exception\ArgumentOrderException; @@ -16,6 +15,7 @@ use pocketmine\utils\AssumptionFailedError; use pocketmine\utils\TextFormat as TF; use xenialdan\MagicWE2\API; +use xenialdan\MagicWE2\commands\args\BlocksArgument; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\SessionHelper; use xenialdan\MagicWE2\Loader; @@ -31,7 +31,7 @@ class CylinderCommand extends BaseCommand */ protected function prepare(): void { - $this->registerArgument(0, new RawStringArgument("blocks", false)); + $this->registerArgument(0, new BlocksArgument("blocks", false)); $this->registerArgument(1, new IntegerArgument("diameter", false)); $this->registerArgument(2, new IntegerArgument("height", true)); $this->registerArgument(3, new TextArgument("flags", true)); @@ -61,10 +61,9 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo try { $messages = []; $error = false; - $blocks = (string)$args["blocks"];//TODO change to Palette + $blocks = $args["blocks"]; $diameter = (int)$args["diameter"]; $height = (int)($args["height"] ?? 1); - $newblocks = API::blockParser($blocks, $messages, $error); foreach ($messages as $message) { $sender->sendMessage($message); } @@ -77,7 +76,7 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo $cylSelection = new Selection($session->getUUID(), $sender->getWorld()); $cylSelection->setShape($cyl); $hasFlags = isset($args["flags"]); - API::fillAsync($cylSelection, $session, $newblocks, $hasFlags ? API::flagParser(explode(" ", (string)$args["flags"])) : API::FLAG_BASE); + API::fillAsync($cylSelection, $session, $blocks, $hasFlags ? API::flagParser(explode(" ", (string)$args["flags"])) : API::FLAG_BASE); } else { throw new InvalidArgumentException("Could not fill with the selected blocks"); } diff --git a/src/xenialdan/MagicWE2/commands/region/OverlayCommand.php b/src/xenialdan/MagicWE2/commands/region/OverlayCommand.php index 574266f8..248143a1 100644 --- a/src/xenialdan/MagicWE2/commands/region/OverlayCommand.php +++ b/src/xenialdan/MagicWE2/commands/region/OverlayCommand.php @@ -4,7 +4,6 @@ namespace xenialdan\MagicWE2\commands\region; -use CortexPE\Commando\args\RawStringArgument; use CortexPE\Commando\BaseCommand; use CortexPE\Commando\exception\ArgumentOrderException; use Exception; @@ -12,7 +11,7 @@ use pocketmine\command\CommandSender; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; -use xenialdan\MagicWE2\API; +use xenialdan\MagicWE2\commands\args\BlocksArgument; use xenialdan\MagicWE2\exception\SelectionException; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\SessionHelper; @@ -28,7 +27,7 @@ class OverlayCommand extends BaseCommand */ protected function prepare(): void { - $this->registerArgument(0, new RawStringArgument("blocks", false)); + $this->registerArgument(0, new BlocksArgument("blocks", false)); $this->setPermission("we.command.region.overlay"); } @@ -54,7 +53,7 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo try { $messages = []; $error = false; - $blocks = API::blockParser((string)$args["blocks"], $messages, $error);//TODO change to Palette + $blocks = $args["blocks"]; foreach ($messages as $message) { $sender->sendMessage($message); } diff --git a/src/xenialdan/MagicWE2/commands/region/ReplaceCommand.php b/src/xenialdan/MagicWE2/commands/region/ReplaceCommand.php index 006c391d..f19ffaa6 100644 --- a/src/xenialdan/MagicWE2/commands/region/ReplaceCommand.php +++ b/src/xenialdan/MagicWE2/commands/region/ReplaceCommand.php @@ -4,7 +4,6 @@ namespace xenialdan\MagicWE2\commands\region; -use CortexPE\Commando\args\RawStringArgument; use CortexPE\Commando\args\TextArgument; use CortexPE\Commando\BaseCommand; use CortexPE\Commando\exception\ArgumentOrderException; @@ -14,6 +13,7 @@ use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; use xenialdan\MagicWE2\API; +use xenialdan\MagicWE2\commands\args\BlocksArgument; use xenialdan\MagicWE2\exception\SelectionException; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\SessionHelper; @@ -29,8 +29,8 @@ class ReplaceCommand extends BaseCommand */ protected function prepare(): void { - $this->registerArgument(0, new RawStringArgument("findblocks", false)); - $this->registerArgument(1, new RawStringArgument("replaceblocks", false)); + $this->registerArgument(0, new BlocksArgument("findblocks", false)); + $this->registerArgument(1, new BlocksArgument("replaceblocks", false)); $this->registerArgument(2, new TextArgument("flags", true)); $this->setPermission("we.command.region.replace"); } @@ -57,8 +57,8 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo try { $messages = []; $error = false; - $findBlocks = API::blockParser((string)$args["findblocks"], $messages, $error);//TODO change to Palette - $replaceBlocks = API::blockParser((string)$args["replaceblocks"], $messages, $error);//TODO change to Palette + $findBlocks = $args["findblocks"]; + $replaceBlocks = $args["replaceblocks"]; foreach ($messages as $message) { $sender->sendMessage($message); } diff --git a/src/xenialdan/MagicWE2/commands/region/SetCommand.php b/src/xenialdan/MagicWE2/commands/region/SetCommand.php index 2840a5ff..380f0ee1 100644 --- a/src/xenialdan/MagicWE2/commands/region/SetCommand.php +++ b/src/xenialdan/MagicWE2/commands/region/SetCommand.php @@ -4,7 +4,6 @@ namespace xenialdan\MagicWE2\commands\region; -use CortexPE\Commando\args\RawStringArgument; use CortexPE\Commando\args\TextArgument; use CortexPE\Commando\BaseCommand; use CortexPE\Commando\exception\ArgumentOrderException; @@ -14,6 +13,7 @@ use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; use xenialdan\MagicWE2\API; +use xenialdan\MagicWE2\commands\args\BlocksArgument; use xenialdan\MagicWE2\exception\SelectionException; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\SessionHelper; @@ -29,7 +29,7 @@ class SetCommand extends BaseCommand */ protected function prepare(): void { - $this->registerArgument(0, new RawStringArgument("blocks", false)); + $this->registerArgument(0, new BlocksArgument("blocks", false)); $this->registerArgument(1, new TextArgument("flags", true)); $this->setPermission("we.command.region.set"); } @@ -56,7 +56,7 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo try { $messages = []; $error = false; - $replaceBlocks = API::blockParser((string)$args["blocks"], $messages, $error);//TODO change to Palette + $replaceBlocks = $args["blocks"]; foreach ($messages as $message) { $sender->sendMessage($message); } diff --git a/src/xenialdan/MagicWE2/commands/selection/info/CountCommand.php b/src/xenialdan/MagicWE2/commands/selection/info/CountCommand.php index 3f950800..71c313b1 100644 --- a/src/xenialdan/MagicWE2/commands/selection/info/CountCommand.php +++ b/src/xenialdan/MagicWE2/commands/selection/info/CountCommand.php @@ -4,7 +4,6 @@ namespace xenialdan\MagicWE2\commands\selection\info; -use CortexPE\Commando\args\RawStringArgument; use CortexPE\Commando\args\TextArgument; use CortexPE\Commando\BaseCommand; use CortexPE\Commando\exception\ArgumentOrderException; @@ -14,9 +13,10 @@ use pocketmine\player\Player; use pocketmine\Server; use pocketmine\utils\TextFormat as TF; -use xenialdan\MagicWE2\API; +use xenialdan\MagicWE2\commands\args\BlocksArgument; use xenialdan\MagicWE2\exception\SelectionException; use xenialdan\MagicWE2\exception\SessionException; +use xenialdan\MagicWE2\helper\BlockPalette; use xenialdan\MagicWE2\helper\SessionHelper; use xenialdan\MagicWE2\Loader; use xenialdan\MagicWE2\task\action\CountAction; @@ -32,7 +32,7 @@ class CountCommand extends BaseCommand */ protected function prepare(): void { - $this->registerArgument(0, new RawStringArgument("blocks", true)); + $this->registerArgument(0, new BlocksArgument("blocks", true)); $this->registerArgument(1, new TextArgument("flags", true)); $this->setPermission("we.command.selection.info.count"); } @@ -57,24 +57,20 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo } /** @var Player $sender */ try { - $error = false; - if (!empty($args["blocks"])) { - $messages = []; - API::blockParser(($filterBlocks = (string)$args["blocks"]), $messages, $error);//TODO change to Palette - foreach ($messages as $message) { - $sender->sendMessage($message); - } - } else $filterBlocks = ""; - if (!$error) { - $session = SessionHelper::getUserSession($sender); - if (is_null($session)) { + $error = false; + if (isset($args["blocks"])) { + $filterBlocks = $args["blocks"]; + } else $filterBlocks = BlockPalette::CREATE(); + if (!$error) { + $session = SessionHelper::getUserSession($sender); + if (is_null($session)) { throw new SessionException($lang->translateString('error.nosession', [Loader::getInstance()->getName()])); - } - $selection = $session->getLatestSelection(); - if (is_null($selection)) { + } + $selection = $session->getLatestSelection(); + if (is_null($selection)) { throw new SelectionException($lang->translateString('error.noselection')); - } - if (!$selection->isValid()) { + } + if (!$selection->isValid()) { throw new SelectionException($lang->translateString('error.selectioninvalid')); } if ($selection->getWorld() !== $sender->getWorld()) { @@ -82,12 +78,12 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo } Server::getInstance()->getAsyncPool()->submitTask( new AsyncActionTask( - $session->getUUID(), - $selection, - new CountAction(), - $selection->getShape()->getTouchedChunks($selection->getWorld()), - "", - $filterBlocks + $session->getUUID(), + $selection, + new CountAction(), + $selection->getShape()->getTouchedChunks($selection->getWorld()), + BlockPalette::CREATE(), + $filterBlocks ) ); } else { diff --git a/src/xenialdan/MagicWE2/event/MWEEditEvent.php b/src/xenialdan/MagicWE2/event/MWEEditEvent.php index b044df79..503ebecc 100644 --- a/src/xenialdan/MagicWE2/event/MWEEditEvent.php +++ b/src/xenialdan/MagicWE2/event/MWEEditEvent.php @@ -51,7 +51,7 @@ public function getPlayer(): ?Player { if (($session = $this->getSession()) instanceof UserSession) /** @var UserSession $session */ - $session->getPlayer(); + return $session->getPlayer(); return null; } diff --git a/src/xenialdan/MagicWE2/helper/BlockPalette.php b/src/xenialdan/MagicWE2/helper/BlockPalette.php index 5fa0d600..ae65d428 100644 --- a/src/xenialdan/MagicWE2/helper/BlockPalette.php +++ b/src/xenialdan/MagicWE2/helper/BlockPalette.php @@ -18,7 +18,7 @@ class BlockPalette * @var WeightedRandom */ public WeightedRandom $randomBlockQueries; - public string $name; + public string $name = ""; /** * BlockPalette constructor. @@ -38,7 +38,7 @@ public function __construct(string $name = "") */ public static function fromString(string $blocksQuery): self { - $palette = self::EMPTY(); + $palette = self::CREATE(); $pregSplit = preg_split('/,(?![^\[]*])/', trim($blocksQuery), -1, PREG_SPLIT_NO_EMPTY); if (!is_array($pregSplit)) throw new InvalidArgumentException("Regex matching failed"); @@ -64,31 +64,54 @@ public function addBlockQuery(BlockQuery $query) //TODO addBlock /** - * @return Generator|Block + * @param int $amount + * @return Generator|Block[] * @throws InvalidArgumentException */ public function blocks(int $amount = 1): Generator { - if ($amount < 1) throw new InvalidArgumentException('$amount must be positive'); - $this->randomBlockQueries->setup();//TODO check if performance impact is too big (i.e when calling this method multiple times) + if ($amount < 1) throw new InvalidArgumentException('$amount must be greater than 0'); /** @var BlockFactory $blockFactory */ $blockFactory = BlockFactory::getInstance(); /** @var BlockQuery $blockQuery */ - foreach ($this->randomBlockQueries->generate($amount) as $blockQuery) { + foreach ($this->randomBlockQueries->generate($amount) as $blockQuery) {//TODO yield from? yield $blockFactory->fromFullBlock($blockQuery->blockFullId);//TODO yield blockFullId and do not yield Block? } } /** - * @param Block[] $blocks + * @return Generator|Block[] + */ + public function palette(): Generator + { + /** @var BlockFactory $blockFactory */ + $blockFactory = BlockFactory::getInstance(); + /** @var BlockQuery $blockQuery */ + foreach ($this->randomBlockQueries->indexes() as $blockQuery) {//TODO yield from? + yield $blockFactory->fromFullBlock($blockQuery->blockFullId);//TODO yield blockFullId and do not yield Block? prob nah + } + } + + public function count(): int + { + return $this->randomBlockQueries->count(); + } + + public function empty(): bool + { + return $this->randomBlockQueries->count() === 0; + } + + /** * @return string * @throws JsonException */ - public static function encode(array $blocks): string + public function encode(): string { $e = []; - foreach ($blocks as $block) - /** @noinspection PhpInternalEntityUsedInspection */ $e[] = $block->getFullId(); + /** @var BlockQuery $blockQuery */ + foreach ($this->randomBlockQueries->generate($this->randomBlockQueries->count()) as $blockQuery) + $e[] = $blockQuery->blockFullId; return json_encode($e, JSON_THROW_ON_ERROR); } @@ -107,7 +130,7 @@ public static function decode(string $blocks): array return $e; } - public static function EMPTY(): self + public static function CREATE(): self { return new self; } diff --git a/src/xenialdan/MagicWE2/helper/BlockQuery.php b/src/xenialdan/MagicWE2/helper/BlockQuery.php index 9da0de88..1cda2c2c 100644 --- a/src/xenialdan/MagicWE2/helper/BlockQuery.php +++ b/src/xenialdan/MagicWE2/helper/BlockQuery.php @@ -39,9 +39,9 @@ public function parse(bool $update = true): self { //calling methods should check with hasBlock() before parse() if (!$update && $this->hasBlock()) throw new BlockQueryAlreadyParsedException("FullBlockID is already parsed"); - /** @var BlockStatesParser $blockStatesParser */ - $blockStatesParser = BlockStatesParser::getInstance(); - $blockStatesParser::fromString($this);//this should already set the blockFullId because it is a reference + /** @var BlockStatesParser $blockstateParser */ + $blockstateParser = BlockStatesParser::getInstance(); + $blockstateParser::fromString($this);//this should already set the blockFullId because it is a reference var_dump($this->hasBlock() ? "Has block, " . $this->blockFullId : "Does not have block"); //TODO throw BlockQueryParsingFailedException if blockFullId was not set? `if(!$this->hasBlock())` return $this; diff --git a/src/xenialdan/MagicWE2/helper/BlockStatesEntry.php b/src/xenialdan/MagicWE2/helper/BlockStatesEntry.php index 13fe5a04..4a8270de 100644 --- a/src/xenialdan/MagicWE2/helper/BlockStatesEntry.php +++ b/src/xenialdan/MagicWE2/helper/BlockStatesEntry.php @@ -70,9 +70,8 @@ public function toBlock(): Block { if ($this->block instanceof Block) return $this->block; BlockFactory::getInstance(); - $blocks = BlockStatesParser::getInstance()::fromString($this->blockFull, false); - $block = reset($blocks); - if($block instanceof Block) $this->block = $block; + $block = BlockPalette::fromString($this->blockFull)->blocks()->current(); + if ($block instanceof Block) $this->block = $block; return $this->block; } @@ -91,10 +90,12 @@ public function rotate(int $amount): BlockStatesEntry $block = $clone->toBlock(); $idMapName = str_replace("minecraft:", "", BlockStatesParser::getBlockIdMapName($block)); $key = $idMapName . ":" . $block->getMeta(); + /** @var BlockStatesParser $blockstateParser */ + $blockstateParser = BlockStatesParser::getInstance(); if (strpos($idMapName, "_door") !== false) { - $fromMap = BlockStatesParser::getDoorRotationFlipMap()[$block->getMeta()] ?? null; + $fromMap = $blockstateParser::getDoorRotationFlipMap()[$block->getMeta()] ?? null; } else { - $fromMap = BlockStatesParser::getRotationFlipMap()[$key] ?? null; + $fromMap = $blockstateParser::getRotationFlipMap()[$key] ?? null; } if ($fromMap === null) return $clone; $rotatedStates = $fromMap[$amount] ?? null; @@ -125,15 +126,15 @@ public function rotate(int $amount): BlockStatesEntry } } $clone->blockStates = $bsCompound; - $clone->blockFull = TextFormat::clean(BlockStatesParser::printStates($clone, false)); + $clone->blockFull = TextFormat::clean($blockstateParser::printStates($clone, false)); if (strpos($idMapName, "_door") !== false) { - $clone->block = BlockStatesParser::fromString($clone->blockFull, false)[0]; + $clone->block = $clone->toBlock();//TODO check } else $clone->block = null; return $clone; //TODO reduce useless calls. BSP::fromStates? - #$blockFull = TextFormat::clean(BlockStatesParser::printStates($clone, false)); - #return BlockStatesParser::getStateByBlock(BlockStatesParser::fromString($blockFull)[0]); + #$blockFull = TextFormat::clean($blockstateParser::printStates($clone, false)); + #return BlockStatesParser::getStateByBlock($blockstateParser::fromString($blockFull)[0]); } /** @@ -248,8 +249,8 @@ public function mirror(string $axis): BlockStatesEntry #var_dump($clone->blockFull); return $clone; //TODO reduce useless calls. BSP::fromStates? - #$blockFull = TextFormat::clean(BlockStatesParser::printStates($clone, false)); - #return BlockStatesParser::getStateByBlock(BlockStatesParser::fromString($blockFull)[0]); + #$blockFull = TextFormat::clean($blockstateParser::printStates($clone, false)); + #return BlockStatesParser::getStateByBlock($blockstateParser::fromString($blockFull)[0]); } } \ No newline at end of file diff --git a/src/xenialdan/MagicWE2/helper/BlockStatesParser.php b/src/xenialdan/MagicWE2/helper/BlockStatesParser.php index 59072f1c..5038defb 100644 --- a/src/xenialdan/MagicWE2/helper/BlockStatesParser.php +++ b/src/xenialdan/MagicWE2/helper/BlockStatesParser.php @@ -191,13 +191,14 @@ protected static function getDefaultStates(string $blockIdentifier): CompoundTag * Parses a BlockQuery (acquired using BlockPalette::fromString()) to a block and sets the BlockQuery's blockFullId * @param BlockQuery $query * @return Block - * @throws InvalidArgumentException + * @throws InvalidArgumentException|\pocketmine\block\utils\InvalidBlockStateException + * @noinspection PhpInternalEntityUsedInspection */ public static function fromString(BlockQuery $query): Block { - $selectedBlockName = strtolower(str_replace("minecraft:", "", $query->blockId));//TODO try to keep namespace "minecraft:" to support custom blocks + $namespacedSelectedBlockName = strpos($query->blockId, "minecraft:") === false ? "minecraft:" . $query->blockId : $query->blockId; + $selectedBlockName = strtolower(str_replace("minecraft:", "", $namespacedSelectedBlockName));//TODO try to keep namespace "minecraft:" to support custom blocks - $namespacedSelectedBlockName = strpos($query->blockId, "minecraft:") === false ? "minecraft:" . $selectedBlockName : $selectedBlockName; /** @var LegacyStringToItemParser $legacyStringToItemParser */ $legacyStringToItemParser = LegacyStringToItemParser::getInstance(); $block = $legacyStringToItemParser->parse($selectedBlockName)->getBlock(); @@ -313,7 +314,7 @@ public static function getStateByCompound(CompoundTag $compoundTag): ?BlockState } if (strpos($namespacedSelectedBlockName, "_door") !== false) { - $door = self::buildDoor($namespacedSelectedBlockName, $states); + $door = self::buildDoor(BlockPalette::fromString($namespacedSelectedBlockName)->randomBlockQueries->generate(1)->current(), $states); //return self::getStateByBlock($door); return new BlockStatesEntry($namespacedSelectedBlockName, $states, $door); } @@ -437,7 +438,7 @@ public static function runTests(): void foreach ($tests as $test) { try { Loader::getInstance()->getLogger()->debug(TF::GOLD . "Search query: " . TF::LIGHT_PURPLE . $test); - foreach (self::fromString($test) as $block) { + foreach (BlockPalette::fromString($test)->palette() as $block) { assert($block instanceof Block); $blockStatesEntry = self::getStateByBlock($block); Server::getInstance()->getLogger()->debug(TF::LIGHT_PURPLE . self::printStates($blockStatesEntry, true)); @@ -449,7 +450,7 @@ public static function runTests(): void continue; } } - return;//TODO + //return;//TODO //test flip+rotation /** @noinspection PhpUnreachableStatementInspection */ // $tests2 = [ diff --git a/src/xenialdan/MagicWE2/helper/StructureStore.php b/src/xenialdan/MagicWE2/helper/StructureStore.php index f9e78b22..8a271328 100644 --- a/src/xenialdan/MagicWE2/helper/StructureStore.php +++ b/src/xenialdan/MagicWE2/helper/StructureStore.php @@ -25,6 +25,7 @@ final class StructureStore */ private $schematics; + /** @noinspection MkdirRaceConditionInspection */ public function __construct() { @mkdir(Loader::getInstance()->getDataFolder() . 'structures'); diff --git a/src/xenialdan/MagicWE2/helper/WeightedRandom.php b/src/xenialdan/MagicWE2/helper/WeightedRandom.php index c6942969..d55607b0 100644 --- a/src/xenialdan/MagicWE2/helper/WeightedRandom.php +++ b/src/xenialdan/MagicWE2/helper/WeightedRandom.php @@ -160,4 +160,14 @@ public function generate(int $count): Generator yield $this->indexes[$index]; } } + + /** + * @return Generator + */ + public function indexes(): Generator + { + foreach ($this->indexes as $index) { + yield $index; + } + } } \ No newline at end of file diff --git a/src/xenialdan/MagicWE2/selection/Selection.php b/src/xenialdan/MagicWE2/selection/Selection.php index 2cb0afba..202d6ba5 100644 --- a/src/xenialdan/MagicWE2/selection/Selection.php +++ b/src/xenialdan/MagicWE2/selection/Selection.php @@ -91,7 +91,7 @@ public function setWorld(World $world): void { $this->worldId = $world->getId(); try { - ($ev = new MWESelectionChangeEvent($this, MWESelectionChangeEvent::TYPE_WORLD))->call(); + (new MWESelectionChangeEvent($this, MWESelectionChangeEvent::TYPE_WORLD))->call(); } catch (RuntimeException $e) { } } @@ -128,7 +128,7 @@ public function setPos1(Position $position): void if ($session instanceof Session) { $session->sendMessage(TF::GREEN . $session->getLanguage()->translateString('selection.pos1.set', [$this->pos1->getX(), $this->pos1->getY(), $this->pos1->getZ()])); try { - ($ev = new MWESelectionChangeEvent($this, MWESelectionChangeEvent::TYPE_POS1))->call(); + (new MWESelectionChangeEvent($this, MWESelectionChangeEvent::TYPE_POS1))->call(); } catch (RuntimeException $e) { } } @@ -169,7 +169,7 @@ public function setPos2(Position $position): void if ($session instanceof Session) { $session->sendMessage(TF::GREEN . $session->getLanguage()->translateString('selection.pos2.set', [$this->pos2->getX(), $this->pos2->getY(), $this->pos2->getZ()])); try { - ($ev = new MWESelectionChangeEvent($this, MWESelectionChangeEvent::TYPE_POS2))->call(); + (new MWESelectionChangeEvent($this, MWESelectionChangeEvent::TYPE_POS2))->call(); } catch (RuntimeException $e) { } } @@ -195,7 +195,7 @@ public function setShape(Shape $shape): void { $this->shape = $shape; try { - ($ev = new MWESelectionChangeEvent($this, MWESelectionChangeEvent::TYPE_SHAPE))->call(); + (new MWESelectionChangeEvent($this, MWESelectionChangeEvent::TYPE_SHAPE))->call(); } catch (RuntimeException $e) { }//might cause duplicated call } diff --git a/src/xenialdan/MagicWE2/selection/shape/Cone.php b/src/xenialdan/MagicWE2/selection/shape/Cone.php index 8814e408..fdcd4e2c 100644 --- a/src/xenialdan/MagicWE2/selection/shape/Cone.php +++ b/src/xenialdan/MagicWE2/selection/shape/Cone.php @@ -13,6 +13,7 @@ use pocketmine\world\World; use xenialdan\MagicWE2\API; use xenialdan\MagicWE2\helper\AsyncChunkManager; +use xenialdan\MagicWE2\helper\BlockPalette; class Cone extends Shape { @@ -41,12 +42,12 @@ public function __construct(Vector3 $pasteVector, int $height, int $diameter, bo /** * Returns the blocks by their actual position * @param World|AsyncChunkManager $manager The world or AsyncChunkManager - * @param Block[] $filterblocks If not empty, applying a filter on the block list + * @param BlockPalette $filterblocks If not empty, applying a filter on the block list * @param int $flags * @return Generator|Block[] * @throws Exception */ - public function getBlocks($manager, array $filterblocks = [], int $flags = API::FLAG_BASE): Generator + public function getBlocks($manager, BlockPalette $filterblocks, int $flags = API::FLAG_BASE): Generator { $this->validateChunkManager($manager); $reducePerLayer = ($this->diameter / $this->height); @@ -66,10 +67,10 @@ public function getBlocks($manager, array $filterblocks = [], int $flags = API:: if (API::hasFlag($flags, API::FLAG_KEEP_BLOCKS) && $block->getId() !== BlockLegacyIds::AIR) continue; if (API::hasFlag($flags, API::FLAG_KEEP_AIR) && $block->getId() === BlockLegacyIds::AIR) continue; - if ($block->getPos()->y >= World::Y_MAX || $block->getPos()->y < 0) continue;//TODO fuufufufuuu - if (empty($filterblocks)) yield $block; + if ($block->getPos()->y >= World::Y_MAX || $block->getPos()->y < 0) continue;//TODO fuufufufuuu EDIT: And.. fufufu is what? + if ($filterblocks->empty()) yield $block; else { - foreach ($filterblocks as $filterblock) { + foreach ($filterblocks->palette() as $filterblock) { if (($block->getId() === $filterblock->getId()) && ((API::hasFlag($flags, API::FLAG_VARIANT) && $block->getIdInfo()->getVariant() === $filterblock->getIdInfo()->getVariant()) || (!API::hasFlag($flags, API::FLAG_VARIANT) && ($block->getMeta() === $filterblock->getMeta() || API::hasFlag($flags, API::FLAG_KEEP_META))))) yield $block; } diff --git a/src/xenialdan/MagicWE2/selection/shape/Cube.php b/src/xenialdan/MagicWE2/selection/shape/Cube.php index 640d9ceb..70cc3082 100644 --- a/src/xenialdan/MagicWE2/selection/shape/Cube.php +++ b/src/xenialdan/MagicWE2/selection/shape/Cube.php @@ -13,6 +13,7 @@ use pocketmine\world\World; use xenialdan\MagicWE2\API; use xenialdan\MagicWE2\helper\AsyncChunkManager; +use xenialdan\MagicWE2\helper\BlockPalette; class Cube extends Shape { @@ -28,26 +29,26 @@ public function __construct(Vector3 $pasteVector, int $width) /** * Returns the blocks by their actual position * @param World|AsyncChunkManager $manager The world or AsyncChunkManager - * @param Block[] $filterblocks If not empty, applying a filter on the block list + * @param BlockPalette $filterblocks If not empty, applying a filter on the block list * @param int $flags * @return Generator|Block[] * @throws Exception */ - public function getBlocks($manager, array $filterblocks = [], int $flags = API::FLAG_BASE): Generator - { + public function getBlocks($manager, BlockPalette $filterblocks, int $flags = API::FLAG_BASE): Generator + { $this->validateChunkManager($manager); for ($x = (int)floor($this->getMinVec3()->x), $rx = 0; $x <= floor($this->getMaxVec3()->x); $x++, $rx++) { for ($y = (int)floor($this->getMinVec3()->y), $ry = 0; $y <= floor($this->getMaxVec3()->y); $y++, $ry++) { for ($z = (int)floor($this->getMinVec3()->z), $rz = 0; $z <= floor($this->getMaxVec3()->z); $z++, $rz++) { - $block = API::setComponents($manager->getBlockAt($x, $y, $z), (int)$x, (int)$y, (int)$z); + $block = API::setComponents($manager->getBlockAt($x, $y, $z), $x, $y, $z); if (API::hasFlag($flags, API::FLAG_KEEP_BLOCKS) && $block->getId() !== BlockLegacyIds::AIR) continue; if (API::hasFlag($flags, API::FLAG_KEEP_AIR) && $block->getId() === BlockLegacyIds::AIR) continue; if ($block->getPos()->y >= World::Y_MAX || $block->getPos()->y < 0) continue;//TODO check for removal because relative might be at other y if (API::hasFlag($flags, API::FLAG_HOLLOW) && ($block->getPos()->x > $this->getMinVec3()->getX() && $block->getPos()->x < $this->getMaxVec3()->getX()) && ($block->getPos()->y > $this->getMinVec3()->getY() && $block->getPos()->y < $this->getMaxVec3()->getY()) && ($block->getPos()->z > $this->getMinVec3()->getZ() && $block->getPos()->z < $this->getMaxVec3()->getZ())) continue; - if (empty($filterblocks)) yield $block; + if ($filterblocks->empty()) yield $block; else { - foreach ($filterblocks as $filterblock) { + foreach ($filterblocks->palette() as $filterblock) { if (($block->getId() === $filterblock->getId()) && ((API::hasFlag($flags, API::FLAG_VARIANT) && $block->getIdInfo()->getVariant() === $filterblock->getIdInfo()->getVariant()) || (!API::hasFlag($flags, API::FLAG_VARIANT) && ($block->getMeta() === $filterblock->getMeta() || API::hasFlag($flags, API::FLAG_KEEP_META))))) yield $block; } diff --git a/src/xenialdan/MagicWE2/selection/shape/Cuboid.php b/src/xenialdan/MagicWE2/selection/shape/Cuboid.php index 4f04b235..623ba9a1 100644 --- a/src/xenialdan/MagicWE2/selection/shape/Cuboid.php +++ b/src/xenialdan/MagicWE2/selection/shape/Cuboid.php @@ -13,6 +13,7 @@ use pocketmine\world\World; use xenialdan\MagicWE2\API; use xenialdan\MagicWE2\helper\AsyncChunkManager; +use xenialdan\MagicWE2\helper\BlockPalette; class Cuboid extends Shape { @@ -49,27 +50,27 @@ public static function constructFromPositions(Vector3 $pos1, Vector3 $pos2): sel /** * Returns the blocks by their actual position * @param World|AsyncChunkManager $manager The world or AsyncChunkManager - * @param Block[] $filterblocks If not empty, applying a filter on the block list + * @param BlockPalette $filterblocks If not empty, applying a filter on the block list * @param int $flags * @return Generator|Block[] * @throws Exception */ - public function getBlocks($manager, array $filterblocks = [], int $flags = API::FLAG_BASE): Generator - { + public function getBlocks($manager, BlockPalette $filterblocks, int $flags = API::FLAG_BASE): Generator + { $this->validateChunkManager($manager); for ($x = (int)floor($this->getMinVec3()->x); $x <= floor($this->getMaxVec3()->x); $x++) { for ($y = (int)floor($this->getMinVec3()->y); $y <= floor($this->getMaxVec3()->y); $y++) { for ($z = (int)floor($this->getMinVec3()->z); $z <= floor($this->getMaxVec3()->z); $z++) { - $block = API::setComponents($manager->getBlockAt($x, $y, $z), (int)$x, (int)$y, (int)$z); + $block = API::setComponents($manager->getBlockAt($x, $y, $z), $x, $y, $z); #var_dump("shape getblocks", $block); if (API::hasFlag($flags, API::FLAG_KEEP_BLOCKS) && $block->getId() !== BlockLegacyIds::AIR) continue; if (API::hasFlag($flags, API::FLAG_KEEP_AIR) && $block->getId() === BlockLegacyIds::AIR) continue; if ($block->getPos()->y >= World::Y_MAX || $block->getPos()->y < 0) continue;//TODO check for removal because relative might be at other y if (API::hasFlag($flags, API::FLAG_HOLLOW) && ($block->getPos()->x > $this->getMinVec3()->getX() && $block->getPos()->x < $this->getMaxVec3()->getX()) && ($block->getPos()->y > $this->getMinVec3()->getY() && $block->getPos()->y < $this->getMaxVec3()->getY()) && ($block->getPos()->z > $this->getMinVec3()->getZ() && $block->getPos()->z < $this->getMaxVec3()->getZ())) continue; - if (empty($filterblocks)) yield $block; + if ($filterblocks->empty()) yield $block; else { - foreach ($filterblocks as $filterblock) { + foreach ($filterblocks->palette() as $filterblock) { if (($block->getId() === $filterblock->getId()) && ((API::hasFlag($flags, API::FLAG_VARIANT) && $block->getIdInfo()->getVariant() === $filterblock->getIdInfo()->getVariant()) || (!API::hasFlag($flags, API::FLAG_VARIANT) && ($block->getMeta() === $filterblock->getMeta() || API::hasFlag($flags, API::FLAG_KEEP_META))))) yield $block; } diff --git a/src/xenialdan/MagicWE2/selection/shape/Custom.php b/src/xenialdan/MagicWE2/selection/shape/Custom.php index 90345fdb..efbc0987 100644 --- a/src/xenialdan/MagicWE2/selection/shape/Custom.php +++ b/src/xenialdan/MagicWE2/selection/shape/Custom.php @@ -12,6 +12,7 @@ use pocketmine\world\World; use xenialdan\MagicWE2\API; use xenialdan\MagicWE2\helper\AsyncChunkManager; +use xenialdan\MagicWE2\helper\BlockPalette; class Custom extends Shape { @@ -32,12 +33,12 @@ public function __construct(Vector3 $pasteVector, array $positions) /** * Returns the blocks by their actual position * @param World|AsyncChunkManager $manager The world or AsyncChunkManager - * @param Block[] $filterblocks If not empty, applying a filter on the block list + * @param BlockPalette $filterblocks If not empty, applying a filter on the block list * @param int $flags * @return Generator|Block[] * @throws Exception */ - public function getBlocks($manager, array $filterblocks = [], int $flags = API::FLAG_BASE): Generator + public function getBlocks($manager, BlockPalette $filterblocks, int $flags = API::FLAG_BASE): Generator { $this->validateChunkManager($manager); foreach ($this->positions as $position) { diff --git a/src/xenialdan/MagicWE2/selection/shape/Cylinder.php b/src/xenialdan/MagicWE2/selection/shape/Cylinder.php index 8a97dc8c..6eec93a0 100644 --- a/src/xenialdan/MagicWE2/selection/shape/Cylinder.php +++ b/src/xenialdan/MagicWE2/selection/shape/Cylinder.php @@ -13,6 +13,7 @@ use pocketmine\world\World; use xenialdan\MagicWE2\API; use xenialdan\MagicWE2\helper\AsyncChunkManager; +use xenialdan\MagicWE2\helper\BlockPalette; class Cylinder extends Shape { @@ -34,16 +35,16 @@ public function __construct(Vector3 $pasteVector, int $height, int $diameter) $this->diameter = $diameter; } - /** + /** * Returns the blocks by their actual position * @param World|AsyncChunkManager $manager The world or AsyncChunkManager - * @param Block[] $filterblocks If not empty, applying a filter on the block list + * @param BlockPalette $filterblocks If not empty, applying a filter on the block list * @param int $flags * @return Generator|Block[] * @throws Exception */ - public function getBlocks($manager, array $filterblocks = [], int $flags = API::FLAG_BASE): Generator - { + public function getBlocks($manager, BlockPalette $filterblocks, int $flags = API::FLAG_BASE): Generator + { $this->validateChunkManager($manager); $centerVec2 = new Vector2($this->getPasteVector()->getX(), $this->getPasteVector()->getZ()); for ($x = (int)floor($centerVec2->x - $this->diameter / 2 - 1); $x <= floor($centerVec2->x + $this->diameter / 2 + 1); $x++) { @@ -58,9 +59,9 @@ public function getBlocks($manager, array $filterblocks = [], int $flags = API:: if (API::hasFlag($flags, API::FLAG_KEEP_AIR) && $block->getId() === BlockLegacyIds::AIR) continue; if ($block->getPos()->y >= World::Y_MAX || $block->getPos()->y < 0) continue;//TODO fuufufufuuu - if (empty($filterblocks)) yield $block; + if ($filterblocks->empty()) yield $block; else { - foreach ($filterblocks as $filterblock) { + foreach ($filterblocks->palette() as $filterblock) { if (($block->getId() === $filterblock->getId()) && ((API::hasFlag($flags, API::FLAG_VARIANT) && $block->getIdInfo()->getVariant() === $filterblock->getIdInfo()->getVariant()) || (!API::hasFlag($flags, API::FLAG_VARIANT) && ($block->getMeta() === $filterblock->getMeta() || API::hasFlag($flags, API::FLAG_KEEP_META))))) yield $block; } diff --git a/src/xenialdan/MagicWE2/selection/shape/Ellipsoid.php b/src/xenialdan/MagicWE2/selection/shape/Ellipsoid.php index b2df0172..a414815f 100644 --- a/src/xenialdan/MagicWE2/selection/shape/Ellipsoid.php +++ b/src/xenialdan/MagicWE2/selection/shape/Ellipsoid.php @@ -13,6 +13,7 @@ use pocketmine\world\World; use xenialdan\MagicWE2\API; use xenialdan\MagicWE2\helper\AsyncChunkManager; +use xenialdan\MagicWE2\helper\BlockPalette; class Ellipsoid extends Shape { @@ -38,25 +39,25 @@ public function __construct(Vector3 $pasteVector, int $width, int $height, int $ $this->depth = $depth; } - /** + /** * Returns the blocks by their actual position * @param World|AsyncChunkManager $manager The world or AsyncChunkManager - * @param Block[] $filterblocks If not empty, applying a filter on the block list + * @param BlockPalette $filterblocks If not empty, applying a filter on the block list * @param int $flags * @return Generator|Block[] * @throws Exception */ - public function getBlocks($manager, array $filterblocks = [], int $flags = API::FLAG_BASE): Generator - { - $this->validateChunkManager($manager); - $centerVec2 = new Vector2($this->getPasteVector()->getX(), $this->getPasteVector()->getZ()); - $this->pasteVector = $this->getPasteVector()->add(0, -0.5, 0); - - $xrad = $this->width / 2; - $yrad = $this->height / 2; - $zrad = $this->depth / 2; - $xradSquared = $xrad ** 2; - $yradSquared = $yrad ** 2; + public function getBlocks($manager, BlockPalette $filterblocks, int $flags = API::FLAG_BASE): Generator + { + $this->validateChunkManager($manager); + $centerVec2 = new Vector2($this->getPasteVector()->getX(), $this->getPasteVector()->getZ()); + $this->pasteVector = $this->getPasteVector()->add(0, -0.5, 0); + + $xrad = $this->width / 2; + $yrad = $this->height / 2; + $zrad = $this->depth / 2; + $xradSquared = $xrad ** 2; + $yradSquared = $yrad ** 2; $zradSquared = $zrad ** 2; $targetX = $this->pasteVector->getX(); $targetY = $this->pasteVector->getY(); @@ -77,9 +78,9 @@ public function getBlocks($manager, array $filterblocks = [], int $flags = API:: if (API::hasFlag($flags, API::FLAG_KEEP_AIR) && $block->getId() === BlockLegacyIds::AIR) continue; if ($block->getPos()->y >= World::Y_MAX || $block->getPos()->y < 0) continue;//TODO fuufufufuuu - if (empty($filterblocks)) yield $block; + if ($filterblocks->empty()) yield $block; else { - foreach ($filterblocks as $filterblock) { + foreach ($filterblocks->palette() as $filterblock) { if (($block->getId() === $filterblock->getId()) && ((API::hasFlag($flags, API::FLAG_VARIANT) && $block->getIdInfo()->getVariant() === $filterblock->getIdInfo()->getVariant()) || (!API::hasFlag($flags, API::FLAG_VARIANT) && ($block->getMeta() === $filterblock->getMeta() || API::hasFlag($flags, API::FLAG_KEEP_META))))) yield $block; } diff --git a/src/xenialdan/MagicWE2/selection/shape/Pyramid.php b/src/xenialdan/MagicWE2/selection/shape/Pyramid.php index 7c1d6b63..1e50d505 100644 --- a/src/xenialdan/MagicWE2/selection/shape/Pyramid.php +++ b/src/xenialdan/MagicWE2/selection/shape/Pyramid.php @@ -13,6 +13,7 @@ use pocketmine\world\World; use xenialdan\MagicWE2\API; use xenialdan\MagicWE2\helper\AsyncChunkManager; +use xenialdan\MagicWE2\helper\BlockPalette; class Pyramid extends Shape { @@ -42,16 +43,16 @@ public function __construct(Vector3 $pasteVector, int $width, int $height, int $ $this->flipped = $flipped; } - /** + /** * Returns the blocks by their actual position * @param World|AsyncChunkManager $manager The world or AsyncChunkManager - * @param Block[] $filterblocks If not empty, applying a filter on the block list + * @param BlockPalette $filterblocks If not empty, applying a filter on the block list * @param int $flags * @return Generator|Block[] * @throws Exception */ - public function getBlocks($manager, array $filterblocks = [], int $flags = API::FLAG_BASE): Generator - { + public function getBlocks($manager, BlockPalette $filterblocks, int $flags = API::FLAG_BASE): Generator + { $this->validateChunkManager($manager); $reduceXPerLayer = -($this->width / $this->height); $reduceZPerLayer = -($this->depth / $this->height); @@ -76,9 +77,9 @@ public function getBlocks($manager, array $filterblocks = [], int $flags = API:: if (API::hasFlag($flags, API::FLAG_KEEP_AIR) && $block->getId() === BlockLegacyIds::AIR) continue; if ($block->getPos()->y >= World::Y_MAX || $block->getPos()->y < 0) continue;//TODO fuufufufuuu - if (empty($filterblocks)) yield $block; + if ($filterblocks->empty()) yield $block; else { - foreach ($filterblocks as $filterblock) { + foreach ($filterblocks->palette() as $filterblock) { if (($block->getId() === $filterblock->getId()) && ((API::hasFlag($flags, API::FLAG_VARIANT) && $block->getIdInfo()->getVariant() === $filterblock->getIdInfo()->getVariant()) || (!API::hasFlag($flags, API::FLAG_VARIANT) && ($block->getMeta() === $filterblock->getMeta() || API::hasFlag($flags, API::FLAG_KEEP_META))))) yield $block; } diff --git a/src/xenialdan/MagicWE2/selection/shape/Shape.php b/src/xenialdan/MagicWE2/selection/shape/Shape.php index 5acd29b7..b8661d34 100644 --- a/src/xenialdan/MagicWE2/selection/shape/Shape.php +++ b/src/xenialdan/MagicWE2/selection/shape/Shape.php @@ -15,6 +15,7 @@ use Serializable; use xenialdan\MagicWE2\API; use xenialdan\MagicWE2\helper\AsyncChunkManager; +use xenialdan\MagicWE2\helper\BlockPalette; abstract class Shape implements Serializable { @@ -57,15 +58,15 @@ public function validateChunkManager($manager): void abstract public function getTotalCount(): int; - /** + /** * Returns the blocks by their actual position * @param World|AsyncChunkManager $manager The world or AsyncChunkManager - * @param Block[] $filterblocks If not empty, applying a filter on the block list + * @param BlockPalette $filterblocks If not empty, applying a filter on the block list * @param int $flags * @return Generator|Block[] * @throws Exception */ - abstract public function getBlocks($manager, array $filterblocks = [], int $flags = API::FLAG_BASE): Generator; + abstract public function getBlocks($manager, BlockPalette $filterblocks, int $flags = API::FLAG_BASE): Generator; /** * Returns a flat layer of all included x z positions in selection diff --git a/src/xenialdan/MagicWE2/selection/shape/Sphere.php b/src/xenialdan/MagicWE2/selection/shape/Sphere.php index eaa51370..c5b3951b 100644 --- a/src/xenialdan/MagicWE2/selection/shape/Sphere.php +++ b/src/xenialdan/MagicWE2/selection/shape/Sphere.php @@ -13,6 +13,7 @@ use pocketmine\world\World; use xenialdan\MagicWE2\API; use xenialdan\MagicWE2\helper\AsyncChunkManager; +use xenialdan\MagicWE2\helper\BlockPalette; class Sphere extends Shape { @@ -33,12 +34,12 @@ public function __construct(Vector3 $pasteVector, int $diameter) /** * Returns the blocks by their actual position * @param World|AsyncChunkManager $manager The world or AsyncChunkManager - * @param Block[] $filterblocks If not empty, applying a filter on the block list + * @param BlockPalette $filterblocks If not empty, applying a filter on the block list * @param int $flags * @return Generator|Block[] * @throws Exception */ - public function getBlocks($manager, array $filterblocks = [], int $flags = API::FLAG_BASE): Generator + public function getBlocks($manager, BlockPalette $filterblocks, int $flags = API::FLAG_BASE): Generator { $this->validateChunkManager($manager); for ($x = (int)floor($this->pasteVector->x - $this->diameter / 2 - 1); $x <= floor($this->pasteVector->x + $this->diameter / 2 + 1); $x++) { @@ -52,9 +53,9 @@ public function getBlocks($manager, array $filterblocks = [], int $flags = API:: if (API::hasFlag($flags, API::FLAG_KEEP_AIR) && $block->getId() === BlockLegacyIds::AIR) continue; if ($block->getPos()->y >= World::Y_MAX || $block->getPos()->y < 0) continue;//TODO fufufufuuu - if (empty($filterblocks)) yield $block; + if ($filterblocks->empty()) yield $block; else { - foreach ($filterblocks as $filterblock) { + foreach ($filterblocks->palette() as $filterblock) { if (($block->getId() === $filterblock->getId()) && ((API::hasFlag($flags, API::FLAG_VARIANT) && $block->getIdInfo()->getVariant() === $filterblock->getIdInfo()->getVariant()) || (!API::hasFlag($flags, API::FLAG_VARIANT) && ($block->getMeta() === $filterblock->getMeta() || API::hasFlag($flags, API::FLAG_KEEP_META))))) yield $block; } diff --git a/src/xenialdan/MagicWE2/task/AsyncActionTask.php b/src/xenialdan/MagicWE2/task/AsyncActionTask.php index dfd6de15..9ac49b94 100644 --- a/src/xenialdan/MagicWE2/task/AsyncActionTask.php +++ b/src/xenialdan/MagicWE2/task/AsyncActionTask.php @@ -16,6 +16,7 @@ use xenialdan\MagicWE2\clipboard\RevertClipboard; use xenialdan\MagicWE2\clipboard\SingleClipboard; use xenialdan\MagicWE2\exception\SessionException; +use xenialdan\MagicWE2\helper\BlockPalette; use xenialdan\MagicWE2\helper\Progress; use xenialdan\MagicWE2\helper\SessionHelper; use xenialdan\MagicWE2\Loader; @@ -38,9 +39,9 @@ class AsyncActionTask extends MWEAsyncTask private $touchedChunks; /** @var string */ private $selection; - /** @var string */ + /** @var BlockPalette */ private $blockFilter; - /** @var string */ + /** @var BlockPalette */ private $newBlocks; /** @var TaskAction */ private $action; @@ -51,20 +52,20 @@ class AsyncActionTask extends MWEAsyncTask * @param Selection $selection * @param TaskAction $action * @param string[] $touchedChunks serialized chunks - * @param string $newBlocks - * @param string $blockFilter + * @param BlockPalette $newBlocks + * @param BlockPalette $blockFilter */ - public function __construct(UUID $sessionUUID, Selection $selection, TaskAction $action, array $touchedChunks, string $newBlocks = "", string $blockFilter = "") - { - $this->start = microtime(true); - $this->sessionUUID = $sessionUUID->toString(); - $this->selection = serialize($selection); - $this->action = $action; - $this->touchedChunks = serialize($touchedChunks); - $this->newBlocks = $newBlocks; - $this->blockFilter = $blockFilter; + public function __construct(UUID $sessionUUID, Selection $selection, TaskAction $action, array $touchedChunks, BlockPalette $newBlocks, BlockPalette $blockFilter) + { + $this->start = microtime(true); + $this->sessionUUID = $sessionUUID->toString(); + $this->selection = serialize($selection); + $this->action = $action; + $this->touchedChunks = serialize($touchedChunks); + $this->newBlocks = $newBlocks; + $this->blockFilter = $blockFilter; - try { + try { $session = SessionHelper::getSessionByUUID($sessionUUID); if ($session instanceof UserSession) { $player = $session->getPlayer(); @@ -103,10 +104,8 @@ public function onRun(): void #$oldBlocks = []; $messages = []; $error = false; - $newBlocks = API::blockParser($this->newBlocks, $messages, $error);//TODO error handling - $blockFilter = API::blockParser($this->blockFilter, $messages, $error);//TODO error handling /** @var Progress $progress */ - foreach ($this->action->execute($this->sessionUUID, $selection, $manager, $changed, $newBlocks, $blockFilter, $oldBlocks, $messages) as $progress) { + foreach ($this->action->execute($this->sessionUUID, $selection, $manager, $changed, $this->newBlocks, $this->blockFilter, $oldBlocks, $messages) as $progress) { $this->publishProgress($progress); } diff --git a/src/xenialdan/MagicWE2/task/AsyncCopyTask.php b/src/xenialdan/MagicWE2/task/AsyncCopyTask.php index 281d3326..7b2f8c97 100644 --- a/src/xenialdan/MagicWE2/task/AsyncCopyTask.php +++ b/src/xenialdan/MagicWE2/task/AsyncCopyTask.php @@ -14,6 +14,7 @@ use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\AsyncChunkManager; use xenialdan\MagicWE2\helper\BlockEntry; +use xenialdan\MagicWE2\helper\BlockPalette; use xenialdan\MagicWE2\helper\SessionHelper; use xenialdan\MagicWE2\Loader; use xenialdan\MagicWE2\selection\Selection; @@ -94,7 +95,7 @@ private function copyBlocks(Selection $selection, AsyncChunkManager $manager, Si $this->publishProgress([0, "Running, copied $i blocks out of $blockCount"]); $min = $selection->getShape()->getMinVec3(); /** @var Block $block */ - foreach ($selection->getShape()->getBlocks($manager, [], $this->flags) as $block) { + foreach ($selection->getShape()->getBlocks($manager, BlockPalette::CREATE(), $this->flags) as $block) { #var_dump("copy chunk X: " . ($block->getX() >> 4) . " Y: " . ($block->getY() >> 4)); $newv3 = $block->getPos()->subtractVector($min)->floor(); $clipboard->addEntry($newv3->getFloorX(), $newv3->getFloorY(), $newv3->getFloorZ(), new BlockEntry($block->getFullId()));//TODO test tiles diff --git a/src/xenialdan/MagicWE2/task/AsyncCountTask.php b/src/xenialdan/MagicWE2/task/AsyncCountTask.php index 3082410e..c5ffbf3e 100644 --- a/src/xenialdan/MagicWE2/task/AsyncCountTask.php +++ b/src/xenialdan/MagicWE2/task/AsyncCountTask.php @@ -12,6 +12,7 @@ use pocketmine\world\format\io\FastChunkSerializer; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\AsyncChunkManager; +use xenialdan\MagicWE2\helper\BlockPalette; use xenialdan\MagicWE2\helper\SessionHelper; use xenialdan\MagicWE2\Loader; use xenialdan\MagicWE2\selection\Selection; @@ -26,27 +27,27 @@ class AsyncCountTask extends MWEAsyncTask private $selection; /** @var int */ private $flags; - /** @var string */ - private $newBlocks; + /** @var BlockPalette */ + private $filterblocks; /** * AsyncCountTask constructor. * @param Selection $selection * @param UUID $sessionUUID * @param string[] $touchedChunks serialized chunks - * @param Block[] $newBlocks + * @param BlockPalette $filterblocks * @param int $flags - * @throws Exception - */ - public function __construct(UUID $sessionUUID, Selection $selection, array $touchedChunks, array $newBlocks, int $flags) - { - $this->start = microtime(true); - $this->touchedChunks = serialize($touchedChunks); - $this->sessionUUID = $sessionUUID->toString(); - $this->selection = serialize($selection); - $this->newBlocks = serialize($newBlocks); - $this->flags = $flags; - } + * @throws Exception + */ + public function __construct(UUID $sessionUUID, Selection $selection, array $touchedChunks, BlockPalette $filterblocks, int $flags) + { + $this->start = microtime(true); + $this->touchedChunks = serialize($touchedChunks); + $this->sessionUUID = $sessionUUID->toString(); + $this->selection = serialize($selection); + $this->filterblocks = $filterblocks; + $this->flags = $flags; + } /** * Actions to execute when run @@ -65,30 +66,28 @@ public function onRun(): void $selection = unserialize($this->selection/*, ['allowed_classes' => [Selection::class]]*/);//TODO test pm4 $manager = Shape::getChunkManager($chunks); unset($chunks); - /** @var Block[] $newBlocks */ - $newBlocks = unserialize($this->newBlocks/*, ['allowed_classes' => [Block::class]]*/);//TODO test pm4 $totalCount = $selection->getShape()->getTotalCount(); - $counts = $this->countBlocks($selection, $manager, $newBlocks); + $counts = $this->countBlocks($selection, $manager, $this->filterblocks); $this->setResult(compact("counts", "totalCount")); } - /** - * @param Selection $selection - * @param AsyncChunkManager $manager - * @param Block[] $newBlocks - * @return array - * @throws Exception - */ - private function countBlocks(Selection $selection, AsyncChunkManager $manager, array $newBlocks): array - { - $blockCount = $selection->getShape()->getTotalCount(); - $changed = 0; - $this->publishProgress([0, "Running, changed $changed blocks out of $blockCount"]); - $lastchunkx = $lastchunkz = null; - $lastprogress = 0; - $counts = []; - /** @var Block $block */ - foreach ($selection->getShape()->getBlocks($manager, $newBlocks, $this->flags) as $block) { + /** + * @param Selection $selection + * @param AsyncChunkManager $manager + * @param BlockPalette $filterblocks + * @return array + * @throws Exception + */ + private function countBlocks(Selection $selection, AsyncChunkManager $manager, BlockPalette $filterblocks): array + { + $blockCount = $selection->getShape()->getTotalCount(); + $changed = 0; + $this->publishProgress([0, "Running, counting $changed blocks out of $blockCount"]); + $lastchunkx = $lastchunkz = null; + $lastprogress = 0; + $counts = []; + /** @var Block $block */ + foreach ($selection->getShape()->getBlocks($manager, $filterblocks, $this->flags) as $block) { if (is_null($lastchunkx) || ($block->getPos()->x >> 4 !== $lastchunkx && $block->getPos()->z >> 4 !== $lastchunkz)) { $lastchunkx = $block->getPos()->x >> 4; $lastchunkz = $block->getPos()->z >> 4; diff --git a/src/xenialdan/MagicWE2/task/AsyncFillTask.php b/src/xenialdan/MagicWE2/task/AsyncFillTask.php index 1015afde..7d90ec24 100644 --- a/src/xenialdan/MagicWE2/task/AsyncFillTask.php +++ b/src/xenialdan/MagicWE2/task/AsyncFillTask.php @@ -5,6 +5,7 @@ use Exception; use Generator; use InvalidArgumentException; +use MultipleIterator; use pocketmine\block\Block; use pocketmine\utils\AssumptionFailedError; use pocketmine\utils\TextFormat as TF; @@ -31,7 +32,9 @@ class AsyncFillTask extends MWEAsyncTask private $selection; /** @var int */ private $flags; - /** @var string */ + ///** @var string */ + //private $newBlocks; + /** @var BlockPalette */ private $newBlocks; /** @@ -39,17 +42,18 @@ class AsyncFillTask extends MWEAsyncTask * @param UUID $sessionUUID * @param Selection $selection * @param string[] $touchedChunks serialized chunks - * @param Block[] $newBlocks + * @param BlockPalette $newBlocks * @param int $flags * @throws Exception */ - public function __construct(UUID $sessionUUID, Selection $selection, array $touchedChunks, array $newBlocks, int $flags) + public function __construct(UUID $sessionUUID, Selection $selection, array $touchedChunks, BlockPalette $newBlocks, int $flags) { $this->start = microtime(true); $this->sessionUUID = $sessionUUID->toString(); $this->selection = igbinary_serialize($selection); $this->touchedChunks = igbinary_serialize($touchedChunks); - $this->newBlocks = BlockPalette::encode($newBlocks); + //$this->newBlocks = BlockPalette::encode($newBlocks); + $this->newBlocks = $newBlocks;//TODO check if serializes var_dump($this->newBlocks); $this->flags = $flags; } @@ -74,9 +78,10 @@ public function onRun(): void /** @var Selection $selection */ $selection = igbinary_unserialize($this->selection/*, ['allowed_classes' => [Selection::class]]*/);//TODO test pm4 - /** @var Block[] $newBlocks */ - $newBlocks = BlockPalette::decode($this->newBlocks);//TODO test pm4 - $oldBlocks = iterator_to_array($this->execute($selection, $manager, $newBlocks, $changed)); + ///** @var Block[] $newBlocks */ + //$newBlocks = BlockPalette::decode($this->newBlocks);//TODO test pm4 + //$oldBlocks = iterator_to_array($this->execute($selection, $manager, $newBlocks, $changed)); + $oldBlocks = iterator_to_array($this->execute($selection, $manager, $this->newBlocks, $changed)); $resultChunks = $manager->getChunks(); $resultChunks = array_filter($resultChunks, static function (Chunk $chunk) { @@ -93,13 +98,13 @@ public function onRun(): void /** * @param Selection $selection * @param AsyncChunkManager $manager - * @param Block[] $newBlocks + * @param BlockPalette $newBlocks * @param null|int $changed * @return Generator|array[] * @phpstan-return Generator * @throws Exception */ - private function execute(Selection $selection, AsyncChunkManager $manager, array $newBlocks, ?int &$changed): Generator + private function execute(Selection $selection, AsyncChunkManager $manager, BlockPalette $newBlocks, ?int &$changed): Generator { $blockCount = $selection->getShape()->getTotalCount(); $lastchunkx = $lastchunkz = null; @@ -107,8 +112,14 @@ private function execute(Selection $selection, AsyncChunkManager $manager, array $i = 0; $changed = 0; $this->publishProgress([0, "Running, changed $changed blocks out of $blockCount"]); - /** @var Block $block */ - foreach ($selection->getShape()->getBlocks($manager, [], $this->flags) as $block) { + $iterators = new MultipleIterator(); + $iterators->attachIterator($selection->getShape()->getBlocks($manager, BlockPalette::CREATE(), $this->flags)); + $iterators->attachIterator($newBlocks->blocks($blockCount)); + foreach ($iterators as [$block, $new]) { + /** + * @var Block $block + * @var Block $new + */ /*if (API::hasFlag($this->flags, API::FLAG_POSITION_RELATIVE)){ $rel = $block->subtract($selection->shape->getPasteVector()); $block = API::setComponents($block,$rel->x,$rel->y,$rel->z);//TODO COPY TO ALL TASKS @@ -121,8 +132,7 @@ private function execute(Selection $selection, AsyncChunkManager $manager, array continue; } } - $new = clone $newBlocks[array_rand($newBlocks)]; - if ($new->getId() === $block->getId() && $new->getMeta() === $block->getMeta()) continue;//skip same blocks + if ($new->getId() === $block->getId() && $new->getMeta() === $block->getMeta()) continue;//skip same blocks//TODO better method #yield self::undoBlockHackToArray($manager->getBlockAt($block->getPos()->getFloorX(), $block->getPos()->getFloorY(), $block->getPos()->getFloorZ()),$block->getPos()); yield self::singleBlockToData(API::setComponents($manager->getBlockAt($block->getPos()->getFloorX(), $block->getPos()->getFloorY(), $block->getPos()->getFloorZ()), (int)$block->getPos()->x, (int)$block->getPos()->y, (int)$block->getPos()->z)); #yield $block;//backup diff --git a/src/xenialdan/MagicWE2/task/AsyncReplaceTask.php b/src/xenialdan/MagicWE2/task/AsyncReplaceTask.php index a99b32a2..40f747a9 100644 --- a/src/xenialdan/MagicWE2/task/AsyncReplaceTask.php +++ b/src/xenialdan/MagicWE2/task/AsyncReplaceTask.php @@ -5,6 +5,7 @@ use Exception; use Generator; use InvalidArgumentException; +use MultipleIterator; use pocketmine\block\Block; use pocketmine\utils\AssumptionFailedError; use pocketmine\utils\TextFormat as TF; @@ -16,6 +17,7 @@ use xenialdan\MagicWE2\clipboard\RevertClipboard; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\AsyncChunkManager; +use xenialdan\MagicWE2\helper\BlockPalette; use xenialdan\MagicWE2\helper\SessionHelper; use xenialdan\MagicWE2\Loader; use xenialdan\MagicWE2\selection\Selection; @@ -30,9 +32,9 @@ class AsyncReplaceTask extends MWEAsyncTask private $selection; /** @var int */ private $flags; - /** @var string */ + /** @var BlockPalette */ private $replaceBlocks; - /** @var string */ + /** @var BlockPalette */ private $newBlocks; /** @@ -40,21 +42,21 @@ class AsyncReplaceTask extends MWEAsyncTask * @param Selection $selection * @param UUID $sessionUUID * @param string[] $touchedChunks serialized chunks - * @param Block[] $replaceBlocks - * @param Block[] $newBlocks - * @param int $flags - * @throws Exception - */ - public function __construct(UUID $sessionUUID, Selection $selection, array $touchedChunks, array $replaceBlocks, array $newBlocks, int $flags) - { - $this->start = microtime(true); - $this->sessionUUID = $sessionUUID->toString(); - $this->selection = serialize($selection); - $this->touchedChunks = serialize($touchedChunks); - $this->replaceBlocks = serialize($replaceBlocks); - $this->newBlocks = serialize($newBlocks); - $this->flags = $flags; - } + * @param BlockPalette $replaceBlocks + * @param BlockPalette $newBlocks + * @param int $flags + * @throws Exception + */ + public function __construct(UUID $sessionUUID, Selection $selection, array $touchedChunks, BlockPalette $replaceBlocks, BlockPalette $newBlocks, int $flags) + { + $this->start = microtime(true); + $this->sessionUUID = $sessionUUID->toString(); + $this->selection = serialize($selection); + $this->touchedChunks = serialize($touchedChunks); + $this->replaceBlocks = $replaceBlocks; + $this->newBlocks = $newBlocks; + $this->flags = $flags; + } /** * Actions to execute when run @@ -76,12 +78,7 @@ public function onRun(): void /** @var Selection $selection */ $selection = unserialize($this->selection/*, ['allowed_classes' => [Selection::class]]*/);//TODO test pm4 - /** @var Block[] $replaceBlocks */ - $replaceBlocks = unserialize($this->replaceBlocks/*, ['allowed_classes' => [Block::class]]*/);//TODO test pm4 - /** @var Block[] $newBlocks */ - $newBlocks = unserialize($this->newBlocks/*, ['allowed_classes' => [Block::class]]*/);//TODO test pm4 - - $oldBlocks = iterator_to_array($this->execute($selection, $manager, $replaceBlocks, $newBlocks, $changed)); + $oldBlocks = iterator_to_array($this->execute($selection, $manager, $this->replaceBlocks, $this->newBlocks, $changed)); $resultChunks = $manager->getChunks(); $resultChunks = array_filter($resultChunks, static function (Chunk $chunk) { @@ -90,26 +87,32 @@ public function onRun(): void $this->setResult(compact("resultChunks", "oldBlocks", "changed")); } - /** + /** * @param Selection $selection * @param AsyncChunkManager $manager - * @param array $replaceBlocks - * @param Block[] $newBlocks + * @param BlockPalette $replaceBlocks + * @param BlockPalette $newBlocks * @param null|int $changed * @return Generator|array[] * @phpstan-return Generator * @throws Exception */ - private function execute(Selection $selection, AsyncChunkManager $manager, array $replaceBlocks, array $newBlocks, ?int &$changed): Generator - { - $blockCount = $selection->getShape()->getTotalCount(); - $lastchunkx = $lastchunkz = null; - $lastprogress = 0; - $i = 0; - $changed = 0; - $this->publishProgress([0, "Running, changed $changed blocks out of $blockCount"]); - /** @var Block $block */ - foreach ($selection->getShape()->getBlocks($manager, $replaceBlocks, $this->flags) as $block) { + private function execute(Selection $selection, AsyncChunkManager $manager, BlockPalette $replaceBlocks, BlockPalette $newBlocks, ?int &$changed): Generator + { + $blockCount = $selection->getShape()->getTotalCount(); + $lastchunkx = $lastchunkz = null; + $lastprogress = 0; + $i = 0; + $changed = 0; + $this->publishProgress([0, "Running, changed $changed blocks out of $blockCount"]); + $iterators = new MultipleIterator(); + $iterators->attachIterator($selection->getShape()->getBlocks($manager, $replaceBlocks, $this->flags)); + $iterators->attachIterator($newBlocks->blocks($blockCount)); + foreach ($iterators as [$block, $new]) { + /** + * @var Block $block + * @var Block $new + */ if (is_null($lastchunkx) || ($block->getPos()->x >> 4 !== $lastchunkx && $block->getPos()->z >> 4 !== $lastchunkz)) { $lastchunkx = $block->getPos()->x >> 4; $lastchunkz = $block->getPos()->z >> 4; @@ -118,7 +121,6 @@ private function execute(Selection $selection, AsyncChunkManager $manager, array continue; } } - $new = clone $newBlocks[array_rand($newBlocks)]; if ($new->getId() === $block->getId() && $new->getMeta() === $block->getMeta()) continue;//skip same blocks yield self::singleBlockToData(API::setComponents($manager->getBlockAt($block->getPos()->getFloorX(), $block->getPos()->getFloorY(), $block->getPos()->getFloorZ()), (int)$block->getPos()->x, (int)$block->getPos()->y, (int)$block->getPos()->z)); $manager->setBlockAt($block->getPos()->getFloorX(), $block->getPos()->getFloorY(), $block->getPos()->getFloorZ(), $new); diff --git a/src/xenialdan/MagicWE2/task/action/ClipboardAction.php b/src/xenialdan/MagicWE2/task/action/ClipboardAction.php index 0470331c..f3bfa02a 100644 --- a/src/xenialdan/MagicWE2/task/action/ClipboardAction.php +++ b/src/xenialdan/MagicWE2/task/action/ClipboardAction.php @@ -29,7 +29,7 @@ abstract class ClipboardAction * @param string[] $messages * @return Generator|Progress[] */ - abstract public function execute(string $sessionUUID, Selection $selection, ?int &$changed, SingleClipboard &$clipboard, array &$messages = []): Generator; + abstract public function execute(string $sessionUUID, Selection $selection, ?int &$changed, SingleClipboard $clipboard, array &$messages = []): Generator; abstract public static function getName(): string; diff --git a/src/xenialdan/MagicWE2/task/action/CountAction.php b/src/xenialdan/MagicWE2/task/action/CountAction.php index 16a573df..206a5ca2 100644 --- a/src/xenialdan/MagicWE2/task/action/CountAction.php +++ b/src/xenialdan/MagicWE2/task/action/CountAction.php @@ -6,11 +6,11 @@ use Exception; use Generator; -use pocketmine\block\Block; use pocketmine\block\BlockFactory; use pocketmine\utils\TextFormat as TF; use xenialdan\MagicWE2\clipboard\SingleClipboard; use xenialdan\MagicWE2\helper\AsyncChunkManager; +use xenialdan\MagicWE2\helper\BlockPalette; use xenialdan\MagicWE2\helper\Progress; use xenialdan\MagicWE2\selection\Selection; @@ -30,19 +30,19 @@ public static function getName(): string return "Analyze"; } - /** - * @param string $sessionUUID - * @param Selection $selection - * @param AsyncChunkManager $manager - * @param null|int $changed - * @param Block[] $newBlocks - * @param Block[] $blockFilter - * @param SingleClipboard $oldBlocksSingleClipboard blocks before the change - * @param string[] $messages - * @return Generator|Progress[] - * @throws Exception - */ - public function execute(string $sessionUUID, Selection $selection, AsyncChunkManager $manager, ?int &$changed, array $newBlocks, array $blockFilter, SingleClipboard $oldBlocksSingleClipboard, array &$messages = []): Generator + /** + * @param string $sessionUUID + * @param Selection $selection + * @param AsyncChunkManager $manager + * @param null|int $changed + * @param BlockPalette $newBlocks + * @param BlockPalette $blockFilter + * @param SingleClipboard $oldBlocksSingleClipboard blocks before the change + * @param string[] $messages + * @return Generator|Progress[] + * @throws Exception + */ + public function execute(string $sessionUUID, Selection $selection, AsyncChunkManager $manager, ?int &$changed, BlockPalette $newBlocks, BlockPalette $blockFilter, SingleClipboard $oldBlocksSingleClipboard, array &$messages = []): Generator { $changed = 0; #$oldBlocks = []; diff --git a/src/xenialdan/MagicWE2/task/action/CutAction.php b/src/xenialdan/MagicWE2/task/action/CutAction.php index 5cbc01bf..2de6fd56 100644 --- a/src/xenialdan/MagicWE2/task/action/CutAction.php +++ b/src/xenialdan/MagicWE2/task/action/CutAction.php @@ -10,6 +10,7 @@ use xenialdan\MagicWE2\clipboard\SingleClipboard; use xenialdan\MagicWE2\helper\AsyncChunkManager; use xenialdan\MagicWE2\helper\BlockEntry; +use xenialdan\MagicWE2\helper\BlockPalette; use xenialdan\MagicWE2\helper\Progress; use xenialdan\MagicWE2\selection\Selection; @@ -31,19 +32,19 @@ public static function getName(): string return "Cut"; } - /** - * @param string $sessionUUID - * @param Selection $selection - * @param AsyncChunkManager $manager - * @param null|int $changed - * @param Block[] $newBlocks - * @param Block[] $blockFilter - * @param SingleClipboard $oldBlocksSingleClipboard blocks before the change - * @param string[] $messages - * @return Generator|Progress[] - * @throws Exception - */ - public function execute(string $sessionUUID, Selection $selection, AsyncChunkManager $manager, ?int &$changed, array $newBlocks, array $blockFilter, SingleClipboard $oldBlocksSingleClipboard, array &$messages = []): Generator + /** + * @param string $sessionUUID + * @param Selection $selection + * @param AsyncChunkManager $manager + * @param null|int $changed + * @param BlockPalette $newBlocks + * @param BlockPalette $blockFilter + * @param SingleClipboard $oldBlocksSingleClipboard blocks before the change + * @param string[] $messages + * @return Generator|Progress[] + * @throws Exception + */ + public function execute(string $sessionUUID, Selection $selection, AsyncChunkManager $manager, ?int &$changed, BlockPalette $newBlocks, BlockPalette $blockFilter, SingleClipboard $oldBlocksSingleClipboard, array &$messages = []): Generator { $changed = 0; $i = 0; @@ -51,8 +52,9 @@ public function execute(string $sessionUUID, Selection $selection, AsyncChunkMan $count = $selection->getShape()->getTotalCount(); $lastProgress = new Progress(0, ""); $min = $selection->getShape()->getMinVec3(); - foreach ($selection->getShape()->getBlocks($manager, $blockFilter) as $block) { - $new = clone $newBlocks[array_rand($newBlocks)]; + foreach ($selection->getShape()->getBlocks($manager, $blockFilter) as $block) {//TODO Merged iterator + /** @var Block $new */ + $new = $newBlocks->blocks(1)->current();//TODO Merged iterator if ($new->getId() === $block->getId() && $new->getMeta() === $block->getMeta()) continue;//skip same blocks #$oldBlocks[] = API::setComponents($manager->getBlockAt($block->getPos()->getFloorX(), $block->getPos()->getFloorY(), $block->getPos()->getFloorZ()),$block->x, $block->y, $block->z); $newv3 = $block->getPos()->subtractVector($min)->floor();//TODO check if only used for clipboard diff --git a/src/xenialdan/MagicWE2/task/action/FlipAction.php b/src/xenialdan/MagicWE2/task/action/FlipAction.php index aa5f9819..d2ca8187 100644 --- a/src/xenialdan/MagicWE2/task/action/FlipAction.php +++ b/src/xenialdan/MagicWE2/task/action/FlipAction.php @@ -47,7 +47,7 @@ public static function getName(): string * @return Generator|Progress[] * @throws Exception */ - public function execute(string $sessionUUID, Selection $selection, ?int &$changed, SingleClipboard &$clipboard, array &$messages = []): Generator + public function execute(string $sessionUUID, Selection $selection, ?int &$changed, SingleClipboard $clipboard, array &$messages = []): Generator { //TODO modify position. For now, just flip the blocks around their own axis $changed = 0; diff --git a/src/xenialdan/MagicWE2/task/action/RotateAction.php b/src/xenialdan/MagicWE2/task/action/RotateAction.php index 57f1ca98..510a9075 100644 --- a/src/xenialdan/MagicWE2/task/action/RotateAction.php +++ b/src/xenialdan/MagicWE2/task/action/RotateAction.php @@ -42,16 +42,16 @@ public static function getName(): string return "Rotate"; } - /** - * @param string $sessionUUID - * @param Selection $selection - * @param null|int $changed - * @param SingleClipboard $clipboard - * @param string[] $messages - * @return Generator|Progress[] - * @throws Exception - */ - public function execute(string $sessionUUID, Selection $selection, ?int &$changed, SingleClipboard &$clipboard, array &$messages = []): Generator + /** + * @param string $sessionUUID + * @param Selection $selection + * @param null|int $changed + * @param SingleClipboard $clipboard + * @param string[] $messages + * @return Generator|Progress[] + * @throws Exception + */ + public function execute(string $sessionUUID, Selection $selection, ?int &$changed, SingleClipboard $clipboard, array &$messages = []): Generator { //TODO modify position. For now, just flip the blocks around their own axis $changed = 0; diff --git a/src/xenialdan/MagicWE2/task/action/SetBiomeAction.php b/src/xenialdan/MagicWE2/task/action/SetBiomeAction.php index 395e4042..afaf53bc 100644 --- a/src/xenialdan/MagicWE2/task/action/SetBiomeAction.php +++ b/src/xenialdan/MagicWE2/task/action/SetBiomeAction.php @@ -6,9 +6,9 @@ use Exception; use Generator; -use pocketmine\block\Block; use xenialdan\MagicWE2\clipboard\SingleClipboard; use xenialdan\MagicWE2\helper\AsyncChunkManager; +use xenialdan\MagicWE2\helper\BlockPalette; use xenialdan\MagicWE2\helper\Progress; use xenialdan\MagicWE2\selection\Selection; @@ -29,19 +29,19 @@ public static function getName(): string return "Set biome"; } - /** - * @param string $sessionUUID - * @param Selection $selection - * @param AsyncChunkManager $manager - * @param null|int $changed - * @param Block[] $newBlocks - * @param Block[] $blockFilter - * @param SingleClipboard $oldBlocksSingleClipboard blocks before the change - * @param string[] $messages - * @return Generator|Progress[] - * @throws Exception - */ - public function execute(string $sessionUUID, Selection $selection, AsyncChunkManager $manager, ?int &$changed, array $newBlocks, array $blockFilter, SingleClipboard $oldBlocksSingleClipboard, array &$messages = []): Generator + /** + * @param string $sessionUUID + * @param Selection $selection + * @param AsyncChunkManager $manager + * @param null|int $changed + * @param BlockPalette $newBlocks + * @param BlockPalette $blockFilter + * @param SingleClipboard $oldBlocksSingleClipboard blocks before the change + * @param string[] $messages + * @return Generator|Progress[] + * @throws Exception + */ + public function execute(string $sessionUUID, Selection $selection, AsyncChunkManager $manager, ?int &$changed, BlockPalette $newBlocks, BlockPalette $blockFilter, SingleClipboard $oldBlocksSingleClipboard, array &$messages = []): Generator { $changed = 0; #$oldBlocks = []; diff --git a/src/xenialdan/MagicWE2/task/action/SetBlockAction.php b/src/xenialdan/MagicWE2/task/action/SetBlockAction.php index 1d84af51..3413e7bb 100644 --- a/src/xenialdan/MagicWE2/task/action/SetBlockAction.php +++ b/src/xenialdan/MagicWE2/task/action/SetBlockAction.php @@ -10,6 +10,7 @@ use xenialdan\MagicWE2\clipboard\SingleClipboard; use xenialdan\MagicWE2\helper\AsyncChunkManager; use xenialdan\MagicWE2\helper\BlockEntry; +use xenialdan\MagicWE2\helper\BlockPalette; use xenialdan\MagicWE2\helper\Progress; use xenialdan\MagicWE2\selection\Selection; @@ -25,37 +26,38 @@ public static function getName(): string return "Set block"; } - /** - * @param string $sessionUUID - * @param Selection $selection - * @param AsyncChunkManager $manager - * @param null|int $changed - * @param Block[] $newBlocks - * @param Block[] $blockFilter - * @param SingleClipboard $oldBlocksSingleClipboard blocks before the change - * @param string[] $messages - * @return Generator|Progress[] - * @throws Exception - */ - public function execute(string $sessionUUID, Selection $selection, AsyncChunkManager $manager, ?int &$changed, array $newBlocks, array $blockFilter, SingleClipboard $oldBlocksSingleClipboard, array &$messages = []): Generator + /** + * @param string $sessionUUID + * @param Selection $selection + * @param AsyncChunkManager $manager + * @param null|int $changed + * @param BlockPalette $newBlocks + * @param BlockPalette $blockFilter + * @param SingleClipboard $oldBlocksSingleClipboard blocks before the change + * @param string[] $messages + * @return Generator|Progress[] + * @throws Exception + */ + public function execute(string $sessionUUID, Selection $selection, AsyncChunkManager $manager, ?int &$changed, BlockPalette $newBlocks, BlockPalette $blockFilter, SingleClipboard $oldBlocksSingleClipboard, array &$messages = []): Generator { $changed = 0; $i = 0; #$oldBlocks = []; $count = $selection->getShape()->getTotalCount(); $lastProgress = new Progress(0, ""); - foreach ($selection->getShape()->getBlocks($manager, $blockFilter) as $block) { - $new = clone $newBlocks[array_rand($newBlocks)]; + foreach ($selection->getShape()->getBlocks($manager, $blockFilter) as $block) {//TODO merge iterator + /** @var Block $new */ + $new = $newBlocks->blocks(1)->current();//TODO merge iterator if ($new->getId() === $block->getId() && $new->getMeta() === $block->getMeta()) continue;//skip same blocks #$oldBlocks[] = API::setComponents($manager->getBlockAt($block->getPos()->getFloorX(), $block->getPos()->getFloorY(), $block->getPos()->getFloorZ()),$block->x, $block->y, $block->z); - $oldBlocksSingleClipboard->addEntry($block->getPos()->getFloorX(), $block->getPos()->getFloorY(), $block->getPos()->getFloorZ(), BlockEntry::fromBlock($block)); - $manager->setBlockAt($block->getPos()->getFloorX(), $block->getPos()->getFloorY(), $block->getPos()->getFloorZ(), $new); - if ($manager->getBlockArrayAt($block->getPos()->getFloorX(), $block->getPos()->getFloorY(), $block->getPos()->getFloorZ()) !== [$block->getId(), $block->getMeta()]) { - $changed++; - } - $i++; - $progress = new Progress($i / $count, "Changed {$changed} blocks out of {$count}"); - if (floor($progress->progress * 100) > floor($lastProgress->progress * 100)) { + $oldBlocksSingleClipboard->addEntry($block->getPos()->getFloorX(), $block->getPos()->getFloorY(), $block->getPos()->getFloorZ(), BlockEntry::fromBlock($block)); + $manager->setBlockAt($block->getPos()->getFloorX(), $block->getPos()->getFloorY(), $block->getPos()->getFloorZ(), $new); + if ($manager->getBlockArrayAt($block->getPos()->getFloorX(), $block->getPos()->getFloorY(), $block->getPos()->getFloorZ()) !== [$block->getId(), $block->getMeta()]) { + $changed++; + } + $i++; + $progress = new Progress($i / $count, "Changed {$changed} blocks out of {$count}"); + if (floor($progress->progress * 100) > floor($lastProgress->progress * 100)) { yield $progress; $lastProgress = $progress; } diff --git a/src/xenialdan/MagicWE2/task/action/TaskAction.php b/src/xenialdan/MagicWE2/task/action/TaskAction.php index 20f83d54..08571715 100644 --- a/src/xenialdan/MagicWE2/task/action/TaskAction.php +++ b/src/xenialdan/MagicWE2/task/action/TaskAction.php @@ -5,10 +5,10 @@ namespace xenialdan\MagicWE2\task\action; use Generator; -use pocketmine\block\Block; use pocketmine\math\Vector3; use xenialdan\MagicWE2\clipboard\SingleClipboard; use xenialdan\MagicWE2\helper\AsyncChunkManager; +use xenialdan\MagicWE2\helper\BlockPalette; use xenialdan\MagicWE2\helper\Progress; use xenialdan\MagicWE2\selection\Selection; @@ -33,22 +33,22 @@ abstract class TaskAction * @param Selection $selection * @param AsyncChunkManager $manager * @param null|int $changed - * @param Block[] $newBlocks - * @param Block[] $blockFilter + * @param BlockPalette $newBlocks + * @param BlockPalette $blockFilter * @param SingleClipboard $oldBlocksSingleClipboard blocks before the change * @param string[] $messages - * @return Generator|Progress[] - */ - abstract public function execute(string $sessionUUID, Selection $selection, AsyncChunkManager $manager, ?int &$changed, array $newBlocks, array $blockFilter, SingleClipboard $oldBlocksSingleClipboard, array &$messages = []): Generator; + * @return Generator|Progress[] + */ + abstract public function execute(string $sessionUUID, Selection $selection, AsyncChunkManager $manager, ?int &$changed, BlockPalette $newBlocks, BlockPalette $blockFilter, SingleClipboard $oldBlocksSingleClipboard, array &$messages = []): Generator; abstract public static function getName(): string; - /** - * @param Vector3|null $clipboardVector - */ - public function setClipboardVector(?Vector3 $clipboardVector): void - { - if ($clipboardVector instanceof Vector3) $clipboardVector = $clipboardVector->asVector3()->floor(); - $this->clipboardVector = $clipboardVector; + /** + * @param Vector3|null $clipboardVector + */ + public function setClipboardVector(?Vector3 $clipboardVector): void + { + if ($clipboardVector instanceof Vector3) $clipboardVector = $clipboardVector->asVector3()->floor(); + $this->clipboardVector = $clipboardVector; } } \ No newline at end of file diff --git a/src/xenialdan/MagicWE2/task/action/TestAction.php b/src/xenialdan/MagicWE2/task/action/TestAction.php index 7d446503..6603dee4 100644 --- a/src/xenialdan/MagicWE2/task/action/TestAction.php +++ b/src/xenialdan/MagicWE2/task/action/TestAction.php @@ -6,10 +6,10 @@ use Exception; use Generator; -use pocketmine\block\Block; use pocketmine\block\BlockFactory; use xenialdan\MagicWE2\clipboard\SingleClipboard; use xenialdan\MagicWE2\helper\AsyncChunkManager; +use xenialdan\MagicWE2\helper\BlockPalette; use xenialdan\MagicWE2\helper\Progress; use xenialdan\MagicWE2\selection\Selection; @@ -29,26 +29,26 @@ public static function getName(): string return "Test"; } - /** - * @param string $sessionUUID - * @param Selection $selection - * @param AsyncChunkManager $manager - * @param null|int $changed - * @param Block[] $newBlocks - * @param Block[] $blockFilter - * @param SingleClipboard $oldBlocksSingleClipboard blocks before the change - * @param string[] $messages - * @return Generator|Progress[] - * @throws Exception - */ - public function execute(string $sessionUUID, Selection $selection, AsyncChunkManager $manager, ?int &$changed, array $newBlocks, array $blockFilter, SingleClipboard $oldBlocksSingleClipboard, array &$messages = []): Generator + /** + * @param string $sessionUUID + * @param Selection $selection + * @param AsyncChunkManager $manager + * @param null|int $changed + * @param BlockPalette $newBlocks + * @param BlockPalette $blockFilter + * @param SingleClipboard $oldBlocksSingleClipboard blocks before the change + * @param string[] $messages + * @return Generator|Progress[] + * @throws Exception + */ + public function execute(string $sessionUUID, Selection $selection, AsyncChunkManager $manager, ?int &$changed, BlockPalette $newBlocks, BlockPalette $blockFilter, SingleClipboard $oldBlocksSingleClipboard, array &$messages = []): Generator { $changed = 0; #$oldBlocks = []; $count = $selection->getShape()->getTotalCount(); $lastProgress = new Progress(0, ""); BlockFactory::getInstance(); - foreach ($selection->getShape()->getBlocks($manager, []) as $block) { + foreach ($selection->getShape()->getBlocks($manager, $blockFilter) as $block) { $changed++; $messages[] = $block->getPos()->asVector3()->__toString() . " " . $block->getName(); $progress = new Progress($changed / $count, "$changed/$count"); diff --git a/src/xenialdan/MagicWE2/task/action/ThawAction.php b/src/xenialdan/MagicWE2/task/action/ThawAction.php index 37c22f8e..fdb5d81c 100644 --- a/src/xenialdan/MagicWE2/task/action/ThawAction.php +++ b/src/xenialdan/MagicWE2/task/action/ThawAction.php @@ -6,11 +6,11 @@ use Exception; use Generator; -use pocketmine\block\Block; -use xenialdan\MagicWE2\API; +use pocketmine\block\VanillaBlocks; use xenialdan\MagicWE2\clipboard\SingleClipboard; use xenialdan\MagicWE2\helper\AsyncChunkManager; use xenialdan\MagicWE2\helper\BlockEntry; +use xenialdan\MagicWE2\helper\BlockPalette; use xenialdan\MagicWE2\helper\Progress; use xenialdan\MagicWE2\selection\Selection; @@ -26,34 +26,31 @@ public static function getName(): string return "Thaw"; } - /** + /** * @param string $sessionUUID * @param Selection $selection * @param AsyncChunkManager $manager * @param null|int $changed - * @param Block[] $newBlocks - * @param Block[] $blockFilter + * @param BlockPalette $newBlocks + * @param BlockPalette $blockFilter * @param SingleClipboard $oldBlocksSingleClipboard blocks before the change * @param string[] $messages * @return Generator|Progress[] * @throws Exception - * @noinspection SuspiciousAssignmentsInspection */ - public function execute(string $sessionUUID, Selection $selection, AsyncChunkManager $manager, ?int &$changed, array $newBlocks, array $blockFilter, SingleClipboard $oldBlocksSingleClipboard, array &$messages = []): Generator + public function execute(string $sessionUUID, Selection $selection, AsyncChunkManager $manager, ?int &$changed, BlockPalette $newBlocks, BlockPalette $blockFilter, SingleClipboard $oldBlocksSingleClipboard, array &$messages = []): Generator { $changed = 0; $i = 0; #$oldBlocks = []; $count = $selection->getShape()->getTotalCount(); - $lastProgress = new Progress(0, ""); + $lastProgress = new Progress(0, "Thaw action is still under TODO"); - $m = []; - $e = false; - $blockFilter = API::blockParser("snow_block,snow_layer,ice", $m, $e); - $newBlocks = API::blockParser("air,air,water", $m, $e); - foreach ($blockFilter as $ib => $blockF) { - foreach ($selection->getShape()->getBlocks($manager, [$blockF]) as $block) { - $new = clone $newBlocks[$ib]; + $blockFilterA = [VanillaBlocks::SNOW_LAYER(), VanillaBlocks::SNOW(), VanillaBlocks::ICE()]; + $newBlocksA = [VanillaBlocks::AIR(), VanillaBlocks::AIR(), VanillaBlocks::WATER()]; + foreach ($blockFilterA as $ib => $blockF) { + foreach ($selection->getShape()->getBlocks($manager, BlockPalette::CREATE()) as $block) {//TODO merged generator iterating blocks and newblocks + $new = clone $newBlocksA[$ib]; #$oldBlocks[] = API::setComponents($manager->getBlockAt($block->getPos()->getFloorX(), $block->getPos()->getFloorY(), $block->getPos()->getFloorZ()),$block->x, $block->y, $block->z); $oldBlocksSingleClipboard->addEntry($block->getPos()->getFloorX(), $block->getPos()->getFloorY(), $block->getPos()->getFloorZ(), BlockEntry::fromBlock($block)); $manager->setBlockAt($block->getPos()->getFloorX(), $block->getPos()->getFloorY(), $block->getPos()->getFloorZ(), $new); diff --git a/src/xenialdan/MagicWE2/tool/Brush.php b/src/xenialdan/MagicWE2/tool/Brush.php index 9bfe3d38..ef9d2cc6 100644 --- a/src/xenialdan/MagicWE2/tool/Brush.php +++ b/src/xenialdan/MagicWE2/tool/Brush.php @@ -30,6 +30,7 @@ use xenialdan\MagicWE2\exception\ActionNotFoundException; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\exception\ShapeNotFoundException; +use xenialdan\MagicWE2\helper\BlockPalette; use xenialdan\MagicWE2\helper\SessionHelper; use xenialdan\MagicWE2\Loader; use xenialdan\MagicWE2\selection\shape\ShapeRegistry; @@ -170,20 +171,14 @@ public function getForm(bool $new = true, array $errors = []): CustomForm //error checks $error = []; try { - $m = []; - $e = false; - API::blockParser($blocks, $m, $e); - if ($e) throw new InvalidArgumentException(implode(TF::EOL, $m)); - if (empty($blocks)) throw new AssumptionFailedError("Blocks cannot be empty!"); + $p = BlockPalette::fromString($blocks); + if ($p->empty()) throw new AssumptionFailedError("Blocks cannot be empty!"); } catch (Exception $ex) { $error['blocks'] = $ex->getMessage(); } try { - $m = []; - $e = false; - API::blockParser($filter, $m, $e); - if ($e) throw new InvalidArgumentException(implode(TF::EOL, $m)); - } catch (Exception $ex) { + BlockPalette::fromString($filter); + } catch (Exception $ex) { $error['filter'] = $ex->getMessage(); } try { diff --git a/src/xenialdan/MagicWE2/tool/Flood.php b/src/xenialdan/MagicWE2/tool/Flood.php index c6ba3104..5bfd3d7f 100644 --- a/src/xenialdan/MagicWE2/tool/Flood.php +++ b/src/xenialdan/MagicWE2/tool/Flood.php @@ -14,6 +14,7 @@ use pocketmine\world\World; use xenialdan\MagicWE2\API; use xenialdan\MagicWE2\helper\AsyncChunkManager; +use xenialdan\MagicWE2\helper\BlockPalette; class Flood extends WETool { @@ -38,12 +39,12 @@ public function __construct(int $limit) /** * Returns the blocks by their actual position * @param World|AsyncChunkManager $manager The world or AsyncChunkManager - * @param Block[] $filterblocks If not empty, applying a filter on the block list + * @param BlockPalette $filterblocks If not empty, applying a filter on the block list * @param int $flags * @return Generator|Block[] * @throws Exception */ - public function getBlocks($manager, array $filterblocks = [], int $flags = API::FLAG_BASE): Generator + public function getBlocks($manager, BlockPalette $filterblocks, int $flags = API::FLAG_BASE): Generator { $this->validateChunkManager($manager); $this->y = $this->getCenter()->getFloorY(); @@ -66,7 +67,7 @@ public function getBlocks($manager, array $filterblocks = [], int $flags = API:: public function getLayer($manager, int $flags = API::FLAG_BASE): Generator { $this->validateChunkManager($manager); - foreach ($this->getBlocks($manager, []) as $block) { + foreach ($this->getBlocks($manager, BlockPalette::CREATE()) as $block) { yield new Vector2($block->getPos()->x, $block->getPos()->z); } } From ae3500d186f760a1ac18a8da644b2c768f487896 Mon Sep 17 00:00:00 2001 From: XenialDan Date: Fri, 25 Dec 2020 16:09:58 +0100 Subject: [PATCH 03/67] Use regex to reduce server load when parsing commands --- .../MagicWE2/commands/args/BlocksArgument.php | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/src/xenialdan/MagicWE2/commands/args/BlocksArgument.php b/src/xenialdan/MagicWE2/commands/args/BlocksArgument.php index cb7ec85d..d01cbb8b 100644 --- a/src/xenialdan/MagicWE2/commands/args/BlocksArgument.php +++ b/src/xenialdan/MagicWE2/commands/args/BlocksArgument.php @@ -5,9 +5,7 @@ namespace xenialdan\MagicWE2\commands\args; use CortexPE\Commando\args\RawStringArgument; -use InvalidArgumentException; use pocketmine\command\CommandSender; -use xenialdan\MagicWE2\exception\BlockQueryAlreadyParsedException; use xenialdan\MagicWE2\helper\BlockPalette; class BlocksArgument extends RawStringArgument @@ -16,13 +14,10 @@ class BlocksArgument extends RawStringArgument public function canParse(string $testString, CommandSender $sender): bool { //TODO optimize; TODO check if returning false here triggers argument being passed to another $arg - try { - //TODO if regex match '/,(?![^\[]*])/' return true - BlockPalette::fromString($testString); - } catch (BlockQueryAlreadyParsedException | InvalidArgumentException $e) { - return false; - } - return true; + //TODO if regex match '/,(?![^\[]*])/' return true + $pattern = '/[\w:]+(?:\[[\w=,]*])?%?\d*/'; + $r = preg_match_all($pattern, $testString); + return $r !== false && $r >= 1; } /** From 51be9778966184dee42d3c0ef668344199199654 Mon Sep 17 00:00:00 2001 From: XenialDan Date: Fri, 25 Dec 2020 16:25:53 +0100 Subject: [PATCH 04/67] Remove unused leftovers --- .../commands/generation/CylinderCommand.php | 35 ++++------ .../commands/region/OverlayCommand.php | 68 ++++++++----------- .../commands/region/ReplaceCommand.php | 68 ++++++++----------- .../MagicWE2/commands/region/SetCommand.php | 67 ++++++++---------- 4 files changed, 100 insertions(+), 138 deletions(-) diff --git a/src/xenialdan/MagicWE2/commands/generation/CylinderCommand.php b/src/xenialdan/MagicWE2/commands/generation/CylinderCommand.php index 1b6ed008..500b49cc 100644 --- a/src/xenialdan/MagicWE2/commands/generation/CylinderCommand.php +++ b/src/xenialdan/MagicWE2/commands/generation/CylinderCommand.php @@ -54,32 +54,23 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo } } if (!$sender instanceof Player) { - $sender->sendMessage(TF::RED . $lang->translateString('error.runingame')); - return; - } - /** @var Player $sender */ - try { - $messages = []; - $error = false; + $sender->sendMessage(TF::RED . $lang->translateString('error.runingame')); + return; + } + /** @var Player $sender */ + try { $blocks = $args["blocks"]; $diameter = (int)$args["diameter"]; $height = (int)($args["height"] ?? 1); - foreach ($messages as $message) { - $sender->sendMessage($message); - } - if (!$error) { - $session = SessionHelper::getUserSession($sender); - if (is_null($session)) { - throw new SessionException($lang->translateString('error.nosession', [Loader::getInstance()->getName()])); - } - $cyl = new Cylinder($sender->getPosition()->asVector3()->floor(), $height, $diameter); - $cylSelection = new Selection($session->getUUID(), $sender->getWorld()); - $cylSelection->setShape($cyl); - $hasFlags = isset($args["flags"]); - API::fillAsync($cylSelection, $session, $blocks, $hasFlags ? API::flagParser(explode(" ", (string)$args["flags"])) : API::FLAG_BASE); - } else { - throw new InvalidArgumentException("Could not fill with the selected blocks"); + $session = SessionHelper::getUserSession($sender); + if (is_null($session)) { + throw new SessionException($lang->translateString('error.nosession', [Loader::getInstance()->getName()])); } + $cyl = new Cylinder($sender->getPosition()->asVector3()->floor(), $height, $diameter); + $cylSelection = new Selection($session->getUUID(), $sender->getWorld()); + $cylSelection->setShape($cyl); + $hasFlags = isset($args["flags"]); + API::fillAsync($cylSelection, $session, $blocks, $hasFlags ? API::flagParser(explode(" ", (string)$args["flags"])) : API::FLAG_BASE); } catch (Exception $error) { $sender->sendMessage(Loader::PREFIX . TF::RED . $lang->translateString('error.command-error')); $sender->sendMessage(Loader::PREFIX . TF::RED . $error->getMessage()); diff --git a/src/xenialdan/MagicWE2/commands/region/OverlayCommand.php b/src/xenialdan/MagicWE2/commands/region/OverlayCommand.php index 248143a1..a8069582 100644 --- a/src/xenialdan/MagicWE2/commands/region/OverlayCommand.php +++ b/src/xenialdan/MagicWE2/commands/region/OverlayCommand.php @@ -36,47 +36,37 @@ protected function prepare(): void * @param string $aliasUsed * @param mixed[] $args */ - public function onRun(CommandSender $sender, string $aliasUsed, array $args): void - { - $lang = Loader::getInstance()->getLanguage(); - if ($sender instanceof Player && SessionHelper::hasSession($sender)) { - try { - $lang = SessionHelper::getUserSession($sender)->getLanguage(); - } catch (SessionException $e) { - } - } - if (!$sender instanceof Player) { - $sender->sendMessage(TF::RED . $lang->translateString('error.runingame')); - return; - } - /** @var Player $sender */ - try { - $messages = []; - $error = false; - $blocks = $args["blocks"]; - foreach ($messages as $message) { - $sender->sendMessage($message); + public function onRun(CommandSender $sender, string $aliasUsed, array $args): void + { + $lang = Loader::getInstance()->getLanguage(); + if ($sender instanceof Player && SessionHelper::hasSession($sender)) { + try { + $lang = SessionHelper::getUserSession($sender)->getLanguage(); + } catch (SessionException $e) { + } + } + if (!$sender instanceof Player) { + $sender->sendMessage(TF::RED . $lang->translateString('error.runingame')); + return; + } + /** @var Player $sender */ + try { + //$blocks = $args["blocks"];//TODO reenable when used + $session = SessionHelper::getUserSession($sender); + if (is_null($session)) { + throw new SessionException($lang->translateString('error.nosession', [Loader::getInstance()->getName()])); + } + $selection = $session->getLatestSelection(); + if (is_null($selection)) { + throw new SelectionException($lang->translateString('error.noselection')); + } + if (!$selection->isValid()) { + throw new SelectionException($lang->translateString('error.selectioninvalid')); } - $return = !$error; - if ($return) { - $session = SessionHelper::getUserSession($sender); - if (is_null($session)) { - throw new SessionException($lang->translateString('error.nosession', [Loader::getInstance()->getName()])); - } - $selection = $session->getLatestSelection(); - if (is_null($selection)) { - throw new SelectionException($lang->translateString('error.noselection')); - } - if (!$selection->isValid()) { - throw new SelectionException($lang->translateString('error.selectioninvalid')); - } - if ($selection->getWorld() !== $sender->getWorld()) { - $sender->sendMessage(Loader::PREFIX . TF::GOLD . $lang->translateString('warning.differentworld')); - } - #API::overlayReplaceAsync($selection, $session, [], $blocks, API::flagParser(explode(" ", strval($args["flags"])))); - } else { - throw new InvalidArgumentException("Could not replace with the selected blocks"); + if ($selection->getWorld() !== $sender->getWorld()) { + $sender->sendMessage(Loader::PREFIX . TF::GOLD . $lang->translateString('warning.differentworld')); } + #API::overlayReplaceAsync($selection, $session, [], $blocks, API::flagParser(explode(" ", strval($args["flags"])))); } catch (Exception $error) { $sender->sendMessage(Loader::PREFIX . TF::RED . $lang->translateString('error.command-error')); $sender->sendMessage(Loader::PREFIX . TF::RED . $error->getMessage()); diff --git a/src/xenialdan/MagicWE2/commands/region/ReplaceCommand.php b/src/xenialdan/MagicWE2/commands/region/ReplaceCommand.php index f19ffaa6..bac9bf73 100644 --- a/src/xenialdan/MagicWE2/commands/region/ReplaceCommand.php +++ b/src/xenialdan/MagicWE2/commands/region/ReplaceCommand.php @@ -40,49 +40,39 @@ protected function prepare(): void * @param string $aliasUsed * @param mixed[] $args */ - public function onRun(CommandSender $sender, string $aliasUsed, array $args): void - { - $lang = Loader::getInstance()->getLanguage(); - if ($sender instanceof Player && SessionHelper::hasSession($sender)) { - try { - $lang = SessionHelper::getUserSession($sender)->getLanguage(); - } catch (SessionException $e) { - } - } - if (!$sender instanceof Player) { - $sender->sendMessage(TF::RED . $lang->translateString('error.runingame')); - return; - } - /** @var Player $sender */ - try { - $messages = []; - $error = false; + public function onRun(CommandSender $sender, string $aliasUsed, array $args): void + { + $lang = Loader::getInstance()->getLanguage(); + if ($sender instanceof Player && SessionHelper::hasSession($sender)) { + try { + $lang = SessionHelper::getUserSession($sender)->getLanguage(); + } catch (SessionException $e) { + } + } + if (!$sender instanceof Player) { + $sender->sendMessage(TF::RED . $lang->translateString('error.runingame')); + return; + } + /** @var Player $sender */ + try { $findBlocks = $args["findblocks"]; $replaceBlocks = $args["replaceblocks"]; - foreach ($messages as $message) { - $sender->sendMessage($message); + $session = SessionHelper::getUserSession($sender); + if (is_null($session)) { + throw new SessionException($lang->translateString('error.nosession', [Loader::getInstance()->getName()])); + } + $selection = $session->getLatestSelection(); + if (is_null($selection)) { + throw new SelectionException($lang->translateString('error.noselection')); + } + if (!$selection->isValid()) { + throw new SelectionException($lang->translateString('error.selectioninvalid')); } - $return = !$error; - if ($return) { - $session = SessionHelper::getUserSession($sender); - if (is_null($session)) { - throw new SessionException($lang->translateString('error.nosession', [Loader::getInstance()->getName()])); - } - $selection = $session->getLatestSelection(); - if (is_null($selection)) { - throw new SelectionException($lang->translateString('error.noselection')); - } - if (!$selection->isValid()) { - throw new SelectionException($lang->translateString('error.selectioninvalid')); - } - if ($selection->getWorld() !== $sender->getWorld()) { - $sender->sendMessage(Loader::PREFIX . TF::GOLD . $lang->translateString('warning.differentworld')); - } - $hasFlags = isset($args["flags"]); - API::replaceAsync($selection, $session, $findBlocks, $replaceBlocks, $hasFlags ? API::flagParser(explode(" ", (string)$args["flags"])) : API::FLAG_BASE); - } else { - throw new InvalidArgumentException("Could not replace with the selected blocks"); + if ($selection->getWorld() !== $sender->getWorld()) { + $sender->sendMessage(Loader::PREFIX . TF::GOLD . $lang->translateString('warning.differentworld')); } + $hasFlags = isset($args["flags"]); + API::replaceAsync($selection, $session, $findBlocks, $replaceBlocks, $hasFlags ? API::flagParser(explode(" ", (string)$args["flags"])) : API::FLAG_BASE); } catch (Exception $error) { $sender->sendMessage(Loader::PREFIX . TF::RED . $lang->translateString('error.command-error')); $sender->sendMessage(Loader::PREFIX . TF::RED . $error->getMessage()); diff --git a/src/xenialdan/MagicWE2/commands/region/SetCommand.php b/src/xenialdan/MagicWE2/commands/region/SetCommand.php index 380f0ee1..bca8b276 100644 --- a/src/xenialdan/MagicWE2/commands/region/SetCommand.php +++ b/src/xenialdan/MagicWE2/commands/region/SetCommand.php @@ -39,47 +39,38 @@ protected function prepare(): void * @param string $aliasUsed * @param mixed[] $args */ - public function onRun(CommandSender $sender, string $aliasUsed, array $args): void - { - $lang = Loader::getInstance()->getLanguage(); - if ($sender instanceof Player && SessionHelper::hasSession($sender)) { - try { - $lang = SessionHelper::getUserSession($sender)->getLanguage(); - } catch (SessionException $e) { - } - } - if (!$sender instanceof Player) { - $sender->sendMessage(TF::RED . $lang->translateString('error.runingame')); - return; - } - /** @var Player $sender */ - try { - $messages = []; - $error = false; + public function onRun(CommandSender $sender, string $aliasUsed, array $args): void + { + $lang = Loader::getInstance()->getLanguage(); + if ($sender instanceof Player && SessionHelper::hasSession($sender)) { + try { + $lang = SessionHelper::getUserSession($sender)->getLanguage(); + } catch (SessionException $e) { + } + } + if (!$sender instanceof Player) { + $sender->sendMessage(TF::RED . $lang->translateString('error.runingame')); + return; + } + /** @var Player $sender */ + try { $replaceBlocks = $args["blocks"]; - foreach ($messages as $message) { - $sender->sendMessage($message); + $session = SessionHelper::getUserSession($sender); + if (is_null($session)) { + throw new SessionException($lang->translateString('error.nosession', [Loader::getInstance()->getName()])); + } + $selection = $session->getLatestSelection(); + if (is_null($selection)) { + throw new SelectionException($lang->translateString('error.noselection')); + } + if (!$selection->isValid()) { + throw new SelectionException($lang->translateString('error.selectioninvalid')); } - if (!$error) { - $session = SessionHelper::getUserSession($sender); - if (is_null($session)) { - throw new SessionException($lang->translateString('error.nosession', [Loader::getInstance()->getName()])); - } - $selection = $session->getLatestSelection(); - if (is_null($selection)) { - throw new SelectionException($lang->translateString('error.noselection')); - } - if (!$selection->isValid()) { - throw new SelectionException($lang->translateString('error.selectioninvalid')); - } - if ($selection->getWorld() !== $sender->getWorld()) { - $sender->sendMessage(Loader::PREFIX . TF::GOLD . $lang->translateString('warning.differentworld')); - } - $hasFlags = isset($args["flags"]); - API::fillAsync($selection, $session, $replaceBlocks, $hasFlags ? API::flagParser(explode(" ", (string)$args["flags"])) : API::FLAG_BASE); - } else { - throw new InvalidArgumentException("Could not fill with the selected blocks"); + if ($selection->getWorld() !== $sender->getWorld()) { + $sender->sendMessage(Loader::PREFIX . TF::GOLD . $lang->translateString('warning.differentworld')); } + $hasFlags = isset($args["flags"]); + API::fillAsync($selection, $session, $replaceBlocks, $hasFlags ? API::flagParser(explode(" ", (string)$args["flags"])) : API::FLAG_BASE); } catch (Exception $error) { $sender->sendMessage(Loader::PREFIX . TF::RED . $lang->translateString('error.command-error')); $sender->sendMessage(Loader::PREFIX . TF::RED . $error->getMessage()); From 7292315181050d65a788cd329327677f168120ec Mon Sep 17 00:00:00 2001 From: XenialDan Date: Fri, 25 Dec 2020 16:35:01 +0100 Subject: [PATCH 05/67] =?UTF-8?q?=F0=9F=86=97=20phpstan,=20as=20you=20wish?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../commands/selection/info/CountCommand.php | 81 +++++++++---------- .../MagicWE2/helper/BlockPalette.php | 6 +- .../MagicWE2/helper/BlockStatesParser.php | 2 +- 3 files changed, 42 insertions(+), 47 deletions(-) diff --git a/src/xenialdan/MagicWE2/commands/selection/info/CountCommand.php b/src/xenialdan/MagicWE2/commands/selection/info/CountCommand.php index 71c313b1..ba220907 100644 --- a/src/xenialdan/MagicWE2/commands/selection/info/CountCommand.php +++ b/src/xenialdan/MagicWE2/commands/selection/info/CountCommand.php @@ -42,53 +42,48 @@ protected function prepare(): void * @param string $aliasUsed * @param mixed[] $args */ - public function onRun(CommandSender $sender, string $aliasUsed, array $args): void - { - $lang = Loader::getInstance()->getLanguage(); - if ($sender instanceof Player && SessionHelper::hasSession($sender)) { - try { - $lang = SessionHelper::getUserSession($sender)->getLanguage(); - } catch (SessionException $e) { - } - } - if (!$sender instanceof Player) { - $sender->sendMessage(TF::RED . $lang->translateString('error.runingame')); - return; - } - /** @var Player $sender */ - try { - $error = false; + public function onRun(CommandSender $sender, string $aliasUsed, array $args): void + { + $lang = Loader::getInstance()->getLanguage(); + if ($sender instanceof Player && SessionHelper::hasSession($sender)) { + try { + $lang = SessionHelper::getUserSession($sender)->getLanguage(); + } catch (SessionException $e) { + } + } + if (!$sender instanceof Player) { + $sender->sendMessage(TF::RED . $lang->translateString('error.runingame')); + return; + } + /** @var Player $sender */ + try { if (isset($args["blocks"])) { $filterBlocks = $args["blocks"]; } else $filterBlocks = BlockPalette::CREATE(); - if (!$error) { - $session = SessionHelper::getUserSession($sender); - if (is_null($session)) { - throw new SessionException($lang->translateString('error.nosession', [Loader::getInstance()->getName()])); - } - $selection = $session->getLatestSelection(); - if (is_null($selection)) { - throw new SelectionException($lang->translateString('error.noselection')); - } - if (!$selection->isValid()) { - throw new SelectionException($lang->translateString('error.selectioninvalid')); - } - if ($selection->getWorld() !== $sender->getWorld()) { - $session->sendMessage(TF::GOLD . $lang->translateString('warning.differentworld')); - } - Server::getInstance()->getAsyncPool()->submitTask( - new AsyncActionTask( - $session->getUUID(), - $selection, - new CountAction(), - $selection->getShape()->getTouchedChunks($selection->getWorld()), - BlockPalette::CREATE(), - $filterBlocks - ) - ); - } else { - throw new InvalidArgumentException("Could not count the selected blocks"); + $session = SessionHelper::getUserSession($sender); + if (is_null($session)) { + throw new SessionException($lang->translateString('error.nosession', [Loader::getInstance()->getName()])); + } + $selection = $session->getLatestSelection(); + if (is_null($selection)) { + throw new SelectionException($lang->translateString('error.noselection')); + } + if (!$selection->isValid()) { + throw new SelectionException($lang->translateString('error.selectioninvalid')); + } + if ($selection->getWorld() !== $sender->getWorld()) { + $session->sendMessage(TF::GOLD . $lang->translateString('warning.differentworld')); } + Server::getInstance()->getAsyncPool()->submitTask( + new AsyncActionTask( + $session->getUUID(), + $selection, + new CountAction(), + $selection->getShape()->getTouchedChunks($selection->getWorld()), + BlockPalette::CREATE(), + $filterBlocks + ) + ); } catch (Exception $error) { $sender->sendMessage(Loader::PREFIX . TF::RED . $lang->translateString('error.command-error')); $sender->sendMessage(Loader::PREFIX . TF::RED . $error->getMessage()); diff --git a/src/xenialdan/MagicWE2/helper/BlockPalette.php b/src/xenialdan/MagicWE2/helper/BlockPalette.php index ae65d428..cd6ebe79 100644 --- a/src/xenialdan/MagicWE2/helper/BlockPalette.php +++ b/src/xenialdan/MagicWE2/helper/BlockPalette.php @@ -32,11 +32,11 @@ public function __construct(string $name = "") /** * @param string $blocksQuery - * @return static + * @return BlockPalette * @throws InvalidArgumentException * @throws BlockQueryAlreadyParsedException */ - public static function fromString(string $blocksQuery): self + public static function fromString(string $blocksQuery): BlockPalette { $palette = self::CREATE(); @@ -56,7 +56,7 @@ public static function fromString(string $blocksQuery): self return $palette; } - public function addBlockQuery(BlockQuery $query) + public function addBlockQuery(BlockQuery $query): void { $this->randomBlockQueries->add($query, $query->weight); } diff --git a/src/xenialdan/MagicWE2/helper/BlockStatesParser.php b/src/xenialdan/MagicWE2/helper/BlockStatesParser.php index 5038defb..088b2a26 100644 --- a/src/xenialdan/MagicWE2/helper/BlockStatesParser.php +++ b/src/xenialdan/MagicWE2/helper/BlockStatesParser.php @@ -276,7 +276,7 @@ public static function fromString(BlockQuery $query): Block $blocks[] = $block; } } - if (empty($blocks) && !$block instanceof Block) throw new InvalidArgumentException("No block $namespacedSelectedBlockName matching $query->query could be found");//no block found //TODO r12 map only has blocks up to id 255. On 4.0.0, return Item::fromString()? + if (count($blocks) < 1) throw new InvalidArgumentException("No block $namespacedSelectedBlockName matching $query->query could be found");//no block found //TODO r12 map only has blocks up to id 255. On 4.0.0, return Item::fromString()? if (count($blocks) === 1) { $block = $blocks[0]; $query->blockFullId = $block->getFullId(); From f5f13921850f4f73412f4edb070e2a4b278c1d06 Mon Sep 17 00:00:00 2001 From: XenialDan Date: Sat, 13 Feb 2021 01:09:34 +0100 Subject: [PATCH 06/67] Add PHP8.0 support --- .poggit.yml | 8 ++++---- plugin.yml | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/.poggit.yml b/.poggit.yml index 60589a8d..efee4424 100644 --- a/.poggit.yml +++ b/.poggit.yml @@ -11,21 +11,21 @@ projects: phpstan: false libs: - src: BlockHorizons/libschematic/libschematic - version: ^2.0.0 + version: ^2.0.1 - src: thebigsmilexd/customui/customui version: ^4.0.0 branch: PM4 - src: thebigsmilexd/apibossbar/apibossbar - version: ^0.1.3 + version: ^0.1.4 branch: PM4 - src: CortexPE/Commando/Commando version: ^3.0.0 branch: PM4 - src: muqsit/invmenu/InvMenu - version: ^4.0.1 + version: ^4.1.0 branch: "4.0" - src: thebigsmilexd/libstructure/libstructure - version: ^0.1.1 + version: ^0.1.2 branch: mcstructure - src: buchwasa/ScoreFactory/ScoreFactory version: ^3.0.1 diff --git a/plugin.yml b/plugin.yml index 248563a9..da583228 100644 --- a/plugin.yml +++ b/plugin.yml @@ -1,9 +1,9 @@ --- name: MagicWE2 main: xenialdan\MagicWE2\Loader -version: 10.1.2 +version: 10.1.3 api: ["4.0.0"] -php: "7.4" +php: [ "7.4", "8.0" ] authors: - XenialDan description: Lag free asynchronous world editor for PMMP with plenty of options From ded5dadd35e596c3e54010b2ea7a27c3dd8427d1 Mon Sep 17 00:00:00 2001 From: XenialDan Date: Sat, 13 Feb 2021 18:47:02 +0100 Subject: [PATCH 07/67] Schematics, Structures and exported Clipboards: unified as "Assets" - Bumped version to 10.1.4, see #221 - plugin_data/structures & plugin_data/schematics folders got merged into plugin_data/assets - Added AssetCommand for handling assets. Still under TODO - Added AssetCollection to cache assets - For now, just dump Asset items to console - vecToString and boolToString moved to API - Added TAG_MAGIC_WE_ASSET to API - UserSession brushes are now saved in a Map - Load schematics and mcstructure in one code block - Code reformat on whole project --- plugin.yml | 3 +- src/xenialdan/MagicWE2/API.php | 11 + src/xenialdan/MagicWE2/EventListener.php | 30 +- src/xenialdan/MagicWE2/Loader.php | 38 +- .../MagicWE2/clipboard/Clipboard.php | 50 +-- .../MagicWE2/clipboard/RevertClipboard.php | 14 +- .../MagicWE2/clipboard/SingleClipboard.php | 42 +-- .../MagicWE2/commands/DonateCommand.php | 28 +- .../MagicWE2/commands/HelpCommand.php | 36 +- .../MagicWE2/commands/InfoCommand.php | 20 +- .../MagicWE2/commands/LanguageCommand.php | 52 +-- .../MagicWE2/commands/LimitCommand.php | 24 +- .../MagicWE2/commands/ReportCommand.php | 20 +- .../MagicWE2/commands/SetRangeCommand.php | 24 +- .../MagicWE2/commands/TestCommand.php | 4 +- .../MagicWE2/commands/VersionCommand.php | 12 +- .../commands/args/LanguageArgument.php | 8 +- .../commands/args/MirrorAxisArgument.php | 2 +- .../commands/args/RotateAngleArgument.php | 4 +- .../commands/biome/BiomeInfoCommand.php | 100 ++--- .../commands/biome/BiomeListCommand.php | 26 +- .../commands/biome/SetBiomeCommand.php | 36 +- .../MagicWE2/commands/brush/BrushCommand.php | 129 +++---- .../clipboard/ClearClipboardCommand.php | 32 +- .../commands/clipboard/CopyCommand.php | 38 +- .../commands/clipboard/Cut2Command.php | 58 +-- .../commands/clipboard/CutCommand.php | 40 +- .../commands/clipboard/FlipCommand.php | 40 +- .../commands/clipboard/PasteCommand.php | 18 +- .../commands/clipboard/RotateCommand.php | 36 +- .../debug/PlaceAllBlockstatesCommand.php | 22 +- .../commands/history/ClearhistoryCommand.php | 32 +- .../MagicWE2/commands/history/RedoCommand.php | 30 +- .../MagicWE2/commands/history/UndoCommand.php | 31 +- .../commands/selection/HPos1Command.php | 74 ++-- .../commands/selection/HPos2Command.php | 74 ++-- .../commands/selection/Pos1Command.php | 64 ++-- .../commands/selection/Pos2Command.php | 64 ++-- .../selection/info/ListChunksCommand.php | 56 +-- .../commands/selection/info/SizeCommand.php | 46 +-- .../MagicWE2/commands/tool/DebugCommand.php | 46 +-- .../MagicWE2/commands/tool/FloodCommand.php | 82 ++-- .../commands/tool/ToggledebugCommand.php | 30 +- .../commands/tool/TogglewandCommand.php | 30 +- .../MagicWE2/commands/tool/WandCommand.php | 46 +-- .../commands/utility/CalculateCommand.php | 18 +- src/xenialdan/MagicWE2/event/MWEEditEvent.php | 86 ++--- .../event/MWESelectionChangeEvent.php | 16 +- .../MagicWE2/helper/AsyncChunkManager.php | 16 +- src/xenialdan/MagicWE2/helper/BlockQuery.php | 2 +- src/xenialdan/MagicWE2/helper/Progress.php | 10 +- src/xenialdan/MagicWE2/helper/Scoreboard.php | 25 +- .../MagicWE2/helper/StructureStore.php | 8 +- .../MagicWE2/selection/shape/Cube.php | 68 ++-- .../MagicWE2/selection/shape/Cuboid.php | 84 ++--- .../MagicWE2/selection/shape/Cylinder.php | 72 ++-- .../MagicWE2/selection/shape/Ellipsoid.php | 114 +++--- .../MagicWE2/selection/shape/Pyramid.php | 82 ++-- .../MagicWE2/selection/shape/Shape.php | 126 +++---- .../selection/shape/ShapeRegistry.php | 94 ++--- .../MagicWE2/session/PluginSession.php | 42 +-- src/xenialdan/MagicWE2/session/Session.php | 352 +++++++++--------- .../MagicWE2/session/UserSession.php | 13 +- src/xenialdan/MagicWE2/session/data/Asset.php | 129 +++++++ .../MagicWE2/session/data/AssetCollection.php | 72 ++++ src/xenialdan/MagicWE2/session/data/TODO.md | 5 + .../MagicWE2/task/AsyncActionTask.php | 54 +-- .../task/AsyncClipboardActionTask.php | 20 +- src/xenialdan/MagicWE2/task/AsyncCopyTask.php | 58 +-- .../MagicWE2/task/AsyncCountTask.php | 20 +- .../MagicWE2/task/AsyncReplaceTask.php | 14 +- .../MagicWE2/task/AsyncRevertTask.php | 38 +- .../MagicWE2/task/action/ActionRegistry.php | 78 ++-- .../MagicWE2/task/action/CountAction.php | 16 +- .../MagicWE2/task/action/CutAction.php | 6 +- .../MagicWE2/task/action/FlipAction.php | 72 ++-- .../MagicWE2/task/action/RotateAction.php | 4 +- .../MagicWE2/task/action/SetBiomeAction.php | 12 +- .../MagicWE2/task/action/SetBlockAction.php | 24 +- .../MagicWE2/task/action/TaskAction.php | 2 +- .../MagicWE2/task/action/ThawAction.php | 18 +- src/xenialdan/MagicWE2/tool/Brush.php | 213 ++++++----- .../MagicWE2/tool/BrushProperties.php | 154 ++++---- src/xenialdan/MagicWE2/tool/WETool.php | 2 +- 84 files changed, 2079 insertions(+), 1862 deletions(-) create mode 100644 src/xenialdan/MagicWE2/session/data/Asset.php create mode 100644 src/xenialdan/MagicWE2/session/data/AssetCollection.php create mode 100644 src/xenialdan/MagicWE2/session/data/TODO.md diff --git a/plugin.yml b/plugin.yml index da583228..77b3e85f 100644 --- a/plugin.yml +++ b/plugin.yml @@ -1,9 +1,10 @@ --- name: MagicWE2 main: xenialdan\MagicWE2\Loader -version: 10.1.3 +version: 10.1.4 api: ["4.0.0"] php: [ "7.4", "8.0" ] +softdepend: [ "DEVirion" ] authors: - XenialDan description: Lag free asynchronous world editor for PMMP with plenty of options diff --git a/src/xenialdan/MagicWE2/API.php b/src/xenialdan/MagicWE2/API.php index f8b14a33..5ac3eca8 100644 --- a/src/xenialdan/MagicWE2/API.php +++ b/src/xenialdan/MagicWE2/API.php @@ -70,6 +70,7 @@ class API public const TAG_MAGIC_WE = "MagicWE"; public const TAG_MAGIC_WE_BRUSH = "MagicWEBrush"; + public const TAG_MAGIC_WE_ASSET = "MagicWEAsset"; //TODO Split into separate Class (SchematicStorage?) /** @var Clipboard[] */ @@ -529,4 +530,14 @@ public static function setComponents(Block $block, int $x, int $y, int $z): Bloc [$block->getPos()->x, $block->getPos()->y, $block->getPos()->z] = [$x, $y, $z]; return $block; } + + public static function vecToString(Vector3 $v): string + { + return TF::RESET . "[" . TF::RED . $v->getFloorX() . TF::RESET . ":" . TF::GREEN . $v->getFloorY() . TF::RESET . ":" . TF::BLUE . $v->getFloorZ() . TF::RESET . "]"; + } + + public static function boolToString(bool $b): string + { + return $b ? TF::RESET . TF::GREEN . "On" . TF::RESET : TF::RESET . TF::RED . "Off" . TF::RESET; + } } \ No newline at end of file diff --git a/src/xenialdan/MagicWE2/EventListener.php b/src/xenialdan/MagicWE2/EventListener.php index 2e5e9846..513f3a81 100644 --- a/src/xenialdan/MagicWE2/EventListener.php +++ b/src/xenialdan/MagicWE2/EventListener.php @@ -67,8 +67,8 @@ public function onSessionLoad(MWESessionLoadEvent $event): void if (Loader::hasScoreboard()) { try { if (($session = $event->getSession()) instanceof UserSession && $session->isSidebarEnabled()) - /** @var UserSession $session */ - $session->sidebar->handleScoreboard($session); + /** @var UserSession $session */ + $session->sidebar->handleScoreboard($session); } catch (InvalidArgumentException $e) { Loader::getInstance()->getLogger()->logException($e); } @@ -146,6 +146,24 @@ public function onBreak(BlockBreakEvent $event): void } } +// /** +// * @param BlockPlaceEvent $event +// * @throws AssumptionFailedError +// * @throws Error +// */ +// public function onPlace(BlockPlaceEvent $event): void +// { +// if (!is_null($event->getItem()->getNamedTag()->getCompoundTag(API::TAG_MAGIC_WE)) || !is_null($event->getItem()->getNamedTag()->getCompoundTag(API::TAG_MAGIC_WE_BRUSH))) { +// $event->cancel(); +// try { +// $this->onBreakBlock($event); +// } catch (Exception $error) { +// $event->getPlayer()->sendMessage(Loader::PREFIX . TF::RED . "Interaction failed!"); +// $event->getPlayer()->sendMessage(Loader::PREFIX . TF::RED . $error->getMessage()); +// } +// } +// } + /** * TODO use tool classes * @param BlockBreakEvent $event @@ -195,7 +213,7 @@ private function onBreakBlock(BlockBreakEvent $event): void */ private function onRightClickBlock(PlayerInteractEvent $event): void { - if (!is_null($event->getItem()->getNamedTag()->getCompoundTag(API::TAG_MAGIC_WE))) { + if (!is_null($event->getItem()->getNamedTag()->getCompoundTag(API::TAG_MAGIC_WE)) || !is_null($event->getItem()->getNamedTag()->getCompoundTag(API::TAG_MAGIC_WE_ASSET))) { $event->cancel(); $session = SessionHelper::getUserSession($event->getPlayer()); if (!$session instanceof UserSession) return; @@ -229,6 +247,12 @@ private function onRightClickBlock(PlayerInteractEvent $event): void #} break; } + default: + { + var_dump($event->getItem()); + $event->cancel(); + break; + } } } } diff --git a/src/xenialdan/MagicWE2/Loader.php b/src/xenialdan/MagicWE2/Loader.php index 608e22b1..079f052b 100644 --- a/src/xenialdan/MagicWE2/Loader.php +++ b/src/xenialdan/MagicWE2/Loader.php @@ -23,6 +23,7 @@ use RuntimeException; use xenialdan\apibossbar\DiverseBossBar; use xenialdan\customui\API as CustomUIAPI; +use xenialdan\MagicWE2\commands\asset\AssetCommand; use xenialdan\MagicWE2\commands\biome\BiomeInfoCommand; use xenialdan\MagicWE2\commands\biome\BiomeListCommand; use xenialdan\MagicWE2\commands\biome\SetBiomeCommand; @@ -71,6 +72,7 @@ use xenialdan\MagicWE2\helper\BlockStatesParser; use xenialdan\MagicWE2\helper\SessionHelper; use xenialdan\MagicWE2\selection\shape\ShapeRegistry; +use xenialdan\MagicWE2\session\data\AssetCollection; use xenialdan\MagicWE2\session\UserSession; use xenialdan\MagicWE2\task\action\ActionRegistry; @@ -100,6 +102,8 @@ class Loader extends PluginBase public $wailaBossBar; /** @var null|string */ public static $scoreboardAPI; + /** @var AssetCollection */ + public static AssetCollection $assetCollection; /** * Returns an instance of the plugin @@ -173,8 +177,9 @@ public function onLoad(): void } $blockstateparserInstance->setAliasMap(json_decode($fileGetContents, true, 512, JSON_THROW_ON_ERROR)); - #StructureStore::getInstance(); - $blockstateparserInstance::runTests();//TODO REMOVE, DEBUG!!!!!!! + //$blockstateparserInstance::runTests();//TODO REMOVE, DEBUG!!!!!!! + + self::$assetCollection = new AssetCollection(); } /** @@ -211,6 +216,8 @@ public function onEnable(): void new HPos1Command($this, "/hpos1", "Set position 1 to targeted block", ["/h1"]), new HPos2Command($this, "/hpos2", "Set position 2 to targeted block", ["/h2"]), new ChunkCommand($this, "/chunk", "Set the selection to your current chunk"), + /* -- assets -- */ + new AssetCommand($this, "/asset", "Manage assets (schematics, structures, clipboard)"), /* -- tool -- */ new WandCommand($this, "/wand", "Gives you the selection wand"), new TogglewandCommand($this, "/togglewand", "Toggle the wand tool on/off", ["/toggleeditwand"]), @@ -315,33 +322,6 @@ public function onEnable(): void } else { $this->getLogger()->notice(TF::RED . "Scoreboard API NOT found, can NOT use scoreboards"); } -// .mcstructure loading tests -// $world = self::getInstance()->getServer()->getWorldManager()->getDefaultWorld(); -// if ($world !== null) { -// $spawn = $world->getSafeSpawn()->asVector3(); -// $structureFiles = glob($this->getDataFolder() . 'structures' . DIRECTORY_SEPARATOR . "*.mcstructure"); -// if ($structureFiles !== false) -// foreach ($structureFiles as $file) { -// $this->getLogger()->debug(TF::GOLD . "Loading " . basename($file)); -// try { -// /** @var StructureStore $instance */ -// $instance = StructureStore::getInstance(); -// $structure = $instance->loadStructure(basename($file)); -// //this will dump wrong blocks for now -// foreach ($structure->blocks() as $block) { -// #$this->getLogger()->debug($block->getPos()->asVector3() . ' ' . BlockStatesParser::printStates(BlockStatesParser::getStateByBlock($block), false)); -// $world->setBlock(($at = $spawn->addVector($block->getPos()->asVector3())), $block); -// if (($tile = $structure->translateBlockEntity(Position::fromObject($block->getPos()->asVector3(), $world), $at)) instanceof Tile) { -// $tileAt = $world->getTileAt($block->getPos()->getFloorX(), $block->getPos()->getFloorY(), $block->getPos()->getFloorZ()); -// if ($tileAt !== null) $world->removeTile($tileAt); -// $world->addTile($tile); -// } -// } -// } catch (Exception $e) { -// $this->getLogger()->debug($e->getMessage()); -// } -// } -// } //register WAILA bar $this->wailaBossBar = new DiverseBossBar(); diff --git a/src/xenialdan/MagicWE2/clipboard/Clipboard.php b/src/xenialdan/MagicWE2/clipboard/Clipboard.php index 997776ed..455c2f93 100644 --- a/src/xenialdan/MagicWE2/clipboard/Clipboard.php +++ b/src/xenialdan/MagicWE2/clipboard/Clipboard.php @@ -46,11 +46,11 @@ public static function getChunkManager(array $chunks): AsyncChunkManager return $manager; } - /** - * @return World - * @throws Exception - */ - public function getWorld(): World + /** + * @return World + * @throws Exception + */ + public function getWorld(): World { if (is_null($this->worldId)) { throw new SelectionException("World is not set!"); @@ -70,27 +70,27 @@ public function setWorld(World $world): void $this->worldId = $world->getId(); } - /** - * @return int - */ - public function getWorldId(): int - { + /** + * @return int + */ + public function getWorldId(): int + { return $this->worldId; - } + } - /** - * @return string - */ - public function getCustomName(): string - { - return $this->customName; - } + /** + * @return string + */ + public function getCustomName(): string + { + return $this->customName; + } - /** - * @param string $customName - */ - public function setCustomName(string $customName): void - { - $this->customName = $customName; - } + /** + * @param string $customName + */ + public function setCustomName(string $customName): void + { + $this->customName = $customName; + } } \ No newline at end of file diff --git a/src/xenialdan/MagicWE2/clipboard/RevertClipboard.php b/src/xenialdan/MagicWE2/clipboard/RevertClipboard.php index 558bfa92..28543856 100644 --- a/src/xenialdan/MagicWE2/clipboard/RevertClipboard.php +++ b/src/xenialdan/MagicWE2/clipboard/RevertClipboard.php @@ -38,10 +38,10 @@ public function __construct(int $worldId, array $chunks = [], array $blocksAfter * String representation of object * @link http://php.net/manual/en/serializable.serialize.php * @return string the string representation of the object or null - * @since 5.1.0 - */ - public function serialize() - { + * @since 5.1.0 + */ + public function serialize() + { $chunks = []; foreach ($this->chunks as $hash => $chunk) { $chunks[$hash] = FastChunkSerializer::serialize($chunk); @@ -53,7 +53,7 @@ public function serialize() ]); } - /** + /** * Constructs the object * @link http://php.net/manual/en/serializable.unserialize.php * @param string $serialized

@@ -63,8 +63,8 @@ public function serialize() * @since 5.1.0 * @noinspection PhpMissingParamTypeInspection */ - public function unserialize($serialized) - { + public function unserialize($serialized) + { [ $this->worldId, $chunks, diff --git a/src/xenialdan/MagicWE2/clipboard/SingleClipboard.php b/src/xenialdan/MagicWE2/clipboard/SingleClipboard.php index 5715a006..5ef5c624 100644 --- a/src/xenialdan/MagicWE2/clipboard/SingleClipboard.php +++ b/src/xenialdan/MagicWE2/clipboard/SingleClipboard.php @@ -55,23 +55,23 @@ public function iterateEntries(?int &$x, ?int &$y, ?int &$z): Generator public function getTotalCount(): int { return count($this->entries); - } + } - /** - * String representation of object - * @link https://php.net/manual/en/serializable.serialize.php - * @return string the string representation of the object or null - * @since 5.1 - */ - public function serialize() - { - // TODO: Implement serialize() method. - return serialize([ - $this->entries, - $this->selection, - $this->position - ]); - } + /** + * String representation of object + * @link https://php.net/manual/en/serializable.serialize.php + * @return string the string representation of the object or null + * @since 5.1 + */ + public function serialize() + { + // TODO: Implement serialize() method. + return serialize([ + $this->entries, + $this->selection, + $this->position + ]); + } /** * Constructs the object @@ -83,13 +83,13 @@ public function serialize() * @since 5.1 * @noinspection PhpMissingParamTypeInspection */ - public function unserialize($serialized) - { - // TODO: Implement unserialize() method. - [ + public function unserialize($serialized) + { + // TODO: Implement unserialize() method. + [ $this->entries, $this->selection, $this->position ] = unserialize($serialized/*, ['allowed_classes' => [BlockEntry::class, Selection::class, Vector3::class]]*/); - } + } } \ No newline at end of file diff --git a/src/xenialdan/MagicWE2/commands/DonateCommand.php b/src/xenialdan/MagicWE2/commands/DonateCommand.php index 7ed4ce88..25187922 100644 --- a/src/xenialdan/MagicWE2/commands/DonateCommand.php +++ b/src/xenialdan/MagicWE2/commands/DonateCommand.php @@ -31,20 +31,20 @@ protected function prepare(): void * @param string $aliasUsed * @param mixed[] $args */ - public function onRun(CommandSender $sender, string $aliasUsed, array $args): void - { - $lang = Loader::getInstance()->getLanguage(); - if ($sender instanceof Player && SessionHelper::hasSession($sender)) { - try { - $lang = SessionHelper::getUserSession($sender)->getLanguage(); - } catch (SessionException $e) { - } - } - try { - $name = TF::DARK_PURPLE . "[" . TF::GOLD . "XenialDan" . TF::DARK_PURPLE . "] "; - $sender->sendMessage($name . "Greetings! Would you like to buy me an energy drink to stay awake during coding sessions?"); - $sender->sendMessage($name . "Donations are welcomed! Consider donating on " . TF::DARK_AQUA . "Pay" . TF::AQUA . "Pal:"); - $sender->sendMessage($name . TF::DARK_AQUA . "https://www.paypal.me/xenialdan"); + public function onRun(CommandSender $sender, string $aliasUsed, array $args): void + { + $lang = Loader::getInstance()->getLanguage(); + if ($sender instanceof Player && SessionHelper::hasSession($sender)) { + try { + $lang = SessionHelper::getUserSession($sender)->getLanguage(); + } catch (SessionException $e) { + } + } + try { + $name = TF::DARK_PURPLE . "[" . TF::GOLD . "XenialDan" . TF::DARK_PURPLE . "] "; + $sender->sendMessage($name . "Greetings! Would you like to buy me an energy drink to stay awake during coding sessions?"); + $sender->sendMessage($name . "Donations are welcomed! Consider donating on " . TF::DARK_AQUA . "Pay" . TF::AQUA . "Pal:"); + $sender->sendMessage($name . TF::DARK_AQUA . "https://www.paypal.me/xenialdan"); $sender->sendMessage($name . "Thank you! With " . TF::BOLD . TF::RED . "<3" . TF::RESET . TF::DARK_PURPLE . " - MagicWE2 by https://github.com/thebigsmileXD"); $colorHeart = (random_int(0, 1) === 1 ? TF::DARK_RED : TF::DARK_PURPLE); $sender->sendMessage( diff --git a/src/xenialdan/MagicWE2/commands/HelpCommand.php b/src/xenialdan/MagicWE2/commands/HelpCommand.php index e3025f90..84ccc5e1 100644 --- a/src/xenialdan/MagicWE2/commands/HelpCommand.php +++ b/src/xenialdan/MagicWE2/commands/HelpCommand.php @@ -35,18 +35,18 @@ protected function prepare(): void * @param string $aliasUsed * @param mixed[] $args */ - public function onRun(CommandSender $sender, string $aliasUsed, array $args): void - { - $lang = Loader::getInstance()->getLanguage(); - if ($sender instanceof Player && SessionHelper::hasSession($sender)) { - try { - $lang = SessionHelper::getUserSession($sender)->getLanguage(); - } catch (SessionException $e) { - } - } - try { - $cmds = []; - if (empty($args["command"])) { + public function onRun(CommandSender $sender, string $aliasUsed, array $args): void + { + $lang = Loader::getInstance()->getLanguage(); + if ($sender instanceof Player && SessionHelper::hasSession($sender)) { + try { + $lang = SessionHelper::getUserSession($sender)->getLanguage(); + } catch (SessionException $e) { + } + } + try { + $cmds = []; + if (empty($args["command"])) { foreach (array_filter(Loader::getInstance()->getServer()->getCommandMap()->getCommands(), static function (Command $command) use ($sender) { return strpos($command->getName(), "/") !== false && $command->testPermissionSilent($sender); }) as $cmd) { @@ -60,12 +60,12 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo $sender->sendMessage(TF::RED . str_replace("/", "//", $lang->translateString("%commands.generic.notFound"))); return; } - foreach ($cmds as $command) { - $message = TF::LIGHT_PURPLE . "/" . $command->getName(); - if (!empty(($aliases = $command->getAliases()))) { - foreach ($aliases as $i => $alias) { - $aliases[$i] = "/" . $alias; - } + foreach ($cmds as $command) { + $message = TF::LIGHT_PURPLE . "/" . $command->getName(); + if (!empty(($aliases = $command->getAliases()))) { + foreach ($aliases as $i => $alias) { + $aliases[$i] = "/" . $alias; + } $message .= TF::DARK_PURPLE . " [" . implode(",", $aliases) . "]"; } $message .= TF::AQUA . " " . $command->getDescription() . TF::EOL . " - " . $command->getUsage(); diff --git a/src/xenialdan/MagicWE2/commands/InfoCommand.php b/src/xenialdan/MagicWE2/commands/InfoCommand.php index 905a0419..074a598d 100644 --- a/src/xenialdan/MagicWE2/commands/InfoCommand.php +++ b/src/xenialdan/MagicWE2/commands/InfoCommand.php @@ -31,16 +31,16 @@ protected function prepare(): void * @param string $aliasUsed * @param mixed[] $args */ - public function onRun(CommandSender $sender, string $aliasUsed, array $args): void - { - $lang = Loader::getInstance()->getLanguage(); - if ($sender instanceof Player && SessionHelper::hasSession($sender)) { - try { - $lang = SessionHelper::getUserSession($sender)->getLanguage(); - } catch (SessionException $e) { - } - } - try { + public function onRun(CommandSender $sender, string $aliasUsed, array $args): void + { + $lang = Loader::getInstance()->getLanguage(); + if ($sender instanceof Player && SessionHelper::hasSession($sender)) { + try { + $lang = SessionHelper::getUserSession($sender)->getLanguage(); + } catch (SessionException $e) { + } + } + try { $sender->sendMessage(rtrim(Loader::PREFIX, " ") . " " . $lang->translateString('command.info.title')); foreach (Loader::getInfo() as $i => $line) { if ($i <= 1) continue; diff --git a/src/xenialdan/MagicWE2/commands/LanguageCommand.php b/src/xenialdan/MagicWE2/commands/LanguageCommand.php index 4f5a40a2..dadf3305 100644 --- a/src/xenialdan/MagicWE2/commands/LanguageCommand.php +++ b/src/xenialdan/MagicWE2/commands/LanguageCommand.php @@ -38,36 +38,36 @@ protected function prepare(): void * @param string $aliasUsed * @param mixed[] $args */ - public function onRun(CommandSender $sender, string $aliasUsed, array $args): void - { - $lang = Loader::getInstance()->getLanguage(); - if ($sender instanceof Player && SessionHelper::hasSession($sender)) { - try { - $lang = SessionHelper::getUserSession($sender)->getLanguage(); - } catch (SessionException $e) { - } - } - if (!$sender instanceof Player) { - $sender->sendMessage(TF::RED . $lang->translateString('error.runingame')); - return; - } - /** @var Player $sender */ - try { - $session = SessionHelper::getUserSession($sender); - if (is_null($session)) { + public function onRun(CommandSender $sender, string $aliasUsed, array $args): void + { + $lang = Loader::getInstance()->getLanguage(); + if ($sender instanceof Player && SessionHelper::hasSession($sender)) { + try { + $lang = SessionHelper::getUserSession($sender)->getLanguage(); + } catch (SessionException $e) { + } + } + if (!$sender instanceof Player) { + $sender->sendMessage(TF::RED . $lang->translateString('error.runingame')); + return; + } + /** @var Player $sender */ + try { + $session = SessionHelper::getUserSession($sender); + if (is_null($session)) { throw new SessionException($lang->translateString('error.nosession', [Loader::getInstance()->getName()])); - } - if (isset($args["language"])) { + } + if (isset($args["language"])) { $session->setLanguage((string)$args["language"]); return; } - $languages = Loader::getInstance()->getLanguageList(); - $form = new CustomForm(Loader::PREFIX . TF::BOLD . TF::DARK_PURPLE . $lang->translateString('ui.language.title')); - $form->addElement(new Label($lang->translateString('ui.language.label'))); - $dropdown = new Dropdown($lang->translateString('ui.language.dropdown'), array_values($languages)); - $dropdown->setOptionAsDefault($session->getLanguage()->getName()); - $form->addElement($dropdown); - $form->setCallable(function (Player $player, $data) use ($session, $languages) { + $languages = Loader::getInstance()->getLanguageList(); + $form = new CustomForm(Loader::PREFIX . TF::BOLD . TF::DARK_PURPLE . $lang->translateString('ui.language.title')); + $form->addElement(new Label($lang->translateString('ui.language.label'))); + $dropdown = new Dropdown($lang->translateString('ui.language.dropdown'), array_values($languages)); + $dropdown->setOptionAsDefault($session->getLanguage()->getName()); + $form->addElement($dropdown); + $form->setCallable(function (Player $player, $data) use ($session, $languages) { $langShort = array_search($data[1], $languages, true); if (!is_string($langShort)) throw new InvalidArgumentException("Invalid data received"); $session->setLanguage($langShort); diff --git a/src/xenialdan/MagicWE2/commands/LimitCommand.php b/src/xenialdan/MagicWE2/commands/LimitCommand.php index 80320b37..0fd34061 100644 --- a/src/xenialdan/MagicWE2/commands/LimitCommand.php +++ b/src/xenialdan/MagicWE2/commands/LimitCommand.php @@ -36,18 +36,18 @@ protected function prepare(): void * @param string $aliasUsed * @param mixed[] $args */ - public function onRun(CommandSender $sender, string $aliasUsed, array $args): void - { - $lang = Loader::getInstance()->getLanguage(); - if ($sender instanceof Player && SessionHelper::hasSession($sender)) { - try { - $lang = SessionHelper::getUserSession($sender)->getLanguage(); - } catch (SessionException $e) { - } - } - try { - if (empty($args["limit"])) { - $limit = Loader::getInstance()->getConfig()->get("limit", -1); + public function onRun(CommandSender $sender, string $aliasUsed, array $args): void + { + $lang = Loader::getInstance()->getLanguage(); + if ($sender instanceof Player && SessionHelper::hasSession($sender)) { + try { + $lang = SessionHelper::getUserSession($sender)->getLanguage(); + } catch (SessionException $e) { + } + } + try { + if (empty($args["limit"])) { + $limit = Loader::getInstance()->getConfig()->get("limit", -1); $sender->sendMessage(Loader::PREFIX . TF::GREEN . $lang->translateString('command.limit.current', [($limit < 0 ? ucfirst(Loader::getInstance()->getLanguage()->translateString('disabled')) : $limit)])); } else { Loader::getInstance()->getConfig()->set("limit", (int)$args["limit"]); diff --git a/src/xenialdan/MagicWE2/commands/ReportCommand.php b/src/xenialdan/MagicWE2/commands/ReportCommand.php index 4712eb1d..1691b8b7 100644 --- a/src/xenialdan/MagicWE2/commands/ReportCommand.php +++ b/src/xenialdan/MagicWE2/commands/ReportCommand.php @@ -36,16 +36,16 @@ protected function prepare(): void * @param string $aliasUsed * @param mixed[] $args */ - public function onRun(CommandSender $sender, string $aliasUsed, array $args): void - { - $lang = Loader::getInstance()->getLanguage(); - if ($sender instanceof Player && SessionHelper::hasSession($sender)) { - try { - $lang = SessionHelper::getUserSession($sender)->getLanguage(); - } catch (SessionException $e) { - } - } - try { + public function onRun(CommandSender $sender, string $aliasUsed, array $args): void + { + $lang = Loader::getInstance()->getLanguage(); + if ($sender instanceof Player && SessionHelper::hasSession($sender)) { + try { + $lang = SessionHelper::getUserSession($sender)->getLanguage(); + } catch (SessionException $e) { + } + } + try { $url = "Please report your bug with this link (link also in console)" . TF::EOL; $url .= "https://github.com/thebigsmileXD/MagicWE2/issues/new?labels=Bug&body="; $url .= urlencode( diff --git a/src/xenialdan/MagicWE2/commands/SetRangeCommand.php b/src/xenialdan/MagicWE2/commands/SetRangeCommand.php index cf7556c3..60e1171d 100644 --- a/src/xenialdan/MagicWE2/commands/SetRangeCommand.php +++ b/src/xenialdan/MagicWE2/commands/SetRangeCommand.php @@ -36,18 +36,18 @@ protected function prepare(): void * @param string $aliasUsed * @param mixed[] $args */ - public function onRun(CommandSender $sender, string $aliasUsed, array $args): void - { - $lang = Loader::getInstance()->getLanguage(); - if ($sender instanceof Player && SessionHelper::hasSession($sender)) { - try { - $lang = SessionHelper::getUserSession($sender)->getLanguage(); - } catch (SessionException $e) { - } - } - try { - if (empty($args["range"])) { - $range = Loader::getInstance()->getToolDistance(); + public function onRun(CommandSender $sender, string $aliasUsed, array $args): void + { + $lang = Loader::getInstance()->getLanguage(); + if ($sender instanceof Player && SessionHelper::hasSession($sender)) { + try { + $lang = SessionHelper::getUserSession($sender)->getLanguage(); + } catch (SessionException $e) { + } + } + try { + if (empty($args["range"])) { + $range = Loader::getInstance()->getToolDistance(); $sender->sendMessage(Loader::PREFIX . TF::GREEN . $lang->translateString('command.setrange.current', [$range])); } else { Loader::getInstance()->getConfig()->set("tool-range", (int)$args["range"]); diff --git a/src/xenialdan/MagicWE2/commands/TestCommand.php b/src/xenialdan/MagicWE2/commands/TestCommand.php index 8c76455b..f16dc71a 100644 --- a/src/xenialdan/MagicWE2/commands/TestCommand.php +++ b/src/xenialdan/MagicWE2/commands/TestCommand.php @@ -46,8 +46,8 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo } } try { - //TODO REMOVE DEBUG - $pluginSession = SessionHelper::createPluginSession(Loader::getInstance()); + //TODO REMOVE DEBUG + $pluginSession = SessionHelper::createPluginSession(Loader::getInstance()); $selection = new Selection($pluginSession->getUUID(), Server::getInstance()->getWorldManager()->getDefaultWorld(), 0, 0, 0, 0, 0, 0); $pluginSession->addSelection($selection); Server::getInstance()->getAsyncPool()->submitTask( diff --git a/src/xenialdan/MagicWE2/commands/VersionCommand.php b/src/xenialdan/MagicWE2/commands/VersionCommand.php index 290d38e6..b8166e60 100644 --- a/src/xenialdan/MagicWE2/commands/VersionCommand.php +++ b/src/xenialdan/MagicWE2/commands/VersionCommand.php @@ -31,12 +31,12 @@ protected function prepare(): void * @param string $aliasUsed * @param mixed[] $args */ - public function onRun(CommandSender $sender, string $aliasUsed, array $args): void - { - $lang = Loader::getInstance()->getLanguage(); - if ($sender instanceof Player && SessionHelper::hasSession($sender)) { - try { - $lang = SessionHelper::getUserSession($sender)->getLanguage(); + public function onRun(CommandSender $sender, string $aliasUsed, array $args): void + { + $lang = Loader::getInstance()->getLanguage(); + if ($sender instanceof Player && SessionHelper::hasSession($sender)) { + try { + $lang = SessionHelper::getUserSession($sender)->getLanguage(); } catch (SessionException $e) { } } diff --git a/src/xenialdan/MagicWE2/commands/args/LanguageArgument.php b/src/xenialdan/MagicWE2/commands/args/LanguageArgument.php index 942f98dd..e4d86fc0 100644 --- a/src/xenialdan/MagicWE2/commands/args/LanguageArgument.php +++ b/src/xenialdan/MagicWE2/commands/args/LanguageArgument.php @@ -32,8 +32,8 @@ public function getEnumValues(): array return array_values(Loader::getInstance()->getLanguageList()); } - public function getEnumName(): string - { - return "language"; - } + public function getEnumName(): string + { + return "language"; + } } \ No newline at end of file diff --git a/src/xenialdan/MagicWE2/commands/args/MirrorAxisArgument.php b/src/xenialdan/MagicWE2/commands/args/MirrorAxisArgument.php index 5090e1b5..fd2fb847 100644 --- a/src/xenialdan/MagicWE2/commands/args/MirrorAxisArgument.php +++ b/src/xenialdan/MagicWE2/commands/args/MirrorAxisArgument.php @@ -9,7 +9,7 @@ class MirrorAxisArgument extends StringEnumArgument { - protected const VALUES = ["x" => "x", "z" => "z", "y" => "y", "xz" => "xz"]; + protected const VALUES = ["x" => "x", "z" => "z", "y" => "y", "xz" => "xz"]; public function getTypeName(): string { diff --git a/src/xenialdan/MagicWE2/commands/args/RotateAngleArgument.php b/src/xenialdan/MagicWE2/commands/args/RotateAngleArgument.php index 9b2000c1..5503e86d 100644 --- a/src/xenialdan/MagicWE2/commands/args/RotateAngleArgument.php +++ b/src/xenialdan/MagicWE2/commands/args/RotateAngleArgument.php @@ -9,8 +9,8 @@ class RotateAngleArgument extends StringEnumArgument { - /** @var array */ - protected const VALUES = ["90" => 90, "180" => 180, "270" => 270]; + /** @var array */ + protected const VALUES = ["90" => 90, "180" => 180, "270" => 270]; public function getTypeName(): string { diff --git a/src/xenialdan/MagicWE2/commands/biome/BiomeInfoCommand.php b/src/xenialdan/MagicWE2/commands/biome/BiomeInfoCommand.php index dac556ce..99e09a86 100644 --- a/src/xenialdan/MagicWE2/commands/biome/BiomeInfoCommand.php +++ b/src/xenialdan/MagicWE2/commands/biome/BiomeInfoCommand.php @@ -43,28 +43,28 @@ protected function prepare(): void * @param string $aliasUsed * @param mixed[] $args */ - public function onRun(CommandSender $sender, string $aliasUsed, array $args): void - { - $lang = Loader::getInstance()->getLanguage(); - if ($sender instanceof Player && SessionHelper::hasSession($sender)) { - try { - $lang = SessionHelper::getUserSession($sender)->getLanguage(); - } catch (SessionException $e) { - } - } - if (!$sender instanceof Player) { - $sender->sendMessage(TF::RED . $lang->translateString('error.runingame')); - return; - } - /** @var Player $sender */ - try { - $session = SessionHelper::getUserSession($sender); - if (is_null($session)) { + public function onRun(CommandSender $sender, string $aliasUsed, array $args): void + { + $lang = Loader::getInstance()->getLanguage(); + if ($sender instanceof Player && SessionHelper::hasSession($sender)) { + try { + $lang = SessionHelper::getUserSession($sender)->getLanguage(); + } catch (SessionException $e) { + } + } + if (!$sender instanceof Player) { + $sender->sendMessage(TF::RED . $lang->translateString('error.runingame')); + return; + } + /** @var Player $sender */ + try { + $session = SessionHelper::getUserSession($sender); + if (is_null($session)) { throw new SessionException($lang->translateString('error.nosession', [Loader::getInstance()->getName()])); - } - $biomeNames = (new ReflectionClass(Biome::class))->getConstants(); - $biomeNames = array_flip($biomeNames); - unset($biomeNames[Biome::MAX_BIOMES]); + } + $biomeNames = (new ReflectionClass(Biome::class))->getConstants(); + $biomeNames = array_flip($biomeNames); + unset($biomeNames[Biome::MAX_BIOMES]); array_walk($biomeNames, static function (&$value, $key) { $value = BiomeRegistry::getInstance()->getBiome($key)->getName(); }); @@ -85,37 +85,37 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo $session->sendMessage(TF::DARK_AQUA . $lang->translateString('command.biomeinfo.atposition')); $session->sendMessage(TF::AQUA . "ID: $biomeId Name: " . $biomeNames[$biomeId]); } - return; - } - $selection = $session->getLatestSelection(); - if (is_null($selection)) { + return; + } + $selection = $session->getLatestSelection(); + if (is_null($selection)) { throw new SelectionException($lang->translateString('error.noselection')); - } - if (!$selection->isValid()) { + } + if (!$selection->isValid()) { throw new SelectionException($lang->translateString('error.selectioninvalid')); - } - if ($selection->getWorld() !== $sender->getWorld()) { + } + if ($selection->getWorld() !== $sender->getWorld()) { $sender->sendMessage(Loader::PREFIX . TF::GOLD . $lang->translateString('warning.differentworld')); - } - $touchedChunks = $selection->getShape()->getTouchedChunks($selection->getWorld()); - $biomes = []; - foreach ($touchedChunks as $touchedChunk) { - for ($x = 0; $x < 16; $x++) - for ($z = 0; $z < 16; $z++) + } + $touchedChunks = $selection->getShape()->getTouchedChunks($selection->getWorld()); + $biomes = []; + foreach ($touchedChunks as $touchedChunk) { + for ($x = 0; $x < 16; $x++) + for ($z = 0; $z < 16; $z++) $biomes[] = (FastChunkSerializer::deserialize($touchedChunk)->getBiomeId($x, $z)); - } - $biomes = array_unique($biomes); - $session->sendMessage(TF::DARK_AQUA . $lang->translateString('command.biomeinfo.result', [count($biomes)])); - foreach ($biomes as $biomeId) { - $session->sendMessage(TF::AQUA . $lang->translateString('command.biomeinfo.result.line', [$biomeId, $biomeNames[$biomeId]])); - } - } catch (Exception $error) { - $sender->sendMessage(Loader::PREFIX . TF::RED . $lang->translateString('error.command-error')); - $sender->sendMessage(Loader::PREFIX . TF::RED . $error->getMessage()); - $sender->sendMessage($this->getUsage()); - } catch (Error $error) { - Loader::getInstance()->getLogger()->logException($error); - $sender->sendMessage(Loader::PREFIX . TF::RED . $error->getMessage()); - } - } + } + $biomes = array_unique($biomes); + $session->sendMessage(TF::DARK_AQUA . $lang->translateString('command.biomeinfo.result', [count($biomes)])); + foreach ($biomes as $biomeId) { + $session->sendMessage(TF::AQUA . $lang->translateString('command.biomeinfo.result.line', [$biomeId, $biomeNames[$biomeId]])); + } + } catch (Exception $error) { + $sender->sendMessage(Loader::PREFIX . TF::RED . $lang->translateString('error.command-error')); + $sender->sendMessage(Loader::PREFIX . TF::RED . $error->getMessage()); + $sender->sendMessage($this->getUsage()); + } catch (Error $error) { + Loader::getInstance()->getLogger()->logException($error); + $sender->sendMessage(Loader::PREFIX . TF::RED . $error->getMessage()); + } + } } diff --git a/src/xenialdan/MagicWE2/commands/biome/BiomeListCommand.php b/src/xenialdan/MagicWE2/commands/biome/BiomeListCommand.php index bc5bdcb8..41ad97ce 100644 --- a/src/xenialdan/MagicWE2/commands/biome/BiomeListCommand.php +++ b/src/xenialdan/MagicWE2/commands/biome/BiomeListCommand.php @@ -34,19 +34,19 @@ protected function prepare(): void * @param string $aliasUsed * @param mixed[] $args */ - public function onRun(CommandSender $sender, string $aliasUsed, array $args): void - { - $lang = Loader::getInstance()->getLanguage(); - if ($sender instanceof Player && SessionHelper::hasSession($sender)) { - try { - $lang = SessionHelper::getUserSession($sender)->getLanguage(); - /** @var Player $sender */ - $session = SessionHelper::getUserSession($sender); - if (is_null($session)) { + public function onRun(CommandSender $sender, string $aliasUsed, array $args): void + { + $lang = Loader::getInstance()->getLanguage(); + if ($sender instanceof Player && SessionHelper::hasSession($sender)) { + try { + $lang = SessionHelper::getUserSession($sender)->getLanguage(); + /** @var Player $sender */ + $session = SessionHelper::getUserSession($sender); + if (is_null($session)) { throw new SessionException($lang->translateString('error.nosession', [Loader::getInstance()->getName()])); - } - $session->sendMessage(TF::DARK_AQUA . $lang->translateString('command.biomelist.title')); - foreach ((new ReflectionClass(Biome::class))->getConstants() as $name => $value) { + } + $session->sendMessage(TF::DARK_AQUA . $lang->translateString('command.biomelist.title')); + foreach ((new ReflectionClass(Biome::class))->getConstants() as $name => $value) { if ($value === Biome::MAX_BIOMES) continue; $name = BiomeRegistry::getInstance()->getBiome($value)->getName(); $session->sendMessage(TF::AQUA . $lang->translateString('command.biomelist.result.line', [$value, $name])); @@ -58,5 +58,5 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo $sender->sendMessage($this->getUsage()); } } - } + } } diff --git a/src/xenialdan/MagicWE2/commands/biome/SetBiomeCommand.php b/src/xenialdan/MagicWE2/commands/biome/SetBiomeCommand.php index c6e2b224..d7d0219f 100644 --- a/src/xenialdan/MagicWE2/commands/biome/SetBiomeCommand.php +++ b/src/xenialdan/MagicWE2/commands/biome/SetBiomeCommand.php @@ -39,25 +39,25 @@ protected function prepare(): void * @param string $aliasUsed * @param mixed[] $args */ - public function onRun(CommandSender $sender, string $aliasUsed, array $args): void - { - $lang = Loader::getInstance()->getLanguage(); - if ($sender instanceof Player && SessionHelper::hasSession($sender)) { - try { - $lang = SessionHelper::getUserSession($sender)->getLanguage(); - } catch (SessionException $e) { - } - } - if (!$sender instanceof Player) { - $sender->sendMessage(TF::RED . $lang->translateString('error.runingame')); - return; - } - /** @var Player $sender */ - try { - $session = SessionHelper::getUserSession($sender); - if (is_null($session)) { + public function onRun(CommandSender $sender, string $aliasUsed, array $args): void + { + $lang = Loader::getInstance()->getLanguage(); + if ($sender instanceof Player && SessionHelper::hasSession($sender)) { + try { + $lang = SessionHelper::getUserSession($sender)->getLanguage(); + } catch (SessionException $e) { + } + } + if (!$sender instanceof Player) { + $sender->sendMessage(TF::RED . $lang->translateString('error.runingame')); + return; + } + /** @var Player $sender */ + try { + $session = SessionHelper::getUserSession($sender); + if (is_null($session)) { throw new SessionException($lang->translateString('error.nosession', [Loader::getInstance()->getName()])); - } + } $selection = $session->getLatestSelection(); if (is_null($selection)) { throw new SelectionException($lang->translateString('error.noselection')); diff --git a/src/xenialdan/MagicWE2/commands/brush/BrushCommand.php b/src/xenialdan/MagicWE2/commands/brush/BrushCommand.php index 013e9d9b..b9990695 100644 --- a/src/xenialdan/MagicWE2/commands/brush/BrushCommand.php +++ b/src/xenialdan/MagicWE2/commands/brush/BrushCommand.php @@ -25,75 +25,76 @@ class BrushCommand extends BaseCommand { - /** - * This is where all the arguments, permissions, sub-commands, etc would be registered - * @throws InvalidArgumentException - */ - protected function prepare(): void - { - $this->registerSubCommand(new BrushNameCommand("name", "Get name or rename a brush")); + /** + * This is where all the arguments, permissions, sub-commands, etc would be registered + * @throws InvalidArgumentException + */ + protected function prepare(): void + { + $this->registerSubCommand(new BrushNameCommand("name", "Get name or rename a brush")); $this->setPermission("we.command.brush"); - } + } - /** + /** * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args */ - public function onRun(CommandSender $sender, string $aliasUsed, array $args): void - { - $lang = Loader::getInstance()->getLanguage(); - if ($sender instanceof Player && SessionHelper::hasSession($sender)) { - try { - $lang = SessionHelper::getUserSession($sender)->getLanguage(); - } catch (SessionException $e) { - } - } - if (!$sender instanceof Player) { - $sender->sendMessage(TF::RED . $lang->translateString('error.runingame')); - return; - } - /** @var Player $sender */ - try { - $session = SessionHelper::getUserSession($sender); - if (!$session instanceof UserSession) { - throw new SessionException($lang->translateString('error.nosession', [Loader::getInstance()->getName()])); - } - $form = new SimpleForm(Loader::PREFIX . TF::BOLD . TF::DARK_PURPLE . $lang->translateString('ui.brush.title'), $lang->translateString('ui.brush.content')); - $form->addButton(new Button($lang->translateString('ui.brush.create'))); - $form->addButton(new Button($lang->translateString('ui.brush.getsession'))); - $form->addButton(new Button($lang->translateString('ui.brush.edithand'))); - $form->setCallable(function (Player $player, $data) use ($lang, $session) { - try { - switch ($data) { - case $lang->translateString('ui.brush.create'): - { - $brush = new Brush(new BrushProperties()); - if ($brush instanceof Brush) { - $player->sendForm($brush->getForm()); - } - break; - } - case $lang->translateString('ui.brush.getsession'): - { - $menu = InvMenu::create(InvMenu::TYPE_DOUBLE_CHEST); - foreach ($session->getBrushes() as $brush) { - $menu->getInventory()->addItem($brush->toItem()); - } - $menu->send($player, "Session brushes"); - break; - } - case $lang->translateString('ui.brush.edithand'): - { - $brush = $session->getBrushFromItem($player->getInventory()->getItemInHand()); - if ($brush instanceof Brush) { - $player->sendForm($brush->getForm(false)); - } - break; - } - } - return null; - } catch (Exception $error) { + public function onRun(CommandSender $sender, string $aliasUsed, array $args): void + { + $lang = Loader::getInstance()->getLanguage(); + if ($sender instanceof Player && SessionHelper::hasSession($sender)) { + try { + $lang = SessionHelper::getUserSession($sender)->getLanguage(); + } catch (SessionException $e) { + } + } + if (!$sender instanceof Player) { + $sender->sendMessage(TF::RED . $lang->translateString('error.runingame')); + return; + } + /** @var Player $sender */ + try { + $session = SessionHelper::getUserSession($sender); + if (!$session instanceof UserSession) { + throw new SessionException($lang->translateString('error.nosession', [Loader::getInstance()->getName()])); + } + $form = new SimpleForm(Loader::PREFIX . TF::BOLD . TF::DARK_PURPLE . $lang->translateString('ui.brush.title'), $lang->translateString('ui.brush.content')); + $form->addButton(new Button($lang->translateString('ui.brush.create'))); + $form->addButton(new Button($lang->translateString('ui.brush.getsession'))); + $form->addButton(new Button($lang->translateString('ui.brush.edithand'))); + $form->setCallable(function (Player $player, $data) use ($lang, $session) { + try { + switch ($data) { + case $lang->translateString('ui.brush.create'): + { + $brush = new Brush(new BrushProperties()); + if ($brush instanceof Brush) { + $player->sendForm($brush->getForm()); + } + break; + } + case $lang->translateString('ui.brush.getsession'): + { + $menu = InvMenu::create(InvMenu::TYPE_DOUBLE_CHEST); + foreach ($session->getBrushes() as $brush) { + var_dump($brush); + $menu->getInventory()->addItem($brush->toItem()); + } + $menu->send($player, "Session brushes"); + break; + } + case $lang->translateString('ui.brush.edithand'): + { + $brush = $session->getBrushFromItem($player->getInventory()->getItemInHand()); + if ($brush instanceof Brush) { + $player->sendForm($brush->getForm(false)); + } + break; + } + } + return null; + } catch (Exception $error) { $session->sendMessage(TF::RED . $lang->translateString('error')); $session->sendMessage(TF::RED . $error->getMessage()); } @@ -123,5 +124,5 @@ public static function generateLore(array $elements, array $data): array $return[] = ($element->getText() . ": " . $data[$i]); } return $return; - } + } } diff --git a/src/xenialdan/MagicWE2/commands/clipboard/ClearClipboardCommand.php b/src/xenialdan/MagicWE2/commands/clipboard/ClearClipboardCommand.php index 45c65689..cc782867 100644 --- a/src/xenialdan/MagicWE2/commands/clipboard/ClearClipboardCommand.php +++ b/src/xenialdan/MagicWE2/commands/clipboard/ClearClipboardCommand.php @@ -32,22 +32,22 @@ protected function prepare(): void * @param string $aliasUsed * @param mixed[] $args */ - public function onRun(CommandSender $sender, string $aliasUsed, array $args): void - { - $lang = Loader::getInstance()->getLanguage(); - if ($sender instanceof Player && SessionHelper::hasSession($sender)) { - try { - $lang = SessionHelper::getUserSession($sender)->getLanguage(); - } catch (SessionException $e) { - } - } - if (!$sender instanceof Player) { - $sender->sendMessage(TF::RED . $lang->translateString('error.runingame')); - return; - } - /** @var Player $sender */ - try { - $session = SessionHelper::getUserSession($sender); + public function onRun(CommandSender $sender, string $aliasUsed, array $args): void + { + $lang = Loader::getInstance()->getLanguage(); + if ($sender instanceof Player && SessionHelper::hasSession($sender)) { + try { + $lang = SessionHelper::getUserSession($sender)->getLanguage(); + } catch (SessionException $e) { + } + } + if (!$sender instanceof Player) { + $sender->sendMessage(TF::RED . $lang->translateString('error.runingame')); + return; + } + /** @var Player $sender */ + try { + $session = SessionHelper::getUserSession($sender); if (!$session instanceof UserSession) { throw new SessionException($lang->translateString('error.nosession', [Loader::getInstance()->getName()])); } diff --git a/src/xenialdan/MagicWE2/commands/clipboard/CopyCommand.php b/src/xenialdan/MagicWE2/commands/clipboard/CopyCommand.php index 77b6b53a..b006a33a 100644 --- a/src/xenialdan/MagicWE2/commands/clipboard/CopyCommand.php +++ b/src/xenialdan/MagicWE2/commands/clipboard/CopyCommand.php @@ -37,26 +37,26 @@ protected function prepare(): void * @param string $aliasUsed * @param mixed[] $args */ - public function onRun(CommandSender $sender, string $aliasUsed, array $args): void - { - $lang = Loader::getInstance()->getLanguage(); - if ($sender instanceof Player && SessionHelper::hasSession($sender)) { - try { - $lang = SessionHelper::getUserSession($sender)->getLanguage(); - } catch (SessionException $e) { - } - } - if (!$sender instanceof Player) { - $sender->sendMessage(TF::RED . $lang->translateString('error.runingame')); - return; - } - /** @var Player $sender */ - try { - $session = SessionHelper::getUserSession($sender); - if (is_null($session)) { + public function onRun(CommandSender $sender, string $aliasUsed, array $args): void + { + $lang = Loader::getInstance()->getLanguage(); + if ($sender instanceof Player && SessionHelper::hasSession($sender)) { + try { + $lang = SessionHelper::getUserSession($sender)->getLanguage(); + } catch (SessionException $e) { + } + } + if (!$sender instanceof Player) { + $sender->sendMessage(TF::RED . $lang->translateString('error.runingame')); + return; + } + /** @var Player $sender */ + try { + $session = SessionHelper::getUserSession($sender); + if (is_null($session)) { throw new SessionException($lang->translateString('error.nosession', [Loader::getInstance()->getName()])); - } - $selection = $session->getLatestSelection(); + } + $selection = $session->getLatestSelection(); if (is_null($selection)) { throw new SelectionException($lang->translateString('error.noselection')); } diff --git a/src/xenialdan/MagicWE2/commands/clipboard/Cut2Command.php b/src/xenialdan/MagicWE2/commands/clipboard/Cut2Command.php index 876f721d..7dc16cec 100644 --- a/src/xenialdan/MagicWE2/commands/clipboard/Cut2Command.php +++ b/src/xenialdan/MagicWE2/commands/clipboard/Cut2Command.php @@ -41,41 +41,41 @@ protected function prepare(): void * @param string $aliasUsed * @param mixed[] $args */ - public function onRun(CommandSender $sender, string $aliasUsed, array $args): void - { - $lang = Loader::getInstance()->getLanguage(); - if ($sender instanceof Player && SessionHelper::hasSession($sender)) { - try { - $lang = SessionHelper::getUserSession($sender)->getLanguage(); - } catch (SessionException $e) { - } - } - if (!$sender instanceof Player) { - $sender->sendMessage(TF::RED . $lang->translateString('error.runingame')); - return; - } - /** @var Player $sender */ - try { - $session = SessionHelper::getUserSession($sender); - if (is_null($session)) { + public function onRun(CommandSender $sender, string $aliasUsed, array $args): void + { + $lang = Loader::getInstance()->getLanguage(); + if ($sender instanceof Player && SessionHelper::hasSession($sender)) { + try { + $lang = SessionHelper::getUserSession($sender)->getLanguage(); + } catch (SessionException $e) { + } + } + if (!$sender instanceof Player) { + $sender->sendMessage(TF::RED . $lang->translateString('error.runingame')); + return; + } + /** @var Player $sender */ + try { + $session = SessionHelper::getUserSession($sender); + if (is_null($session)) { throw new SessionException($lang->translateString('error.nosession', [Loader::getInstance()->getName()])); - } - $selection = $session->getLatestSelection(); - if (is_null($selection)) { + } + $selection = $session->getLatestSelection(); + if (is_null($selection)) { throw new SelectionException($lang->translateString('error.noselection')); - } - if (!$selection->isValid()) { + } + if (!$selection->isValid()) { throw new SelectionException($lang->translateString('error.selectioninvalid')); - } - if ($selection->getWorld() !== $sender->getWorld()) { + } + if ($selection->getWorld() !== $sender->getWorld()) { $sender->sendMessage(Loader::PREFIX . TF::GOLD . $lang->translateString('warning.differentworld')); - } - #$hasFlags = isset($args["flags"]); - $action = new CutAction(); + } + #$hasFlags = isset($args["flags"]); + $action = new CutAction(); $offset = $selection->getShape()->getMinVec3()->subtractVector($session->getPlayer()->getPosition()->asVector3()->floor())->floor(); $action->setClipboardVector($offset); - Server::getInstance()->getAsyncPool()->submitTask( - new AsyncActionTask( + Server::getInstance()->getAsyncPool()->submitTask( + new AsyncActionTask( $session->getUUID(), $selection, $action, diff --git a/src/xenialdan/MagicWE2/commands/clipboard/CutCommand.php b/src/xenialdan/MagicWE2/commands/clipboard/CutCommand.php index 769daffe..16a56bc0 100644 --- a/src/xenialdan/MagicWE2/commands/clipboard/CutCommand.php +++ b/src/xenialdan/MagicWE2/commands/clipboard/CutCommand.php @@ -38,27 +38,27 @@ protected function prepare(): void * @param string $aliasUsed * @param mixed[] $args */ - public function onRun(CommandSender $sender, string $aliasUsed, array $args): void - { - $lang = Loader::getInstance()->getLanguage(); - if ($sender instanceof Player && SessionHelper::hasSession($sender)) { - try { - $lang = SessionHelper::getUserSession($sender)->getLanguage(); - } catch (SessionException $e) { - } - } - if (!$sender instanceof Player) { - $sender->sendMessage(TF::RED . $lang->translateString('error.runingame')); - return; - } - /** @var Player $sender */ - try { - $session = SessionHelper::getUserSession($sender); - if (is_null($session)) { + public function onRun(CommandSender $sender, string $aliasUsed, array $args): void + { + $lang = Loader::getInstance()->getLanguage(); + if ($sender instanceof Player && SessionHelper::hasSession($sender)) { + try { + $lang = SessionHelper::getUserSession($sender)->getLanguage(); + } catch (SessionException $e) { + } + } + if (!$sender instanceof Player) { + $sender->sendMessage(TF::RED . $lang->translateString('error.runingame')); + return; + } + /** @var Player $sender */ + try { + $session = SessionHelper::getUserSession($sender); + if (is_null($session)) { throw new SessionException($lang->translateString('error.nosession', [Loader::getInstance()->getName()])); - } - $selection = $session->getLatestSelection(); - if (is_null($selection)) { + } + $selection = $session->getLatestSelection(); + if (is_null($selection)) { throw new SelectionException($lang->translateString('error.noselection')); } if (!$selection->isValid()) { diff --git a/src/xenialdan/MagicWE2/commands/clipboard/FlipCommand.php b/src/xenialdan/MagicWE2/commands/clipboard/FlipCommand.php index 9f4cc7ef..40fdc672 100644 --- a/src/xenialdan/MagicWE2/commands/clipboard/FlipCommand.php +++ b/src/xenialdan/MagicWE2/commands/clipboard/FlipCommand.php @@ -40,21 +40,21 @@ protected function prepare(): void * @param string $aliasUsed * @param mixed[] $args */ - public function onRun(CommandSender $sender, string $aliasUsed, array $args): void - { - $lang = Loader::getInstance()->getLanguage(); - if ($sender instanceof Player && SessionHelper::hasSession($sender)) { - try { - $lang = SessionHelper::getUserSession($sender)->getLanguage(); - } catch (SessionException $e) { - } - } - if (!$sender instanceof Player) { - $sender->sendMessage(TF::RED . $lang->translateString('error.runingame')); - return; - } - /** @var Player $sender */ - try { + public function onRun(CommandSender $sender, string $aliasUsed, array $args): void + { + $lang = Loader::getInstance()->getLanguage(); + if ($sender instanceof Player && SessionHelper::hasSession($sender)) { + try { + $lang = SessionHelper::getUserSession($sender)->getLanguage(); + } catch (SessionException $e) { + } + } + if (!$sender instanceof Player) { + $sender->sendMessage(TF::RED . $lang->translateString('error.runingame')); + return; + } + /** @var Player $sender */ + try { $axis = (string)$args["axis"];//TODO change to Axis[] $sender->sendMessage(Loader::PREFIX . $lang->translateString('command.flip.try', [$axis])); $session = SessionHelper::getUserSession($sender); @@ -66,11 +66,11 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo throw new SessionException($lang->translateString('error.noclipboard')); } $action = new FlipAction($axis); - #$offset = $selection->getShape()->getMinVec3()->subtract($session->getPlayer()->asVector3()->floor())->floor(); - #$action->setClipboardVector($offset); - Server::getInstance()->getAsyncPool()->submitTask( - new AsyncClipboardActionTask( - $session->getUUID(), + #$offset = $selection->getShape()->getMinVec3()->subtract($session->getPlayer()->asVector3()->floor())->floor(); + #$action->setClipboardVector($offset); + Server::getInstance()->getAsyncPool()->submitTask( + new AsyncClipboardActionTask( + $session->getUUID(), $clipboard->selection, $action, $clipboard diff --git a/src/xenialdan/MagicWE2/commands/clipboard/PasteCommand.php b/src/xenialdan/MagicWE2/commands/clipboard/PasteCommand.php index 55b1ec66..e3660ddd 100644 --- a/src/xenialdan/MagicWE2/commands/clipboard/PasteCommand.php +++ b/src/xenialdan/MagicWE2/commands/clipboard/PasteCommand.php @@ -50,16 +50,16 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo } } if (!$sender instanceof Player) { - $sender->sendMessage(TF::RED . $lang->translateString('error.runingame')); - return; - } - /** @var Player $sender */ - try { - $session = SessionHelper::getUserSession($sender); - if (is_null($session)) { + $sender->sendMessage(TF::RED . $lang->translateString('error.runingame')); + return; + } + /** @var Player $sender */ + try { + $session = SessionHelper::getUserSession($sender); + if (is_null($session)) { throw new SessionException($lang->translateString('error.nosession', [Loader::getInstance()->getName()])); - } - $clipboard = $session->getCurrentClipboard(); + } + $clipboard = $session->getCurrentClipboard(); if (is_null($clipboard)) { throw new SelectionException($lang->translateString('error.noclipboard')); } diff --git a/src/xenialdan/MagicWE2/commands/clipboard/RotateCommand.php b/src/xenialdan/MagicWE2/commands/clipboard/RotateCommand.php index 961e8a3d..bb624bcf 100644 --- a/src/xenialdan/MagicWE2/commands/clipboard/RotateCommand.php +++ b/src/xenialdan/MagicWE2/commands/clipboard/RotateCommand.php @@ -41,25 +41,25 @@ protected function prepare(): void * @param string $aliasUsed * @param mixed[] $args */ - public function onRun(CommandSender $sender, string $aliasUsed, array $args): void - { - $lang = Loader::getInstance()->getLanguage(); - if ($sender instanceof Player && SessionHelper::hasSession($sender)) { - try { - $lang = SessionHelper::getUserSession($sender)->getLanguage(); - } catch (SessionException $e) { - } - } - if (!$sender instanceof Player) { - $sender->sendMessage(TF::RED . $lang->translateString('error.runingame')); - return; - } - /** @var Player $sender */ - try { - $angle = (int)$args["angle"]; + public function onRun(CommandSender $sender, string $aliasUsed, array $args): void + { + $lang = Loader::getInstance()->getLanguage(); + if ($sender instanceof Player && SessionHelper::hasSession($sender)) { + try { + $lang = SessionHelper::getUserSession($sender)->getLanguage(); + } catch (SessionException $e) { + } + } + if (!$sender instanceof Player) { + $sender->sendMessage(TF::RED . $lang->translateString('error.runingame')); + return; + } + /** @var Player $sender */ + try { + $angle = (int)$args["angle"]; $aroundOrigin = $args["aroundOrigin"] ?? true; - $sender->sendMessage(Loader::PREFIX . $lang->translateString('command.rotate.try', [$angle])); - $session = SessionHelper::getUserSession($sender); + $sender->sendMessage(Loader::PREFIX . $lang->translateString('command.rotate.try', [$angle])); + $session = SessionHelper::getUserSession($sender); if (is_null($session)) { throw new SessionException($lang->translateString('error.nosession', [Loader::getInstance()->getName()])); } diff --git a/src/xenialdan/MagicWE2/commands/debug/PlaceAllBlockstatesCommand.php b/src/xenialdan/MagicWE2/commands/debug/PlaceAllBlockstatesCommand.php index c4ca5474..a213c2a9 100644 --- a/src/xenialdan/MagicWE2/commands/debug/PlaceAllBlockstatesCommand.php +++ b/src/xenialdan/MagicWE2/commands/debug/PlaceAllBlockstatesCommand.php @@ -31,17 +31,17 @@ protected function prepare(): void * @param string $aliasUsed * @param mixed[] $args */ - public function onRun(CommandSender $sender, string $aliasUsed, array $args): void - { - $lang = Loader::getInstance()->getLanguage(); - if ($sender instanceof Player && SessionHelper::hasSession($sender)) { - try { - $lang = SessionHelper::getUserSession($sender)->getLanguage(); - } catch (SessionException $e) { - } - } - if (!$sender instanceof Player) { - $sender->sendMessage(TF::RED . $lang->translateString('error.runingame')); + public function onRun(CommandSender $sender, string $aliasUsed, array $args): void + { + $lang = Loader::getInstance()->getLanguage(); + if ($sender instanceof Player && SessionHelper::hasSession($sender)) { + try { + $lang = SessionHelper::getUserSession($sender)->getLanguage(); + } catch (SessionException $e) { + } + } + if (!$sender instanceof Player) { + $sender->sendMessage(TF::RED . $lang->translateString('error.runingame')); return; } /** @var Player $sender */ diff --git a/src/xenialdan/MagicWE2/commands/history/ClearhistoryCommand.php b/src/xenialdan/MagicWE2/commands/history/ClearhistoryCommand.php index 42e1eb13..6fd92d1e 100644 --- a/src/xenialdan/MagicWE2/commands/history/ClearhistoryCommand.php +++ b/src/xenialdan/MagicWE2/commands/history/ClearhistoryCommand.php @@ -32,22 +32,22 @@ protected function prepare(): void * @param string $aliasUsed * @param mixed[] $args */ - public function onRun(CommandSender $sender, string $aliasUsed, array $args): void - { - $lang = Loader::getInstance()->getLanguage(); - if ($sender instanceof Player && SessionHelper::hasSession($sender)) { - try { - $lang = SessionHelper::getUserSession($sender)->getLanguage(); - } catch (SessionException $e) { - } - } - if (!$sender instanceof Player) { - $sender->sendMessage(TF::RED . $lang->translateString('error.runingame')); - return; - } - /** @var Player $sender */ - try { - $session = SessionHelper::getUserSession($sender); + public function onRun(CommandSender $sender, string $aliasUsed, array $args): void + { + $lang = Loader::getInstance()->getLanguage(); + if ($sender instanceof Player && SessionHelper::hasSession($sender)) { + try { + $lang = SessionHelper::getUserSession($sender)->getLanguage(); + } catch (SessionException $e) { + } + } + if (!$sender instanceof Player) { + $sender->sendMessage(TF::RED . $lang->translateString('error.runingame')); + return; + } + /** @var Player $sender */ + try { + $session = SessionHelper::getUserSession($sender); if (!$session instanceof UserSession) { throw new SessionException($lang->translateString('error.nosession', [Loader::getInstance()->getName()])); } diff --git a/src/xenialdan/MagicWE2/commands/history/RedoCommand.php b/src/xenialdan/MagicWE2/commands/history/RedoCommand.php index c2f197d6..937e5efd 100644 --- a/src/xenialdan/MagicWE2/commands/history/RedoCommand.php +++ b/src/xenialdan/MagicWE2/commands/history/RedoCommand.php @@ -32,21 +32,21 @@ protected function prepare(): void * @param string $aliasUsed * @param mixed[] $args */ - public function onRun(CommandSender $sender, string $aliasUsed, array $args): void - { - $lang = Loader::getInstance()->getLanguage(); - if ($sender instanceof Player && SessionHelper::hasSession($sender)) { - try { - $lang = SessionHelper::getUserSession($sender)->getLanguage(); - } catch (SessionException $e) { - } - } - if (!$sender instanceof Player) { - $sender->sendMessage(TF::RED . $lang->translateString('error.runingame')); - return; - } - /** @var Player $sender */ - try { + public function onRun(CommandSender $sender, string $aliasUsed, array $args): void + { + $lang = Loader::getInstance()->getLanguage(); + if ($sender instanceof Player && SessionHelper::hasSession($sender)) { + try { + $lang = SessionHelper::getUserSession($sender)->getLanguage(); + } catch (SessionException $e) { + } + } + if (!$sender instanceof Player) { + $sender->sendMessage(TF::RED . $lang->translateString('error.runingame')); + return; + } + /** @var Player $sender */ + try { $session = SessionHelper::getUserSession($sender); if (!$session instanceof UserSession) { throw new SessionException($lang->translateString('error.nosession', [Loader::getInstance()->getName()])); diff --git a/src/xenialdan/MagicWE2/commands/history/UndoCommand.php b/src/xenialdan/MagicWE2/commands/history/UndoCommand.php index cb55719c..da8476dc 100644 --- a/src/xenialdan/MagicWE2/commands/history/UndoCommand.php +++ b/src/xenialdan/MagicWE2/commands/history/UndoCommand.php @@ -26,26 +26,27 @@ protected function prepare(): void { $this->setPermission("we.command.history.undo"); } + /** * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args */ - public function onRun(CommandSender $sender, string $aliasUsed, array $args): void - { - $lang = Loader::getInstance()->getLanguage(); - if ($sender instanceof Player && SessionHelper::hasSession($sender)) { - try { - $lang = SessionHelper::getUserSession($sender)->getLanguage(); - } catch (SessionException $e) { - } - } - if (!$sender instanceof Player) { - $sender->sendMessage(TF::RED . $lang->translateString('error.runingame')); - return; - } - /** @var Player $sender */ - try { + public function onRun(CommandSender $sender, string $aliasUsed, array $args): void + { + $lang = Loader::getInstance()->getLanguage(); + if ($sender instanceof Player && SessionHelper::hasSession($sender)) { + try { + $lang = SessionHelper::getUserSession($sender)->getLanguage(); + } catch (SessionException $e) { + } + } + if (!$sender instanceof Player) { + $sender->sendMessage(TF::RED . $lang->translateString('error.runingame')); + return; + } + /** @var Player $sender */ + try { $session = SessionHelper::getUserSession($sender); if (!$session instanceof UserSession) { throw new SessionException($lang->translateString('error.nosession', [Loader::getInstance()->getName()])); diff --git a/src/xenialdan/MagicWE2/commands/selection/HPos1Command.php b/src/xenialdan/MagicWE2/commands/selection/HPos1Command.php index 3c5dfda4..bcfdcc69 100644 --- a/src/xenialdan/MagicWE2/commands/selection/HPos1Command.php +++ b/src/xenialdan/MagicWE2/commands/selection/HPos1Command.php @@ -34,42 +34,42 @@ protected function prepare(): void * @param string $aliasUsed * @param mixed[] $args */ - public function onRun(CommandSender $sender, string $aliasUsed, array $args): void - { - $lang = Loader::getInstance()->getLanguage(); - if ($sender instanceof Player && SessionHelper::hasSession($sender)) { - try { - $lang = SessionHelper::getUserSession($sender)->getLanguage(); - } catch (SessionException $e) { - } - } - if (!$sender instanceof Player) { - $sender->sendMessage(TF::RED . $lang->translateString('error.runingame')); - return; - } - /** @var Player $sender */ - try { - $session = SessionHelper::getUserSession($sender); - if (!$session instanceof UserSession) { + public function onRun(CommandSender $sender, string $aliasUsed, array $args): void + { + $lang = Loader::getInstance()->getLanguage(); + if ($sender instanceof Player && SessionHelper::hasSession($sender)) { + try { + $lang = SessionHelper::getUserSession($sender)->getLanguage(); + } catch (SessionException $e) { + } + } + if (!$sender instanceof Player) { + $sender->sendMessage(TF::RED . $lang->translateString('error.runingame')); + return; + } + /** @var Player $sender */ + try { + $session = SessionHelper::getUserSession($sender); + if (!$session instanceof UserSession) { throw new SessionException($lang->translateString('error.nosession', [Loader::getInstance()->getName()])); - } - $selection = $session->getLatestSelection() ?? $session->addSelection(new Selection($session->getUUID(), $sender->getWorld())); // TODO check if the selection inside of the session updates - if (is_null($selection)) { - throw new Error("No selection created - Check the console for errors"); - } - $target = $sender->getTargetBlock(Loader::getInstance()->getToolDistance()); - if ($target === null) { - $sender->sendMessage(Loader::PREFIX . TF::RED . $lang->translateString('error.notarget')); - return; - } - $selection->setPos1($target->getPos()); - } catch (Exception $error) { - $sender->sendMessage(Loader::PREFIX . TF::RED . $lang->translateString('error.command-error')); - $sender->sendMessage(Loader::PREFIX . TF::RED . $error->getMessage()); - $sender->sendMessage($this->getUsage()); - } catch (Error $error) { - Loader::getInstance()->getLogger()->logException($error); - $sender->sendMessage(Loader::PREFIX . TF::RED . $error->getMessage()); - } - } + } + $selection = $session->getLatestSelection() ?? $session->addSelection(new Selection($session->getUUID(), $sender->getWorld())); // TODO check if the selection inside of the session updates + if (is_null($selection)) { + throw new Error("No selection created - Check the console for errors"); + } + $target = $sender->getTargetBlock(Loader::getInstance()->getToolDistance()); + if ($target === null) { + $sender->sendMessage(Loader::PREFIX . TF::RED . $lang->translateString('error.notarget')); + return; + } + $selection->setPos1($target->getPos()); + } catch (Exception $error) { + $sender->sendMessage(Loader::PREFIX . TF::RED . $lang->translateString('error.command-error')); + $sender->sendMessage(Loader::PREFIX . TF::RED . $error->getMessage()); + $sender->sendMessage($this->getUsage()); + } catch (Error $error) { + Loader::getInstance()->getLogger()->logException($error); + $sender->sendMessage(Loader::PREFIX . TF::RED . $error->getMessage()); + } + } } diff --git a/src/xenialdan/MagicWE2/commands/selection/HPos2Command.php b/src/xenialdan/MagicWE2/commands/selection/HPos2Command.php index e813db0f..a217a941 100644 --- a/src/xenialdan/MagicWE2/commands/selection/HPos2Command.php +++ b/src/xenialdan/MagicWE2/commands/selection/HPos2Command.php @@ -34,42 +34,42 @@ protected function prepare(): void * @param string $aliasUsed * @param mixed[] $args */ - public function onRun(CommandSender $sender, string $aliasUsed, array $args): void - { - $lang = Loader::getInstance()->getLanguage(); - if ($sender instanceof Player && SessionHelper::hasSession($sender)) { - try { - $lang = SessionHelper::getUserSession($sender)->getLanguage(); - } catch (SessionException $e) { - } - } - if (!$sender instanceof Player) { - $sender->sendMessage(TF::RED . $lang->translateString('error.runingame')); - return; - } - /** @var Player $sender */ - try { - $session = SessionHelper::getUserSession($sender); - if (!$session instanceof UserSession) { + public function onRun(CommandSender $sender, string $aliasUsed, array $args): void + { + $lang = Loader::getInstance()->getLanguage(); + if ($sender instanceof Player && SessionHelper::hasSession($sender)) { + try { + $lang = SessionHelper::getUserSession($sender)->getLanguage(); + } catch (SessionException $e) { + } + } + if (!$sender instanceof Player) { + $sender->sendMessage(TF::RED . $lang->translateString('error.runingame')); + return; + } + /** @var Player $sender */ + try { + $session = SessionHelper::getUserSession($sender); + if (!$session instanceof UserSession) { throw new SessionException($lang->translateString('error.nosession', [Loader::getInstance()->getName()])); - } - $selection = $session->getLatestSelection() ?? $session->addSelection(new Selection($session->getUUID(), $sender->getWorld())); // TODO check if the selection inside of the session updates - if (is_null($selection)) { - throw new Error("No selection created - Check the console for errors"); - } - $target = $sender->getTargetBlock(Loader::getInstance()->getToolDistance()); - if ($target === null) { - $sender->sendMessage(Loader::PREFIX . TF::RED . $lang->translateString('error.notarget')); - return; - } - $selection->setPos2($target->getPos()); - } catch (Exception $error) { - $sender->sendMessage(Loader::PREFIX . TF::RED . $lang->translateString('error.command-error')); - $sender->sendMessage(Loader::PREFIX . TF::RED . $error->getMessage()); - $sender->sendMessage($this->getUsage()); - } catch (Error $error) { - Loader::getInstance()->getLogger()->logException($error); - $sender->sendMessage(Loader::PREFIX . TF::RED . $error->getMessage()); - } - } + } + $selection = $session->getLatestSelection() ?? $session->addSelection(new Selection($session->getUUID(), $sender->getWorld())); // TODO check if the selection inside of the session updates + if (is_null($selection)) { + throw new Error("No selection created - Check the console for errors"); + } + $target = $sender->getTargetBlock(Loader::getInstance()->getToolDistance()); + if ($target === null) { + $sender->sendMessage(Loader::PREFIX . TF::RED . $lang->translateString('error.notarget')); + return; + } + $selection->setPos2($target->getPos()); + } catch (Exception $error) { + $sender->sendMessage(Loader::PREFIX . TF::RED . $lang->translateString('error.command-error')); + $sender->sendMessage(Loader::PREFIX . TF::RED . $error->getMessage()); + $sender->sendMessage($this->getUsage()); + } catch (Error $error) { + Loader::getInstance()->getLogger()->logException($error); + $sender->sendMessage(Loader::PREFIX . TF::RED . $error->getMessage()); + } + } } diff --git a/src/xenialdan/MagicWE2/commands/selection/Pos1Command.php b/src/xenialdan/MagicWE2/commands/selection/Pos1Command.php index 85d21d2f..b95a1bef 100644 --- a/src/xenialdan/MagicWE2/commands/selection/Pos1Command.php +++ b/src/xenialdan/MagicWE2/commands/selection/Pos1Command.php @@ -34,37 +34,37 @@ protected function prepare(): void * @param string $aliasUsed * @param mixed[] $args */ - public function onRun(CommandSender $sender, string $aliasUsed, array $args): void - { - $lang = Loader::getInstance()->getLanguage(); - if ($sender instanceof Player && SessionHelper::hasSession($sender)) { - try { - $lang = SessionHelper::getUserSession($sender)->getLanguage(); - } catch (SessionException $e) { - } - } - if (!$sender instanceof Player) { - $sender->sendMessage(TF::RED . $lang->translateString('error.runingame')); - return; - } - /** @var Player $sender */ - try { - $session = SessionHelper::getUserSession($sender); - if (!$session instanceof UserSession) { + public function onRun(CommandSender $sender, string $aliasUsed, array $args): void + { + $lang = Loader::getInstance()->getLanguage(); + if ($sender instanceof Player && SessionHelper::hasSession($sender)) { + try { + $lang = SessionHelper::getUserSession($sender)->getLanguage(); + } catch (SessionException $e) { + } + } + if (!$sender instanceof Player) { + $sender->sendMessage(TF::RED . $lang->translateString('error.runingame')); + return; + } + /** @var Player $sender */ + try { + $session = SessionHelper::getUserSession($sender); + if (!$session instanceof UserSession) { throw new SessionException($lang->translateString('error.nosession', [Loader::getInstance()->getName()])); - } - $selection = $session->getLatestSelection() ?? $session->addSelection(new Selection($session->getUUID(), $sender->getWorld())); // TODO check if the selection inside of the session updates - if (is_null($selection)) { - throw new Error("No selection created - Check the console for errors"); - } - $selection->setPos1($sender->getPosition()); - } catch (Exception $error) { - $sender->sendMessage(Loader::PREFIX . TF::RED . $lang->translateString('error.command-error')); - $sender->sendMessage(Loader::PREFIX . TF::RED . $error->getMessage()); - $sender->sendMessage($this->getUsage()); - } catch (Error $error) { - Loader::getInstance()->getLogger()->logException($error); - $sender->sendMessage(Loader::PREFIX . TF::RED . $error->getMessage()); - } - } + } + $selection = $session->getLatestSelection() ?? $session->addSelection(new Selection($session->getUUID(), $sender->getWorld())); // TODO check if the selection inside of the session updates + if (is_null($selection)) { + throw new Error("No selection created - Check the console for errors"); + } + $selection->setPos1($sender->getPosition()); + } catch (Exception $error) { + $sender->sendMessage(Loader::PREFIX . TF::RED . $lang->translateString('error.command-error')); + $sender->sendMessage(Loader::PREFIX . TF::RED . $error->getMessage()); + $sender->sendMessage($this->getUsage()); + } catch (Error $error) { + Loader::getInstance()->getLogger()->logException($error); + $sender->sendMessage(Loader::PREFIX . TF::RED . $error->getMessage()); + } + } } diff --git a/src/xenialdan/MagicWE2/commands/selection/Pos2Command.php b/src/xenialdan/MagicWE2/commands/selection/Pos2Command.php index 3667021c..d3e2d781 100644 --- a/src/xenialdan/MagicWE2/commands/selection/Pos2Command.php +++ b/src/xenialdan/MagicWE2/commands/selection/Pos2Command.php @@ -34,37 +34,37 @@ protected function prepare(): void * @param string $aliasUsed * @param mixed[] $args */ - public function onRun(CommandSender $sender, string $aliasUsed, array $args): void - { - $lang = Loader::getInstance()->getLanguage(); - if ($sender instanceof Player && SessionHelper::hasSession($sender)) { - try { - $lang = SessionHelper::getUserSession($sender)->getLanguage(); - } catch (SessionException $e) { - } - } - if (!$sender instanceof Player) { - $sender->sendMessage(TF::RED . $lang->translateString('error.runingame')); - return; - } - /** @var Player $sender */ - try { - $session = SessionHelper::getUserSession($sender); - if (!$session instanceof UserSession) { + public function onRun(CommandSender $sender, string $aliasUsed, array $args): void + { + $lang = Loader::getInstance()->getLanguage(); + if ($sender instanceof Player && SessionHelper::hasSession($sender)) { + try { + $lang = SessionHelper::getUserSession($sender)->getLanguage(); + } catch (SessionException $e) { + } + } + if (!$sender instanceof Player) { + $sender->sendMessage(TF::RED . $lang->translateString('error.runingame')); + return; + } + /** @var Player $sender */ + try { + $session = SessionHelper::getUserSession($sender); + if (!$session instanceof UserSession) { throw new SessionException($lang->translateString('error.nosession', [Loader::getInstance()->getName()])); - } - $selection = $session->getLatestSelection() ?? $session->addSelection(new Selection($session->getUUID(), $sender->getWorld())); // TODO check if the selection inside of the session updates - if (is_null($selection)) { - throw new Error("No selection created - Check the console for errors"); - } - $selection->setPos2($sender->getPosition()); - } catch (Exception $error) { - $sender->sendMessage(Loader::PREFIX . TF::RED . $lang->translateString('error.command-error')); - $sender->sendMessage(Loader::PREFIX . TF::RED . $error->getMessage()); - $sender->sendMessage($this->getUsage()); - } catch (Error $error) { - Loader::getInstance()->getLogger()->logException($error); - $sender->sendMessage(Loader::PREFIX . TF::RED . $error->getMessage()); - } - } + } + $selection = $session->getLatestSelection() ?? $session->addSelection(new Selection($session->getUUID(), $sender->getWorld())); // TODO check if the selection inside of the session updates + if (is_null($selection)) { + throw new Error("No selection created - Check the console for errors"); + } + $selection->setPos2($sender->getPosition()); + } catch (Exception $error) { + $sender->sendMessage(Loader::PREFIX . TF::RED . $lang->translateString('error.command-error')); + $sender->sendMessage(Loader::PREFIX . TF::RED . $error->getMessage()); + $sender->sendMessage($this->getUsage()); + } catch (Error $error) { + Loader::getInstance()->getLogger()->logException($error); + $sender->sendMessage(Loader::PREFIX . TF::RED . $error->getMessage()); + } + } } diff --git a/src/xenialdan/MagicWE2/commands/selection/info/ListChunksCommand.php b/src/xenialdan/MagicWE2/commands/selection/info/ListChunksCommand.php index 00c577e7..c5de7b0d 100644 --- a/src/xenialdan/MagicWE2/commands/selection/info/ListChunksCommand.php +++ b/src/xenialdan/MagicWE2/commands/selection/info/ListChunksCommand.php @@ -34,38 +34,38 @@ protected function prepare(): void * @param string $aliasUsed * @param mixed[] $args */ - public function onRun(CommandSender $sender, string $aliasUsed, array $args): void - { - $lang = Loader::getInstance()->getLanguage(); - if ($sender instanceof Player && SessionHelper::hasSession($sender)) { - try { - $lang = SessionHelper::getUserSession($sender)->getLanguage(); - } catch (SessionException $e) { - } - } - if (!$sender instanceof Player) { - $sender->sendMessage(TF::RED . $lang->translateString('error.runingame')); - return; - } - /** @var Player $sender */ - try { - $session = SessionHelper::getUserSession($sender); - if (is_null($session)) { + public function onRun(CommandSender $sender, string $aliasUsed, array $args): void + { + $lang = Loader::getInstance()->getLanguage(); + if ($sender instanceof Player && SessionHelper::hasSession($sender)) { + try { + $lang = SessionHelper::getUserSession($sender)->getLanguage(); + } catch (SessionException $e) { + } + } + if (!$sender instanceof Player) { + $sender->sendMessage(TF::RED . $lang->translateString('error.runingame')); + return; + } + /** @var Player $sender */ + try { + $session = SessionHelper::getUserSession($sender); + if (is_null($session)) { throw new SessionException($lang->translateString('error.nosession', [Loader::getInstance()->getName()])); - } - $selection = $session->getLatestSelection(); - if (is_null($selection)) { + } + $selection = $session->getLatestSelection(); + if (is_null($selection)) { throw new SelectionException($lang->translateString('error.noselection')); - } - if (!$selection->isValid()) { + } + if (!$selection->isValid()) { throw new SelectionException($lang->translateString('error.selectioninvalid')); - } - if ($selection->getWorld() !== $sender->getWorld()) { + } + if ($selection->getWorld() !== $sender->getWorld()) { $sender->sendMessage(Loader::PREFIX . TF::GOLD . $lang->translateString('warning.differentworld')); - } - $touchedChunks = $selection->getShape()->getTouchedChunks($selection->getWorld()); - $session->sendMessage(TF::DARK_AQUA . $lang->translateString('command.listchunks.found', [count($touchedChunks)])); - foreach ($touchedChunks as $chunkHash => $touchedChunk) { + } + $touchedChunks = $selection->getShape()->getTouchedChunks($selection->getWorld()); + $session->sendMessage(TF::DARK_AQUA . $lang->translateString('command.listchunks.found', [count($touchedChunks)])); + foreach ($touchedChunks as $chunkHash => $touchedChunk) { $chunk = FastChunkSerializer::deserialize($touchedChunk); $biomes = []; for ($x = 0; $x < 16; $x++) diff --git a/src/xenialdan/MagicWE2/commands/selection/info/SizeCommand.php b/src/xenialdan/MagicWE2/commands/selection/info/SizeCommand.php index 9e505846..4c1e0b04 100644 --- a/src/xenialdan/MagicWE2/commands/selection/info/SizeCommand.php +++ b/src/xenialdan/MagicWE2/commands/selection/info/SizeCommand.php @@ -32,32 +32,32 @@ protected function prepare(): void * @param string $aliasUsed * @param mixed[] $args */ - public function onRun(CommandSender $sender, string $aliasUsed, array $args): void - { - $lang = Loader::getInstance()->getLanguage(); - if ($sender instanceof Player && SessionHelper::hasSession($sender)) { - try { - $lang = SessionHelper::getUserSession($sender)->getLanguage(); - } catch (SessionException $e) { - } - } - if (!$sender instanceof Player) { - $sender->sendMessage(TF::RED . $lang->translateString('error.runingame')); - return; - } - /** @var Player $sender */ - try { - $session = SessionHelper::getUserSession($sender); - if (is_null($session)) { + public function onRun(CommandSender $sender, string $aliasUsed, array $args): void + { + $lang = Loader::getInstance()->getLanguage(); + if ($sender instanceof Player && SessionHelper::hasSession($sender)) { + try { + $lang = SessionHelper::getUserSession($sender)->getLanguage(); + } catch (SessionException $e) { + } + } + if (!$sender instanceof Player) { + $sender->sendMessage(TF::RED . $lang->translateString('error.runingame')); + return; + } + /** @var Player $sender */ + try { + $session = SessionHelper::getUserSession($sender); + if (is_null($session)) { throw new SessionException($lang->translateString('error.nosession', [Loader::getInstance()->getName()])); - } - $selection = $session->getLatestSelection(); - if (is_null($selection)) { + } + $selection = $session->getLatestSelection(); + if (is_null($selection)) { throw new SelectionException($lang->translateString('error.noselection')); - } - if (!$selection->isValid()) { + } + if (!$selection->isValid()) { throw new SelectionException($lang->translateString('error.selectioninvalid')); - } + } if ($selection->getWorld() !== $sender->getWorld()) { $sender->sendMessage(Loader::PREFIX . TF::GOLD . $lang->translateString('warning.differentworld')); } diff --git a/src/xenialdan/MagicWE2/commands/tool/DebugCommand.php b/src/xenialdan/MagicWE2/commands/tool/DebugCommand.php index f4114fa8..c985a19b 100644 --- a/src/xenialdan/MagicWE2/commands/tool/DebugCommand.php +++ b/src/xenialdan/MagicWE2/commands/tool/DebugCommand.php @@ -37,21 +37,21 @@ protected function prepare(): void * @param string $aliasUsed * @param mixed[] $args */ - public function onRun(CommandSender $sender, string $aliasUsed, array $args): void - { - $lang = Loader::getInstance()->getLanguage(); - if ($sender instanceof Player && SessionHelper::hasSession($sender)) { - try { - $lang = SessionHelper::getUserSession($sender)->getLanguage(); - } catch (SessionException $e) { - } - } - if (!$sender instanceof Player) { - $sender->sendMessage(TF::RED . $lang->translateString('error.runingame')); - return; - } - /** @var Player $sender */ - try { + public function onRun(CommandSender $sender, string $aliasUsed, array $args): void + { + $lang = Loader::getInstance()->getLanguage(); + if ($sender instanceof Player && SessionHelper::hasSession($sender)) { + try { + $lang = SessionHelper::getUserSession($sender)->getLanguage(); + } catch (SessionException $e) { + } + } + if (!$sender instanceof Player) { + $sender->sendMessage(TF::RED . $lang->translateString('error.runingame')); + return; + } + /** @var Player $sender */ + try { $item = ItemFactory::getInstance()->get(ItemIds::STICK); $item->addEnchantment(new EnchantmentInstance(Loader::$ench)); $item->setCustomName(Loader::PREFIX . TF::BOLD . TF::DARK_PURPLE . $lang->translateString('tool.debug')); @@ -63,12 +63,12 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo $item->getNamedTag()->setTag(API::TAG_MAGIC_WE, CompoundTag::create()); $sender->getInventory()->addItem($item); } catch (Exception $error) { - $sender->sendMessage(Loader::PREFIX . TF::RED . $lang->translateString('error.command-error')); - $sender->sendMessage(Loader::PREFIX . TF::RED . $error->getMessage()); - $sender->sendMessage($this->getUsage()); - } catch (Error $error) { - Loader::getInstance()->getLogger()->logException($error); - $sender->sendMessage(Loader::PREFIX . TF::RED . $error->getMessage()); - } - } + $sender->sendMessage(Loader::PREFIX . TF::RED . $lang->translateString('error.command-error')); + $sender->sendMessage(Loader::PREFIX . TF::RED . $error->getMessage()); + $sender->sendMessage($this->getUsage()); + } catch (Error $error) { + Loader::getInstance()->getLogger()->logException($error); + $sender->sendMessage(Loader::PREFIX . TF::RED . $error->getMessage()); + } + } } diff --git a/src/xenialdan/MagicWE2/commands/tool/FloodCommand.php b/src/xenialdan/MagicWE2/commands/tool/FloodCommand.php index 581c81a5..edee3614 100644 --- a/src/xenialdan/MagicWE2/commands/tool/FloodCommand.php +++ b/src/xenialdan/MagicWE2/commands/tool/FloodCommand.php @@ -26,45 +26,45 @@ protected function prepare(): void * @param string $aliasUsed * @param mixed[] $args */ - public function onRun(CommandSender $sender, string $aliasUsed, array $args): void - { - $sender->sendMessage(TF::RED . "TEMPORARILY DISABLED!"); - /* - if (!$sender instanceof Player) return; - /** @var Player $sender * / - $lang = Loader::getInstance()->getLanguage(); - try { - if ($sender instanceof Player) { - $form = new CustomForm(Loader::PREFIX . TF::BOLD . TF::DARK_PURPLE . $lang->translateString('ui.flood.title')); - $form->addElement(new Slider($lang->translateString('ui.flood.options.limit'), 0, 5000, 500.0)); - $form->addElement(new Input($lang->translateString('ui.flood.options.blocks'), $lang->translateString('ui.flood.options.blocks.placeholder'))); - $form->addElement(new Label($lang->translateString('ui.flood.options.label.infoapply'))); - $form->setCallable(function (Player $player, $data) use ($form) { - $item = ItemFactory::get(ItemIds::BUCKET, 1); - $item->addEnchantment(new EnchantmentInstance(Enchantment::getEnchantment(Loader::FAKE_ENCH_ID))); - $item->setCustomName(Loader::PREFIX . TF::BOLD . TF::DARK_PURPLE . 'Flood'); - $item->setLore(BrushCommand::generateLore($form->getContent(), $data)); - $item->setNamedTagEntry(new CompoundTag(API::TAG_MAGIC_WE, [ - new StringTag("blocks", $data[1]), - new FloatTag("limit", $data[0]), - ])); - $player->getInventory()->addItem($item); - }); - $sender->sendForm($form); - } else { - $sender->sendMessage(TF::RED . "Console can not use this command."); - } - } catch (\Exception $error) { - $sender->sendMessage(Loader::PREFIX . TF::RED . Loader::getInstance()->getLanguage()->translateString('error.command-error')); - $sender->sendMessage(Loader::PREFIX . TF::RED . $error->getMessage()); - $sender->sendMessage($this->getUsage()); - } catch (\ArgumentCountError $error) { - $sender->sendMessage(Loader::PREFIX . TF::RED . Loader::getInstance()->getLanguage()->translateString('error.command-error')); - $sender->sendMessage(Loader::PREFIX . TF::RED . $error->getMessage()); - $sender->sendMessage($this->getUsage()); - } catch (\Error $error) { - Loader::getInstance()->getLogger()->logException($error); - $sender->sendMessage(Loader::PREFIX . TF::RED . $error->getMessage()); - }*/ - } + public function onRun(CommandSender $sender, string $aliasUsed, array $args): void + { + $sender->sendMessage(TF::RED . "TEMPORARILY DISABLED!"); + /* + if (!$sender instanceof Player) return; + /** @var Player $sender * / + $lang = Loader::getInstance()->getLanguage(); + try { + if ($sender instanceof Player) { + $form = new CustomForm(Loader::PREFIX . TF::BOLD . TF::DARK_PURPLE . $lang->translateString('ui.flood.title')); + $form->addElement(new Slider($lang->translateString('ui.flood.options.limit'), 0, 5000, 500.0)); + $form->addElement(new Input($lang->translateString('ui.flood.options.blocks'), $lang->translateString('ui.flood.options.blocks.placeholder'))); + $form->addElement(new Label($lang->translateString('ui.flood.options.label.infoapply'))); + $form->setCallable(function (Player $player, $data) use ($form) { + $item = ItemFactory::get(ItemIds::BUCKET, 1); + $item->addEnchantment(new EnchantmentInstance(Enchantment::getEnchantment(Loader::FAKE_ENCH_ID))); + $item->setCustomName(Loader::PREFIX . TF::BOLD . TF::DARK_PURPLE . 'Flood'); + $item->setLore(BrushCommand::generateLore($form->getContent(), $data)); + $item->setNamedTagEntry(new CompoundTag(API::TAG_MAGIC_WE, [ + new StringTag("blocks", $data[1]), + new FloatTag("limit", $data[0]), + ])); + $player->getInventory()->addItem($item); + }); + $sender->sendForm($form); + } else { + $sender->sendMessage(TF::RED . "Console can not use this command."); + } + } catch (\Exception $error) { + $sender->sendMessage(Loader::PREFIX . TF::RED . Loader::getInstance()->getLanguage()->translateString('error.command-error')); + $sender->sendMessage(Loader::PREFIX . TF::RED . $error->getMessage()); + $sender->sendMessage($this->getUsage()); + } catch (\ArgumentCountError $error) { + $sender->sendMessage(Loader::PREFIX . TF::RED . Loader::getInstance()->getLanguage()->translateString('error.command-error')); + $sender->sendMessage(Loader::PREFIX . TF::RED . $error->getMessage()); + $sender->sendMessage($this->getUsage()); + } catch (\Error $error) { + Loader::getInstance()->getLogger()->logException($error); + $sender->sendMessage(Loader::PREFIX . TF::RED . $error->getMessage()); + }*/ + } } diff --git a/src/xenialdan/MagicWE2/commands/tool/ToggledebugCommand.php b/src/xenialdan/MagicWE2/commands/tool/ToggledebugCommand.php index 9e4b44bb..ddfa6c8b 100644 --- a/src/xenialdan/MagicWE2/commands/tool/ToggledebugCommand.php +++ b/src/xenialdan/MagicWE2/commands/tool/ToggledebugCommand.php @@ -30,21 +30,21 @@ protected function prepare(): void * @param string $aliasUsed * @param mixed[] $args */ - public function onRun(CommandSender $sender, string $aliasUsed, array $args): void - { - $lang = Loader::getInstance()->getLanguage(); - if ($sender instanceof Player && SessionHelper::hasSession($sender)) { - try { - $lang = SessionHelper::getUserSession($sender)->getLanguage(); - } catch (SessionException $e) { - } - } - if (!$sender instanceof Player) { - $sender->sendMessage(TF::RED . $lang->translateString('error.runingame')); - return; - } - /** @var Player $sender */ - try { + public function onRun(CommandSender $sender, string $aliasUsed, array $args): void + { + $lang = Loader::getInstance()->getLanguage(); + if ($sender instanceof Player && SessionHelper::hasSession($sender)) { + try { + $lang = SessionHelper::getUserSession($sender)->getLanguage(); + } catch (SessionException $e) { + } + } + if (!$sender instanceof Player) { + $sender->sendMessage(TF::RED . $lang->translateString('error.runingame')); + return; + } + /** @var Player $sender */ + try { $session = SessionHelper::getUserSession($sender); if (is_null($session)) { throw new SessionException($lang->translateString('error.nosession', [Loader::getInstance()->getName()])); diff --git a/src/xenialdan/MagicWE2/commands/tool/TogglewandCommand.php b/src/xenialdan/MagicWE2/commands/tool/TogglewandCommand.php index f17861dc..053e18d9 100644 --- a/src/xenialdan/MagicWE2/commands/tool/TogglewandCommand.php +++ b/src/xenialdan/MagicWE2/commands/tool/TogglewandCommand.php @@ -30,21 +30,21 @@ protected function prepare(): void * @param string $aliasUsed * @param mixed[] $args */ - public function onRun(CommandSender $sender, string $aliasUsed, array $args): void - { - $lang = Loader::getInstance()->getLanguage(); - if ($sender instanceof Player && SessionHelper::hasSession($sender)) { - try { - $lang = SessionHelper::getUserSession($sender)->getLanguage(); - } catch (SessionException $e) { - } - } - if (!$sender instanceof Player) { - $sender->sendMessage(TF::RED . $lang->translateString('error.runingame')); - return; - } - /** @var Player $sender */ - try { + public function onRun(CommandSender $sender, string $aliasUsed, array $args): void + { + $lang = Loader::getInstance()->getLanguage(); + if ($sender instanceof Player && SessionHelper::hasSession($sender)) { + try { + $lang = SessionHelper::getUserSession($sender)->getLanguage(); + } catch (SessionException $e) { + } + } + if (!$sender instanceof Player) { + $sender->sendMessage(TF::RED . $lang->translateString('error.runingame')); + return; + } + /** @var Player $sender */ + try { $session = SessionHelper::getUserSession($sender); if (is_null($session)) { throw new SessionException($lang->translateString('error.nosession', [Loader::getInstance()->getName()])); diff --git a/src/xenialdan/MagicWE2/commands/tool/WandCommand.php b/src/xenialdan/MagicWE2/commands/tool/WandCommand.php index 8177e95c..591bc32e 100644 --- a/src/xenialdan/MagicWE2/commands/tool/WandCommand.php +++ b/src/xenialdan/MagicWE2/commands/tool/WandCommand.php @@ -38,21 +38,21 @@ protected function prepare(): void * @param string $aliasUsed * @param mixed[] $args */ - public function onRun(CommandSender $sender, string $aliasUsed, array $args): void - { - $lang = Loader::getInstance()->getLanguage(); - if ($sender instanceof Player && SessionHelper::hasSession($sender)) { - try { - $lang = SessionHelper::getUserSession($sender)->getLanguage(); - } catch (SessionException $e) { - } - } - if (!$sender instanceof Player) { - $sender->sendMessage(TF::RED . $lang->translateString('error.runingame')); - return; - } - /** @var Player $sender */ - try { + public function onRun(CommandSender $sender, string $aliasUsed, array $args): void + { + $lang = Loader::getInstance()->getLanguage(); + if ($sender instanceof Player && SessionHelper::hasSession($sender)) { + try { + $lang = SessionHelper::getUserSession($sender)->getLanguage(); + } catch (SessionException $e) { + } + } + if (!$sender instanceof Player) { + $sender->sendMessage(TF::RED . $lang->translateString('error.runingame')); + return; + } + /** @var Player $sender */ + try { /** @var Durable $item */ $item = ItemFactory::getInstance()->get(ItemIds::WOODEN_AXE); $item->addEnchantment(new EnchantmentInstance(Loader::$ench)); @@ -66,12 +66,12 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo $item->getNamedTag()->setTag(API::TAG_MAGIC_WE, CompoundTag::create()); if (!$sender->getInventory()->contains($item)) $sender->getInventory()->addItem($item); } catch (Exception $error) { - $sender->sendMessage(Loader::PREFIX . TF::RED . $lang->translateString('error.command-error')); - $sender->sendMessage(Loader::PREFIX . TF::RED . $error->getMessage()); - $sender->sendMessage($this->getUsage()); - } catch (Error $error) { - Loader::getInstance()->getLogger()->logException($error); - $sender->sendMessage(Loader::PREFIX . TF::RED . $error->getMessage()); - } - } + $sender->sendMessage(Loader::PREFIX . TF::RED . $lang->translateString('error.command-error')); + $sender->sendMessage(Loader::PREFIX . TF::RED . $error->getMessage()); + $sender->sendMessage($this->getUsage()); + } catch (Error $error) { + Loader::getInstance()->getLogger()->logException($error); + $sender->sendMessage(Loader::PREFIX . TF::RED . $error->getMessage()); + } + } } diff --git a/src/xenialdan/MagicWE2/commands/utility/CalculateCommand.php b/src/xenialdan/MagicWE2/commands/utility/CalculateCommand.php index 113c1e56..d8687873 100644 --- a/src/xenialdan/MagicWE2/commands/utility/CalculateCommand.php +++ b/src/xenialdan/MagicWE2/commands/utility/CalculateCommand.php @@ -37,15 +37,15 @@ protected function prepare(): void * @param string $aliasUsed * @param mixed[] $args */ - public function onRun(CommandSender $sender, string $aliasUsed, array $args): void - { - $lang = Loader::getInstance()->getLanguage(); - if ($sender instanceof Player && SessionHelper::hasSession($sender)) { - try { - $lang = SessionHelper::getUserSession($sender)->getLanguage(); - } catch (SessionException $e) { - } - } + public function onRun(CommandSender $sender, string $aliasUsed, array $args): void + { + $lang = Loader::getInstance()->getLanguage(); + if ($sender instanceof Player && SessionHelper::hasSession($sender)) { + try { + $lang = SessionHelper::getUserSession($sender)->getLanguage(); + } catch (SessionException $e) { + } + } try { $sender->sendMessage((string)$args["expression"] . " = " . API::evalAsMath((string)$args["expression"])); } catch (CalculationException $error) { diff --git a/src/xenialdan/MagicWE2/event/MWEEditEvent.php b/src/xenialdan/MagicWE2/event/MWEEditEvent.php index 503ebecc..004b011e 100644 --- a/src/xenialdan/MagicWE2/event/MWEEditEvent.php +++ b/src/xenialdan/MagicWE2/event/MWEEditEvent.php @@ -30,54 +30,54 @@ class MWEEditEvent extends MWEEvent implements Cancellable */ public function __construct(Plugin $plugin, array $oldBlocks, array $newBlocks, ?Session $session) { - parent::__construct($plugin); - $this->oldBlocks = $oldBlocks; - $this->newBlocks = $newBlocks; - $this->session = $session; - } + parent::__construct($plugin); + $this->oldBlocks = $oldBlocks; + $this->newBlocks = $newBlocks; + $this->session = $session; + } - /** - * @return null|Session - */ - public function getSession(): ?Session - { - return $this->session; - } + /** + * @return null|Session + */ + public function getSession(): ?Session + { + return $this->session; + } - /** - * @return null|Player - */ - public function getPlayer(): ?Player - { - if (($session = $this->getSession()) instanceof UserSession) - /** @var UserSession $session */ - return $session->getPlayer(); - return null; - } + /** + * @return null|Player + */ + public function getPlayer(): ?Player + { + if (($session = $this->getSession()) instanceof UserSession) + /** @var UserSession $session */ + return $session->getPlayer(); + return null; + } - /** - * @param null|Player $player - */ - public function setPlayer(?Player $player): void - { - if (($session = $this->getSession()) instanceof UserSession) - /** @var UserSession $session */ - $session->setPlayer($player); - } + /** + * @param null|Player $player + */ + public function setPlayer(?Player $player): void + { + if (($session = $this->getSession()) instanceof UserSession) + /** @var UserSession $session */ + $session->setPlayer($player); + } - /** - * @return Block[] - */ - public function getOldBlocks(): array - { - return $this->oldBlocks; - } + /** + * @return Block[] + */ + public function getOldBlocks(): array + { + return $this->oldBlocks; + } - /** - * @return Block[] - */ - public function getNewBlocks(): array - { + /** + * @return Block[] + */ + public function getNewBlocks(): array + { return $this->newBlocks; } diff --git a/src/xenialdan/MagicWE2/event/MWESelectionChangeEvent.php b/src/xenialdan/MagicWE2/event/MWESelectionChangeEvent.php index 6cdbe748..6fa42f2f 100644 --- a/src/xenialdan/MagicWE2/event/MWESelectionChangeEvent.php +++ b/src/xenialdan/MagicWE2/event/MWESelectionChangeEvent.php @@ -49,15 +49,15 @@ public function setSelection(Selection $selection): void $this->selection = $selection; } - /** - * @return null|Session - */ - public function getSession(): ?Session - { - return $this->session; - } + /** + * @return null|Session + */ + public function getSession(): ?Session + { + return $this->session; + } - /** + /** * @return null|Player */ public function getPlayer(): ?Player diff --git a/src/xenialdan/MagicWE2/helper/AsyncChunkManager.php b/src/xenialdan/MagicWE2/helper/AsyncChunkManager.php index 4ef07060..d05e0d1f 100644 --- a/src/xenialdan/MagicWE2/helper/AsyncChunkManager.php +++ b/src/xenialdan/MagicWE2/helper/AsyncChunkManager.php @@ -8,16 +8,16 @@ class AsyncChunkManager extends SimpleChunkManager { - public function getBlockArrayAt(int $x, int $y, int $z): array//TODO replace with getFullBlock + public function getBlockArrayAt(int $x, int $y, int $z): array//TODO replace with getFullBlock { return [$this->getBlockAt($x, $y, $z)->getId(), $this->getBlockAt($x, $y, $z)->getMeta()]; } - /** - * @return Chunk[] - */ - public function getChunks(): array - { - return $this->chunks; - } + /** + * @return Chunk[] + */ + public function getChunks(): array + { + return $this->chunks; + } } \ No newline at end of file diff --git a/src/xenialdan/MagicWE2/helper/BlockQuery.php b/src/xenialdan/MagicWE2/helper/BlockQuery.php index 1cda2c2c..dce14490 100644 --- a/src/xenialdan/MagicWE2/helper/BlockQuery.php +++ b/src/xenialdan/MagicWE2/helper/BlockQuery.php @@ -42,7 +42,7 @@ public function parse(bool $update = true): self /** @var BlockStatesParser $blockstateParser */ $blockstateParser = BlockStatesParser::getInstance(); $blockstateParser::fromString($this);//this should already set the blockFullId because it is a reference - var_dump($this->hasBlock() ? "Has block, " . $this->blockFullId : "Does not have block"); + //var_dump($this->hasBlock() ? "Has block, " . $this->blockFullId : "Does not have block"); //TODO throw BlockQueryParsingFailedException if blockFullId was not set? `if(!$this->hasBlock())` return $this; } diff --git a/src/xenialdan/MagicWE2/helper/Progress.php b/src/xenialdan/MagicWE2/helper/Progress.php index 41d2690e..fc67e892 100644 --- a/src/xenialdan/MagicWE2/helper/Progress.php +++ b/src/xenialdan/MagicWE2/helper/Progress.php @@ -20,10 +20,10 @@ public function __construct(float $progress, string $info) { $this->progress = $progress; $this->string = $info; - } + } - public function __toString() - { - return "Progress: " . $this->progress . " String: " . $this->string; - } + public function __toString() + { + return "Progress: " . $this->progress . " String: " . $this->string; + } } \ No newline at end of file diff --git a/src/xenialdan/MagicWE2/helper/Scoreboard.php b/src/xenialdan/MagicWE2/helper/Scoreboard.php index d2d782e2..a980eb31 100644 --- a/src/xenialdan/MagicWE2/helper/Scoreboard.php +++ b/src/xenialdan/MagicWE2/helper/Scoreboard.php @@ -11,6 +11,7 @@ use pocketmine\utils\TextFormat as TF; use ReflectionClass; use ReflectionException; +use xenialdan\MagicWE2\API; use xenialdan\MagicWE2\clipboard\SingleClipboard; use xenialdan\MagicWE2\Loader; use xenialdan\MagicWE2\selection\Selection; @@ -28,18 +29,18 @@ public function handleScoreboard(UserSession $session): void $line = 0; $selection = $session->getLatestSelection(); ScoreFactory::setScoreLine($player, ++$line, TF::GOLD . $session->getLanguage()->translateString("spacer", ["Selection"])); - ScoreFactory::setScoreLine($player, ++$line, TF::ITALIC . "Position: " . TF::RESET . "{$this->vecToString($selection->getPos1()->asVector3())} » {$this->vecToString($selection->getPos2()->asVector3())}"); + ScoreFactory::setScoreLine($player, ++$line, TF::ITALIC . "Position: " . TF::RESET . API::vecToString($selection->getPos1()->asVector3()) . " » " . API::vecToString($selection->getPos2()->asVector3())); ScoreFactory::setScoreLine($player, ++$line, TF::ITALIC . "World: " . TF::RESET . $selection->getWorld()->getFolderName()); ScoreFactory::setScoreLine($player, ++$line, TF::ITALIC . "Shape: " . TF::RESET . (new ReflectionClass($selection->shape))->getShortName()); - ScoreFactory::setScoreLine($player, ++$line, TF::ITALIC . "Size: " . TF::RESET . "{$this->vecToString(new Vector3($selection->getSizeX(),$selection->getSizeY(),$selection->getSizeZ()))} ({$selection->getShape()->getTotalCount()})"); + ScoreFactory::setScoreLine($player, ++$line, TF::ITALIC . "Size: " . TF::RESET . API::vecToString(new Vector3($selection->getSizeX(), $selection->getSizeY(), $selection->getSizeZ())) . " ({$selection->getShape()->getTotalCount()})"); ScoreFactory::setScoreLine($player, ++$line, TF::GOLD . $session->getLanguage()->translateString("spacer", ["Settings"])); ScoreFactory::setScoreLine($player, ++$line, TF::ITALIC . "Tool Range: " . TF::RESET . Loader::getInstance()->getToolDistance()); $editLimit = Loader::getInstance()->getEditLimit(); - ScoreFactory::setScoreLine($player, ++$line, TF::ITALIC . "Limit: " . TF::RESET . ($editLimit === -1 ? $this->boolToString(false) : $editLimit)); - ScoreFactory::setScoreLine($player, ++$line, TF::ITALIC . "Wand Tool: " . TF::RESET . $this->boolToString($session->isWandEnabled())); - ScoreFactory::setScoreLine($player, ++$line, TF::ITALIC . "Debug Tool: " . TF::RESET . $this->boolToString($session->isDebugToolEnabled())); - ScoreFactory::setScoreLine($player, ++$line, TF::ITALIC . "WAILA: " . TF::RESET . $this->boolToString($session->isWailaEnabled())); + ScoreFactory::setScoreLine($player, ++$line, TF::ITALIC . "Limit: " . TF::RESET . ($editLimit === -1 ? API::boolToString(false) : $editLimit)); + ScoreFactory::setScoreLine($player, ++$line, TF::ITALIC . "Wand Tool: " . TF::RESET . API::boolToString($session->isWandEnabled())); + ScoreFactory::setScoreLine($player, ++$line, TF::ITALIC . "Debug Tool: " . TF::RESET . API::boolToString($session->isDebugToolEnabled())); + ScoreFactory::setScoreLine($player, ++$line, TF::ITALIC . "WAILA: " . TF::RESET . API::boolToString($session->isWailaEnabled())); if (($cb = $session->getCurrentClipboard()) instanceof SingleClipboard) { ScoreFactory::setScoreLine($player, ++$line, TF::GOLD . $session->getLanguage()->translateString("spacer", ["Clipboard"])); @@ -48,7 +49,7 @@ public function handleScoreboard(UserSession $session): void ScoreFactory::setScoreLine($player, ++$line, TF::ITALIC . "Name: " . TF::RESET . $cb->customName); if ($cb->selection instanceof Selection) { ScoreFactory::setScoreLine($player, ++$line, TF::ITALIC . "Shape: " . TF::RESET . (new ReflectionClass($cb->selection->shape))->getShortName()); - ScoreFactory::setScoreLine($player, ++$line, TF::ITALIC . "Size: " . TF::RESET . "{$this->vecToString(new Vector3($cb->selection->getSizeX(),$cb->selection->getSizeY(),$cb->selection->getSizeZ()))} ({$cb->getTotalCount()})"); + ScoreFactory::setScoreLine($player, ++$line, TF::ITALIC . "Size: " . TF::RESET . API::vecToString(new Vector3($cb->selection->getSizeX(), $cb->selection->getSizeY(), $cb->selection->getSizeZ())) . " ({$cb->getTotalCount()})"); } } //todo current block palette, schematics, brushes @@ -57,14 +58,4 @@ public function handleScoreboard(UserSession $session): void } } } - - private function vecToString(Vector3 $v): string - { - return TF::RESET . "[" . TF::RED . $v->getFloorX() . TF::RESET . ":" . TF::GREEN . $v->getFloorY() . TF::RESET . ":" . TF::BLUE . $v->getFloorZ() . TF::RESET . "]"; - } - - private function boolToString(bool $b): string - { - return $b ? TF::RESET . TF::GREEN . "On" . TF::RESET : TF::RESET . TF::RED . "Off" . TF::RESET; - } } \ No newline at end of file diff --git a/src/xenialdan/MagicWE2/helper/StructureStore.php b/src/xenialdan/MagicWE2/helper/StructureStore.php index 8a271328..969f7192 100644 --- a/src/xenialdan/MagicWE2/helper/StructureStore.php +++ b/src/xenialdan/MagicWE2/helper/StructureStore.php @@ -28,8 +28,7 @@ final class StructureStore /** @noinspection MkdirRaceConditionInspection */ public function __construct() { - @mkdir(Loader::getInstance()->getDataFolder() . 'structures'); - @mkdir(Loader::getInstance()->getDataFolder() . 'schematics'); + @mkdir(Loader::getInstance()->getDataFolder() . 'assets'); } /** @@ -44,9 +43,8 @@ public function loadStructure(string $filename, bool $override = true): MCStruct { $id = pathinfo($filename, PATHINFO_FILENAME); if (!$override && array_key_exists($id, $this->structures)) throw new InvalidArgumentException("Can not override $id"); - $path = Loader::getInstance()->getDataFolder() . 'structures' . DIRECTORY_SEPARATOR . $id . '.mcstructure';//TODO redundant? + $path = Loader::getInstance()->getDataFolder() . 'assets' . DIRECTORY_SEPARATOR . $id . '.mcstructure'; $structure = new MCStructure(); - $structure->parse($path); $this->structures[$id] = $structure; return $this->structures[$id]; @@ -76,7 +74,7 @@ public function loadSchematic(string $filename, bool $override = true): Schemati { $id = pathinfo($filename, PATHINFO_FILENAME); if (!$override && array_key_exists($id, $this->schematics)) throw new InvalidArgumentException("Can not override $id"); - $path = Loader::getInstance()->getDataFolder() . 'schematics' . DIRECTORY_SEPARATOR . $id . '.schematic'; + $path = Loader::getInstance()->getDataFolder() . 'assets' . DIRECTORY_SEPARATOR . $id . '.schematic'; $schematic = new Schematic(); $schematic->parse($path); $this->schematics[$id] = $schematic; diff --git a/src/xenialdan/MagicWE2/selection/shape/Cube.php b/src/xenialdan/MagicWE2/selection/shape/Cube.php index 70cc3082..acc3779e 100644 --- a/src/xenialdan/MagicWE2/selection/shape/Cube.php +++ b/src/xenialdan/MagicWE2/selection/shape/Cube.php @@ -54,9 +54,9 @@ public function getBlocks($manager, BlockPalette $filterblocks, int $flags = API } } } - } - } - } + } + } + } /** * Returns a flat layer of all included x z positions in selection @@ -65,7 +65,7 @@ public function getBlocks($manager, BlockPalette $filterblocks, int $flags = API * @return Generator|Vector2[] * @throws Exception */ - public function getLayer($manager, int $flags = API::FLAG_BASE): Generator + public function getLayer($manager, int $flags = API::FLAG_BASE): Generator { $this->validateChunkManager($manager); for ($x = (int)floor($this->getMinVec3()->x); $x <= floor($this->getMaxVec3()->x); $x++) { @@ -75,13 +75,13 @@ public function getLayer($manager, int $flags = API::FLAG_BASE): Generator } } - /** - * @param World|AsyncChunkManager $manager - * @return string[] fastSerialized chunks - * @throws Exception - */ - public function getTouchedChunks($manager): array - { + /** + * @param World|AsyncChunkManager $manager + * @return string[] fastSerialized chunks + * @throws Exception + */ + public function getTouchedChunks($manager): array + { $this->validateChunkManager($manager); $maxX = ($this->getMaxVec3()->x + 1) >> 4; $minX = $this->getMinVec3()->x >> 4; @@ -97,30 +97,30 @@ public function getTouchedChunks($manager): array print "Touched Chunk at: $x:$z" . PHP_EOL; $touchedChunks[World::chunkHash($x, $z)] = FastChunkSerializer::serialize($chunk); } - } - print "Touched chunks count: " . count($touchedChunks) . PHP_EOL; - return $touchedChunks; - } + } + print "Touched chunks count: " . count($touchedChunks) . PHP_EOL; + return $touchedChunks; + } - public function getAABB(): AxisAlignedBB - { - return new AxisAlignedBB( - ceil($this->pasteVector->x - $this->width / 2), - $this->pasteVector->y, - ceil($this->pasteVector->z - $this->width / 2), - -1 + ceil($this->pasteVector->x - $this->width / 2) + $this->width, - -1 + $this->pasteVector->y + $this->width, - -1 + ceil($this->pasteVector->z - $this->width / 2) + $this->width - ); - } + public function getAABB(): AxisAlignedBB + { + return new AxisAlignedBB( + ceil($this->pasteVector->x - $this->width / 2), + $this->pasteVector->y, + ceil($this->pasteVector->z - $this->width / 2), + -1 + ceil($this->pasteVector->x - $this->width / 2) + $this->width, + -1 + $this->pasteVector->y + $this->width, + -1 + ceil($this->pasteVector->z - $this->width / 2) + $this->width + ); + } - public function getTotalCount(): int - { - return $this->width ** 3; - } + public function getTotalCount(): int + { + return $this->width ** 3; + } - public static function getName(): string - { - return "Cube"; - } + public static function getName(): string + { + return "Cube"; + } } \ No newline at end of file diff --git a/src/xenialdan/MagicWE2/selection/shape/Cuboid.php b/src/xenialdan/MagicWE2/selection/shape/Cuboid.php index 623ba9a1..6189615a 100644 --- a/src/xenialdan/MagicWE2/selection/shape/Cuboid.php +++ b/src/xenialdan/MagicWE2/selection/shape/Cuboid.php @@ -33,14 +33,14 @@ class Cuboid extends Shape */ public function __construct(Vector3 $pasteVector, int $width, int $height, int $depth) { - $this->pasteVector = $pasteVector; - $this->width = $width; - $this->height = $height; - $this->depth = $depth; - } + $this->pasteVector = $pasteVector; + $this->width = $width; + $this->height = $height; + $this->depth = $depth; + } - public static function constructFromPositions(Vector3 $pos1, Vector3 $pos2): self - { + public static function constructFromPositions(Vector3 $pos1, Vector3 $pos2): self + { $width = (int)abs($pos1->getX() - $pos2->getX()) + 1; $height = (int)abs($pos1->getY() - $pos2->getY()) + 1; $depth = (int)abs($pos1->getZ() - $pos2->getZ()) + 1; @@ -76,9 +76,9 @@ public function getBlocks($manager, BlockPalette $filterblocks, int $flags = API } } } - } - } - } + } + } + } /** * Returns a flat layer of all included x z positions in selection @@ -87,7 +87,7 @@ public function getBlocks($manager, BlockPalette $filterblocks, int $flags = API * @return Generator|Vector2[] * @throws Exception */ - public function getLayer($manager, int $flags = API::FLAG_BASE): Generator + public function getLayer($manager, int $flags = API::FLAG_BASE): Generator { $this->validateChunkManager($manager); for ($x = (int)floor($this->getMinVec3()->x); $x <= floor($this->getMaxVec3()->x); $x++) { @@ -97,13 +97,13 @@ public function getLayer($manager, int $flags = API::FLAG_BASE): Generator } } - /** - * @param World|AsyncChunkManager $manager - * @return string[] fastSerialized chunks - * @throws Exception - */ - public function getTouchedChunks($manager): array - { + /** + * @param World|AsyncChunkManager $manager + * @return string[] fastSerialized chunks + * @throws Exception + */ + public function getTouchedChunks($manager): array + { $this->validateChunkManager($manager); $maxX = ($this->getMaxVec3()->x + 1) >> 4; $minX = $this->getMinVec3()->x >> 4; @@ -119,31 +119,31 @@ public function getTouchedChunks($manager): array $touchedChunks[World::chunkHash($x, $z)] = FastChunkSerializer::serialize($chunk); } } - return $touchedChunks; - } + return $touchedChunks; + } - public function getAABB(): AxisAlignedBB - { - return new AxisAlignedBB( - ceil($this->pasteVector->x - $this->width / 2), - $this->pasteVector->y, - ceil($this->pasteVector->z - $this->depth / 2), - -1 + ceil($this->pasteVector->x - $this->width / 2) + $this->width, - -1 + $this->pasteVector->y + $this->height, - -1 + ceil($this->pasteVector->z - $this->depth / 2) + $this->depth - ); - } + public function getAABB(): AxisAlignedBB + { + return new AxisAlignedBB( + ceil($this->pasteVector->x - $this->width / 2), + $this->pasteVector->y, + ceil($this->pasteVector->z - $this->depth / 2), + -1 + ceil($this->pasteVector->x - $this->width / 2) + $this->width, + -1 + $this->pasteVector->y + $this->height, + -1 + ceil($this->pasteVector->z - $this->depth / 2) + $this->depth + ); + } - /** - * @return int - */ - public function getTotalCount(): int - { - return $this->width * $this->height * $this->depth; - } + /** + * @return int + */ + public function getTotalCount(): int + { + return $this->width * $this->height * $this->depth; + } - public static function getName(): string - { - return "Cuboid"; - } + public static function getName(): string + { + return "Cuboid"; + } } \ No newline at end of file diff --git a/src/xenialdan/MagicWE2/selection/shape/Cylinder.php b/src/xenialdan/MagicWE2/selection/shape/Cylinder.php index 6eec93a0..c5b7a947 100644 --- a/src/xenialdan/MagicWE2/selection/shape/Cylinder.php +++ b/src/xenialdan/MagicWE2/selection/shape/Cylinder.php @@ -31,9 +31,9 @@ class Cylinder extends Shape public function __construct(Vector3 $pasteVector, int $height, int $diameter) { $this->pasteVector = $pasteVector; - $this->height = $height; - $this->diameter = $diameter; - } + $this->height = $height; + $this->diameter = $diameter; + } /** * Returns the blocks by their actual position @@ -67,9 +67,9 @@ public function getBlocks($manager, BlockPalette $filterblocks, int $flags = API } } } - } - } - } + } + } + } /** * Returns a flat layer of all included x z positions in selection @@ -78,7 +78,7 @@ public function getBlocks($manager, BlockPalette $filterblocks, int $flags = API * @return Generator|Vector2[] * @throws Exception */ - public function getLayer($manager, int $flags = API::FLAG_BASE): Generator + public function getLayer($manager, int $flags = API::FLAG_BASE): Generator { $this->validateChunkManager($manager); $centerVec2 = new Vector2($this->getPasteVector()->getX(), $this->getPasteVector()->getZ()); @@ -92,13 +92,13 @@ public function getLayer($manager, int $flags = API::FLAG_BASE): Generator } } - /** - * @param World|AsyncChunkManager $manager - * @return string[] fastSerialized chunks - * @throws Exception - */ - public function getTouchedChunks($manager): array - {//TODO optimize to remove "corner" chunks + /** + * @param World|AsyncChunkManager $manager + * @return string[] fastSerialized chunks + * @throws Exception + */ + public function getTouchedChunks($manager): array + {//TODO optimize to remove "corner" chunks $this->validateChunkManager($manager); $maxX = ($this->getMaxVec3()->x + 1) >> 4; $minX = $this->getMinVec3()->x >> 4; @@ -114,30 +114,30 @@ public function getTouchedChunks($manager): array print "Touched Chunk at: $x:$z" . PHP_EOL; $touchedChunks[World::chunkHash($x, $z)] = FastChunkSerializer::serialize($chunk); } - } - print "Touched chunks count: " . count($touchedChunks) . PHP_EOL; - return $touchedChunks; - } + } + print "Touched chunks count: " . count($touchedChunks) . PHP_EOL; + return $touchedChunks; + } - public function getAABB(): AxisAlignedBB - { - return new AxisAlignedBB( - floor($this->pasteVector->x - $this->diameter / 2), - $this->pasteVector->y, - floor($this->pasteVector->z - $this->diameter / 2), - -1 + floor($this->pasteVector->x - $this->diameter / 2) + $this->diameter, - -1 + $this->pasteVector->y + $this->height, - -1 + floor($this->pasteVector->z - $this->diameter / 2) + $this->diameter - ); - } + public function getAABB(): AxisAlignedBB + { + return new AxisAlignedBB( + floor($this->pasteVector->x - $this->diameter / 2), + $this->pasteVector->y, + floor($this->pasteVector->z - $this->diameter / 2), + -1 + floor($this->pasteVector->x - $this->diameter / 2) + $this->diameter, + -1 + $this->pasteVector->y + $this->height, + -1 + floor($this->pasteVector->z - $this->diameter / 2) + $this->diameter + ); + } - public function getTotalCount(): int - { + public function getTotalCount(): int + { return (int)ceil(M_PI * (($this->diameter / 2) ** 2) * $this->height); - } + } - public static function getName(): string - { - return "Cylinder"; - } + public static function getName(): string + { + return "Cylinder"; + } } \ No newline at end of file diff --git a/src/xenialdan/MagicWE2/selection/shape/Ellipsoid.php b/src/xenialdan/MagicWE2/selection/shape/Ellipsoid.php index a414815f..68cd59d3 100644 --- a/src/xenialdan/MagicWE2/selection/shape/Ellipsoid.php +++ b/src/xenialdan/MagicWE2/selection/shape/Ellipsoid.php @@ -33,11 +33,11 @@ class Ellipsoid extends Shape */ public function __construct(Vector3 $pasteVector, int $width, int $height, int $depth) { - $this->pasteVector = $pasteVector; - $this->width = $width; - $this->height = $height; - $this->depth = $depth; - } + $this->pasteVector = $pasteVector; + $this->width = $width; + $this->height = $height; + $this->depth = $depth; + } /** * Returns the blocks by their actual position @@ -58,12 +58,12 @@ public function getBlocks($manager, BlockPalette $filterblocks, int $flags = API $zrad = $this->depth / 2; $xradSquared = $xrad ** 2; $yradSquared = $yrad ** 2; - $zradSquared = $zrad ** 2; - $targetX = $this->pasteVector->getX(); - $targetY = $this->pasteVector->getY(); - $targetZ = $this->pasteVector->getZ(); + $zradSquared = $zrad ** 2; + $targetX = $this->pasteVector->getX(); + $targetY = $this->pasteVector->getY(); + $targetZ = $this->pasteVector->getZ(); - for ($x = (int)floor($centerVec2->x - $this->width / 2 /*- 1*/); $x <= floor($centerVec2->x + $this->width / 2 /*+ 1*/); $x++) { + for ($x = (int)floor($centerVec2->x - $this->width / 2 /*- 1*/); $x <= floor($centerVec2->x + $this->width / 2 /*+ 1*/); $x++) { $xSquared = ($targetX - $x) ** 2; for ($y = (int)floor($this->getPasteVector()->y) + 1, $ry = 0; $y <= floor($this->getPasteVector()->y + $this->height); $y++, $ry++) { $ySquared = ($targetY - $y + $yrad) ** 2; @@ -86,9 +86,9 @@ public function getBlocks($manager, BlockPalette $filterblocks, int $flags = API } } } - } - } - } + } + } + } /** * Returns a flat layer of all included x z positions in selection @@ -97,17 +97,17 @@ public function getBlocks($manager, BlockPalette $filterblocks, int $flags = API * @return Generator|Vector2[] * @throws Exception */ - public function getLayer($manager, int $flags = API::FLAG_BASE): Generator - { - $this->validateChunkManager($manager); - $centerVec2 = new Vector2($this->getPasteVector()->getX(), $this->getPasteVector()->getZ()); - - $xrad = $this->width / 2; - $zrad = $this->depth / 2; - $xradSquared = $xrad ** 2; - $zradSquared = $zrad ** 2; - $targetX = $this->pasteVector->getX(); - $targetZ = $this->pasteVector->getZ(); + public function getLayer($manager, int $flags = API::FLAG_BASE): Generator + { + $this->validateChunkManager($manager); + $centerVec2 = new Vector2($this->getPasteVector()->getX(), $this->getPasteVector()->getZ()); + + $xrad = $this->width / 2; + $zrad = $this->depth / 2; + $xradSquared = $xrad ** 2; + $zradSquared = $zrad ** 2; + $targetX = $this->pasteVector->getX(); + $targetZ = $this->pasteVector->getZ(); for ($x = (int)floor($centerVec2->x - $this->width / 2 /*- 1*/); $x <= floor($centerVec2->x + $this->width / 2 /*+ 1*/); $x++) { $xSquared = ($targetX - $x) ** 2; @@ -118,15 +118,15 @@ public function getLayer($manager, int $flags = API::FLAG_BASE): Generator yield new Vector2($x, $z); } } - } - - /** - * @param World|AsyncChunkManager $manager - * @return string[] fastSerialized chunks - * @throws Exception - */ - public function getTouchedChunks($manager): array - {//TODO optimize to remove "corner" chunks + } + + /** + * @param World|AsyncChunkManager $manager + * @return string[] fastSerialized chunks + * @throws Exception + */ + public function getTouchedChunks($manager): array + {//TODO optimize to remove "corner" chunks $this->validateChunkManager($manager); $maxX = ($this->getMaxVec3()->x + 1) >> 4; $minX = $this->getMinVec3()->x >> 4; @@ -142,30 +142,30 @@ public function getTouchedChunks($manager): array print "Touched Chunk at: $x:$z" . PHP_EOL; $touchedChunks[World::chunkHash($x, $z)] = FastChunkSerializer::serialize($chunk); } - } - print "Touched chunks count: " . count($touchedChunks) . PHP_EOL; - return $touchedChunks; - } - - public function getAABB(): AxisAlignedBB - { - return new AxisAlignedBB( - floor($this->pasteVector->x - $this->width / 2), - $this->pasteVector->y, - floor($this->pasteVector->z - $this->depth / 2), - -1 + floor($this->pasteVector->x - $this->width / 2) + $this->width, - -1 + $this->pasteVector->y + $this->height, - -1 + floor($this->pasteVector->z - $this->depth / 2) + $this->depth - ); - } - - public function getTotalCount(): int - { + } + print "Touched chunks count: " . count($touchedChunks) . PHP_EOL; + return $touchedChunks; + } + + public function getAABB(): AxisAlignedBB + { + return new AxisAlignedBB( + floor($this->pasteVector->x - $this->width / 2), + $this->pasteVector->y, + floor($this->pasteVector->z - $this->depth / 2), + -1 + floor($this->pasteVector->x - $this->width / 2) + $this->width, + -1 + $this->pasteVector->y + $this->height, + -1 + floor($this->pasteVector->z - $this->depth / 2) + $this->depth + ); + } + + public function getTotalCount(): int + { return (int)floor(4 * M_PI * (($this->width / 2) + 1) * (($this->height / 2) + 1) * (($this->depth / 2) + 1) / 3); - } + } - public static function getName(): string - { - return "Ellipsoid"; - } + public static function getName(): string + { + return "Ellipsoid"; + } } \ No newline at end of file diff --git a/src/xenialdan/MagicWE2/selection/shape/Pyramid.php b/src/xenialdan/MagicWE2/selection/shape/Pyramid.php index 1e50d505..2a0cf42e 100644 --- a/src/xenialdan/MagicWE2/selection/shape/Pyramid.php +++ b/src/xenialdan/MagicWE2/selection/shape/Pyramid.php @@ -35,13 +35,13 @@ class Pyramid extends Shape * @param bool $flipped */ public function __construct(Vector3 $pasteVector, int $width, int $height, int $depth, bool $flipped = false) - { - $this->pasteVector = $pasteVector; - $this->width = $width; - $this->height = $height; - $this->depth = $depth; - $this->flipped = $flipped; - } + { + $this->pasteVector = $pasteVector; + $this->width = $width; + $this->height = $height; + $this->depth = $depth; + $this->flipped = $flipped; + } /** * Returns the blocks by their actual position @@ -85,9 +85,9 @@ public function getBlocks($manager, BlockPalette $filterblocks, int $flags = API } } } - } - } - } + } + } + } /** * Returns a flat layer of all included x z positions in selection @@ -96,7 +96,7 @@ public function getBlocks($manager, BlockPalette $filterblocks, int $flags = API * @return Generator|Vector2[] * @throws Exception */ - public function getLayer($manager, int $flags = API::FLAG_BASE): Generator + public function getLayer($manager, int $flags = API::FLAG_BASE): Generator { $this->validateChunkManager($manager); $centerVec2 = new Vector2($this->getPasteVector()->getX(), $this->getPasteVector()->getZ()); @@ -108,13 +108,13 @@ public function getLayer($manager, int $flags = API::FLAG_BASE): Generator } } - /** - * @param World|AsyncChunkManager $manager - * @return string[] fastSerialized chunks - * @throws Exception - */ - public function getTouchedChunks($manager): array - {//TODO optimize to remove "corner" chunks + /** + * @param World|AsyncChunkManager $manager + * @return string[] fastSerialized chunks + * @throws Exception + */ + public function getTouchedChunks($manager): array + {//TODO optimize to remove "corner" chunks $this->validateChunkManager($manager); $maxX = ($this->getMaxVec3()->x + 1) >> 4; $minX = $this->getMinVec3()->x >> 4; @@ -130,30 +130,30 @@ public function getTouchedChunks($manager): array print "Touched Chunk at: $x:$z" . PHP_EOL; $touchedChunks[World::chunkHash($x, $z)] = FastChunkSerializer::serialize($chunk); } - } - print "Touched chunks count: " . count($touchedChunks) . PHP_EOL; - return $touchedChunks; - } + } + print "Touched chunks count: " . count($touchedChunks) . PHP_EOL; + return $touchedChunks; + } - public function getAABB(): AxisAlignedBB - { - return new AxisAlignedBB( - floor($this->pasteVector->x - $this->width / 2), - $this->pasteVector->y, - floor($this->pasteVector->z - $this->depth / 2), - -1 + floor($this->pasteVector->x - $this->width / 2) + $this->width, - -1 + $this->pasteVector->y + $this->height, - -1 + floor($this->pasteVector->z - $this->depth / 2) + $this->depth - ); - } + public function getAABB(): AxisAlignedBB + { + return new AxisAlignedBB( + floor($this->pasteVector->x - $this->width / 2), + $this->pasteVector->y, + floor($this->pasteVector->z - $this->depth / 2), + -1 + floor($this->pasteVector->x - $this->width / 2) + $this->width, + -1 + $this->pasteVector->y + $this->height, + -1 + floor($this->pasteVector->z - $this->depth / 2) + $this->depth + ); + } - public function getTotalCount(): int - { - return (int)ceil((1 / 3) * ($this->width * $this->depth) * $this->height); - } + public function getTotalCount(): int + { + return (int)ceil((1 / 3) * ($this->width * $this->depth) * $this->height); + } - public static function getName(): string - { - return "Pyramid"; - } + public static function getName(): string + { + return "Pyramid"; + } } \ No newline at end of file diff --git a/src/xenialdan/MagicWE2/selection/shape/Shape.php b/src/xenialdan/MagicWE2/selection/shape/Shape.php index b8661d34..a0ee1b8d 100644 --- a/src/xenialdan/MagicWE2/selection/shape/Shape.php +++ b/src/xenialdan/MagicWE2/selection/shape/Shape.php @@ -32,13 +32,13 @@ public function setPasteVector(Vector3 $pasteVector): void $this->pasteVector = $pasteVector->asVector3(); } - /** - * Creates a chunk manager used for async editing - * @param Chunk[] $chunks - * @return AsyncChunkManager - */ - public static function getChunkManager(array $chunks): AsyncChunkManager - { + /** + * Creates a chunk manager used for async editing + * @param Chunk[] $chunks + * @return AsyncChunkManager + */ + public static function getChunkManager(array $chunks): AsyncChunkManager + { $manager = new AsyncChunkManager(); foreach ($chunks as $hash => $chunk) { World::getXZ($hash, $chunkX, $chunkZ); @@ -47,16 +47,16 @@ public static function getChunkManager(array $chunks): AsyncChunkManager return $manager; } - /** - * @param mixed $manager - * @throws InvalidArgumentException - */ - public function validateChunkManager($manager): void - { - if (!$manager instanceof World && !$manager instanceof AsyncChunkManager) throw new InvalidArgumentException(get_class($manager) . " is not an instance of World or AsyncChunkManager"); - } + /** + * @param mixed $manager + * @throws InvalidArgumentException + */ + public function validateChunkManager($manager): void + { + if (!$manager instanceof World && !$manager instanceof AsyncChunkManager) throw new InvalidArgumentException(get_class($manager) . " is not an instance of World or AsyncChunkManager"); + } - abstract public function getTotalCount(): int; + abstract public function getTotalCount(): int; /** * Returns the blocks by their actual position @@ -75,52 +75,52 @@ abstract public function getBlocks($manager, BlockPalette $filterblocks, int $fl * @return Generator|Vector2[] * @throws Exception */ - abstract public function getLayer($manager, int $flags = API::FLAG_BASE): Generator; - - /** - * @param ChunkManager $manager - * @return string[] fastSerialized chunks - * @throws Exception - */ - abstract public function getTouchedChunks(ChunkManager $manager): array; - - abstract public function getAABB(): AxisAlignedBB; - - /** - * @return Vector3 - */ - public function getMinVec3(): Vector3 - { - return new Vector3($this->getAABB()->minX, $this->getAABB()->minY, $this->getAABB()->minZ); - } - - /** - * @return Vector3 - */ - public function getMaxVec3(): Vector3 - { - return new Vector3($this->getAABB()->maxX, $this->getAABB()->maxY, $this->getAABB()->maxZ); - } - - abstract public static function getName(): string; - - public function getShapeProperties(): array - { + abstract public function getLayer($manager, int $flags = API::FLAG_BASE): Generator; + + /** + * @param ChunkManager $manager + * @return string[] fastSerialized chunks + * @throws Exception + */ + abstract public function getTouchedChunks(ChunkManager $manager): array; + + abstract public function getAABB(): AxisAlignedBB; + + /** + * @return Vector3 + */ + public function getMinVec3(): Vector3 + { + return new Vector3($this->getAABB()->minX, $this->getAABB()->minY, $this->getAABB()->minZ); + } + + /** + * @return Vector3 + */ + public function getMaxVec3(): Vector3 + { + return new Vector3($this->getAABB()->maxX, $this->getAABB()->maxY, $this->getAABB()->maxZ); + } + + abstract public static function getName(): string; + + public function getShapeProperties(): array + { return array_diff(get_object_vars($this), get_class_vars(__CLASS__)); - } - - /** - * String representation of object - * @link http://php.net/manual/en/serializable.serialize.php - * @return string the string representation of the object or null - * @since 5.1.0 - */ - public function serialize() - { - return serialize((array)$this); - } - - /** + } + + /** + * String representation of object + * @link http://php.net/manual/en/serializable.serialize.php + * @return string the string representation of the object or null + * @since 5.1.0 + */ + public function serialize() + { + return serialize((array)$this); + } + + /** * Constructs the object * @link http://php.net/manual/en/serializable.unserialize.php * @param string $serialized

@@ -130,8 +130,8 @@ public function serialize() * @since 5.1.0 * @noinspection PhpMissingParamTypeInspection */ - public function unserialize($serialized) - { + public function unserialize($serialized) + { $unserialize = unserialize($serialized/*, ['allowed_classes' => [__CLASS__]]*/);//TODO test pm4 array_walk($unserialize, function ($value, $key) { $this->$key = $value; diff --git a/src/xenialdan/MagicWE2/selection/shape/ShapeRegistry.php b/src/xenialdan/MagicWE2/selection/shape/ShapeRegistry.php index 7dfd1f74..d6279fbc 100644 --- a/src/xenialdan/MagicWE2/selection/shape/ShapeRegistry.php +++ b/src/xenialdan/MagicWE2/selection/shape/ShapeRegistry.php @@ -20,57 +20,57 @@ class ShapeRegistry//todo use SingletonTrait public const PYRAMID = "Pyramid"; public const ELLIPSOID = "Ellipsoid"; - public function __construct() - { - self::registerShape(self::SPHERE, Sphere::class); - self::registerShape(self::CUBE, Cube::class); - self::registerShape(self::CUBOID, Cuboid::class); - self::registerShape(self::CYLINDER, Cylinder::class); - self::registerShape(self::CONE, Cone::class); - self::registerShape(self::PYRAMID, Pyramid::class); - self::registerShape(self::ELLIPSOID, Ellipsoid::class); - self::registerShape(self::CUSTOM, Custom::class); - } + public function __construct() + { + self::registerShape(self::SPHERE, Sphere::class); + self::registerShape(self::CUBE, Cube::class); + self::registerShape(self::CUBOID, Cuboid::class); + self::registerShape(self::CYLINDER, Cylinder::class); + self::registerShape(self::CONE, Cone::class); + self::registerShape(self::PYRAMID, Pyramid::class); + self::registerShape(self::ELLIPSOID, Ellipsoid::class); + self::registerShape(self::CUSTOM, Custom::class); + } - public static function registerShape(string $name, string $class): void - { - self::$shapes[$name] = $class; - } + public static function registerShape(string $name, string $class): void + { + self::$shapes[$name] = $class; + } - /** - * @return array - */ - public static function getShapes(): array - { - return self::$shapes; - } + /** + * @return array + */ + public static function getShapes(): array + { + return self::$shapes; + } - /** - * @param string $name - * @return string - * @throws ShapeNotFoundException - */ - public static function getShape(string $name): string - { - if (isset(self::$shapes[$name])) return self::$shapes[$name]; - throw new ShapeNotFoundException("Shape $name not found"); - } + /** + * @param string $name + * @return string + * @throws ShapeNotFoundException + */ + public static function getShape(string $name): string + { + if (isset(self::$shapes[$name])) return self::$shapes[$name]; + throw new ShapeNotFoundException("Shape $name not found"); + } - /** - * @param string $shapeClass - * @return string - * @throws ShapeNotFoundException - */ - public static function getShapeName(string $shapeClass): string - { - $names = array_flip(self::$shapes); - if (isset($names[$shapeClass])) return $names[$shapeClass]; - throw new ShapeNotFoundException("Shape $shapeClass not found"); - } + /** + * @param string $shapeClass + * @return string + * @throws ShapeNotFoundException + */ + public static function getShapeName(string $shapeClass): string + { + $names = array_flip(self::$shapes); + if (isset($names[$shapeClass])) return $names[$shapeClass]; + throw new ShapeNotFoundException("Shape $shapeClass not found"); + } - public static function getDefaultShapeProperties(string $className): array - { - return array_diff_key(get_class_vars($className), get_class_vars(Shape::class)); - } + public static function getDefaultShapeProperties(string $className): array + { + return array_diff_key(get_class_vars($className), get_class_vars(Shape::class)); + } } \ No newline at end of file diff --git a/src/xenialdan/MagicWE2/session/PluginSession.php b/src/xenialdan/MagicWE2/session/PluginSession.php index ad6698ee..ad97b95a 100644 --- a/src/xenialdan/MagicWE2/session/PluginSession.php +++ b/src/xenialdan/MagicWE2/session/PluginSession.php @@ -23,25 +23,25 @@ public function __construct(Plugin $plugin) } public function getPlugin(): Plugin - { - return $this->plugin; - } - - public function __toString() - { - return __CLASS__ . - " UUID: " . $this->getUUID()->__toString() . - " Plugin: " . $this->getPlugin()->getName() . - " Selections: " . count($this->getSelections()) . - " Latest: " . $this->getLatestSelectionUUID() . - " Clipboards: " . count($this->getClipboards()) . - " Current: " . $this->getCurrentClipboardIndex() . - " Undos: " . count($this->undoHistory) . - " Redos: " . count($this->redoHistory); - } - - public function sendMessage(string $message): void - { - $this->plugin->getLogger()->info(Loader::PREFIX . $message); - } + { + return $this->plugin; + } + + public function __toString() + { + return __CLASS__ . + " UUID: " . $this->getUUID()->__toString() . + " Plugin: " . $this->getPlugin()->getName() . + " Selections: " . count($this->getSelections()) . + " Latest: " . $this->getLatestSelectionUUID() . + " Clipboards: " . count($this->getClipboards()) . + " Current: " . $this->getCurrentClipboardIndex() . + " Undos: " . count($this->undoHistory) . + " Redos: " . count($this->redoHistory); + } + + public function sendMessage(string $message): void + { + $this->plugin->getLogger()->info(Loader::PREFIX . $message); + } } \ No newline at end of file diff --git a/src/xenialdan/MagicWE2/session/Session.php b/src/xenialdan/MagicWE2/session/Session.php index 06ac0dfe..c3f6cf17 100644 --- a/src/xenialdan/MagicWE2/session/Session.php +++ b/src/xenialdan/MagicWE2/session/Session.php @@ -49,7 +49,7 @@ public function getUUID(): UUID } /** - * @param UUID $uuid + * @param UUID $uuid */ public function setUUID(UUID $uuid): void { @@ -103,203 +103,203 @@ public function &getLatestSelection(): ?Selection } /** - * @return Selection[] - */ - public function getSelections(): array - { - return $this->selections; - } + * @return Selection[] + */ + public function getSelections(): array + { + return $this->selections; + } - /** - * @param mixed $selections - */ - public function setSelections($selections): void - { - $this->selections = $selections; - } + /** + * @param mixed $selections + */ + public function setSelections($selections): void + { + $this->selections = $selections; + } - /** - * @return UUID|null - */ - public function getLatestSelectionUUID(): ?UUID - { - return $this->latestselection; - } + /** + * @return UUID|null + */ + public function getLatestSelectionUUID(): ?UUID + { + return $this->latestselection; + } - /** - * @param UUID $latestselection - */ - public function setLatestSelectionUUID(UUID $latestselection): void - { - $this->latestselection = $latestselection; - } + /** + * @param UUID $latestselection + */ + public function setLatestSelectionUUID(UUID $latestselection): void + { + $this->latestselection = $latestselection; + } - /** - * @return int - */ - public function getCurrentClipboardIndex(): int - { - return $this->currentClipboard; - } + /** + * @return int + */ + public function getCurrentClipboardIndex(): int + { + return $this->currentClipboard; + } - /** - * @return null|Clipboard - */ - public function getCurrentClipboard(): ?Clipboard - { - return $this->clipboards[$this->currentClipboard] ?? null; - } + /** + * @return null|Clipboard + */ + public function getCurrentClipboard(): ?Clipboard + { + return $this->clipboards[$this->currentClipboard] ?? null; + } - /** - * @param string $name - * @return null|Clipboard - */ - public function getClipboardByName(string $name): ?Clipboard - { - foreach ($this->clipboards as $clipboard) { - if ($clipboard->getCustomName() === $name) return $clipboard; - } - return null; - } + /** + * @param string $name + * @return null|Clipboard + */ + public function getClipboardByName(string $name): ?Clipboard + { + foreach ($this->clipboards as $clipboard) { + if ($clipboard->getCustomName() === $name) return $clipboard; + } + return null; + } - /** - * @param int $id - * @return null|Clipboard - */ - public function getClipboardById(int $id): ?Clipboard - { - return $this->clipboards[$id] ?? null; - } + /** + * @param int $id + * @return null|Clipboard + */ + public function getClipboardById(int $id): ?Clipboard + { + return $this->clipboards[$id] ?? null; + } - /** - * TODO - * @return Clipboard[] - */ - public function getClipboards(): array - { - return $this->clipboards; - } + /** + * TODO + * @return Clipboard[] + */ + public function getClipboards(): array + { + return $this->clipboards; + } - /** - * TODO - * @param Clipboard[] $clipboards - * @return bool - */ - public function setClipboards(array $clipboards): bool - { - $this->clipboards = $clipboards; - return true; - } + /** + * TODO + * @param Clipboard[] $clipboards + * @return bool + */ + public function setClipboards(array $clipboards): bool + { + $this->clipboards = $clipboards; + return true; + } - /** - * @param Clipboard $clipboard - * @param bool $setAsCurrent - * @return int The index of the clipboard - */ - public function addClipboard(Clipboard $clipboard, bool $setAsCurrent = true): int - { - $amount = array_push($this->clipboards, $clipboard); - if ($amount > self::MAX_CLIPBOARDS) array_shift($this->clipboards); - $i = array_search($clipboard, $this->clipboards, true); - if ($i !== false) { - if ($setAsCurrent) $this->currentClipboard = (int)$i; - return (int)$i; - } - return -1; - } + /** + * @param Clipboard $clipboard + * @param bool $setAsCurrent + * @return int The index of the clipboard + */ + public function addClipboard(Clipboard $clipboard, bool $setAsCurrent = true): int + { + $amount = array_push($this->clipboards, $clipboard); + if ($amount > self::MAX_CLIPBOARDS) array_shift($this->clipboards); + $i = array_search($clipboard, $this->clipboards, true); + if ($i !== false) { + if ($setAsCurrent) $this->currentClipboard = (int)$i; + return (int)$i; + } + return -1; + } - /** - * @param RevertClipboard $revertClipboard - */ - public function addRevert(RevertClipboard $revertClipboard): void - { - $this->redoHistory->clear(); - $this->undoHistory->push($revertClipboard); - while ($this->undoHistory->count() > self::MAX_HISTORY) { - $this->undoHistory->shift(); - } - } + /** + * @param RevertClipboard $revertClipboard + */ + public function addRevert(RevertClipboard $revertClipboard): void + { + $this->redoHistory->clear(); + $this->undoHistory->push($revertClipboard); + while ($this->undoHistory->count() > self::MAX_HISTORY) { + $this->undoHistory->shift(); + } + } - /** - * @throws Exception - */ - public function undo(): void - { - if ($this->undoHistory->count() === 0) { - $this->sendMessage(TF::RED . $this->getLanguage()->translateString('session.undo.none')); - return; - } - /** @var RevertClipboard $revertClipboard */ - $revertClipboard = $this->undoHistory->pop(); + /** + * @throws Exception + */ + public function undo(): void + { + if ($this->undoHistory->count() === 0) { + $this->sendMessage(TF::RED . $this->getLanguage()->translateString('session.undo.none')); + return; + } + /** @var RevertClipboard $revertClipboard */ + $revertClipboard = $this->undoHistory->pop(); $world = $revertClipboard->getWorld(); - foreach ($revertClipboard->chunks as $hash => $chunk) { + foreach ($revertClipboard->chunks as $hash => $chunk) { World::getXZ($hash, $x, $z); $revertClipboard->chunks[$hash] = $world->getChunk($x, $z); } - Server::getInstance()->getAsyncPool()->submitTask(new AsyncRevertTask($this->getUUID(), $revertClipboard, AsyncRevertTask::TYPE_UNDO)); - $this->sendMessage(TF::GREEN . $this->getLanguage()->translateString('session.undo.left', [count($this->undoHistory)])); - } + Server::getInstance()->getAsyncPool()->submitTask(new AsyncRevertTask($this->getUUID(), $revertClipboard, AsyncRevertTask::TYPE_UNDO)); + $this->sendMessage(TF::GREEN . $this->getLanguage()->translateString('session.undo.left', [count($this->undoHistory)])); + } - /** - * @throws InvalidArgumentException - * @throws RuntimeException - */ - public function redo(): void - { - if ($this->redoHistory->count() === 0) { - $this->sendMessage(TF::RED . $this->getLanguage()->translateString('session.redo.none')); - return; - } - /** @var RevertClipboard $revertClipboard */ - $revertClipboard = $this->redoHistory->pop(); - Server::getInstance()->getAsyncPool()->submitTask(new AsyncRevertTask($this->getUUID(), $revertClipboard, AsyncRevertTask::TYPE_REDO)); - $this->sendMessage(TF::GREEN . $this->getLanguage()->translateString('session.redo.left', [count($this->redoHistory)])); - } + /** + * @throws InvalidArgumentException + * @throws RuntimeException + */ + public function redo(): void + { + if ($this->redoHistory->count() === 0) { + $this->sendMessage(TF::RED . $this->getLanguage()->translateString('session.redo.none')); + return; + } + /** @var RevertClipboard $revertClipboard */ + $revertClipboard = $this->redoHistory->pop(); + Server::getInstance()->getAsyncPool()->submitTask(new AsyncRevertTask($this->getUUID(), $revertClipboard, AsyncRevertTask::TYPE_REDO)); + $this->sendMessage(TF::GREEN . $this->getLanguage()->translateString('session.redo.left', [count($this->redoHistory)])); + } - public function clearHistory(): void - { - $this->undoHistory->clear(); - $this->redoHistory->clear(); - } + public function clearHistory(): void + { + $this->undoHistory->clear(); + $this->redoHistory->clear(); + } - public function clearClipboard(): void - { - $this->setClipboards([]); - $this->currentClipboard = -1; - } + public function clearClipboard(): void + { + $this->setClipboards([]); + $this->currentClipboard = -1; + } - /** - * @return Language - */ - public function getLanguage(): Language - { - return Loader::getInstance()->getLanguage(); - } + /** + * @return Language + */ + public function getLanguage(): Language + { + return Loader::getInstance()->getLanguage(); + } abstract public function sendMessage(string $message): void; - public function __toString() - { - return __CLASS__ . - " UUID: " . $this->getUUID()->__toString() . - " Selections: " . count($this->getSelections()) . - " Latest: " . $this->getLatestSelectionUUID() . - " Clipboards: " . count($this->getClipboards()) . - " Current: " . $this->getCurrentClipboardIndex() . - " Undos: " . count($this->undoHistory) . - " Redos: " . count($this->redoHistory); - } + public function __toString() + { + return __CLASS__ . + " UUID: " . $this->getUUID()->__toString() . + " Selections: " . count($this->getSelections()) . + " Latest: " . $this->getLatestSelectionUUID() . + " Clipboards: " . count($this->getClipboards()) . + " Current: " . $this->getCurrentClipboardIndex() . + " Undos: " . count($this->undoHistory) . + " Redos: " . count($this->redoHistory); + } - /* - * TODO list: - * session storing/recovering from file/cleanup if too old - * session items - * recover session items + commands to get back already created/configured items/tool/brushes - * proper multi-selection-usage - * setState/getState on big actions, status bar/boss bar/texts/titles/popups - * inspect other player's sessions - * destroy session if owning player lost permission/gets banned - * optimise destroySession/__destruct of sessions - * clipboard selection (renaming?) - */ + /* + * TODO list: + * session storing/recovering from file/cleanup if too old + * session items + * recover session items + commands to get back already created/configured items/tool/brushes + * proper multi-selection-usage + * setState/getState on big actions, status bar/boss bar/texts/titles/popups + * inspect other player's sessions + * destroy session if owning player lost permission/gets banned + * optimise destroySession/__destruct of sessions + * clipboard selection (renaming?) + */ } \ No newline at end of file diff --git a/src/xenialdan/MagicWE2/session/UserSession.php b/src/xenialdan/MagicWE2/session/UserSession.php index 9960dfa1..f7990736 100644 --- a/src/xenialdan/MagicWE2/session/UserSession.php +++ b/src/xenialdan/MagicWE2/session/UserSession.php @@ -5,6 +5,7 @@ namespace xenialdan\MagicWE2\session; use Ds\Deque; +use Ds\Map; use Exception; use InvalidArgumentException; use jackmd\scorefactory\ScoreFactory; @@ -25,6 +26,8 @@ use xenialdan\MagicWE2\exception\ShapeNotFoundException; use xenialdan\MagicWE2\helper\Scoreboard; use xenialdan\MagicWE2\Loader; +use xenialdan\MagicWE2\session\data\Asset; +use xenialdan\MagicWE2\session\data\BrushStore; use xenialdan\MagicWE2\tool\Brush; use xenialdan\MagicWE2\tool\BrushProperties; @@ -44,8 +47,10 @@ class UserSession extends Session implements JsonSerializable //TODO use JsonMap private $wailaEnabled = true; /** @var bool */ private $sidebarEnabled = true;//TODO settings/commands - /** @var Brush[] */ - private $brushes = []; + /** @var Map */ + private Map $brushes; + /** @var Map */ + private Map $assets; /** @var Language|null */ private $lang; @@ -61,6 +66,8 @@ public function __construct(Player $player) } $this->undoHistory = new Deque(); $this->redoHistory = new Deque(); + $this->brushes = new Map(); + $this->assets = new Map(); try { if (is_null($this->lang)) $this->lang = new Language(Language::FALLBACK_LANGUAGE, Loader::getInstance()->getLanguageFolder()); @@ -308,7 +315,7 @@ public function replaceBrush(Brush $brush): void */ public function getBrushes(): array { - return $this->brushes; + return $this->brushes->values()->toArray(); } public function cleanupInventory(): void diff --git a/src/xenialdan/MagicWE2/session/data/Asset.php b/src/xenialdan/MagicWE2/session/data/Asset.php new file mode 100644 index 00000000..a0642aba --- /dev/null +++ b/src/xenialdan/MagicWE2/session/data/Asset.php @@ -0,0 +1,129 @@ +filename = $filename; + $this->displayname = pathinfo($filename, PATHINFO_FILENAME); + $this->structure = $value; + $this->locked = $locked; + $this->ownerXuid = $ownerXuid; + } + + public function getSize(): Vector3 + { + if ($this->structure instanceof Schematic) return new Vector3($this->structure->getWidth(), $this->structure->getHeight(), $this->structure->getLength()); + if ($this->structure instanceof MCStructure) return $this->structure->getSize(); + if ($this->structure instanceof SingleClipboard) return new Vector3($this->structure->selection->getSizeX(), $this->structure->selection->getSizeY(), $this->structure->selection->getSizeZ()); + throw new UnexpectedValueException('Invalid class as Asset'); + } + + public function getTotalCount(): int + { + if ($this->structure instanceof Schematic || $this->structure instanceof MCStructure) return $this->getSize()->getFloorX() * $this->getSize()->getFloorY() * $this->getSize()->getFloorZ(); + if ($this->structure instanceof SingleClipboard) return $this->structure->getTotalCount(); + throw new UnexpectedValueException('Invalid class as Asset'); + } + + public function getOrigin(): Vector3 + { + if ($this->structure instanceof Schematic) return new Vector3(0, 0, 0); + if ($this->structure instanceof MCStructure) return $this->structure->getStructureWorldOrigin(); + if ($this->structure instanceof SingleClipboard) return $this->structure->position; + throw new UnexpectedValueException('Invalid class as Asset'); + } + + /** + * @param bool $renew + * @return Item + * @throws InvalidArgumentException + * @throws TypeError + */ + public function toItem(bool $renew = false): Item + { + if ($this->item !== null && !$renew) return $this->item; + $item = ItemFactory::getInstance()->get(ItemIds::SCAFFOLDING); + $item->addEnchantment(new EnchantmentInstance(Loader::$ench)); + [$filename, $displayname, $type, $locked, $owner] = $this->jsonSerialize(); + $item->getNamedTag()->setTag(API::TAG_MAGIC_WE_ASSET, + CompoundTag::create() + ->setString("filename", $filename) + ->setString("displayname", $displayname) + ->setString("type", $type) + ->setByte("locked", $locked ? 1 : 0) + ->setString("owner", $owner) + ); + $item->setCustomName(Loader::PREFIX . TF::BOLD . TF::DARK_PURPLE . $displayname); + $item->setLore($this->generateLore()); + $this->item = $item; + return $item; + } + + /** + * @return array + */ + private function generateLore(): array + { + $return = []; + foreach ($this->jsonSerialize() as $k => $v) { + if ($v === '' || $v === 'displayname') continue; + if (is_bool($v)) { + $return[] = (ucfirst($k) . ": " . ($v ? "Yes" : "No")); + continue; + } + $return[] = (ucfirst($k) . ": " . $v); + } + return $return; + } + + public function jsonSerialize() + { + return [ + 'filename' => $this->filename, + 'displayname' => $this->displayname, + 'type' => $this->structure instanceof Schematic ? self::TYPE_SCHEMATIC : ($this->structure instanceof MCStructure ? self::TYPE_MCSTRUCTURE : ($this->structure instanceof SingleClipboard ? self::TYPE_CLIPBOARD : '')), + 'locked' => $this->locked, + 'owner' => $this->ownerXuid ?? '', + ]; + } +} \ No newline at end of file diff --git a/src/xenialdan/MagicWE2/session/data/AssetCollection.php b/src/xenialdan/MagicWE2/session/data/AssetCollection.php new file mode 100644 index 00000000..47bb1aae --- /dev/null +++ b/src/xenialdan/MagicWE2/session/data/AssetCollection.php @@ -0,0 +1,72 @@ + */ + public Map $assets; + + public function __construct() + { + $this->assets = new Map(); + $this->initFolders(); + } + + /** @return Asset[] */ + public function getAssets(): array + { + return $this->assets->values()->toArray(); + } + + /** @return Asset[] */ + public function getAssetsGlobal(): array + { + return $this->assets->filter(function (string $key, Asset $value) { + return $value->ownerXuid !== ''; + })->values()->toArray(); + } + + /** + * @param string|null $xuid + * @return Asset[] + */ + public function getPlayerAssets(?string $xuid = null): array + { + return $this->assets->filter(function (string $key, Asset $value) use ($xuid) { + return $value->ownerXuid === $xuid; + })->values()->toArray(); + } + + private function initFolders() + { + //Load mcstructure and schematic files and lock them to prevent editing + $store = $this; + $schematicFiles = array_merge(glob(Loader::getInstance()->getDataFolder() . 'assets' . DIRECTORY_SEPARATOR . "*.mcstructure"), glob(Loader::getInstance()->getDataFolder() . 'assets' . DIRECTORY_SEPARATOR . "*.schematic"));//glob might return false + if ($schematicFiles !== false) + foreach ($schematicFiles as $file) { + ['basename' => $basename, 'extension' => $extension] = pathinfo($file); + Loader::getInstance()->getLogger()->debug(TF::GOLD . "Loading " . $basename); + try { + if ($extension === 'mcstructure') { + $store->assets->put($basename, new Asset($basename, StructureStore::getInstance()->loadStructure($basename), true)); + } else if ($extension === 'schematic') { + $store->assets->put($basename, new Asset($basename, StructureStore::getInstance()->loadSchematic($basename), true)); + } + } catch (StructureFileException $e) { + Loader::getInstance()->getLogger()->debug($e->getMessage()); + } + } + } +} \ No newline at end of file diff --git a/src/xenialdan/MagicWE2/session/data/TODO.md b/src/xenialdan/MagicWE2/session/data/TODO.md new file mode 100644 index 00000000..9143b8a6 --- /dev/null +++ b/src/xenialdan/MagicWE2/session/data/TODO.md @@ -0,0 +1,5 @@ +# Session data serialization +- [] Brushes +- [x] Assets (session + global) +- [] Palettes +- [] Clipboards \ No newline at end of file diff --git a/src/xenialdan/MagicWE2/task/AsyncActionTask.php b/src/xenialdan/MagicWE2/task/AsyncActionTask.php index 9ac49b94..38241469 100644 --- a/src/xenialdan/MagicWE2/task/AsyncActionTask.php +++ b/src/xenialdan/MagicWE2/task/AsyncActionTask.php @@ -27,13 +27,13 @@ class AsyncActionTask extends MWEAsyncTask { - /* - * Intention: - * Shape: get blocks from a shape. Shape can contain options - * Filterblocks: filter out blocks that are not needed - * Action: action to run on the remaining blocks, return previous blocks - * Strings: Begin, completion, bossbar, other stuff can be in the action - */ + /* + * Intention: + * Shape: get blocks from a shape. Shape can contain options + * Filterblocks: filter out blocks that are not needed + * Action: action to run on the remaining blocks, return previous blocks + * Strings: Begin, completion, bossbar, other stuff can be in the action + */ /** @var string */ private $touchedChunks; @@ -66,25 +66,25 @@ public function __construct(UUID $sessionUUID, Selection $selection, TaskAction $this->blockFilter = $blockFilter; try { - $session = SessionHelper::getSessionByUUID($sessionUUID); - if ($session instanceof UserSession) { - $player = $session->getPlayer(); - /** @var Player $player */ - $session->getBossBar()->showTo([$player]); - $session->getBossBar()->setTitle("Running {$action::getName()} action");//TODO better string - } - } catch (SessionException $e) { - Loader::getInstance()->getLogger()->logException($e); - } - } + $session = SessionHelper::getSessionByUUID($sessionUUID); + if ($session instanceof UserSession) { + $player = $session->getPlayer(); + /** @var Player $player */ + $session->getBossBar()->showTo([$player]); + $session->getBossBar()->setTitle("Running {$action::getName()} action");//TODO better string + } + } catch (SessionException $e) { + Loader::getInstance()->getLogger()->logException($e); + } + } - /** - * Actions to execute when run - * - * @return void - * @throws Exception - */ - public function onRun(): void + /** + * Actions to execute when run + * + * @return void + * @throws Exception + */ + public function onRun(): void { $this->publishProgress(new Progress(0, "Preparing {$this->action::getName()}")); @@ -162,6 +162,6 @@ public function onCompletion(): void $session->addRevert(new RevertClipboard($selection->worldId, $undoChunks, self::multipleBlocksToData($oldBlocksBlocks))); if ($this->action->addClipboard) $session->addClipboard($oldBlocks); - } - } + } + } } \ No newline at end of file diff --git a/src/xenialdan/MagicWE2/task/AsyncClipboardActionTask.php b/src/xenialdan/MagicWE2/task/AsyncClipboardActionTask.php index 2e10b805..2481a4cc 100644 --- a/src/xenialdan/MagicWE2/task/AsyncClipboardActionTask.php +++ b/src/xenialdan/MagicWE2/task/AsyncClipboardActionTask.php @@ -58,17 +58,17 @@ public function __construct(UUID $sessionUUID, Selection $selection, ClipboardAc $session->getBossBar()->setTitle("Running {$action::getName()} clipboard action");//TODO better string } } catch (SessionException $e) { - Loader::getInstance()->getLogger()->logException($e); - } - } + Loader::getInstance()->getLogger()->logException($e); + } + } - /** - * Actions to execute when run - * - * @return void - * @throws Exception - */ - public function onRun(): void + /** + * Actions to execute when run + * + * @return void + * @throws Exception + */ + public function onRun(): void { $this->publishProgress(new Progress(0, "Preparing {$this->action::getName()}")); BlockStatesParser::$doorRotPath = $this->doorRotPath; diff --git a/src/xenialdan/MagicWE2/task/AsyncCopyTask.php b/src/xenialdan/MagicWE2/task/AsyncCopyTask.php index 7b2f8c97..350040da 100644 --- a/src/xenialdan/MagicWE2/task/AsyncCopyTask.php +++ b/src/xenialdan/MagicWE2/task/AsyncCopyTask.php @@ -42,23 +42,23 @@ class AsyncCopyTask extends MWEAsyncTask * @param int $flags * @throws Exception */ - public function __construct(UUID $sessionUUID, Selection $selection, Vector3 $offset, array $chunks, int $flags) - { - $this->start = microtime(true); - $this->chunks = serialize($chunks); - $this->sessionUUID = $sessionUUID->toString(); - $this->selection = serialize($selection); - $this->offset = $offset->asVector3()->floor(); - $this->flags = $flags; - } + public function __construct(UUID $sessionUUID, Selection $selection, Vector3 $offset, array $chunks, int $flags) + { + $this->start = microtime(true); + $this->chunks = serialize($chunks); + $this->sessionUUID = $sessionUUID->toString(); + $this->selection = serialize($selection); + $this->offset = $offset->asVector3()->floor(); + $this->flags = $flags; + } - /** - * Actions to execute when run - * - * @return void - * @throws Exception - */ - public function onRun(): void + /** + * Actions to execute when run + * + * @return void + * @throws Exception + */ + public function onRun(): void { $this->publishProgress([0, "Start"]); $chunks = array_map(static function ($chunk) { @@ -76,17 +76,17 @@ public function onRun(): void $totalCount = $selection->getShape()->getTotalCount(); $copied = $this->copyBlocks($selection, $manager, $clipboard); #$clipboard->setShape($selection->getShape()); - #$clipboard->chunks = $manager->getChunks(); - $this->setResult(compact("clipboard", "copied", "totalCount")); - } + #$clipboard->chunks = $manager->getChunks(); + $this->setResult(compact("clipboard", "copied", "totalCount")); + } - /** - * @param Selection $selection - * @param AsyncChunkManager $manager - * @param SingleClipboard $clipboard - * @return int - * @throws Exception - */ + /** + * @param Selection $selection + * @param AsyncChunkManager $manager + * @param SingleClipboard $clipboard + * @return int + * @throws Exception + */ private function copyBlocks(Selection $selection, AsyncChunkManager $manager, SingleClipboard $clipboard): int { $blockCount = $selection->getShape()->getTotalCount(); @@ -107,10 +107,10 @@ private function copyBlocks(Selection $selection, AsyncChunkManager $manager, Si $lastprogress = $progress; } } - return $i; - } + return $i; + } - public function onCompletion(): void + public function onCompletion(): void { try { $session = SessionHelper::getSessionByUUID(UUID::fromString($this->sessionUUID)); diff --git a/src/xenialdan/MagicWE2/task/AsyncCountTask.php b/src/xenialdan/MagicWE2/task/AsyncCountTask.php index c5ffbf3e..13cd8c8d 100644 --- a/src/xenialdan/MagicWE2/task/AsyncCountTask.php +++ b/src/xenialdan/MagicWE2/task/AsyncCountTask.php @@ -49,13 +49,13 @@ public function __construct(UUID $sessionUUID, Selection $selection, array $touc $this->flags = $flags; } - /** - * Actions to execute when run - * - * @return void - * @throws Exception - */ - public function onRun(): void + /** + * Actions to execute when run + * + * @return void + * @throws Exception + */ + public function onRun(): void { $this->publishProgress([0, "Start"]); $chunks = unserialize($this->touchedChunks/*, ['allowed_classes' => [false]]*/);//TODO test pm4 @@ -133,7 +133,7 @@ public function onCompletion(): void $session->sendMessage(TF::AQUA . $count . "x | " . round($count / $totalCount * 100) . "% | " . $block); } } catch (SessionException $e) { - Loader::getInstance()->getLogger()->logException($e); - } - } + Loader::getInstance()->getLogger()->logException($e); + } + } } \ No newline at end of file diff --git a/src/xenialdan/MagicWE2/task/AsyncReplaceTask.php b/src/xenialdan/MagicWE2/task/AsyncReplaceTask.php index 40f747a9..8bb780ab 100644 --- a/src/xenialdan/MagicWE2/task/AsyncReplaceTask.php +++ b/src/xenialdan/MagicWE2/task/AsyncReplaceTask.php @@ -58,13 +58,13 @@ public function __construct(UUID $sessionUUID, Selection $selection, array $touc $this->flags = $flags; } - /** - * Actions to execute when run - * - * @return void - * @throws Exception - */ - public function onRun(): void + /** + * Actions to execute when run + * + * @return void + * @throws Exception + */ + public function onRun(): void { $this->publishProgress([0, "Start"]); diff --git a/src/xenialdan/MagicWE2/task/AsyncRevertTask.php b/src/xenialdan/MagicWE2/task/AsyncRevertTask.php index 399083ea..d98b1a58 100644 --- a/src/xenialdan/MagicWE2/task/AsyncRevertTask.php +++ b/src/xenialdan/MagicWE2/task/AsyncRevertTask.php @@ -36,18 +36,18 @@ class AsyncRevertTask extends MWEAsyncTask public function __construct(UUID $sessionUUID, RevertClipboard $clipboard, $type = self::TYPE_UNDO) { $this->sessionUUID = $sessionUUID->toString(); - $this->start = microtime(true); - $this->clipboard = serialize($clipboard); - $this->type = $type; - } + $this->start = microtime(true); + $this->clipboard = serialize($clipboard); + $this->type = $type; + } - /** - * Actions to execute when run - * - * @return void - * @throws Exception - */ - public function onRun(): void + /** + * Actions to execute when run + * + * @return void + * @throws Exception + */ + public function onRun(): void { $this->publishProgress([0, "Start"]); /** @var RevertClipboard $clipboard */ @@ -142,12 +142,12 @@ public function onCompletion(): void break; } case self::TYPE_REDO: - { - $session->sendMessage(TF::GREEN . $session->getLanguage()->translateString('task.revert.redo.success', [$this->generateTookString(), $changed, $totalCount])); - $session->undoHistory->push($clipboard); - break; - } - } - } - } + { + $session->sendMessage(TF::GREEN . $session->getLanguage()->translateString('task.revert.redo.success', [$this->generateTookString(), $changed, $totalCount])); + $session->undoHistory->push($clipboard); + break; + } + } + } + } } \ No newline at end of file diff --git a/src/xenialdan/MagicWE2/task/action/ActionRegistry.php b/src/xenialdan/MagicWE2/task/action/ActionRegistry.php index 62c503f5..0376b361 100644 --- a/src/xenialdan/MagicWE2/task/action/ActionRegistry.php +++ b/src/xenialdan/MagicWE2/task/action/ActionRegistry.php @@ -20,44 +20,44 @@ public function __construct() } public static function registerAction(string $name, string $class): void - { - self::$actions[$name] = $class; - } - - /** - * @return array - */ - public static function getActions(): array - { - return self::$actions; - } - - /** - * @param string $name - * @return string - * @throws ActionNotFoundException - */ - public static function getAction(string $name): string - { - if (isset(self::$actions[$name])) return self::$actions[$name]; - throw new ActionNotFoundException("Action $name not found"); - } - - /** - * @param string $actionClass - * @return string - * @throws ActionNotFoundException - */ - public static function getActionName(string $actionClass): string - { - $names = array_flip(self::$actions); - if (isset($names[$actionClass])) return $names[$actionClass]; - throw new ActionNotFoundException("Action $actionClass not found"); - } - - public static function getDefaultActionProperties(string $className): array - { - return array_diff_key(get_class_vars($className), get_class_vars(TaskAction::class)); - } + { + self::$actions[$name] = $class; + } + + /** + * @return array + */ + public static function getActions(): array + { + return self::$actions; + } + + /** + * @param string $name + * @return string + * @throws ActionNotFoundException + */ + public static function getAction(string $name): string + { + if (isset(self::$actions[$name])) return self::$actions[$name]; + throw new ActionNotFoundException("Action $name not found"); + } + + /** + * @param string $actionClass + * @return string + * @throws ActionNotFoundException + */ + public static function getActionName(string $actionClass): string + { + $names = array_flip(self::$actions); + if (isset($names[$actionClass])) return $names[$actionClass]; + throw new ActionNotFoundException("Action $actionClass not found"); + } + + public static function getDefaultActionProperties(string $className): array + { + return array_diff_key(get_class_vars($className), get_class_vars(TaskAction::class)); + } } \ No newline at end of file diff --git a/src/xenialdan/MagicWE2/task/action/CountAction.php b/src/xenialdan/MagicWE2/task/action/CountAction.php index 206a5ca2..ec841ec8 100644 --- a/src/xenialdan/MagicWE2/task/action/CountAction.php +++ b/src/xenialdan/MagicWE2/task/action/CountAction.php @@ -60,15 +60,15 @@ public function execute(string $sessionUUID, Selection $selection, AsyncChunkMan if (floor($progress->progress * 100) > floor($lastProgress->progress * 100)) { yield $progress; $lastProgress = $progress; - } - } - $messages[] = TF::DARK_AQUA . count($counts) . " blocks found in a total of $count blocks"; - uasort($counts, static function ($a, $b) { + } + } + $messages[] = TF::DARK_AQUA . count($counts) . " blocks found in a total of $count blocks"; + uasort($counts, static function ($a, $b) { if ($a === $b) return 0; return ($a > $b) ? -1 : 1; }); - foreach ($counts as $block => $countb) { - $messages[] = TF::AQUA . $countb . "x | " . round($countb / $count * 100) . "% | " . $block; - } - } + foreach ($counts as $block => $countb) { + $messages[] = TF::AQUA . $countb . "x | " . round($countb / $count * 100) . "% | " . $block; + } + } } \ No newline at end of file diff --git a/src/xenialdan/MagicWE2/task/action/CutAction.php b/src/xenialdan/MagicWE2/task/action/CutAction.php index 2de6fd56..a32b0d86 100644 --- a/src/xenialdan/MagicWE2/task/action/CutAction.php +++ b/src/xenialdan/MagicWE2/task/action/CutAction.php @@ -68,7 +68,7 @@ public function execute(string $sessionUUID, Selection $selection, AsyncChunkMan if (floor($progress->progress * 100) > floor($lastProgress->progress * 100)) { yield $progress; $lastProgress = $progress; - } - } - } + } + } + } } \ No newline at end of file diff --git a/src/xenialdan/MagicWE2/task/action/FlipAction.php b/src/xenialdan/MagicWE2/task/action/FlipAction.php index d2ca8187..cd08b739 100644 --- a/src/xenialdan/MagicWE2/task/action/FlipAction.php +++ b/src/xenialdan/MagicWE2/task/action/FlipAction.php @@ -38,16 +38,16 @@ public static function getName(): string return "Flip"; } - /** - * @param string $sessionUUID - * @param Selection $selection - * @param null|int $changed - * @param SingleClipboard $clipboard - * @param string[] $messages - * @return Generator|Progress[] - * @throws Exception - */ - public function execute(string $sessionUUID, Selection $selection, ?int &$changed, SingleClipboard $clipboard, array &$messages = []): Generator + /** + * @param string $sessionUUID + * @param Selection $selection + * @param null|int $changed + * @param SingleClipboard $clipboard + * @param string[] $messages + * @return Generator|Progress[] + * @throws Exception + */ + public function execute(string $sessionUUID, Selection $selection, ?int &$changed, SingleClipboard $clipboard, array &$messages = []): Generator { //TODO modify position. For now, just flip the blocks around their own axis $changed = 0; @@ -58,34 +58,34 @@ public function execute(string $sessionUUID, Selection $selection, ?int &$change $clonedClipboard = clone $clipboard; $x = $y = $z = null; $maxX = $clipboard->selection->getSizeX() - 1; - $maxY = $clipboard->selection->getSizeY() - 1; - $maxZ = $clipboard->selection->getSizeZ() - 1; - foreach ($clipboard->iterateEntries($x, $y, $z) as $blockEntry) { - #var_dump("$x $y $z"); - if ($this->axis === self::AXIS_Z || $this->axis === self::AXIS_XZ) - $x = $maxX - $x; - if ($this->axis === self::AXIS_X || $this->axis === self::AXIS_XZ) - $z = $maxZ - $z; - if ($this->axis === self::AXIS_Y) - $y = $maxY - $y; - #var_dump("$x $y $z"); + $maxY = $clipboard->selection->getSizeY() - 1; + $maxZ = $clipboard->selection->getSizeZ() - 1; + foreach ($clipboard->iterateEntries($x, $y, $z) as $blockEntry) { + #var_dump("$x $y $z"); + if ($this->axis === self::AXIS_Z || $this->axis === self::AXIS_XZ) + $x = $maxX - $x; + if ($this->axis === self::AXIS_X || $this->axis === self::AXIS_XZ) + $z = $maxZ - $z; + if ($this->axis === self::AXIS_Y) + $y = $maxY - $y; + #var_dump("$x $y $z"); $block1 = $blockEntry->toBlock(); $blockStatesEntry = BlockStatesParser::getInstance()::getStateByBlock($block1); $mirrored = $blockStatesEntry->mirror($this->axis); - $block = $mirrored->toBlock(); - $entry = BlockEntry::fromBlock($block); + $block = $mirrored->toBlock(); + $entry = BlockEntry::fromBlock($block); //var_dump($blockStatesEntry->__toString(), $mirrored->__toString(), $block); - /** @var int $x */ - /** @var int $y */ - /** @var int $z */ - $clonedClipboard->addEntry($x, $y, $z, $entry); - $changed++; - $progress = new Progress($changed / $count, "$changed/$count"); - if (floor($progress->progress * 100) > floor($lastProgress->progress * 100)) { - yield $progress; - $lastProgress = $progress; - } - } - $clipboard = $clonedClipboard; - } + /** @var int $x */ + /** @var int $y */ + /** @var int $z */ + $clonedClipboard->addEntry($x, $y, $z, $entry); + $changed++; + $progress = new Progress($changed / $count, "$changed/$count"); + if (floor($progress->progress * 100) > floor($lastProgress->progress * 100)) { + yield $progress; + $lastProgress = $progress; + } + } + $clipboard = $clonedClipboard; + } } \ No newline at end of file diff --git a/src/xenialdan/MagicWE2/task/action/RotateAction.php b/src/xenialdan/MagicWE2/task/action/RotateAction.php index 510a9075..5dd52b09 100644 --- a/src/xenialdan/MagicWE2/task/action/RotateAction.php +++ b/src/xenialdan/MagicWE2/task/action/RotateAction.php @@ -39,8 +39,8 @@ public function __construct(int $rotation, bool $aroundOrigin = true) public static function getName(): string { - return "Rotate"; - } + return "Rotate"; + } /** * @param string $sessionUUID diff --git a/src/xenialdan/MagicWE2/task/action/SetBiomeAction.php b/src/xenialdan/MagicWE2/task/action/SetBiomeAction.php index afaf53bc..678194a3 100644 --- a/src/xenialdan/MagicWE2/task/action/SetBiomeAction.php +++ b/src/xenialdan/MagicWE2/task/action/SetBiomeAction.php @@ -52,10 +52,10 @@ public function execute(string $sessionUUID, Selection $selection, AsyncChunkMan $manager->getChunk($vec2->x >> 4, $vec2->y >> 4)->setBiomeId($vec2->x % 16, $vec2->y % 16, $this->biomeId); $changed++; $progress = new Progress($changed / $count, "Changed Biome for $changed/$count blocks"); - if (floor($progress->progress * 100) > floor($lastProgress->progress * 100)) { - yield $progress; - $lastProgress = $progress; - } - } - } + if (floor($progress->progress * 100) > floor($lastProgress->progress * 100)) { + yield $progress; + $lastProgress = $progress; + } + } + } } \ No newline at end of file diff --git a/src/xenialdan/MagicWE2/task/action/SetBlockAction.php b/src/xenialdan/MagicWE2/task/action/SetBlockAction.php index 3413e7bb..f1375769 100644 --- a/src/xenialdan/MagicWE2/task/action/SetBlockAction.php +++ b/src/xenialdan/MagicWE2/task/action/SetBlockAction.php @@ -17,14 +17,14 @@ class SetBlockAction extends TaskAction { - public function __construct() - { - } + public function __construct() + { + } - public static function getName(): string - { - return "Set block"; - } + public static function getName(): string + { + return "Set block"; + } /** * @param string $sessionUUID @@ -58,9 +58,9 @@ public function execute(string $sessionUUID, Selection $selection, AsyncChunkMan $i++; $progress = new Progress($i / $count, "Changed {$changed} blocks out of {$count}"); if (floor($progress->progress * 100) > floor($lastProgress->progress * 100)) { - yield $progress; - $lastProgress = $progress; - } - } - } + yield $progress; + $lastProgress = $progress; + } + } + } } \ No newline at end of file diff --git a/src/xenialdan/MagicWE2/task/action/TaskAction.php b/src/xenialdan/MagicWE2/task/action/TaskAction.php index 08571715..d99e25ca 100644 --- a/src/xenialdan/MagicWE2/task/action/TaskAction.php +++ b/src/xenialdan/MagicWE2/task/action/TaskAction.php @@ -50,5 +50,5 @@ public function setClipboardVector(?Vector3 $clipboardVector): void { if ($clipboardVector instanceof Vector3) $clipboardVector = $clipboardVector->asVector3()->floor(); $this->clipboardVector = $clipboardVector; - } + } } \ No newline at end of file diff --git a/src/xenialdan/MagicWE2/task/action/ThawAction.php b/src/xenialdan/MagicWE2/task/action/ThawAction.php index fdb5d81c..6ac2559b 100644 --- a/src/xenialdan/MagicWE2/task/action/ThawAction.php +++ b/src/xenialdan/MagicWE2/task/action/ThawAction.php @@ -17,14 +17,14 @@ class ThawAction extends TaskAction { - public function __construct() - { - } + public function __construct() + { + } - public static function getName(): string - { - return "Thaw"; - } + public static function getName(): string + { + return "Thaw"; + } /** * @param string $sessionUUID @@ -64,6 +64,6 @@ public function execute(string $sessionUUID, Selection $selection, AsyncChunkMan $lastProgress = $progress; } } - } - } + } + } } \ No newline at end of file diff --git a/src/xenialdan/MagicWE2/tool/Brush.php b/src/xenialdan/MagicWE2/tool/Brush.php index ef9d2cc6..8c84a5c5 100644 --- a/src/xenialdan/MagicWE2/tool/Brush.php +++ b/src/xenialdan/MagicWE2/tool/Brush.php @@ -8,11 +8,9 @@ use InvalidArgumentException; use JsonException; use pocketmine\data\bedrock\BiomeIds; -use pocketmine\item\Durable; use pocketmine\item\enchantment\EnchantmentInstance; use pocketmine\item\Item; -use pocketmine\item\ItemFactory; -use pocketmine\item\ItemIds; +use pocketmine\item\VanillaItems; use pocketmine\nbt\tag\CompoundTag; use pocketmine\player\Player; use pocketmine\utils\AssumptionFailedError; @@ -69,8 +67,7 @@ public function getName(): string */ public function toItem(): Item { - /** @var Durable $item */ - $item = ItemFactory::getInstance()->get(ItemIds::WOODEN_SHOVEL); + $item = VanillaItems::WOODEN_SHOVEL(); $item->addEnchantment(new EnchantmentInstance(Loader::$ench)); $uuid = $this->properties->uuid ?? UUID::fromRandom()->toString(); $this->properties->uuid = $uuid; @@ -109,16 +106,16 @@ public function getForm(bool $new = true, array $errors = []): CustomForm $dropdownShape = new Dropdown((isset($errors['shape']) ? TF::RED : "") . "Shape" . ($errors['shape'] ?? "")); foreach (Loader::getShapeRegistry()::getShapes() as $name => $class) { if ($name === ShapeRegistry::CUSTOM) continue; - $dropdownShape->addOption($name, $class === $brushProperties->shape); - } - $form->addElement($dropdownShape); - } else { - $form->addElement(new Label($brushProperties->getShapeName())); - } - // Action - $dropdownAction = new Dropdown("Action"); - foreach (ActionRegistry::getActions() as $name => $class) { - $dropdownAction->addOption($name, $class === $brushProperties->action); + $dropdownShape->addOption($name, $class === $brushProperties->shape); + } + $form->addElement($dropdownShape); + } else { + $form->addElement(new Label($brushProperties->getShapeName())); + } + // Action + $dropdownAction = new Dropdown("Action"); + foreach (ActionRegistry::getActions() as $name => $class) { + $dropdownAction->addOption($name, $class === $brushProperties->action); } $form->addElement($dropdownAction); // Name @@ -142,14 +139,14 @@ public function getForm(bool $new = true, array $errors = []): CustomForm $form->addElement($element); } } - // Function - $form->setCallable(function (Player $player, $data) use ($form, $new) { - #var_dump(__LINE__, $data); - #$data = array_slice($data, 0, 7); - [$shape, $action, $name, $blocks, $filter, $biome, $hollow] = $data; - $extraData = []; - #var_dump(__LINE__, array_slice($data, 7)); - $base = ShapeRegistry::getDefaultShapeProperties(ShapeRegistry::getShape($shape)); + // Function + $form->setCallable(function (Player $player, $data) use ($form, $new) { + #var_dump(__LINE__, $data); + #$data = array_slice($data, 0, 7); + [$shape, $action, $name, $blocks, $filter, $biome, $hollow] = $data; + $extraData = []; + #var_dump(__LINE__, array_slice($data, 7)); + $base = ShapeRegistry::getDefaultShapeProperties(ShapeRegistry::getShape($shape)); foreach (array_slice($data, 7, null, true) as $i => $value) { #var_dump($i, $value, gettype($value), gettype($base[lcfirst($form->getElement($i)->getText())])); if (is_int($base[lcfirst($form->getElement($i)->getText())])) $value = (int)$value; @@ -174,104 +171,104 @@ public function getForm(bool $new = true, array $errors = []): CustomForm $p = BlockPalette::fromString($blocks); if ($p->empty()) throw new AssumptionFailedError("Blocks cannot be empty!"); } catch (Exception $ex) { - $error['blocks'] = $ex->getMessage(); - } - try { + $error['blocks'] = $ex->getMessage(); + } + try { BlockPalette::fromString($filter); } catch (Exception $ex) { - $error['filter'] = $ex->getMessage(); - } - try { - $shape = Loader::getShapeRegistry()::getShape($shape); - } catch (Exception $ex) { - $error['shape'] = $ex->getMessage(); - } - try { - $action = Loader::getActionRegistry()::getAction($action); - } catch (Exception $ex) { - $error['action'] = $ex->getMessage(); - } - try { + $error['filter'] = $ex->getMessage(); + } + try { + $shape = Loader::getShapeRegistry()::getShape($shape); + } catch (Exception $ex) { + $error['shape'] = $ex->getMessage(); + } + try { + $action = Loader::getActionRegistry()::getAction($action); + } catch (Exception $ex) { + $error['action'] = $ex->getMessage(); + } + try { if (!is_int($biomeId)) throw new AssumptionFailedError("Biome not found"); - } catch (Exception $ex) { - $error['biome'] = $ex->getMessage(); - } + } catch (Exception $ex) { + $error['biome'] = $ex->getMessage(); + } - //Set properties (called before resending, so form contains errors) - if (!empty(trim(TF::clean($name)))) $this->properties->customName = $name; - if (!isset($error['shape'])) { - $this->properties->shape = $shape; - if (!$new && !empty($extraData)) - $this->properties->shapeProperties = $extraData; - } - if (!isset($error['action'])) $this->properties->action = $action; - /*if (!isset($error['blocks']))*/ - $this->properties->blocks = $blocks; - /*if (!isset($error['filter']))*/ - $this->properties->filter = $filter; - $this->properties->hollow = $hollow; + //Set properties (called before resending, so form contains errors) + if (!empty(trim(TF::clean($name)))) $this->properties->customName = $name; + if (!isset($error['shape'])) { + $this->properties->shape = $shape; + if (!$new && !empty($extraData)) + $this->properties->shapeProperties = $extraData; + } + if (!isset($error['action'])) $this->properties->action = $action; + /*if (!isset($error['blocks']))*/ + $this->properties->blocks = $blocks; + /*if (!isset($error['filter']))*/ + $this->properties->filter = $filter; + $this->properties->hollow = $hollow; - //Resend form upon error - if (!empty($error)) { - $player->sendForm($this->getForm($new, $error)); - return; - } + //Resend form upon error + if (!empty($error)) { + $player->sendForm($this->getForm($new, $error)); + return; + } - //Debug - #print_r($extraData); - try { - $brush = $this; - $session = SessionHelper::getUserSession($player); - if (!$session instanceof UserSession) { + //Debug + #print_r($extraData); + try { + $brush = $this; + $session = SessionHelper::getUserSession($player); + if (!$session instanceof UserSession) { throw new SessionException(Loader::getInstance()->getLanguage()->translateString('error.nosession', [Loader::getInstance()->getName()])); - } - if (!$new) { - $session->replaceBrush($brush); - } else { - $player->sendForm($this->getExtradataForm($this->properties->shape)); - } - } catch (Exception $ex) { - $player->sendMessage($ex->getMessage()); - Loader::getInstance()->getLogger()->logException($ex); - } - }); - return $form; - } catch (Exception $e) { + } + if (!$new) { + $session->replaceBrush($brush); + } else { + $player->sendForm($this->getExtradataForm($this->properties->shape)); + } + } catch (Exception $ex) { + $player->sendMessage($ex->getMessage()); + Loader::getInstance()->getLogger()->logException($ex); + } + }); + return $form; + } catch (Exception $e) { throw new AssumptionFailedError("Could not create brush form"); - } - } + } + } - private function getExtradataForm(string $shapeClass): CustomForm - { - $form = new CustomForm("Shape settings"); - #foreach (($defaultReplaced = array_merge(ShapeRegistry::getDefaultShapeProperties($shapeClass), $this->properties->shapeProperties)) as $name => $value) { - $base = ShapeRegistry::getDefaultShapeProperties($shapeClass); - foreach (($defaultReplaced = array_replace($base, array_intersect_key($this->properties->shapeProperties, $base))) as $name => $value) { + private function getExtradataForm(string $shapeClass): CustomForm + { + $form = new CustomForm("Shape settings"); + #foreach (($defaultReplaced = array_merge(ShapeRegistry::getDefaultShapeProperties($shapeClass), $this->properties->shapeProperties)) as $name => $value) { + $base = ShapeRegistry::getDefaultShapeProperties($shapeClass); + foreach (($defaultReplaced = array_replace($base, array_intersect_key($this->properties->shapeProperties, $base))) as $name => $value) { if (is_bool($value)) $form->addElement(new Toggle(ucfirst($name), $value)); else $form->addElement(new Input(ucfirst($name), $name . " (" . gettype($value) . ")", (string)$value)); } - #var_dump($this->properties->shapeProperties); - #var_dump('Base', $base); - #var_dump('Default Replaced', $defaultReplaced); - $form->setCallable(function (Player $player, $data) use ($defaultReplaced, $base) { - //TODO validation, resending etc. - $extraData = []; - $names = array_keys($defaultReplaced); - foreach ($data as $index => $value) { + #var_dump($this->properties->shapeProperties); + #var_dump('Base', $base); + #var_dump('Default Replaced', $defaultReplaced); + $form->setCallable(function (Player $player, $data) use ($defaultReplaced, $base) { + //TODO validation, resending etc. + $extraData = []; + $names = array_keys($defaultReplaced); + foreach ($data as $index => $value) { if (is_int($base[$names[$index]])) $value = (int)$value; - $extraData[$names[$index]] = $value; - } - $this->properties->shapeProperties = $extraData; + $extraData[$names[$index]] = $value; + } + $this->properties->shapeProperties = $extraData; - $brush = $this; - $session = SessionHelper::getUserSession($player); - if (!$session instanceof UserSession) { + $brush = $this; + $session = SessionHelper::getUserSession($player); + if (!$session instanceof UserSession) { throw new SessionException(Loader::getInstance()->getLanguage()->translateString('error.nosession', [Loader::getInstance()->getName()])); - } - $this->properties->uuid = UUID::fromRandom()->toString(); - $session->addBrush($brush); - $player->getInventory()->addItem($brush->toItem()); - }); - return $form; - } + } + $this->properties->uuid = UUID::fromRandom()->toString(); + $session->addBrush($brush); + $player->getInventory()->addItem($brush->toItem()); + }); + return $form; + } } \ No newline at end of file diff --git a/src/xenialdan/MagicWE2/tool/BrushProperties.php b/src/xenialdan/MagicWE2/tool/BrushProperties.php index 7b86e50d..c19f9594 100644 --- a/src/xenialdan/MagicWE2/tool/BrushProperties.php +++ b/src/xenialdan/MagicWE2/tool/BrushProperties.php @@ -53,98 +53,98 @@ class BrushProperties implements JsonSerializable */ public function jsonSerialize() { - return (array)$this; - } + return (array)$this; + } - /** - * @param array $json - * @return BrushProperties - * @throws InvalidArgumentException - */ - public static function fromJson(array $json): BrushProperties - { - if (($json["version"] ?? 0) !== self::VERSION) throw new InvalidArgumentException("Version mismatch"); - $properties = new self; - foreach ($json as $key => $value) { - $properties->$key = $value; - } - return $properties; - } + /** + * @param array $json + * @return BrushProperties + * @throws InvalidArgumentException + */ + public static function fromJson(array $json): BrushProperties + { + if (($json["version"] ?? 0) !== self::VERSION) throw new InvalidArgumentException("Version mismatch"); + $properties = new self; + foreach ($json as $key => $value) { + $properties->$key = $value; + } + return $properties; + } - public function getName(): string - { - $str = ""; - try { - $str = trim(($this->hasCustomName() ? $this->customName : $this->getShapeName()) /*. " " . $this->action->getName() . */); - } catch (ShapeNotFoundException $e) { - } - if (stripos(TF::clean($str), "brush") === false) { - $str .= " Brush"; - } - return $str; - } + public function getName(): string + { + $str = ""; + try { + $str = trim(($this->hasCustomName() ? $this->customName : $this->getShapeName()) /*. " " . $this->action->getName() . */); + } catch (ShapeNotFoundException $e) { + } + if (stripos(TF::clean($str), "brush") === false) { + $str .= " Brush"; + } + return $str; + } - /** - * @return string - * @throws ShapeNotFoundException - */ - public function getShapeName(): string - { - return is_subclass_of($this->shape, Shape::class) ? ShapeRegistry::getShapeName($this->shape) : ""; - } + /** + * @return string + * @throws ShapeNotFoundException + */ + public function getShapeName(): string + { + return is_subclass_of($this->shape, Shape::class) ? ShapeRegistry::getShapeName($this->shape) : ""; + } - /** - * @return string - * @throws ActionNotFoundException - */ - public function getActionName(): string - { - return is_subclass_of($this->action, TaskAction::class) ? ActionRegistry::getActionName($this->action) : ""; - } + /** + * @return string + * @throws ActionNotFoundException + */ + public function getActionName(): string + { + return is_subclass_of($this->action, TaskAction::class) ? ActionRegistry::getActionName($this->action) : ""; + } - public function hasCustomName(): bool - { - return !empty($this->customName); - } + public function hasCustomName(): bool + { + return !empty($this->customName); + } - /** - * @param string $customName If empty, the name will be reset - */ - public function setCustomName(string $customName = ""): void - { - $this->customName = $customName; - } + /** + * @param string $customName If empty, the name will be reset + */ + public function setCustomName(string $customName = ""): void + { + $this->customName = $customName; + } - /** + /** * @return array * @throws ActionNotFoundException * @throws ShapeNotFoundException * @noinspection NestedTernaryOperatorInspection */ - public function generateLore(): array - { - $shapeProperties = array_map(static function ($k, $v): string { + public function generateLore(): array + { + $shapeProperties = array_map(static function ($k, $v): string { return TF::GOLD . " " . ucfirst($k) . " = " . (is_bool($v) ? ($v ? "Yes" : "No") : $v); }, array_keys($this->shapeProperties), $this->shapeProperties); $actionProperties = array_map(static function ($k, $v): string { return TF::GOLD . " " . ucfirst($k) . " = " . (is_bool($v) ? ($v ? "Yes" : "No") : $v); }, array_keys($this->actionProperties), $this->actionProperties); - return array_merge( - [ - TF::GOLD . "Shape: {$this->getShapeName()}", - ], - $shapeProperties, - [ - TF::GOLD . "Action: {$this->getActionName()}", - ], - $actionProperties, - [ - TF::GOLD . "Blocks: {$this->blocks}", - TF::GOLD . "Filter: {$this->filter}", - TF::GOLD . "Biome: {$this->biomeId}", - TF::GOLD . "Hollow: " . ($this->hollow ? "Yes" : "No"), - //TF::GOLD . "UUID: {$this->uuid}", - ] - ); - } + return array_merge( + [ + TF::GOLD . "Shape: {$this->getShapeName()}", + ], + $shapeProperties, + [ + TF::GOLD . "Action: {$this->getActionName()}", + ], + $actionProperties, + [ + TF::GOLD . "Blocks: {$this->blocks}", + TF::GOLD . "Filter: {$this->filter}", + TF::GOLD . "Biome: {$this->biomeId}", + TF::GOLD . "Hollow: " . ($this->hollow ? "Yes" : "No"), + //TF::GOLD . "UUID: {$this->uuid}", + ] + ); + } } \ No newline at end of file diff --git a/src/xenialdan/MagicWE2/tool/WETool.php b/src/xenialdan/MagicWE2/tool/WETool.php index 59295ec2..67222c03 100644 --- a/src/xenialdan/MagicWE2/tool/WETool.php +++ b/src/xenialdan/MagicWE2/tool/WETool.php @@ -7,6 +7,6 @@ abstract class WETool { - abstract public function getName(): string; + abstract public function getName(): string; } \ No newline at end of file From 994b127199ff9d31ad6663767d1ce9334fdb799c Mon Sep 17 00:00:00 2001 From: XenialDan Date: Sat, 13 Feb 2021 22:29:47 +0100 Subject: [PATCH 08/67] Fix #222: Changed text colors for readability & consistency --- src/xenialdan/MagicWE2/API.php | 2 +- src/xenialdan/MagicWE2/Loader.php | 6 ++- .../MagicWE2/commands/DonateCommand.php | 6 +-- .../MagicWE2/commands/HelpCommand.php | 6 +-- .../MagicWE2/commands/LanguageCommand.php | 2 +- .../MagicWE2/commands/brush/BrushCommand.php | 5 +- .../MagicWE2/commands/tool/DebugCommand.php | 8 +-- .../MagicWE2/commands/tool/FloodCommand.php | 4 +- .../MagicWE2/commands/tool/WandCommand.php | 8 +-- .../MagicWE2/helper/BlockStatesParser.php | 2 +- src/xenialdan/MagicWE2/helper/Scoreboard.php | 24 ++++----- src/xenialdan/MagicWE2/session/data/Asset.php | 51 ++++++++++--------- src/xenialdan/MagicWE2/tool/Brush.php | 2 +- .../MagicWE2/tool/BrushProperties.php | 16 +++--- 14 files changed, 73 insertions(+), 69 deletions(-) diff --git a/src/xenialdan/MagicWE2/API.php b/src/xenialdan/MagicWE2/API.php index 5ac3eca8..05c4e52a 100644 --- a/src/xenialdan/MagicWE2/API.php +++ b/src/xenialdan/MagicWE2/API.php @@ -533,7 +533,7 @@ public static function setComponents(Block $block, int $x, int $y, int $z): Bloc public static function vecToString(Vector3 $v): string { - return TF::RESET . "[" . TF::RED . $v->getFloorX() . TF::RESET . ":" . TF::GREEN . $v->getFloorY() . TF::RESET . ":" . TF::BLUE . $v->getFloorZ() . TF::RESET . "]"; + return TF::RESET . "[" . TF::RED . $v->getFloorX() . TF::RESET . ":" . TF::GREEN . $v->getFloorY() . TF::RESET . ":" . TF::AQUA . $v->getFloorZ() . TF::RESET . "]"; } public static function boolToString(bool $b): string diff --git a/src/xenialdan/MagicWE2/Loader.php b/src/xenialdan/MagicWE2/Loader.php index 079f052b..d232ab7e 100644 --- a/src/xenialdan/MagicWE2/Loader.php +++ b/src/xenialdan/MagicWE2/Loader.php @@ -79,7 +79,9 @@ class Loader extends PluginBase { public const FAKE_ENCH_ID = 201; - public const PREFIX = TF::BOLD . TF::GOLD . "[MagicWE2]" . TF::RESET . " "; + public const PREFIX = TF::RESET . TF::BOLD . TF::GOLD . "[MagicWE2]" . TF::RESET . " "; + public const PREFIX_ASSETS = TF::RESET . TF::BOLD . TF::GOLD . "[Asset]" . TF::RESET . " "; + public const PREFIX_FORM = TF::RESET . TF::BOLD . TF::DARK_PURPLE . "[MWE2]" . TF::RESET . " "; /** @var Loader|null */ private static $instance; /** @var null|ShapeRegistry */ @@ -257,7 +259,7 @@ public function onEnable(): void //new PumpkinsCommand($this,"/pumpkins", "Generate pumpkin patches"), /* -- clipboard -- */ new CopyCommand($this, "/copy", "Copy the selection to the clipboard"), - new PasteCommand($this, "/paste", "Paste the clipboard’s contents"), + new PasteCommand($this, "/paste", "Paste the clipboard's contents"), new CutCommand($this, "/cut", "Cut the selection to the clipboard"), new Cut2Command($this, "/cut2", "Cut the selection to the clipboard - the new way"), new ClearClipboardCommand($this, "/clearclipboard", "Clear your clipboard"), diff --git a/src/xenialdan/MagicWE2/commands/DonateCommand.php b/src/xenialdan/MagicWE2/commands/DonateCommand.php index 25187922..db3e865e 100644 --- a/src/xenialdan/MagicWE2/commands/DonateCommand.php +++ b/src/xenialdan/MagicWE2/commands/DonateCommand.php @@ -41,12 +41,12 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo } } try { - $name = TF::DARK_PURPLE . "[" . TF::GOLD . "XenialDan" . TF::DARK_PURPLE . "] "; + $name = TF::LIGHT_PURPLE . "[" . TF::GOLD . "XenialDan" . TF::LIGHT_PURPLE . "] "; $sender->sendMessage($name . "Greetings! Would you like to buy me an energy drink to stay awake during coding sessions?"); $sender->sendMessage($name . "Donations are welcomed! Consider donating on " . TF::DARK_AQUA . "Pay" . TF::AQUA . "Pal:"); $sender->sendMessage($name . TF::DARK_AQUA . "https://www.paypal.me/xenialdan"); - $sender->sendMessage($name . "Thank you! With " . TF::BOLD . TF::RED . "<3" . TF::RESET . TF::DARK_PURPLE . " - MagicWE2 by https://github.com/thebigsmileXD"); - $colorHeart = (random_int(0, 1) === 1 ? TF::DARK_RED : TF::DARK_PURPLE); + $sender->sendMessage($name . "Thank you! With " . TF::BOLD . TF::RED . "<3" . TF::RESET . TF::LIGHT_PURPLE . " - MagicWE2 by https://github.com/thebigsmileXD"); + $colorHeart = (random_int(0, 1) === 1 ? TF::DARK_RED : TF::LIGHT_PURPLE); $sender->sendMessage( TF::BOLD . $colorHeart . " **** **** " . TF::EOL . TF::BOLD . $colorHeart . " ** ** ** ** " . TF::EOL . diff --git a/src/xenialdan/MagicWE2/commands/HelpCommand.php b/src/xenialdan/MagicWE2/commands/HelpCommand.php index 84ccc5e1..6fa89cf6 100644 --- a/src/xenialdan/MagicWE2/commands/HelpCommand.php +++ b/src/xenialdan/MagicWE2/commands/HelpCommand.php @@ -61,14 +61,14 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo return; } foreach ($cmds as $command) { - $message = TF::LIGHT_PURPLE . "/" . $command->getName(); + $message = TF::RESET . TF::BOLD . TF::GOLD . "/" . $command->getName(); if (!empty(($aliases = $command->getAliases()))) { foreach ($aliases as $i => $alias) { $aliases[$i] = "/" . $alias; } - $message .= TF::DARK_PURPLE . " [" . implode(",", $aliases) . "]"; + $message .= TF::RESET . TF::LIGHT_PURPLE . " [" . implode(",", $aliases) . "]"; } - $message .= TF::AQUA . " " . $command->getDescription() . TF::EOL . " - " . $command->getUsage(); + $message .= TF::RESET . TF::WHITE . " " . $command->getDescription() . TF::EOL . " » " . $command->getUsage(); $sender->sendMessage($message); } } catch (Exception $error) { diff --git a/src/xenialdan/MagicWE2/commands/LanguageCommand.php b/src/xenialdan/MagicWE2/commands/LanguageCommand.php index dadf3305..8e6701e2 100644 --- a/src/xenialdan/MagicWE2/commands/LanguageCommand.php +++ b/src/xenialdan/MagicWE2/commands/LanguageCommand.php @@ -62,7 +62,7 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo return; } $languages = Loader::getInstance()->getLanguageList(); - $form = new CustomForm(Loader::PREFIX . TF::BOLD . TF::DARK_PURPLE . $lang->translateString('ui.language.title')); + $form = new CustomForm(Loader::PREFIX_FORM . TF::BOLD . TF::DARK_PURPLE . $lang->translateString('ui.language.title')); $form->addElement(new Label($lang->translateString('ui.language.label'))); $dropdown = new Dropdown($lang->translateString('ui.language.dropdown'), array_values($languages)); $dropdown->setOptionAsDefault($session->getLanguage()->getName()); diff --git a/src/xenialdan/MagicWE2/commands/brush/BrushCommand.php b/src/xenialdan/MagicWE2/commands/brush/BrushCommand.php index b9990695..89d8d708 100644 --- a/src/xenialdan/MagicWE2/commands/brush/BrushCommand.php +++ b/src/xenialdan/MagicWE2/commands/brush/BrushCommand.php @@ -59,7 +59,7 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo if (!$session instanceof UserSession) { throw new SessionException($lang->translateString('error.nosession', [Loader::getInstance()->getName()])); } - $form = new SimpleForm(Loader::PREFIX . TF::BOLD . TF::DARK_PURPLE . $lang->translateString('ui.brush.title'), $lang->translateString('ui.brush.content')); + $form = new SimpleForm(Loader::PREFIX_FORM . TF::BOLD . TF::DARK_PURPLE . $lang->translateString('ui.brush.title'), $lang->translateString('ui.brush.content')); $form->addButton(new Button($lang->translateString('ui.brush.create'))); $form->addButton(new Button($lang->translateString('ui.brush.getsession'))); $form->addButton(new Button($lang->translateString('ui.brush.edithand'))); @@ -78,7 +78,6 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo { $menu = InvMenu::create(InvMenu::TYPE_DOUBLE_CHEST); foreach ($session->getBrushes() as $brush) { - var_dump($brush); $menu->getInventory()->addItem($brush->toItem()); } $menu->send($player, "Session brushes"); @@ -112,7 +111,7 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo * @param array $data * @return array */ - public static function generateLore(array $elements, array $data): array + public static function generateLore(array $elements, array $data): array//TODO remove? { $return = []; foreach ($elements as $i => $element) { diff --git a/src/xenialdan/MagicWE2/commands/tool/DebugCommand.php b/src/xenialdan/MagicWE2/commands/tool/DebugCommand.php index c985a19b..1a0f544e 100644 --- a/src/xenialdan/MagicWE2/commands/tool/DebugCommand.php +++ b/src/xenialdan/MagicWE2/commands/tool/DebugCommand.php @@ -54,11 +54,11 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo try { $item = ItemFactory::getInstance()->get(ItemIds::STICK); $item->addEnchantment(new EnchantmentInstance(Loader::$ench)); - $item->setCustomName(Loader::PREFIX . TF::BOLD . TF::DARK_PURPLE . $lang->translateString('tool.debug')); + $item->setCustomName(Loader::PREFIX . TF::BOLD . TF::LIGHT_PURPLE . $lang->translateString('tool.debug')); $item->setLore([ - $lang->translateString('tool.debug.lore.1'), - $lang->translateString('tool.debug.lore.2'), - $lang->translateString('tool.debug.lore.3') + TF::RESET . $lang->translateString('tool.debug.lore.1'), + TF::RESET . $lang->translateString('tool.debug.lore.2'), + TF::RESET . $lang->translateString('tool.debug.lore.3') ]); $item->getNamedTag()->setTag(API::TAG_MAGIC_WE, CompoundTag::create()); $sender->getInventory()->addItem($item); diff --git a/src/xenialdan/MagicWE2/commands/tool/FloodCommand.php b/src/xenialdan/MagicWE2/commands/tool/FloodCommand.php index edee3614..c830e6f2 100644 --- a/src/xenialdan/MagicWE2/commands/tool/FloodCommand.php +++ b/src/xenialdan/MagicWE2/commands/tool/FloodCommand.php @@ -35,14 +35,14 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo $lang = Loader::getInstance()->getLanguage(); try { if ($sender instanceof Player) { - $form = new CustomForm(Loader::PREFIX . TF::BOLD . TF::DARK_PURPLE . $lang->translateString('ui.flood.title')); + $form = new CustomForm(Loader::PREFIX . TF::BOLD . TF::LIGHT_PURPLE . $lang->translateString('ui.flood.title')); $form->addElement(new Slider($lang->translateString('ui.flood.options.limit'), 0, 5000, 500.0)); $form->addElement(new Input($lang->translateString('ui.flood.options.blocks'), $lang->translateString('ui.flood.options.blocks.placeholder'))); $form->addElement(new Label($lang->translateString('ui.flood.options.label.infoapply'))); $form->setCallable(function (Player $player, $data) use ($form) { $item = ItemFactory::get(ItemIds::BUCKET, 1); $item->addEnchantment(new EnchantmentInstance(Enchantment::getEnchantment(Loader::FAKE_ENCH_ID))); - $item->setCustomName(Loader::PREFIX . TF::BOLD . TF::DARK_PURPLE . 'Flood'); + $item->setCustomName(Loader::PREFIX . TF::BOLD . TF::LIGHT_PURPLE . 'Flood'); $item->setLore(BrushCommand::generateLore($form->getContent(), $data)); $item->setNamedTagEntry(new CompoundTag(API::TAG_MAGIC_WE, [ new StringTag("blocks", $data[1]), diff --git a/src/xenialdan/MagicWE2/commands/tool/WandCommand.php b/src/xenialdan/MagicWE2/commands/tool/WandCommand.php index 591bc32e..e9d7be49 100644 --- a/src/xenialdan/MagicWE2/commands/tool/WandCommand.php +++ b/src/xenialdan/MagicWE2/commands/tool/WandCommand.php @@ -57,11 +57,11 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo $item = ItemFactory::getInstance()->get(ItemIds::WOODEN_AXE); $item->addEnchantment(new EnchantmentInstance(Loader::$ench)); $item->setUnbreakable(true); - $item->setCustomName(Loader::PREFIX . TF::BOLD . TF::DARK_PURPLE . $lang->translateString('tool.wand')); + $item->setCustomName(Loader::PREFIX . TF::BOLD . TF::LIGHT_PURPLE . $lang->translateString('tool.wand')); $item->setLore([ - $lang->translateString('tool.wand.lore.1'), - $lang->translateString('tool.wand.lore.2'), - $lang->translateString('tool.wand.lore.3') + TF::RESET . $lang->translateString('tool.wand.lore.1'), + TF::RESET . $lang->translateString('tool.wand.lore.2'), + TF::RESET . $lang->translateString('tool.wand.lore.3') ]); $item->getNamedTag()->setTag(API::TAG_MAGIC_WE, CompoundTag::create()); if (!$sender->getInventory()->contains($item)) $sender->getInventory()->addItem($item); diff --git a/src/xenialdan/MagicWE2/helper/BlockStatesParser.php b/src/xenialdan/MagicWE2/helper/BlockStatesParser.php index 088b2a26..fe5dcc09 100644 --- a/src/xenialdan/MagicWE2/helper/BlockStatesParser.php +++ b/src/xenialdan/MagicWE2/helper/BlockStatesParser.php @@ -354,7 +354,7 @@ public static function printStates(BlockStatesEntry $entry, bool $skipDefaults): if ($statesTagEntry instanceof ByteTag) { $s[] = TF::RED . $statesTagEntryName . "=" . ($statesTagEntry->getValue() ? TF::GREEN . "true" : TF::RED . "false") . TF::RESET; } else if ($statesTagEntry instanceof IntTag) { - $s[] = TF::BLUE . $statesTagEntryName . "=" . TF::BLUE . $statesTagEntry->getValue() . TF::RESET; + $s[] = TF::AQUA . $statesTagEntryName . "=" . TF::AQUA . $statesTagEntry->getValue() . TF::RESET; } else if ($statesTagEntry instanceof StringTag) { $s[] = TF::LIGHT_PURPLE . $statesTagEntryName . "=" . TF::LIGHT_PURPLE . $statesTagEntry->getValue() . TF::RESET; } diff --git a/src/xenialdan/MagicWE2/helper/Scoreboard.php b/src/xenialdan/MagicWE2/helper/Scoreboard.php index a980eb31..35964eab 100644 --- a/src/xenialdan/MagicWE2/helper/Scoreboard.php +++ b/src/xenialdan/MagicWE2/helper/Scoreboard.php @@ -29,27 +29,27 @@ public function handleScoreboard(UserSession $session): void $line = 0; $selection = $session->getLatestSelection(); ScoreFactory::setScoreLine($player, ++$line, TF::GOLD . $session->getLanguage()->translateString("spacer", ["Selection"])); - ScoreFactory::setScoreLine($player, ++$line, TF::ITALIC . "Position: " . TF::RESET . API::vecToString($selection->getPos1()->asVector3()) . " » " . API::vecToString($selection->getPos2()->asVector3())); - ScoreFactory::setScoreLine($player, ++$line, TF::ITALIC . "World: " . TF::RESET . $selection->getWorld()->getFolderName()); - ScoreFactory::setScoreLine($player, ++$line, TF::ITALIC . "Shape: " . TF::RESET . (new ReflectionClass($selection->shape))->getShortName()); - ScoreFactory::setScoreLine($player, ++$line, TF::ITALIC . "Size: " . TF::RESET . API::vecToString(new Vector3($selection->getSizeX(), $selection->getSizeY(), $selection->getSizeZ())) . " ({$selection->getShape()->getTotalCount()})"); + ScoreFactory::setScoreLine($player, ++$line, TF::BOLD . " Position: " . TF::RESET . API::vecToString($selection->getPos1()->asVector3()) . " » " . API::vecToString($selection->getPos2()->asVector3())); + ScoreFactory::setScoreLine($player, ++$line, TF::BOLD . " World: " . TF::RESET . $selection->getWorld()->getFolderName()); + ScoreFactory::setScoreLine($player, ++$line, TF::BOLD . " Shape: " . TF::RESET . (new ReflectionClass($selection->shape))->getShortName()); + ScoreFactory::setScoreLine($player, ++$line, TF::BOLD . " Size: " . TF::RESET . API::vecToString(new Vector3($selection->getSizeX(), $selection->getSizeY(), $selection->getSizeZ())) . " ({$selection->getShape()->getTotalCount()})"); ScoreFactory::setScoreLine($player, ++$line, TF::GOLD . $session->getLanguage()->translateString("spacer", ["Settings"])); - ScoreFactory::setScoreLine($player, ++$line, TF::ITALIC . "Tool Range: " . TF::RESET . Loader::getInstance()->getToolDistance()); + ScoreFactory::setScoreLine($player, ++$line, TF::BOLD . " Tool Range: " . TF::RESET . Loader::getInstance()->getToolDistance()); $editLimit = Loader::getInstance()->getEditLimit(); - ScoreFactory::setScoreLine($player, ++$line, TF::ITALIC . "Limit: " . TF::RESET . ($editLimit === -1 ? API::boolToString(false) : $editLimit)); - ScoreFactory::setScoreLine($player, ++$line, TF::ITALIC . "Wand Tool: " . TF::RESET . API::boolToString($session->isWandEnabled())); - ScoreFactory::setScoreLine($player, ++$line, TF::ITALIC . "Debug Tool: " . TF::RESET . API::boolToString($session->isDebugToolEnabled())); - ScoreFactory::setScoreLine($player, ++$line, TF::ITALIC . "WAILA: " . TF::RESET . API::boolToString($session->isWailaEnabled())); + ScoreFactory::setScoreLine($player, ++$line, TF::BOLD . " Limit: " . TF::RESET . ($editLimit === -1 ? API::boolToString(false) : $editLimit)); + ScoreFactory::setScoreLine($player, ++$line, TF::BOLD . " Wand Tool: " . TF::RESET . API::boolToString($session->isWandEnabled())); + ScoreFactory::setScoreLine($player, ++$line, TF::BOLD . " Debug Tool: " . TF::RESET . API::boolToString($session->isDebugToolEnabled())); + ScoreFactory::setScoreLine($player, ++$line, TF::BOLD . " WAILA: " . TF::RESET . API::boolToString($session->isWailaEnabled())); if (($cb = $session->getCurrentClipboard()) instanceof SingleClipboard) { ScoreFactory::setScoreLine($player, ++$line, TF::GOLD . $session->getLanguage()->translateString("spacer", ["Clipboard"])); /** @var SingleClipboard $cb */ if ($cb->customName !== "") - ScoreFactory::setScoreLine($player, ++$line, TF::ITALIC . "Name: " . TF::RESET . $cb->customName); + ScoreFactory::setScoreLine($player, ++$line, TF::BOLD . " Name: " . TF::RESET . $cb->customName); if ($cb->selection instanceof Selection) { - ScoreFactory::setScoreLine($player, ++$line, TF::ITALIC . "Shape: " . TF::RESET . (new ReflectionClass($cb->selection->shape))->getShortName()); - ScoreFactory::setScoreLine($player, ++$line, TF::ITALIC . "Size: " . TF::RESET . API::vecToString(new Vector3($cb->selection->getSizeX(), $cb->selection->getSizeY(), $cb->selection->getSizeZ())) . " ({$cb->getTotalCount()})"); + ScoreFactory::setScoreLine($player, ++$line, TF::BOLD . " Shape: " . TF::RESET . (new ReflectionClass($cb->selection->shape))->getShortName()); + ScoreFactory::setScoreLine($player, ++$line, TF::BOLD . " Size: " . TF::RESET . API::vecToString(new Vector3($cb->selection->getSizeX(), $cb->selection->getSizeY(), $cb->selection->getSizeZ())) . " ({$cb->getTotalCount()})"); } } //todo current block palette, schematics, brushes diff --git a/src/xenialdan/MagicWE2/session/data/Asset.php b/src/xenialdan/MagicWE2/session/data/Asset.php index a0642aba..324510b2 100644 --- a/src/xenialdan/MagicWE2/session/data/Asset.php +++ b/src/xenialdan/MagicWE2/session/data/Asset.php @@ -24,15 +24,15 @@ class Asset implements JsonSerializable { const TYPE_SCHEMATIC = 'schematic'; - const TYPE_MCSTRUCTURE = 'mcstructure'; - const TYPE_CLIPBOARD = 'clipboard'; + const TYPE_MCSTRUCTURE = 'structure'; + const TYPE_CLIPBOARD = 'clipboard';//TODO consider if this is even worth the efford, or instead just convert it to mcstructure before storing public Schematic|SingleClipboard|MCStructure $structure; public string $filename;//used as identifier public string $displayname; public bool $locked = false; - public ?string $ownerXuid; - private ?Item $item; + public ?string $ownerXuid = null; + private ?Item $item = null; /** * Asset constructor. @@ -84,18 +84,22 @@ public function toItem(bool $renew = false): Item if ($this->item !== null && !$renew) return $this->item; $item = ItemFactory::getInstance()->get(ItemIds::SCAFFOLDING); $item->addEnchantment(new EnchantmentInstance(Loader::$ench)); - [$filename, $displayname, $type, $locked, $owner] = $this->jsonSerialize(); - $item->getNamedTag()->setTag(API::TAG_MAGIC_WE_ASSET, - CompoundTag::create() - ->setString("filename", $filename) - ->setString("displayname", $displayname) - ->setString("type", $type) - ->setByte("locked", $locked ? 1 : 0) - ->setString("owner", $owner) - ); - $item->setCustomName(Loader::PREFIX . TF::BOLD . TF::DARK_PURPLE . $displayname); - $item->setLore($this->generateLore()); - $this->item = $item; + try { + ['filename' => $filename, 'displayname' => $displayname, 'type' => $type, 'locked' => $locked, 'owner' => $owner] = $this->jsonSerialize(); + $item->getNamedTag()->setTag(API::TAG_MAGIC_WE_ASSET, + CompoundTag::create() + ->setString("filename", $filename) + ->setString("displayname", $displayname) + ->setString("type", $type) + ->setByte("locked", $locked ? 1 : 0) + ->setString("owner", $owner) + ); + $item->setCustomName(Loader::PREFIX_ASSETS . TF::BOLD . TF::LIGHT_PURPLE . $displayname); + $item->setLore($this->generateLore()); + $this->item = $item; + } catch (InvalidArgumentException|TypeError $e) { + Loader::getInstance()->getLogger()->logException($e); + } return $item; } @@ -105,14 +109,13 @@ public function toItem(bool $renew = false): Item private function generateLore(): array { $return = []; - foreach ($this->jsonSerialize() as $k => $v) { - if ($v === '' || $v === 'displayname') continue; - if (is_bool($v)) { - $return[] = (ucfirst($k) . ": " . ($v ? "Yes" : "No")); - continue; - } - $return[] = (ucfirst($k) . ": " . $v); - } + ['filename' => $filename, 'displayname' => $displayname, 'type' => $type, 'locked' => $locked] = $this->jsonSerialize(); + if (pathinfo($filename, PATHINFO_FILENAME) !== $displayname) + $return[] = TF::RESET . TF::BOLD . TF::GOLD . "Filename: " . TF::RESET . $filename; + $return[] = TF::RESET . TF::BOLD . TF::GOLD . "Type: " . TF::RESET . ucfirst($type); + $return[] = TF::RESET . TF::BOLD . TF::GOLD . "Locked: " . TF::RESET . ($locked ? TF::GREEN . "Yes" : TF::RED . "No"); + $return[] = TF::RESET . TF::BOLD . TF::GOLD . "Origin: " . TF::RESET . API::vecToString($this->getOrigin()); + $return[] = TF::RESET . TF::BOLD . TF::GOLD . "Size: " . TF::RESET . API::vecToString($this->getSize()) . " ({$this->getTotalCount()})"; return $return; } diff --git a/src/xenialdan/MagicWE2/tool/Brush.php b/src/xenialdan/MagicWE2/tool/Brush.php index 8c84a5c5..9d32390f 100644 --- a/src/xenialdan/MagicWE2/tool/Brush.php +++ b/src/xenialdan/MagicWE2/tool/Brush.php @@ -79,7 +79,7 @@ public function toItem(): Item ->setInt("version", $this->properties->version) ->setString("properties", $properties) ); - $item->setCustomName(Loader::PREFIX . TF::BOLD . TF::DARK_PURPLE . $this->getName()); + $item->setCustomName(Loader::PREFIX . TF::BOLD . TF::LIGHT_PURPLE . $this->getName()); $item->setLore($this->properties->generateLore()); $item->setUnbreakable(); return $item; diff --git a/src/xenialdan/MagicWE2/tool/BrushProperties.php b/src/xenialdan/MagicWE2/tool/BrushProperties.php index c19f9594..a0dc3d99 100644 --- a/src/xenialdan/MagicWE2/tool/BrushProperties.php +++ b/src/xenialdan/MagicWE2/tool/BrushProperties.php @@ -124,25 +124,25 @@ public function setCustomName(string $customName = ""): void public function generateLore(): array { $shapeProperties = array_map(static function ($k, $v): string { - return TF::GOLD . " " . ucfirst($k) . " = " . (is_bool($v) ? ($v ? "Yes" : "No") : $v); + return TF::RESET . TF::AQUA . " " . ucfirst($k) . ": " . TF::RESET . (is_bool($v) ? ($v ? TF::GREEN . "Yes" : TF::RED . "No") : $v); }, array_keys($this->shapeProperties), $this->shapeProperties); $actionProperties = array_map(static function ($k, $v): string { - return TF::GOLD . " " . ucfirst($k) . " = " . (is_bool($v) ? ($v ? "Yes" : "No") : $v); + return TF::RESET . TF::AQUA . " " . ucfirst($k) . ": " . TF::RESET . (is_bool($v) ? ($v ? TF::GREEN . "Yes" : TF::RED . "No") : $v); }, array_keys($this->actionProperties), $this->actionProperties); return array_merge( [ - TF::GOLD . "Shape: {$this->getShapeName()}", + TF::RESET . TF::BOLD . TF::GOLD . "Shape: " . TF::RESET . $this->getShapeName(), ], $shapeProperties, [ - TF::GOLD . "Action: {$this->getActionName()}", + TF::RESET . TF::BOLD . TF::GOLD . "Action: " . TF::RESET . $this->getActionName(), ], $actionProperties, [ - TF::GOLD . "Blocks: {$this->blocks}", - TF::GOLD . "Filter: {$this->filter}", - TF::GOLD . "Biome: {$this->biomeId}", - TF::GOLD . "Hollow: " . ($this->hollow ? "Yes" : "No"), + TF::RESET . TF::BOLD . TF::GOLD . "Blocks: " . TF::RESET . $this->blocks, + TF::RESET . TF::BOLD . TF::GOLD . "Filter: " . TF::RESET . $this->filter, + TF::RESET . TF::BOLD . TF::GOLD . "Biome: " . TF::RESET . $this->biomeId, + TF::RESET . TF::BOLD . TF::GOLD . "Hollow: " . TF::RESET . ($this->hollow ? TF::GREEN . "Yes" : TF::RED . "No"), //TF::GOLD . "UUID: {$this->uuid}", ] ); From 5e70a92aeae6a52c20f125831a45fd0ba50766df Mon Sep 17 00:00:00 2001 From: XenialDan Date: Sat, 13 Feb 2021 23:17:14 +0100 Subject: [PATCH 09/67] Whoopsie, the AssetCommand class slipped --- .../MagicWE2/commands/asset/AssetCommand.php | 139 ++++++++++++++++++ 1 file changed, 139 insertions(+) create mode 100644 src/xenialdan/MagicWE2/commands/asset/AssetCommand.php diff --git a/src/xenialdan/MagicWE2/commands/asset/AssetCommand.php b/src/xenialdan/MagicWE2/commands/asset/AssetCommand.php new file mode 100644 index 00000000..2730d35f --- /dev/null +++ b/src/xenialdan/MagicWE2/commands/asset/AssetCommand.php @@ -0,0 +1,139 @@ +registerSubCommand(new BrushNameCommand("name", "Get name or rename a brush")); + $this->setPermission("we.command.brush");//TODO perm + } + + /** + * @param CommandSender $sender + * @param string $aliasUsed + * @param mixed[] $args + */ + public function onRun(CommandSender $sender, string $aliasUsed, array $args): void + { + $lang = Loader::getInstance()->getLanguage(); + if ($sender instanceof Player && SessionHelper::hasSession($sender)) { + try { + $lang = SessionHelper::getUserSession($sender)->getLanguage(); + } catch (SessionException $e) { + } + } + if (!$sender instanceof Player) { + $sender->sendMessage(TF::RED . $lang->translateString('error.runingame')); + return; + } + /** @var Player $sender */ + try { + $session = SessionHelper::getUserSession($sender); + if (!$session instanceof UserSession) { + throw new SessionException($lang->translateString('error.nosession', [Loader::getInstance()->getName()])); + } + $form = new SimpleForm(Loader::PREFIX_FORM . TF::BOLD . TF::DARK_PURPLE . $lang->translateString('ui.asset.title'), $lang->translateString('ui.asset.content'));//TODO + $form->addButton(new Button($lang->translateString('ui.asset.create.fromclipboard'))); + $form->addButton(new Button($lang->translateString('ui.asset.global'))); + $form->addButton(new Button($lang->translateString('ui.asset.private'))); + $form->setCallable(function (Player $player, $data) use ($lang, $session) { + try { + switch ($data) { + case $lang->translateString('ui.asset.create.fromclipboard'): + { + //export clipboard + //input Name + //toggle lock + //toggle shared asset + //type dropdown? + /* + $brush = new Brush(new BrushProperties()); + if ($brush instanceof Brush) { + $player->sendForm($brush->getForm()); + }*///TODO + break; + } + case $lang->translateString('ui.asset.global'): + { + $menu = InvMenu::create(InvMenu::TYPE_DOUBLE_CHEST); + $store = Loader::$assetCollection; + foreach ($store->getAssetsGlobal() as $asset) { + $menu->getInventory()->addItem($asset->toItem()); + } + $menu->send($player, "Global assets"); + break; + } + case $lang->translateString('ui.asset.private'): + { + $menu = InvMenu::create(InvMenu::TYPE_DOUBLE_CHEST); + $store = Loader::$assetCollection; + $item = VanillaBlocks::CONCRETE()->asItem(); + $item->addEnchantment(new EnchantmentInstance(Loader::$ench)); + foreach ($store->getPlayerAssets($player->getXuid()) as $asset) { + $menu->getInventory()->addItem($asset->toItem()); + } + $menu->send($player, "Private assets"); + break; + } + } + return null; + } catch (Exception $error) { + $session->sendMessage(TF::RED . $lang->translateString('error')); + $session->sendMessage(TF::RED . $error->getMessage()); + Loader::getInstance()->getLogger()->logException($error); + } + }); + $sender->sendForm($form); + } catch (Exception $error) { + $sender->sendMessage(Loader::PREFIX . TF::RED . $lang->translateString('error.command-error')); + $sender->sendMessage(Loader::PREFIX . TF::RED . $error->getMessage()); + $sender->sendMessage($this->getUsage()); + } + } + + /** + * @param UIElement[] $elements + * @param array $data + * @return array + */ + public static function generateLore(array $elements, array $data): array + { + $return = []; + foreach ($elements as $i => $element) { + if ($element instanceof Label) continue; + if ($element instanceof Toggle) { + $return[] = ($element->getText() . ": " . ($data[$i] ? "Yes" : "No")); + continue; + } + $return[] = ($element->getText() . ": " . $data[$i]); + } + return $return; + } +} From cbe446ee1c0e5175cfbefc543e5ccc8e2bb45b32 Mon Sep 17 00:00:00 2001 From: XenialDan Date: Sat, 13 Feb 2021 23:19:52 +0100 Subject: [PATCH 10/67] Upgrade libstructure --- .poggit.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.poggit.yml b/.poggit.yml index efee4424..45bb0a7a 100644 --- a/.poggit.yml +++ b/.poggit.yml @@ -25,7 +25,7 @@ projects: version: ^4.1.0 branch: "4.0" - src: thebigsmilexd/libstructure/libstructure - version: ^0.1.2 + version: ^0.1.3 branch: mcstructure - src: buchwasa/ScoreFactory/ScoreFactory version: ^3.0.1 From b83f45d63e29651873b168377f7015f758daa97e Mon Sep 17 00:00:00 2001 From: XenialDan Date: Sat, 20 Feb 2021 03:50:02 +0100 Subject: [PATCH 11/67] Add clipboard to asset & asset settings form --- .../MagicWE2/clipboard/Clipboard.php | 6 +- .../MagicWE2/commands/args/BlocksArgument.php | 16 ++- .../MagicWE2/commands/asset/AssetCommand.php | 99 +++++++++++++---- .../MagicWE2/helper/BlockPalette.php | 4 +- src/xenialdan/MagicWE2/helper/BlockQuery.php | 9 ++ src/xenialdan/MagicWE2/session/data/Asset.php | 101 ++++++++++++++++-- .../MagicWE2/session/data/AssetCollection.php | 21 ++-- src/xenialdan/MagicWE2/task/AsyncCopyTask.php | 2 +- 8 files changed, 220 insertions(+), 38 deletions(-) diff --git a/src/xenialdan/MagicWE2/clipboard/Clipboard.php b/src/xenialdan/MagicWE2/clipboard/Clipboard.php index 455c2f93..c3ecca1f 100644 --- a/src/xenialdan/MagicWE2/clipboard/Clipboard.php +++ b/src/xenialdan/MagicWE2/clipboard/Clipboard.php @@ -26,10 +26,8 @@ abstract class Clipboard implements Serializable public const FLIP_NORTH = 0x03; public const FLIP_SOUTH = 0x03; - /** @var int|null */ - public $worldId; - /** @var string */ - public $customName = ""; + public ?int $worldId; + public string $customName = ""; /** * Creates a chunk manager used for async editing diff --git a/src/xenialdan/MagicWE2/commands/args/BlocksArgument.php b/src/xenialdan/MagicWE2/commands/args/BlocksArgument.php index d01cbb8b..e076c76a 100644 --- a/src/xenialdan/MagicWE2/commands/args/BlocksArgument.php +++ b/src/xenialdan/MagicWE2/commands/args/BlocksArgument.php @@ -5,8 +5,15 @@ namespace xenialdan\MagicWE2\commands\args; use CortexPE\Commando\args\RawStringArgument; +use InvalidArgumentException as InvalidArgumentExceptionAlias; +use pocketmine\block\utils\InvalidBlockStateException; use pocketmine\command\CommandSender; +use pocketmine\player\Player; +use pocketmine\utils\TextFormat as TF; +use xenialdan\MagicWE2\exception\BlockQueryAlreadyParsedException; use xenialdan\MagicWE2\helper\BlockPalette; +use xenialdan\MagicWE2\helper\SessionHelper; +use xenialdan\MagicWE2\Loader; class BlocksArgument extends RawStringArgument { @@ -28,6 +35,13 @@ public function canParse(string $testString, CommandSender $sender): bool */ public function parse(string $argument, CommandSender $sender) { - return BlockPalette::fromString($argument); + try { + return BlockPalette::fromString($argument); + } catch (BlockQueryAlreadyParsedException|InvalidArgumentExceptionAlias|InvalidBlockStateException $error) { + if ($sender instanceof Player) + SessionHelper::getUserSession($sender)->sendMessage('error.command-error'); + $sender->sendMessage(Loader::PREFIX . TF::RED . $error->getMessage()); + } + return BlockPalette::CREATE(); } } \ No newline at end of file diff --git a/src/xenialdan/MagicWE2/commands/asset/AssetCommand.php b/src/xenialdan/MagicWE2/commands/asset/AssetCommand.php index 2730d35f..e8aba74c 100644 --- a/src/xenialdan/MagicWE2/commands/asset/AssetCommand.php +++ b/src/xenialdan/MagicWE2/commands/asset/AssetCommand.php @@ -4,23 +4,27 @@ namespace xenialdan\MagicWE2\commands\asset; +use BlockHorizons\libschematic\Schematic; use CortexPE\Commando\BaseCommand; use Exception; use InvalidArgumentException; use muqsit\invmenu\InvMenu; -use pocketmine\block\VanillaBlocks; use pocketmine\command\CommandSender; -use pocketmine\item\enchantment\EnchantmentInstance; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; use xenialdan\customui\elements\Button; use xenialdan\customui\elements\Label; use xenialdan\customui\elements\Toggle; use xenialdan\customui\elements\UIElement; +use xenialdan\customui\windows\CustomForm; use xenialdan\customui\windows\SimpleForm; +use xenialdan\libstructure\format\MCStructure; +use xenialdan\MagicWE2\clipboard\SingleClipboard; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\SessionHelper; use xenialdan\MagicWE2\Loader; +use xenialdan\MagicWE2\session\data\Asset; +use xenialdan\MagicWE2\session\data\AssetCollection; use xenialdan\MagicWE2\session\UserSession; class AssetCommand extends BaseCommand @@ -60,46 +64,105 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo throw new SessionException($lang->translateString('error.nosession', [Loader::getInstance()->getName()])); } $form = new SimpleForm(Loader::PREFIX_FORM . TF::BOLD . TF::DARK_PURPLE . $lang->translateString('ui.asset.title'), $lang->translateString('ui.asset.content'));//TODO - $form->addButton(new Button($lang->translateString('ui.asset.create.fromclipboard'))); - $form->addButton(new Button($lang->translateString('ui.asset.global'))); $form->addButton(new Button($lang->translateString('ui.asset.private'))); + $form->addButton(new Button($lang->translateString('ui.asset.global'))); + $form->addButton(new Button($lang->translateString('ui.asset.create.fromclipboard'))); + $form->addButton(new Button($lang->translateString('ui.asset.settings'))); + $form->addButton(new Button($lang->translateString('ui.asset.save'))); $form->setCallable(function (Player $player, $data) use ($lang, $session) { try { + $store = AssetCollection::getInstance(); switch ($data) { case $lang->translateString('ui.asset.create.fromclipboard'): { - //export clipboard + //create clipboard asset //input Name //toggle lock //toggle shared asset //type dropdown? - /* - $brush = new Brush(new BrushProperties()); - if ($brush instanceof Brush) { - $player->sendForm($brush->getForm()); - }*///TODO + $clipboard = $session->getCurrentClipboard(); + if (!$clipboard instanceof SingleClipboard) { + $player->sendMessage($lang->translateString('error.noclipboard')); + break; + } + $asset = new Asset($clipboard->getCustomName(), $clipboard, false, $player->getXuid(), false); + $player->sendForm($asset->getSettingForm()); + break; + } + case $lang->translateString('ui.asset.save'): + { + //save asset + //dropdown asset + //dropdown type + $form = new CustomForm(Loader::PREFIX_FORM . TF::BOLD . TF::DARK_PURPLE . $lang->translateString('ui.asset.select')); + $options = []; + foreach ($store->getUnlockedAssets() as $asset) { + $options[$asset->filename] = $asset->filename; + } + $form->addDropdown("Asset", array_values($options)); + $form->addDropdown("File type", [Asset::TYPE_SCHEMATIC, Asset::TYPE_MCSTRUCTURE]); + $form->setCallable(function (Player $player, $data) use ($lang, $session, $store) { + [$filename, $type] = $data; + /** @var Asset $asset */ + $asset = $store->assets->get($filename); + $player->sendMessage('Saving ' . (string)$asset); + //TODO async + if ($asset->structure instanceof Schematic && $type === Asset::TYPE_SCHEMATIC) { + $file = pathinfo($asset->filename, PATHINFO_BASENAME) . '_' . time() . '.schematic'; + $asset->structure->save($file); + $player->sendMessage("Saved as $file"); + } + if ($asset->structure instanceof MCStructure && $type === Asset::TYPE_MCSTRUCTURE) { + #$asset->structure->save($asset->filename.'.mcstructure'); + $player->sendMessage('TODO'); + } + //$asset->saveAs() //TODO + }); + $player->sendForm($form); + break; + } + case $lang->translateString('ui.asset.settings'): + { + //save asset + //dropdown asset + //dropdown type + $form = new CustomForm(Loader::PREFIX_FORM . TF::BOLD . TF::DARK_PURPLE . $lang->translateString('ui.asset.select')); + $options = []; + foreach (AssetCollection::getInstance()->getAssets() as $asset) { + $options[$asset->filename] = $asset->filename; + } + $form->addDropdown("Asset", array_values($options)); + $form->setCallable(function (Player $player, $data) use ($lang, $session, $store) { + [$filename] = $data; + /** @var Asset $asset */ + $asset = $store->assets->get($filename); + $player->sendForm($asset->getSettingForm()); + }); + $player->sendForm($form); break; } case $lang->translateString('ui.asset.global'): { $menu = InvMenu::create(InvMenu::TYPE_DOUBLE_CHEST); - $store = Loader::$assetCollection; - foreach ($store->getAssetsGlobal() as $asset) { + #$store = Loader::$assetCollection; + foreach ($store->getSharedAssets() as $asset) { $menu->getInventory()->addItem($asset->toItem()); } - $menu->send($player, "Global assets"); + $menu->send($player, "Shared assets (" . count($store->getSharedAssets()) . ")"); break; } case $lang->translateString('ui.asset.private'): { $menu = InvMenu::create(InvMenu::TYPE_DOUBLE_CHEST); - $store = Loader::$assetCollection; - $item = VanillaBlocks::CONCRETE()->asItem(); - $item->addEnchantment(new EnchantmentInstance(Loader::$ench)); - foreach ($store->getPlayerAssets($player->getXuid()) as $asset) { + #$store = Loader::$assetCollection; + $store = AssetCollection::getInstance(); + $playerAssets = $store->getPlayerAssets($player->getXuid()); + var_dump(array_keys($playerAssets), array_keys($store->getPlayerAssets())); + foreach ($playerAssets as $key => $asset) { + var_dump($key, $asset); $menu->getInventory()->addItem($asset->toItem()); } - $menu->send($player, "Private assets"); + $menu->send($player, "Private assets (" . count($playerAssets) . ")"); break; } } diff --git a/src/xenialdan/MagicWE2/helper/BlockPalette.php b/src/xenialdan/MagicWE2/helper/BlockPalette.php index cd6ebe79..34e57bdd 100644 --- a/src/xenialdan/MagicWE2/helper/BlockPalette.php +++ b/src/xenialdan/MagicWE2/helper/BlockPalette.php @@ -9,6 +9,7 @@ use JsonException; use pocketmine\block\Block; use pocketmine\block\BlockFactory; +use pocketmine\block\utils\InvalidBlockStateException; use xenialdan\MagicWE2\exception\BlockQueryAlreadyParsedException; class BlockPalette @@ -33,8 +34,7 @@ public function __construct(string $name = "") /** * @param string $blocksQuery * @return BlockPalette - * @throws InvalidArgumentException - * @throws BlockQueryAlreadyParsedException + * @throws InvalidArgumentException|BlockQueryAlreadyParsedException|InvalidBlockStateException */ public static function fromString(string $blocksQuery): BlockPalette { diff --git a/src/xenialdan/MagicWE2/helper/BlockQuery.php b/src/xenialdan/MagicWE2/helper/BlockQuery.php index dce14490..9d62bd15 100644 --- a/src/xenialdan/MagicWE2/helper/BlockQuery.php +++ b/src/xenialdan/MagicWE2/helper/BlockQuery.php @@ -4,6 +4,8 @@ namespace xenialdan\MagicWE2\helper; +use InvalidArgumentException; +use pocketmine\block\utils\InvalidBlockStateException; use xenialdan\MagicWE2\exception\BlockQueryAlreadyParsedException; final class BlockQuery @@ -35,6 +37,13 @@ public function __construct(string $query, ?string $fullBlockQuery, ?string $blo $this->weight = (float)($weight ?? "100") / 100; } + /** + * @param bool $update + * @return $this + * @throws BlockQueryAlreadyParsedException + * @throws InvalidArgumentException + * @throws InvalidBlockStateException + */ public function parse(bool $update = true): self { //calling methods should check with hasBlock() before parse() diff --git a/src/xenialdan/MagicWE2/session/data/Asset.php b/src/xenialdan/MagicWE2/session/data/Asset.php index 324510b2..7914ab82 100644 --- a/src/xenialdan/MagicWE2/session/data/Asset.php +++ b/src/xenialdan/MagicWE2/session/data/Asset.php @@ -5,6 +5,7 @@ namespace xenialdan\MagicWE2\session\data; use BlockHorizons\libschematic\Schematic; +use Exception; use InvalidArgumentException; use JsonSerializable; use pocketmine\item\enchantment\EnchantmentInstance; @@ -13,13 +14,19 @@ use pocketmine\item\ItemIds; use pocketmine\math\Vector3; use pocketmine\nbt\tag\CompoundTag; +use pocketmine\player\Player; +use pocketmine\utils\AssumptionFailedError; use pocketmine\utils\TextFormat as TF; use TypeError; use UnexpectedValueException; +use xenialdan\customui\windows\CustomForm; use xenialdan\libstructure\format\MCStructure; use xenialdan\MagicWE2\API; use xenialdan\MagicWE2\clipboard\SingleClipboard; +use xenialdan\MagicWE2\exception\SessionException; +use xenialdan\MagicWE2\helper\SessionHelper; use xenialdan\MagicWE2\Loader; +use xenialdan\MagicWE2\session\UserSession; class Asset implements JsonSerializable { @@ -33,6 +40,7 @@ class Asset implements JsonSerializable public bool $locked = false; public ?string $ownerXuid = null; private ?Item $item = null; + public bool $shared = false; /** * Asset constructor. @@ -40,14 +48,16 @@ class Asset implements JsonSerializable * @param Schematic|MCStructure|SingleClipboard $value * @param bool $locked * @param string|null $ownerXuid + * @param bool $shared */ - public function __construct(string $filename, Schematic|SingleClipboard|MCStructure $value, bool $locked = false, ?string $ownerXuid = null) + public function __construct(string $filename, Schematic|SingleClipboard|MCStructure $value, bool $locked = false, ?string $ownerXuid = null, bool $shared = false) { $this->filename = $filename; $this->displayname = pathinfo($filename, PATHINFO_FILENAME); $this->structure = $value; $this->locked = $locked; $this->ownerXuid = $ownerXuid; + $this->shared = $shared; } public function getSize(): Vector3 @@ -77,7 +87,6 @@ public function getOrigin(): Vector3 * @param bool $renew * @return Item * @throws InvalidArgumentException - * @throws TypeError */ public function toItem(bool $renew = false): Item { @@ -85,7 +94,7 @@ public function toItem(bool $renew = false): Item $item = ItemFactory::getInstance()->get(ItemIds::SCAFFOLDING); $item->addEnchantment(new EnchantmentInstance(Loader::$ench)); try { - ['filename' => $filename, 'displayname' => $displayname, 'type' => $type, 'locked' => $locked, 'owner' => $owner] = $this->jsonSerialize(); + ['filename' => $filename, 'displayname' => $displayname, 'type' => $type, 'locked' => $locked, 'owner' => $owner, 'shared' => $shared] = $this->jsonSerialize(); $item->getNamedTag()->setTag(API::TAG_MAGIC_WE_ASSET, CompoundTag::create() ->setString("filename", $filename) @@ -93,11 +102,12 @@ public function toItem(bool $renew = false): Item ->setString("type", $type) ->setByte("locked", $locked ? 1 : 0) ->setString("owner", $owner) + ->setByte("shared", $shared ? 1 : 0) ); $item->setCustomName(Loader::PREFIX_ASSETS . TF::BOLD . TF::LIGHT_PURPLE . $displayname); $item->setLore($this->generateLore()); $this->item = $item; - } catch (InvalidArgumentException|TypeError $e) { + } catch (TypeError $e) { Loader::getInstance()->getLogger()->logException($e); } return $item; @@ -109,16 +119,94 @@ public function toItem(bool $renew = false): Item private function generateLore(): array { $return = []; - ['filename' => $filename, 'displayname' => $displayname, 'type' => $type, 'locked' => $locked] = $this->jsonSerialize(); + ['filename' => $filename, 'displayname' => $displayname, 'type' => $type, 'locked' => $locked, 'owner' => $ownerXuid, 'shared' => $shared] = $this->jsonSerialize(); if (pathinfo($filename, PATHINFO_FILENAME) !== $displayname) $return[] = TF::RESET . TF::BOLD . TF::GOLD . "Filename: " . TF::RESET . $filename; $return[] = TF::RESET . TF::BOLD . TF::GOLD . "Type: " . TF::RESET . ucfirst($type); $return[] = TF::RESET . TF::BOLD . TF::GOLD . "Locked: " . TF::RESET . ($locked ? TF::GREEN . "Yes" : TF::RED . "No"); $return[] = TF::RESET . TF::BOLD . TF::GOLD . "Origin: " . TF::RESET . API::vecToString($this->getOrigin()); $return[] = TF::RESET . TF::BOLD . TF::GOLD . "Size: " . TF::RESET . API::vecToString($this->getSize()) . " ({$this->getTotalCount()})"; + $return[] = TF::RESET . TF::BOLD . TF::GOLD . "Owner: " . TF::RESET . $ownerXuid ?? 'none'; + $return[] = TF::RESET . TF::BOLD . TF::GOLD . "Shared: " . TF::RESET . ($shared ? TF::GREEN . "Yes" : TF::RED . "No"); return $return; } + public function __toString(): string + { + return 'Asset ' . implode(' ', $this->generateLore()); + } + + /** + * @param bool $new true if creating new brush + * @param array $errors + * @return CustomForm + * @throws Exception + * @throws AssumptionFailedError + */ + public function getSettingForm(bool $new = true, array $errors = []): CustomForm + { + //export clipboard + //input Name + //toggle lock + //toggle shared asset + //type dropdown? + try { + // Form + //TODO display errors + $form = new CustomForm("Asset settings"); + $form->addInput("Filename", "Filename", $this->filename); + $form->addToggle("Lock asset", $this->locked); + $form->addToggle("Shared asset", $this->shared); + foreach ($this->generateLore() as $value) { + $form->addLabel($value); + } + // Function + $form->setCallable(function (Player $player, $data) use ($form, $new) { + var_dump(__LINE__, $data); + [$filename, $this->locked, $shared] = $data; + var_dump($filename, $this->locked ? "true" : "false", $shared ? "true" : "false"); + + try { + $session = SessionHelper::getUserSession($player); + if (!$session instanceof UserSession) { + throw new SessionException(Loader::getInstance()->getLanguage()->translateString('error.nosession', [Loader::getInstance()->getName()])); + } + if ($this->locked) { + $session->sendMessage('error.asset.locked'); + return; + } + + /*//Resend form upon error + if (!empty($error)) { + $player->sendForm($this->getForm($new, $error)); + return; + }*/ + $this->filename = $filename; + $this->displayname = pathinfo($filename, PATHINFO_FILENAME); + $this->shared = $shared; + var_dump($this->filename, $this->displayname); + #var_dump(__LINE__, $this); + #print_r(AssetCollection::getInstance()->assets); + #print_r(AssetCollection::getInstance()->assets->toArray()); + #print_r(AssetCollection::getInstance()->assets->values()->toArray()); + #print_r(AssetCollection::getInstance()->assets->keys()->toArray()); + #print_r(AssetCollection::getInstance()->getAssets()); + AssetCollection::getInstance()->assets->put($this->filename, $this);//overwrites + $player->sendMessage("Asset stored in " . ($shared ? 'global' : 'private') . ' collection'); + $player->sendMessage((string)$this); + #$player->sendMessage((string)$this->toItem(true)); + } catch (Exception $ex) { + $player->sendMessage($ex->getMessage()); + Loader::getInstance()->getLogger()->logException($ex); + } + }); + return $form; + } catch (Exception $e) { + Loader::getInstance()->getLogger()->logException($e); + throw new AssumptionFailedError("Could not create asset setting form: " . $e->getMessage()); + } + } + public function jsonSerialize() { return [ @@ -126,7 +214,8 @@ public function jsonSerialize() 'displayname' => $this->displayname, 'type' => $this->structure instanceof Schematic ? self::TYPE_SCHEMATIC : ($this->structure instanceof MCStructure ? self::TYPE_MCSTRUCTURE : ($this->structure instanceof SingleClipboard ? self::TYPE_CLIPBOARD : '')), 'locked' => $this->locked, - 'owner' => $this->ownerXuid ?? '', + 'owner' => $this->ownerXuid ?? 'none', + 'shared' => $this->shared, ]; } } \ No newline at end of file diff --git a/src/xenialdan/MagicWE2/session/data/AssetCollection.php b/src/xenialdan/MagicWE2/session/data/AssetCollection.php index 47bb1aae..dcb5238e 100644 --- a/src/xenialdan/MagicWE2/session/data/AssetCollection.php +++ b/src/xenialdan/MagicWE2/session/data/AssetCollection.php @@ -31,21 +31,30 @@ public function getAssets(): array } /** @return Asset[] */ - public function getAssetsGlobal(): array + public function getUnlockedAssets(): array { return $this->assets->filter(function (string $key, Asset $value) { - return $value->ownerXuid !== ''; + return !$value->locked; + })->values()->toArray(); + } + + /** @return Asset[] */ + public function getSharedAssets(): array + { + return $this->assets->filter(function (string $key, Asset $value) { + return $value->shared; })->values()->toArray(); } /** - * @param string|null $xuid + * @param string|null $xuid If null, returns all player assets, if string, returns a player's assets * @return Asset[] */ public function getPlayerAssets(?string $xuid = null): array { return $this->assets->filter(function (string $key, Asset $value) use ($xuid) { - return $value->ownerXuid === $xuid; + if ($xuid === null) return $value->ownerXuid !== null; + else return $value->ownerXuid === $xuid; })->values()->toArray(); } @@ -60,9 +69,9 @@ private function initFolders() Loader::getInstance()->getLogger()->debug(TF::GOLD . "Loading " . $basename); try { if ($extension === 'mcstructure') { - $store->assets->put($basename, new Asset($basename, StructureStore::getInstance()->loadStructure($basename), true)); + $store->assets->put($basename, new Asset($basename, StructureStore::getInstance()->loadStructure($basename), true, null, true)); } else if ($extension === 'schematic') { - $store->assets->put($basename, new Asset($basename, StructureStore::getInstance()->loadSchematic($basename), true)); + $store->assets->put($basename, new Asset($basename, StructureStore::getInstance()->loadSchematic($basename), true, null, true)); } } catch (StructureFileException $e) { Loader::getInstance()->getLogger()->debug($e->getMessage()); diff --git a/src/xenialdan/MagicWE2/task/AsyncCopyTask.php b/src/xenialdan/MagicWE2/task/AsyncCopyTask.php index 350040da..d0c73d9d 100644 --- a/src/xenialdan/MagicWE2/task/AsyncCopyTask.php +++ b/src/xenialdan/MagicWE2/task/AsyncCopyTask.php @@ -1,4 +1,4 @@ - Date: Sat, 20 Feb 2021 10:22:30 +0100 Subject: [PATCH 12/67] Add asset placement, make scaffolding functional --- src/xenialdan/MagicWE2/API.php | 22 ++ src/xenialdan/MagicWE2/EventListener.php | 16 ++ .../MagicWE2/task/AsyncPasteAssetTask.php | 235 ++++++++++++++++++ 3 files changed, 273 insertions(+) create mode 100644 src/xenialdan/MagicWE2/task/AsyncPasteAssetTask.php diff --git a/src/xenialdan/MagicWE2/API.php b/src/xenialdan/MagicWE2/API.php index 05c4e52a..0a4e3754 100644 --- a/src/xenialdan/MagicWE2/API.php +++ b/src/xenialdan/MagicWE2/API.php @@ -27,7 +27,9 @@ use xenialdan\MagicWE2\exception\LimitExceededException; use xenialdan\MagicWE2\helper\BlockPalette; use xenialdan\MagicWE2\selection\Selection; +use xenialdan\MagicWE2\selection\shape\Cuboid; use xenialdan\MagicWE2\selection\shape\Shape; +use xenialdan\MagicWE2\session\data\Asset; use xenialdan\MagicWE2\session\Session; use xenialdan\MagicWE2\session\UserSession; use xenialdan\MagicWE2\task\action\SetBiomeAction; @@ -36,6 +38,7 @@ use xenialdan\MagicWE2\task\AsyncCopyTask; use xenialdan\MagicWE2\task\AsyncCountTask; use xenialdan\MagicWE2\task\AsyncFillTask; +use xenialdan\MagicWE2\task\AsyncPasteAssetTask; use xenialdan\MagicWE2\task\AsyncPasteTask; use xenialdan\MagicWE2\task\AsyncReplaceTask; use xenialdan\MagicWE2\tool\Brush; @@ -336,6 +339,25 @@ public static function floodArea(Block $target, CompoundTag $settings, Session $ return self::fillAsync($shape, $session, self::blockParser($shape->options['blocks'], $messages, $error), $flags);*/ } + public static function placeAsset(Position $target, Asset $asset, CompoundTag $settings, UserSession $session): bool + { + if (!$settings instanceof CompoundTag) return false; + + #$start = clone $target->asVector3()->floor()->addVector($asset->getOrigin())->floor();//start pos of paste//TODO if using rotate, this fails + #$end = $start->addVector($asset->getSize()->subtractVector($asset->getOrigin()));//add size + //[$target->x,$target->y,$target->z] = [($v=$target->asVector3())->getFloorX(),$v->getFloorY(),$v->getFloorZ()]; + $start = clone $target->asVector3();//start pos of paste//TODO if using rotate, this fails + $end = $start->addVector($asset->getSize());//add size + $shape = Cuboid::constructFromPositions(Vector3::minComponents($start, $end), Vector3::maxComponents($start, $end)); + $shape->setPasteVector($target->asVector3()->subtract(($asset->getSize()->getX() + 1) / 2, 0, ($asset->getSize()->getZ() + 1) / 2));//TODO this causes a size +0.5x +0.5z shift + $selection = new Selection($session->getUUID(), $target->getWorld()); + $selection->setShape($shape); + $aabb = $shape->getAABB(); + $touchedChunks = self::getAABBTouchedChunksTemp($target->getWorld(), $aabb);//TODO clean up or move somewhere else. Better not touch, it works. + Server::getInstance()->getAsyncPool()->submitTask(new AsyncPasteAssetTask($session->getUUID(), $selection, $touchedChunks, $asset)); + return true; + } + /// SCHEMATIC RELATED API PART /** diff --git a/src/xenialdan/MagicWE2/EventListener.php b/src/xenialdan/MagicWE2/EventListener.php index 513f3a81..41f4d4e1 100644 --- a/src/xenialdan/MagicWE2/EventListener.php +++ b/src/xenialdan/MagicWE2/EventListener.php @@ -29,6 +29,7 @@ use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\SessionHelper; use xenialdan\MagicWE2\selection\Selection; +use xenialdan\MagicWE2\session\data\AssetCollection; use xenialdan\MagicWE2\session\UserSession; use xenialdan\MagicWE2\tool\Brush; @@ -247,6 +248,21 @@ private function onRightClickBlock(PlayerInteractEvent $event): void #} break; } + case ItemIds::SCAFFOLDING: + { + $tag = $event->getItem()->getNamedTag()->getCompoundTag(API::TAG_MAGIC_WE_ASSET); + if ($tag !== null) { + $filename = $tag->getString('filename'); + $asset = AssetCollection::getInstance()->assets->get($filename); + $target = $event->getBlock()->getSide($event->getFace())->getPos(); + if (API::placeAsset($target, $asset, $tag, $session)) { + $event->getPlayer()->sendMessage("Asset placed!"); + } else { + $event->getPlayer()->sendMessage("Asset not placed!"); + } + } + break; + } default: { var_dump($event->getItem()); diff --git a/src/xenialdan/MagicWE2/task/AsyncPasteAssetTask.php b/src/xenialdan/MagicWE2/task/AsyncPasteAssetTask.php new file mode 100644 index 00000000..877ee1b7 --- /dev/null +++ b/src/xenialdan/MagicWE2/task/AsyncPasteAssetTask.php @@ -0,0 +1,235 @@ +start = microtime(true); + $this->pasteVector = $selection->getShape()->getPasteVector();#->addVector($asset->getOrigin())->floor(); + #var_dump("paste", $selection->getShape()->getPasteVector(), "cb position", $clipboard->position, "offset", $this->offset, $clipboard); + $this->sessionUUID = $sessionUUID->toString(); + $this->selection = $selection; + $this->touchedChunks = serialize($touchedChunks); + $this->asset = serialize($asset); + } + + /** + * Actions to execute when run + * + * @return void + * @throws InvalidArgumentException + */ + public function onRun(): void + { + $this->publishProgress([0, "Start"]); + + $touchedChunks = array_map(static function ($chunk) {//todo add hash as key + return FastChunkSerializer::deserialize($chunk); + }, unserialize($this->touchedChunks/*, ['allowed_classes' => false]*/));//TODO test pm4 + + $manager = Shape::getChunkManager($touchedChunks); + unset($touchedChunks); + + /** @var Selection $selection */ + //$selection = unserialize($this->selection/*, ['allowed_classes' => [Selection::class]]*/);//TODO test pm4 + $selection = $this->selection; + + /** @var Asset $asset */ + $asset = unserialize($this->asset/*, ['allowed_classes' => [SingleClipboard::class]]*/);//TODO test pm4 + $oldBlocks = iterator_to_array($this->execute($manager, $asset, $changed)); + + $resultChunks = $manager->getChunks(); + $resultChunks = array_filter($resultChunks, static function (Chunk $chunk) { + return $chunk->isDirty(); + }); + $this->setResult(compact("resultChunks", "oldBlocks", "changed")); + } + + /** + * @param AsyncChunkManager $manager + * @param Asset $asset + * @param null|int $changed + * @return Generator + * @throws InvalidArgumentException + * @throws \UnexpectedValueException + * @phpstan-return Generator + */ + private function execute(AsyncChunkManager $manager, Asset $asset, ?int &$changed): Generator + { + $blockCount = $asset->getTotalCount(); + $lastchunkx = $lastchunkz = $x = $y = $z = null; + $lastprogress = 0; + $i = 0; + $changed = 0; + $this->publishProgress([0, "Running, changed $changed blocks out of $blockCount"]); + $structure = $asset->structure; + if ($structure instanceof MCStructure) { + /** @var Block $block */ + foreach ($structure->blocks() as $block) { + var_dump($block->getPos()->asVector3(), $this->pasteVector, $this->selection); + $pos = $block->getPos()->addVector($this->pasteVector); + [$block->getPos()->x, $block->getPos()->y, $block->getPos()->z] = [$x, $y, $z] = [$pos->getFloorX(), $pos->getFloorY(), $pos->getFloorZ()]; + var_dump($block->getPos()->asVector3()); + if (($x >> 4 !== $lastchunkx && $z >> 4 !== $lastchunkz) || is_null($lastchunkx)) { + $lastchunkx = $x >> 4; + $lastchunkz = $z >> 4; + if (is_null($manager->getChunk($x >> 4, $z >> 4))) { + print PHP_EOL . "Paste chunk not found in async paste manager: " . ($x >> 4) . ":" . ($z >> 4) . PHP_EOL; + continue; + } + } + $new = $block; + yield self::singleBlockToData(API::setComponents($manager->getBlockAt($x, $y, $z), (int)$x, (int)$y, (int)$z)); + $manager->setBlockAt($x, $y, $z, $new); + if ($manager->getBlockArrayAt($x, $y, $z) !== [$manager->getBlockAt($x, $y, $z)->getId(), $manager->getBlockAt($x, $y, $z)->getMeta()]) {//TODO remove? Just useless waste imo + $changed++; + } + /// + $i++; + $progress = floor($i / $blockCount * 100); + if ($lastprogress < $progress) {//this prevents spamming packets + $this->publishProgress([$progress, "Running, changed $changed blocks out of $blockCount"]); + $lastprogress = $progress; + } + } + } else if ($structure instanceof SingleClipboard) { + /** @var BlockEntry $entry */ + foreach ($structure->iterateEntries($x, $y, $z) as $entry) { + $v = new Vector3($x, $y, $z); + var_dump($v); + $pos = $v->addVector($this->pasteVector); + [$x, $y, $z] = [$pos->getFloorX(), $pos->getFloorY(), $pos->getFloorZ()]; + if (($x >> 4 !== $lastchunkx && $z >> 4 !== $lastchunkz) || is_null($lastchunkx)) { + $lastchunkx = $x >> 4; + $lastchunkz = $z >> 4; + if (is_null($manager->getChunk($x >> 4, $z >> 4))) { + print PHP_EOL . "Paste chunk not found in async paste manager: " . ($x >> 4) . ":" . ($z >> 4) . PHP_EOL; + continue; + } + } + $new = $entry->toBlock(); + yield self::singleBlockToData(API::setComponents($manager->getBlockAt($x, $y, $z), (int)$x, (int)$y, (int)$z)); + $manager->setBlockAt($x, $y, $z, $new); + if ($manager->getBlockArrayAt($x, $y, $z) !== [$manager->getBlockAt($x, $y, $z)->getId(), $manager->getBlockAt($x, $y, $z)->getMeta()]) {//TODO remove? Just useless waste imo + $changed++; + } + /// + $i++; + $progress = floor($i / $blockCount * 100); + if ($lastprogress < $progress) {//this prevents spamming packets + $this->publishProgress([$progress, "Running, changed $changed blocks out of $blockCount"]); + $lastprogress = $progress; + } + } + } else if ($structure instanceof Schematic) { + foreach ($structure->blocks() as $block) { + $pos = $block->getPos()->addVector($this->pasteVector); + var_dump($pos); + [$block->getPos()->x, $block->getPos()->y, $block->getPos()->z] = [$x, $y, $z] = [$pos->getFloorX(), $pos->getFloorY(), $pos->getFloorZ()]; + if (($x >> 4 !== $lastchunkx && $z >> 4 !== $lastchunkz) || is_null($lastchunkx)) { + $lastchunkx = $x >> 4; + $lastchunkz = $z >> 4; + if (is_null($manager->getChunk($x >> 4, $z >> 4))) { + print PHP_EOL . "Paste chunk not found in async paste manager: " . ($x >> 4) . ":" . ($z >> 4) . PHP_EOL; + continue; + } + } + $new = $block; + yield self::singleBlockToData(API::setComponents($manager->getBlockAt($x, $y, $z), (int)$x, (int)$y, (int)$z)); + $manager->setBlockAt($x, $y, $z, $new); + if ($manager->getBlockArrayAt($x, $y, $z) !== [$manager->getBlockAt($x, $y, $z)->getId(), $manager->getBlockAt($x, $y, $z)->getMeta()]) {//TODO remove? Just useless waste imo + $changed++; + } + /// + $i++; + $progress = floor($i / $blockCount * 100); + if ($lastprogress < $progress) {//this prevents spamming packets + $this->publishProgress([$progress, "Running, changed $changed blocks out of $blockCount"]); + $lastprogress = $progress; + } + } + } + } + + /** + * @throws AssumptionFailedError + * @throws InvalidArgumentException + * @throws Exception + * @throws Exception + */ + public function onCompletion(): void + { + try { + $session = SessionHelper::getSessionByUUID(UUID::fromString($this->sessionUUID)); + if ($session instanceof UserSession) $session->getBossBar()->hideFromAll(); + } catch (SessionException $e) { + Loader::getInstance()->getLogger()->logException($e); + $session = null; + } + $result = $this->getResult(); + /** @var Chunk[] $resultChunks */ + $resultChunks = $result["resultChunks"]; + $undoChunks = array_map(static function ($chunk) { + return FastChunkSerializer::deserialize($chunk); + }, unserialize($this->touchedChunks/*, ['allowed_classes' => false]*/));//TODO test pm4 + $oldBlocks = $result["oldBlocks"];//already data array + $changed = $result["changed"]; + /** @var Selection $selection */ + //$selection = unserialize($this->selection/*, ['allowed_classes' => [Selection::class]]*/);//TODO test pm4 + $selection = $this->selection; + $totalCount = $selection->getShape()->getTotalCount(); + $world = $this->selection->getWorld(); + foreach ($resultChunks as $hash => $chunk) { + World::getXZ($hash, $x, $z); + $world->setChunk($x, $z, $chunk, false); + } + if (!is_null($session)) { + $session->sendMessage(TF::GREEN . $session->getLanguage()->translateString('task.fill.success', [$this->generateTookString(), $changed, $totalCount])); + $session->addRevert(new RevertClipboard($selection->worldId, $undoChunks, $oldBlocks)); + } + } +} \ No newline at end of file From 9dfe62f1e5fe10a3c9f0f7c56b0c12027b3bc136 Mon Sep 17 00:00:00 2001 From: XenialDan Date: Sat, 20 Feb 2021 12:16:22 +0100 Subject: [PATCH 13/67] Kind of fix placement offset --- src/xenialdan/MagicWE2/API.php | 7 ++++--- .../MagicWE2/commands/asset/AssetCommand.php | 4 +++- .../MagicWE2/task/AsyncPasteAssetTask.php | 17 +++++++++++------ 3 files changed, 18 insertions(+), 10 deletions(-) diff --git a/src/xenialdan/MagicWE2/API.php b/src/xenialdan/MagicWE2/API.php index 0a4e3754..2d5fc913 100644 --- a/src/xenialdan/MagicWE2/API.php +++ b/src/xenialdan/MagicWE2/API.php @@ -349,12 +349,13 @@ public static function placeAsset(Position $target, Asset $asset, CompoundTag $s $start = clone $target->asVector3();//start pos of paste//TODO if using rotate, this fails $end = $start->addVector($asset->getSize());//add size $shape = Cuboid::constructFromPositions(Vector3::minComponents($start, $end), Vector3::maxComponents($start, $end)); - $shape->setPasteVector($target->asVector3()->subtract(($asset->getSize()->getX() + 1) / 2, 0, ($asset->getSize()->getZ() + 1) / 2));//TODO this causes a size +0.5x +0.5z shift + $offset = new Vector3($asset->getSize()->getX() / 2, 0, $asset->getSize()->getZ() / 2); + #$shape->setPasteVector($target->asVector3()->subtract(($asset->getSize()->getX()) / 2, 0, ($asset->getSize()->getZ()) / 2));//TODO this causes a size +0.5x +0.5z shift $selection = new Selection($session->getUUID(), $target->getWorld()); $selection->setShape($shape); $aabb = $shape->getAABB(); - $touchedChunks = self::getAABBTouchedChunksTemp($target->getWorld(), $aabb);//TODO clean up or move somewhere else. Better not touch, it works. - Server::getInstance()->getAsyncPool()->submitTask(new AsyncPasteAssetTask($session->getUUID(), $selection, $touchedChunks, $asset)); + $touchedChunks = self::getAABBTouchedChunksTemp($target->getWorld(), $aabb->offset(-$offset->getX(), -$offset->getY(), -$offset->getZ()));//TODO clean up or move somewhere else. Better not touch, it works. + Server::getInstance()->getAsyncPool()->submitTask(new AsyncPasteAssetTask($session->getUUID(), $target->asVector3(), $selection, $touchedChunks, $asset)); return true; } diff --git a/src/xenialdan/MagicWE2/commands/asset/AssetCommand.php b/src/xenialdan/MagicWE2/commands/asset/AssetCommand.php index e8aba74c..64f80306 100644 --- a/src/xenialdan/MagicWE2/commands/asset/AssetCommand.php +++ b/src/xenialdan/MagicWE2/commands/asset/AssetCommand.php @@ -106,9 +106,11 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo /** @var Asset $asset */ $asset = $store->assets->get($filename); $player->sendMessage('Saving ' . (string)$asset); - //TODO async + //TODO async, convert if ($asset->structure instanceof Schematic && $type === Asset::TYPE_SCHEMATIC) { $file = pathinfo($asset->filename, PATHINFO_BASENAME) . '_' . time() . '.schematic'; + $e = ($asset->shared ? '' : ($asset->ownerXuid === null ? '' : $asset->ownerXuid . DIRECTORY_SEPARATOR)); + $file = Loader::getInstance()->getDataFolder() . 'assets' . DIRECTORY_SEPARATOR . $e . $file; $asset->structure->save($file); $player->sendMessage("Saved as $file"); } diff --git a/src/xenialdan/MagicWE2/task/AsyncPasteAssetTask.php b/src/xenialdan/MagicWE2/task/AsyncPasteAssetTask.php index 877ee1b7..38340254 100644 --- a/src/xenialdan/MagicWE2/task/AsyncPasteAssetTask.php +++ b/src/xenialdan/MagicWE2/task/AsyncPasteAssetTask.php @@ -38,18 +38,23 @@ class AsyncPasteAssetTask extends MWEAsyncTask private $asset; /** @var Vector3 */ private $pasteVector; + /** @var Vector3 */ + private $target; /** * AsyncPasteTask constructor. * @param UUID $sessionUUID + * @param Vector3 $target * @param Selection $selection * @param string[] $touchedChunks serialized chunks * @param Asset $asset + * @throws Exception */ - public function __construct(UUID $sessionUUID, Selection $selection, array $touchedChunks, Asset $asset) + public function __construct(UUID $sessionUUID, Vector3 $target, Selection $selection, array $touchedChunks, Asset $asset) { $this->start = microtime(true); $this->pasteVector = $selection->getShape()->getPasteVector();#->addVector($asset->getOrigin())->floor(); + $this->target = $target; #var_dump("paste", $selection->getShape()->getPasteVector(), "cb position", $clipboard->position, "offset", $this->offset, $clipboard); $this->sessionUUID = $sessionUUID->toString(); $this->selection = $selection; @@ -109,11 +114,11 @@ private function execute(AsyncChunkManager $manager, Asset $asset, ?int &$change $structure = $asset->structure; if ($structure instanceof MCStructure) { /** @var Block $block */ - foreach ($structure->blocks() as $block) { - var_dump($block->getPos()->asVector3(), $this->pasteVector, $this->selection); - $pos = $block->getPos()->addVector($this->pasteVector); - [$block->getPos()->x, $block->getPos()->y, $block->getPos()->z] = [$x, $y, $z] = [$pos->getFloorX(), $pos->getFloorY(), $pos->getFloorZ()]; - var_dump($block->getPos()->asVector3()); + foreach ($structure->blocks() as $block) {// [0,0,0 -> sizex,sizey,sizez] + #var_dump($block->getPos()->asVector3(), $this->pasteVector, $this->selection); + $pos = $block->getPos()->addVector($this->target)->subtract($asset->getSize()->getX() / 2, 0, $asset->getSize()->getZ() / 2); + [$block->getPos()->x, $block->getPos()->y, $block->getPos()->z] = [$x, $y, $z] = [$pos->getX(), $pos->getY(), $pos->getZ()]; + #var_dump($block->getPos()->asVector3()); if (($x >> 4 !== $lastchunkx && $z >> 4 !== $lastchunkz) || is_null($lastchunkx)) { $lastchunkx = $x >> 4; $lastchunkz = $z >> 4; From 6ed426c048abf9e87ddd3459c4edb07b4fd74ddf Mon Sep 17 00:00:00 2001 From: XenialDan Date: Sat, 20 Feb 2021 12:38:27 +0100 Subject: [PATCH 14/67] Fixed asset placement --- .../MagicWE2/task/AsyncPasteAssetTask.php | 27 +++++++++---------- 1 file changed, 13 insertions(+), 14 deletions(-) diff --git a/src/xenialdan/MagicWE2/task/AsyncPasteAssetTask.php b/src/xenialdan/MagicWE2/task/AsyncPasteAssetTask.php index 38340254..144e71ad 100644 --- a/src/xenialdan/MagicWE2/task/AsyncPasteAssetTask.php +++ b/src/xenialdan/MagicWE2/task/AsyncPasteAssetTask.php @@ -145,21 +145,21 @@ private function execute(AsyncChunkManager $manager, Asset $asset, ?int &$change /** @var BlockEntry $entry */ foreach ($structure->iterateEntries($x, $y, $z) as $entry) { $v = new Vector3($x, $y, $z); - var_dump($v); - $pos = $v->addVector($this->pasteVector); - [$x, $y, $z] = [$pos->getFloorX(), $pos->getFloorY(), $pos->getFloorZ()]; - if (($x >> 4 !== $lastchunkx && $z >> 4 !== $lastchunkz) || is_null($lastchunkx)) { - $lastchunkx = $x >> 4; - $lastchunkz = $z >> 4; - if (is_null($manager->getChunk($x >> 4, $z >> 4))) { - print PHP_EOL . "Paste chunk not found in async paste manager: " . ($x >> 4) . ":" . ($z >> 4) . PHP_EOL; + $pos = $v->addVector($this->target)->subtract($asset->getSize()->getX() / 2, 0, $asset->getSize()->getZ() / 2); + [$v->x, $v->y, $v->z] = /*[$x, $y, $z] =*/ + [$pos->getX(), $pos->getY(), $pos->getZ()]; + if (($v->x >> 4 !== $lastchunkx && $v->z >> 4 !== $lastchunkz) || is_null($lastchunkx)) { + $lastchunkx = $v->x >> 4; + $lastchunkz = $v->z >> 4; + if (is_null($manager->getChunk($v->x >> 4, $v->z >> 4))) { + print PHP_EOL . "Paste chunk not found in async paste manager: " . ($v->x >> 4) . ":" . ($v->z >> 4) . PHP_EOL; continue; } } $new = $entry->toBlock(); - yield self::singleBlockToData(API::setComponents($manager->getBlockAt($x, $y, $z), (int)$x, (int)$y, (int)$z)); - $manager->setBlockAt($x, $y, $z, $new); - if ($manager->getBlockArrayAt($x, $y, $z) !== [$manager->getBlockAt($x, $y, $z)->getId(), $manager->getBlockAt($x, $y, $z)->getMeta()]) {//TODO remove? Just useless waste imo + yield self::singleBlockToData(API::setComponents($manager->getBlockAt($v->x, $v->y, $v->z), (int)$v->x, (int)$v->y, (int)$v->z)); + $manager->setBlockAt($v->x, $v->y, $v->z, $new); + if ($manager->getBlockArrayAt($v->x, $v->y, $v->z) !== [$manager->getBlockAt($v->x, $v->y, $v->z)->getId(), $manager->getBlockAt($v->x, $v->y, $v->z)->getMeta()]) {//TODO remove? Just useless waste imo $changed++; } /// @@ -172,9 +172,8 @@ private function execute(AsyncChunkManager $manager, Asset $asset, ?int &$change } } else if ($structure instanceof Schematic) { foreach ($structure->blocks() as $block) { - $pos = $block->getPos()->addVector($this->pasteVector); - var_dump($pos); - [$block->getPos()->x, $block->getPos()->y, $block->getPos()->z] = [$x, $y, $z] = [$pos->getFloorX(), $pos->getFloorY(), $pos->getFloorZ()]; + $pos = $block->getPos()->addVector($this->target)->subtract($asset->getSize()->getX() / 2, 0, $asset->getSize()->getZ() / 2); + [$block->getPos()->x, $block->getPos()->y, $block->getPos()->z] = [$x, $y, $z] = [$pos->getX(), $pos->getY(), $pos->getZ()]; if (($x >> 4 !== $lastchunkx && $z >> 4 !== $lastchunkz) || is_null($lastchunkx)) { $lastchunkx = $x >> 4; $lastchunkz = $z >> 4; From 94253171f11a097fb323a6226186aeccfe250ab8 Mon Sep 17 00:00:00 2001 From: XenialDan Date: Tue, 9 Mar 2021 07:03:07 +0100 Subject: [PATCH 15/67] Asset::toSchematic, place asset outline --- src/xenialdan/MagicWE2/EventListener.php | 125 ++++++++++++++++++ src/xenialdan/MagicWE2/Loader.php | 2 + .../MagicWE2/commands/asset/AssetCommand.php | 23 +++- .../MagicWE2/session/UserSession.php | 1 + src/xenialdan/MagicWE2/session/data/Asset.php | 65 +++++++++ 5 files changed, 210 insertions(+), 6 deletions(-) diff --git a/src/xenialdan/MagicWE2/EventListener.php b/src/xenialdan/MagicWE2/EventListener.php index 41f4d4e1..2de376d4 100644 --- a/src/xenialdan/MagicWE2/EventListener.php +++ b/src/xenialdan/MagicWE2/EventListener.php @@ -7,15 +7,19 @@ use InvalidArgumentException; use InvalidStateException; use JsonException; +use pocketmine\block\BlockFactory; +use pocketmine\block\BlockLegacyIds; use pocketmine\entity\InvalidSkinException; use pocketmine\event\block\BlockBreakEvent; use pocketmine\event\Listener; use pocketmine\event\player\PlayerDropItemEvent; use pocketmine\event\player\PlayerInteractEvent; +use pocketmine\event\player\PlayerItemHeldEvent; use pocketmine\event\player\PlayerItemUseEvent; use pocketmine\event\player\PlayerJoinEvent; use pocketmine\event\player\PlayerQuitEvent; use pocketmine\item\ItemIds; +use pocketmine\math\Vector3; use pocketmine\nbt\UnexpectedTagTypeException; use pocketmine\player\Player; use pocketmine\plugin\Plugin; @@ -24,11 +28,14 @@ use pocketmine\world\Position; use RuntimeException; use xenialdan\customui\windows\ModalForm; +use xenialdan\libstructure\StructureUI; +use xenialdan\libstructure\tile\StructureBlockTile; use xenialdan\MagicWE2\event\MWESelectionChangeEvent; use xenialdan\MagicWE2\event\MWESessionLoadEvent; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\SessionHelper; use xenialdan\MagicWE2\selection\Selection; +use xenialdan\MagicWE2\session\data\Asset; use xenialdan\MagicWE2\session\data\AssetCollection; use xenialdan\MagicWE2\session\UserSession; use xenialdan\MagicWE2\tool\Brush; @@ -382,4 +389,122 @@ public function onSelectionChange(MWESelectionChangeEvent $event): void $session->sidebar->handleScoreboard($session); } } + + /** + * TODO use tool classes + * @param PlayerItemHeldEvent $event + * @throws SessionException + * @throws \OutOfBoundsException + */ + public function onChangeSlot(PlayerItemHeldEvent $event): void + { + var_dump($event->getSlot()); + $player = $event->getPlayer(); + #$item = $player->getInventory()->getItemInHand(); + $item = $player->getInventory()->getItem($event->getSlot()); + $session = SessionHelper::getUserSession($player); + if (!is_null(($tag = $item->getNamedTag()->getCompoundTag(API::TAG_MAGIC_WE_ASSET)))) { + if (!$session instanceof UserSession) return; + if ($item->getId() === ItemIds::SCAFFOLDING) { + $filename = $tag->getString('filename'); + $asset = AssetCollection::getInstance()->assets->get($filename); + var_dump($filename, $asset); + #$assets = AssetCollection::getInstance()->getPlayerAssets($player->getXuid()); + $session->displayOutline = true; + #foreach ($assets as $asset) { + $backwards = $player->getDirectionVector()->normalize()->multiply(-1); + $target = $player->getTargetBlock(10)->getPos(); + $target->addVector($backwards);//this selects the block before raytrace + $target->subtract(0, 1, 0);//one block down + $target = Position::fromObject($target, $player->getWorld()); + if ($session->displayOutline && self::sendOutline($player, $target, $asset, $session)) { + $player->sendMessage("Added asset outline for {$asset->filename}!"); + } else { + $player->sendMessage("Did not add asset outline!"); + } + #} + } else { + $session->displayOutline = false; + } + } else { + $session->displayOutline = false; + } + } + + public static function sendOutline(Player $player, Position $target, Asset $asset, UserSession $session): bool + { + var_dump(__METHOD__); + #$start = clone $target->asVector3()->floor()->addVector($asset->getOrigin())->floor();//start pos of paste//TODO if using rotate, this fails + #$end = $start->addVector($asset->getSize()->subtractVector($asset->getOrigin()));//add size + //[$target->x,$target->y,$target->z] = [($v=$target->asVector3())->getFloorX(),$v->getFloorY(),$v->getFloorZ()]; + $start = clone $target->asVector3();//start pos of paste//TODO if using rotate, this fails + $end = $start->addVector($asset->getSize()->subtract(1, 1, 1));//add size, remove 1 because structure block outline always covers 1 block + $offset = new Vector3($asset->getSize()->getX() / 2, 0, $asset->getSize()->getZ() / 2); + $start = $start->subtractVector($offset); + $end = $end->subtractVector($offset); + [$ix, $iy, $iz, $ax, $ay, $az] = [Vector3::minComponents($start, $end)->getFloorX(), Vector3::minComponents($start, $end)->getFloorY(), Vector3::minComponents($start, $end)->getFloorZ(), Vector3::maxComponents($start, $end)->getFloorX(), Vector3::maxComponents($start, $end)->getFloorY(), Vector3::maxComponents($start, $end)->getFloorZ()]; + + $minComponents = new Vector3($ix, $iy, $iz); + $maxComponents = new Vector3($ax, $ay, $az); + $block = BlockFactory::getInstance()->get(BlockLegacyIds::STRUCTURE_BLOCK, 0/*StructureEditorData::TYPE_SAVE*/); + var_dump((string)$block); + $target->world->setBlock($target->asVector3(), $block); + var_dump("placing block", __METHOD__, (string)$target->world->getBlock($target->asVector3())); + /** @var null|StructureBlockTile $tile */ + $tile = $target->world->getTile($target->asVector3()); + if ($tile instanceof StructureBlockTile) { + var_dump($tile->getSpawnCompound()->toString()); + $tile + ->setFromV3($minComponents) + ->setToV3($maxComponents) + //TODO add setOffsetV3 + ->setTitle($asset->displayname) + ->setShowBlocks(true) + ->setShowBoundingBox(true) + ->setShowEntities(false) + ->setShowPlayers(false) + ->setHideStructureBlock(false); + $tile->saveNBT(); + #$target->getWorld()->scheduleDelayedBlockUpdate($target, 1); + var_dump($tile->getSpawnCompound()->toString()); + } else { + var_dump("no tile"); + return false; + } + + return true; + } + + public function onStructureBlockClick(PlayerInteractEvent $event): void + { + $player = $event->getPlayer(); + $blockTouched = $event->getBlock(); + if ($blockTouched->getId() === BlockLegacyIds::STRUCTURE_BLOCK) { + var_dump("Clicked Structure Block", (string)$blockTouched); + $tile = $blockTouched->getPos()->getWorld()->getTile($blockTouched->getPos()->asVector3()); + if ($tile instanceof StructureBlockTile) { + var_dump("Is Structure Block Tile", $tile->getSpawnCompound()->toString()); +// $item = $player->getInventory()->getItemInHand(); +// if (!is_null(($tag = $item->getNamedTag()->getCompoundTag(API::TAG_MAGIC_WE_ASSET)))) { +// $session = SessionHelper::getUserSession($player); +// if (!$session instanceof UserSession) return; +// if ($item->getId() === ItemIds::SCAFFOLDING) { +// $filename = $tag->getString('filename'); +// $asset = AssetCollection::getInstance()->assets->get($filename); +// /** @var StructureBlockInventory $inventory */ +// $inventory = $tile->getInventory(); +// $pk = new StructureBlockUpdatePacket(); +// $pk->structureEditorData = $tile->getStructureEditorData($asset); +// [$pk->x, $pk->y, $pk->z] = [$blockTouched->getPos()->getFloorX(), $blockTouched->getPos()->getFloorY(), $blockTouched->getPos()->getFloorZ()]; +// $pk->isPowered = false; +// $player->getNetworkSession()->sendDataPacket($pk); +// $tile->sendInventory($player); +// var_dump($tile->getSpawnCompound()->toString(), $inventory); +// } +// } + var_dump($blockTouched); + } + } + + } } \ No newline at end of file diff --git a/src/xenialdan/MagicWE2/Loader.php b/src/xenialdan/MagicWE2/Loader.php index d232ab7e..19fdd170 100644 --- a/src/xenialdan/MagicWE2/Loader.php +++ b/src/xenialdan/MagicWE2/Loader.php @@ -23,6 +23,7 @@ use RuntimeException; use xenialdan\apibossbar\DiverseBossBar; use xenialdan\customui\API as CustomUIAPI; +use xenialdan\libstructure\PacketListener; use xenialdan\MagicWE2\commands\asset\AssetCommand; use xenialdan\MagicWE2\commands\biome\BiomeInfoCommand; use xenialdan\MagicWE2\commands\biome\BiomeListCommand; @@ -209,6 +210,7 @@ public function onEnable(): void //$this->loadDonator(); $this->getLogger()->warning("WARNING! Commands and their permissions changed! Make sure to update your permission sets!"); if (!InvMenuHandler::isRegistered()) InvMenuHandler::register($this); + if (!PacketListener::isRegistered()) PacketListener::register($this); //PacketListener::register($this);//TODO currently this just doubles the debug spam $this->getServer()->getPluginManager()->registerEvents(new EventListener($this), $this); $this->getServer()->getCommandMap()->registerAll("MagicWE2", [ diff --git a/src/xenialdan/MagicWE2/commands/asset/AssetCommand.php b/src/xenialdan/MagicWE2/commands/asset/AssetCommand.php index 64f80306..d6d2a6a0 100644 --- a/src/xenialdan/MagicWE2/commands/asset/AssetCommand.php +++ b/src/xenialdan/MagicWE2/commands/asset/AssetCommand.php @@ -107,12 +107,23 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo $asset = $store->assets->get($filename); $player->sendMessage('Saving ' . (string)$asset); //TODO async, convert - if ($asset->structure instanceof Schematic && $type === Asset::TYPE_SCHEMATIC) { - $file = pathinfo($asset->filename, PATHINFO_BASENAME) . '_' . time() . '.schematic'; - $e = ($asset->shared ? '' : ($asset->ownerXuid === null ? '' : $asset->ownerXuid . DIRECTORY_SEPARATOR)); - $file = Loader::getInstance()->getDataFolder() . 'assets' . DIRECTORY_SEPARATOR . $e . $file; - $asset->structure->save($file); - $player->sendMessage("Saved as $file"); + if ($type === Asset::TYPE_SCHEMATIC) { + if ($asset->structure instanceof Schematic) { + $file = pathinfo($asset->filename, PATHINFO_BASENAME) . '_' . time() . '.schematic'; + $e = ($asset->shared ? '' : ($asset->ownerXuid === null ? '' : $asset->ownerXuid . DIRECTORY_SEPARATOR)); + $file = Loader::getInstance()->getDataFolder() . 'assets' . DIRECTORY_SEPARATOR . $e . $file; + mkdir(pathinfo($file, PATHINFO_DIRNAME), 7777, true); + $asset->structure->save($file); + $player->sendMessage("Saved as $file"); + } + if ($asset->structure instanceof MCStructure || $asset->structure instanceof SingleClipboard) { + $file = pathinfo($asset->filename, PATHINFO_BASENAME) . '_' . time() . '.schematic'; + $e = ($asset->shared ? '' : ($asset->ownerXuid === null ? '' : $asset->ownerXuid . DIRECTORY_SEPARATOR)); + $file = Loader::getInstance()->getDataFolder() . 'assets' . DIRECTORY_SEPARATOR . $e . $file; + @mkdir(pathinfo($file, PATHINFO_DIRNAME), 7777, true); + $asset->toSchematic()->save($file); + $player->sendMessage("Saved as $file"); + } } if ($asset->structure instanceof MCStructure && $type === Asset::TYPE_MCSTRUCTURE) { #$asset->structure->save($asset->filename.'.mcstructure'); diff --git a/src/xenialdan/MagicWE2/session/UserSession.php b/src/xenialdan/MagicWE2/session/UserSession.php index f7990736..313435d8 100644 --- a/src/xenialdan/MagicWE2/session/UserSession.php +++ b/src/xenialdan/MagicWE2/session/UserSession.php @@ -53,6 +53,7 @@ class UserSession extends Session implements JsonSerializable //TODO use JsonMap private Map $assets; /** @var Language|null */ private $lang; + public bool $displayOutline = false; public function __construct(Player $player) { diff --git a/src/xenialdan/MagicWE2/session/data/Asset.php b/src/xenialdan/MagicWE2/session/data/Asset.php index 7914ab82..d2ddd05b 100644 --- a/src/xenialdan/MagicWE2/session/data/Asset.php +++ b/src/xenialdan/MagicWE2/session/data/Asset.php @@ -15,6 +15,7 @@ use pocketmine\math\Vector3; use pocketmine\nbt\tag\CompoundTag; use pocketmine\player\Player; +use pocketmine\plugin\PluginException; use pocketmine\utils\AssumptionFailedError; use pocketmine\utils\TextFormat as TF; use TypeError; @@ -131,6 +132,70 @@ private function generateLore(): array return $return; } + public function toSchematic(): Schematic + { + $structure = $this->structure; + if ($structure instanceof Schematic) return $structure; + if ($structure instanceof MCStructure) { + $schematic = new Schematic(); + $blocks = []; + foreach ($structure->iterateEntries($x, $y, $z) as $blockEntry) { + $blocks[] = API::setComponents($blockEntry->toBlock(), (int)$x, (int)$y, (int)$z);//turn BlockEntry to blocks + } + $schematic->setWidth($this->getSize()->getX()); + $schematic->setHeight($this->getSize()->getY()); + $schematic->setLength($this->getSize()->getZ()); + $schematic->setBlockArray($blocks); + return $schematic; + } + if ($structure instanceof SingleClipboard) { + $schematic = new Schematic(); + $blocks = []; + foreach ($structure->iterateEntries($x, $y, $z) as $blockEntry) { + $blocks[] = API::setComponents($blockEntry->toBlock(), (int)$x, (int)$y, (int)$z);//turn BlockEntry to blocks + } + $schematic->setBlockArray($blocks); + return $schematic; + } + throw new PluginException("Wrong type"); + } + + public function toMCStructure(): MCStructure + { + $structure = $this->structure; + if ($structure instanceof MCStructure) return $structure; + throw new PluginException("Can't do this yet"); +// if($structure instanceof Schematic) { +// /*$schematic = new (); +// $blocks=[]; +// foreach ($structure->iterateEntries($x, $y, $z) as $blockEntry) { +// $blocks[] = API::setComponents($blockEntry->toBlock(), (int)$x, (int)$y, (int)$z);//turn BlockEntry to blocks +// } +// $size = $structure->getSize(); +// #$aabb = new AxisAlignedBB(0,0,0,$size->getX(),$size->getY(),$size->getZ()); +// $schematic->setBlockArray(new $blocks); +// $schematic->setWidth($size->getX()); +// $schematic->setHeight($size->getY()); +// $schematic->setLength($size->getZ()); +// return $schematic;*/ +// } +// if($structure instanceof SingleClipboard) { +// $schematic = new Schematic(); +// $blocks=[]; +// foreach ($structure->iterateEntries($x, $y, $z) as $blockEntry) { +// $blocks[] = API::setComponents($blockEntry->toBlock(), (int)$x, (int)$y, (int)$z);//turn BlockEntry to blocks +// } +// $size = $structure->getSize(); +// #$aabb = new AxisAlignedBB(0,0,0,$size->getX(),$size->getY(),$size->getZ()); +// $schematic->setBlockArray(new $blocks); +// $schematic->setWidth($size->getX()); +// $schematic->setHeight($size->getY()); +// $schematic->setLength($size->getZ()); +// return $schematic; +// } +// throw new PluginException("Wrong type"); + } + public function __toString(): string { return 'Asset ' . implode(' ', $this->generateLore()); From 63d08bc97c6c45409d2991a5c9c916e9f87f84af Mon Sep 17 00:00:00 2001 From: XenialDan Date: Tue, 9 Mar 2021 07:27:59 +0100 Subject: [PATCH 16/67] Minimal phpstan patches --- src/xenialdan/MagicWE2/session/data/Asset.php | 15 ++++++--------- .../MagicWE2/session/data/AssetCollection.php | 2 +- .../MagicWE2/task/AsyncPasteAssetTask.php | 12 ++++++------ src/xenialdan/MagicWE2/tool/Brush.php | 2 +- 4 files changed, 14 insertions(+), 17 deletions(-) diff --git a/src/xenialdan/MagicWE2/session/data/Asset.php b/src/xenialdan/MagicWE2/session/data/Asset.php index d2ddd05b..c9317a02 100644 --- a/src/xenialdan/MagicWE2/session/data/Asset.php +++ b/src/xenialdan/MagicWE2/session/data/Asset.php @@ -138,21 +138,18 @@ public function toSchematic(): Schematic if ($structure instanceof Schematic) return $structure; if ($structure instanceof MCStructure) { $schematic = new Schematic(); - $blocks = []; - foreach ($structure->iterateEntries($x, $y, $z) as $blockEntry) { - $blocks[] = API::setComponents($blockEntry->toBlock(), (int)$x, (int)$y, (int)$z);//turn BlockEntry to blocks - } - $schematic->setWidth($this->getSize()->getX()); - $schematic->setHeight($this->getSize()->getY()); - $schematic->setLength($this->getSize()->getZ()); + $blocks = iterator_to_array($structure->blocks()); + $schematic->setWidth((int)$this->getSize()->getX()); + $schematic->setHeight((int)$this->getSize()->getY()); + $schematic->setLength((int)$this->getSize()->getZ()); $schematic->setBlockArray($blocks); return $schematic; } if ($structure instanceof SingleClipboard) { $schematic = new Schematic(); $blocks = []; - foreach ($structure->iterateEntries($x, $y, $z) as $blockEntry) { - $blocks[] = API::setComponents($blockEntry->toBlock(), (int)$x, (int)$y, (int)$z);//turn BlockEntry to blocks + foreach ($structure->iterateEntries($x, $y, $z) as $block) { + $blocks[] = API::setComponents($block->toBlock(), (int)$x, (int)$y, (int)$z);//turn BlockEntry to blocks } $schematic->setBlockArray($blocks); return $schematic; diff --git a/src/xenialdan/MagicWE2/session/data/AssetCollection.php b/src/xenialdan/MagicWE2/session/data/AssetCollection.php index dcb5238e..82902f18 100644 --- a/src/xenialdan/MagicWE2/session/data/AssetCollection.php +++ b/src/xenialdan/MagicWE2/session/data/AssetCollection.php @@ -58,7 +58,7 @@ public function getPlayerAssets(?string $xuid = null): array })->values()->toArray(); } - private function initFolders() + private function initFolders(): void { //Load mcstructure and schematic files and lock them to prevent editing $store = $this; diff --git a/src/xenialdan/MagicWE2/task/AsyncPasteAssetTask.php b/src/xenialdan/MagicWE2/task/AsyncPasteAssetTask.php index 144e71ad..dd715662 100644 --- a/src/xenialdan/MagicWE2/task/AsyncPasteAssetTask.php +++ b/src/xenialdan/MagicWE2/task/AsyncPasteAssetTask.php @@ -128,9 +128,9 @@ private function execute(AsyncChunkManager $manager, Asset $asset, ?int &$change } } $new = $block; - yield self::singleBlockToData(API::setComponents($manager->getBlockAt($x, $y, $z), (int)$x, (int)$y, (int)$z)); - $manager->setBlockAt($x, $y, $z, $new); - if ($manager->getBlockArrayAt($x, $y, $z) !== [$manager->getBlockAt($x, $y, $z)->getId(), $manager->getBlockAt($x, $y, $z)->getMeta()]) {//TODO remove? Just useless waste imo + yield self::singleBlockToData(API::setComponents($manager->getBlockAt((int)$x, (int)$y, (int)$z), (int)$x, (int)$y, (int)$z)); + $manager->setBlockAt((int)$x, (int)$y, (int)$z, $new); + if ($manager->getBlockArrayAt((int)$x, (int)$y, (int)$z) !== [$manager->getBlockAt((int)$x, (int)$y, (int)$z)->getId(), $manager->getBlockAt((int)$x, (int)$y, (int)$z)->getMeta()]) {//TODO remove? Just useless waste imo $changed++; } /// @@ -157,9 +157,9 @@ private function execute(AsyncChunkManager $manager, Asset $asset, ?int &$change } } $new = $entry->toBlock(); - yield self::singleBlockToData(API::setComponents($manager->getBlockAt($v->x, $v->y, $v->z), (int)$v->x, (int)$v->y, (int)$v->z)); - $manager->setBlockAt($v->x, $v->y, $v->z, $new); - if ($manager->getBlockArrayAt($v->x, $v->y, $v->z) !== [$manager->getBlockAt($v->x, $v->y, $v->z)->getId(), $manager->getBlockAt($v->x, $v->y, $v->z)->getMeta()]) {//TODO remove? Just useless waste imo + yield self::singleBlockToData(API::setComponents($manager->getBlockAt((int)$v->x, (int)$v->y, (int)$v->z), (int)$v->x, (int)$v->y, (int)$v->z)); + $manager->setBlockAt((int)$v->x, (int)$v->y, (int)$v->z, $new); + if ($manager->getBlockArrayAt((int)$v->x, (int)$v->y, (int)$v->z) !== [$manager->getBlockAt((int)$v->x, (int)$v->y, (int)$v->z)->getId(), $manager->getBlockAt((int)$v->x, (int)$v->y, (int)$v->z)->getMeta()]) {//TODO remove? Just useless waste imo $changed++; } /// diff --git a/src/xenialdan/MagicWE2/tool/Brush.php b/src/xenialdan/MagicWE2/tool/Brush.php index 9d32390f..eff608bc 100644 --- a/src/xenialdan/MagicWE2/tool/Brush.php +++ b/src/xenialdan/MagicWE2/tool/Brush.php @@ -106,7 +106,7 @@ public function getForm(bool $new = true, array $errors = []): CustomForm $dropdownShape = new Dropdown((isset($errors['shape']) ? TF::RED : "") . "Shape" . ($errors['shape'] ?? "")); foreach (Loader::getShapeRegistry()::getShapes() as $name => $class) { if ($name === ShapeRegistry::CUSTOM) continue; - $dropdownShape->addOption($name, $class === $brushProperties->shape); + $dropdownShape->addOption((string)$name, $class === $brushProperties->shape); } $form->addElement($dropdownShape); } else { From fa1c73aa173015faa42889e49ad093c225c3cc31 Mon Sep 17 00:00:00 2001 From: XenialDan Date: Tue, 9 Mar 2021 07:37:13 +0100 Subject: [PATCH 17/67] Fix other phpstan issues --- src/xenialdan/MagicWE2/EventListener.php | 2 +- src/xenialdan/MagicWE2/commands/asset/AssetCommand.php | 4 ++-- src/xenialdan/MagicWE2/helper/BlockEntry.php | 3 --- src/xenialdan/MagicWE2/helper/BlockStatesParser.php | 1 - src/xenialdan/MagicWE2/selection/Selection.php | 1 - src/xenialdan/MagicWE2/session/UserSession.php | 4 ++-- 6 files changed, 5 insertions(+), 10 deletions(-) diff --git a/src/xenialdan/MagicWE2/EventListener.php b/src/xenialdan/MagicWE2/EventListener.php index 2de376d4..1c52a5ab 100644 --- a/src/xenialdan/MagicWE2/EventListener.php +++ b/src/xenialdan/MagicWE2/EventListener.php @@ -417,7 +417,7 @@ public function onChangeSlot(PlayerItemHeldEvent $event): void $target->addVector($backwards);//this selects the block before raytrace $target->subtract(0, 1, 0);//one block down $target = Position::fromObject($target, $player->getWorld()); - if ($session->displayOutline && self::sendOutline($player, $target, $asset, $session)) { + if (/*$session->displayOutline && */ self::sendOutline($player, $target, $asset, $session)) { $player->sendMessage("Added asset outline for {$asset->filename}!"); } else { $player->sendMessage("Did not add asset outline!"); diff --git a/src/xenialdan/MagicWE2/commands/asset/AssetCommand.php b/src/xenialdan/MagicWE2/commands/asset/AssetCommand.php index d6d2a6a0..7d9b0e98 100644 --- a/src/xenialdan/MagicWE2/commands/asset/AssetCommand.php +++ b/src/xenialdan/MagicWE2/commands/asset/AssetCommand.php @@ -101,7 +101,7 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo } $form->addDropdown("Asset", array_values($options)); $form->addDropdown("File type", [Asset::TYPE_SCHEMATIC, Asset::TYPE_MCSTRUCTURE]); - $form->setCallable(function (Player $player, $data) use ($lang, $session, $store) { + $form->setCallable(function (Player $player, $data) use (/*$lang, $session,*/ $store) { [$filename, $type] = $data; /** @var Asset $asset */ $asset = $store->assets->get($filename); @@ -145,7 +145,7 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo $options[$asset->filename] = $asset->filename; } $form->addDropdown("Asset", array_values($options)); - $form->setCallable(function (Player $player, $data) use ($lang, $session, $store) { + $form->setCallable(function (Player $player, $data) use (/*$lang, $session,*/ $store) { [$filename] = $data; /** @var Asset $asset */ $asset = $store->assets->get($filename); diff --git a/src/xenialdan/MagicWE2/helper/BlockEntry.php b/src/xenialdan/MagicWE2/helper/BlockEntry.php index 5390aae6..0f4de47c 100644 --- a/src/xenialdan/MagicWE2/helper/BlockEntry.php +++ b/src/xenialdan/MagicWE2/helper/BlockEntry.php @@ -36,9 +36,6 @@ public function validate(): bool if ($id === BlockLegacyIds::INFO_UPDATE) { return false; } - if ($this->nbt instanceof CompoundTag && !$this->nbt->valid()) { - return false; - } return true; } diff --git a/src/xenialdan/MagicWE2/helper/BlockStatesParser.php b/src/xenialdan/MagicWE2/helper/BlockStatesParser.php index fe5dcc09..d1a3b0eb 100644 --- a/src/xenialdan/MagicWE2/helper/BlockStatesParser.php +++ b/src/xenialdan/MagicWE2/helper/BlockStatesParser.php @@ -67,7 +67,6 @@ private function __construct() private function loadLegacyMappings(): void { - /** @var R12ToCurrentBlockMapEntry[][] $legacyStateMap */ self::$legacyStateMap = []; $contents = file_get_contents(RESOURCE_PATH . "vanilla/r12_to_current_block_map.bin"); if ($contents === false) throw new PluginException("Can not get contents of r12_to_current_block_map"); diff --git a/src/xenialdan/MagicWE2/selection/Selection.php b/src/xenialdan/MagicWE2/selection/Selection.php index 202d6ba5..e722d195 100644 --- a/src/xenialdan/MagicWE2/selection/Selection.php +++ b/src/xenialdan/MagicWE2/selection/Selection.php @@ -292,7 +292,6 @@ public function serialize() public function unserialize($serialized) { var_dump($serialized); - /** @var Vector3 $pos1 , $pos2 */ [ $this->worldId, $this->pos1, diff --git a/src/xenialdan/MagicWE2/session/UserSession.php b/src/xenialdan/MagicWE2/session/UserSession.php index 313435d8..813145f1 100644 --- a/src/xenialdan/MagicWE2/session/UserSession.php +++ b/src/xenialdan/MagicWE2/session/UserSession.php @@ -47,9 +47,9 @@ class UserSession extends Session implements JsonSerializable //TODO use JsonMap private $wailaEnabled = true; /** @var bool */ private $sidebarEnabled = true;//TODO settings/commands - /** @var Map */ + /** @var Map */ private Map $brushes; - /** @var Map */ + /** @var Map */ private Map $assets; /** @var Language|null */ private $lang; From 7d03a80b0d0c8c5a7a09ec7eb35f78aac0c4c63b Mon Sep 17 00:00:00 2001 From: XenialDan Date: Sun, 18 Apr 2021 01:12:59 +0200 Subject: [PATCH 18/67] pmmp removed hasTag --- .../MagicWE2/helper/BlockStatesEntry.php | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/src/xenialdan/MagicWE2/helper/BlockStatesEntry.php b/src/xenialdan/MagicWE2/helper/BlockStatesEntry.php index 4a8270de..19fdc2c1 100644 --- a/src/xenialdan/MagicWE2/helper/BlockStatesEntry.php +++ b/src/xenialdan/MagicWE2/helper/BlockStatesEntry.php @@ -169,15 +169,15 @@ public function mirror(string $axis): BlockStatesEntry $bsCompound = clone $clone->blockStates;//TODO check if clone is necessary #$bsCompound->setName("minecraft:$key");//TODO this might cause issues with the parser since it stays same //seems to work ¯\_(ツ)_/¯ if ($axis === FlipAction::AXIS_Y && !(//TODO maybe add vine + mushroom block directions - $bsCompound->hasTag("attachment") || - $bsCompound->hasTag("facing_direction") || - $bsCompound->hasTag("hanging") || - $bsCompound->hasTag("lever_direction") || - $bsCompound->hasTag("rail_direction") || - $bsCompound->hasTag("top_slot_bit") || - $bsCompound->hasTag("torch_facing_direction") || - $bsCompound->hasTag("upper_block_bit") || - $bsCompound->hasTag("upside_down_bit") + $bsCompound->getTag("attachment") !== null || + $bsCompound->getTag("facing_direction") !== null || + $bsCompound->getTag("hanging") !== null || + $bsCompound->getTag("lever_direction") !== null || + $bsCompound->getTag("rail_direction") !== null || + $bsCompound->getTag("top_slot_bit") !== null || + $bsCompound->getTag("torch_facing_direction") !== null || + $bsCompound->getTag("upper_block_bit") !== null || + $bsCompound->getTag("upside_down_bit") !== null )) {//ugly hack for y flip #var_dump("nothing can be flipped around y axis"); return $clone; From b6b8ff16691420aacd4e524582344bd128404be7 Mon Sep 17 00:00:00 2001 From: XenialDan Date: Sun, 18 Apr 2021 01:15:38 +0200 Subject: [PATCH 19/67] Upgrade required libstructure version --- .poggit.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.poggit.yml b/.poggit.yml index 45bb0a7a..a55289ea 100644 --- a/.poggit.yml +++ b/.poggit.yml @@ -25,7 +25,7 @@ projects: version: ^4.1.0 branch: "4.0" - src: thebigsmilexd/libstructure/libstructure - version: ^0.1.3 + version: ^0.1.4 branch: mcstructure - src: buchwasa/ScoreFactory/ScoreFactory version: ^3.0.1 From 6e631aeb24f0999523278d1ec9f2e78a3c8a9e5e Mon Sep 17 00:00:00 2001 From: XenialDan Date: Fri, 23 Apr 2021 05:55:34 +0200 Subject: [PATCH 20/67] Change UUID to Ramsey\Uuid, Fix #223 --- plugin.yml | 2 +- .../MagicWE2/helper/SessionHelper.php | 21 ++++++++------- .../MagicWE2/selection/Selection.php | 23 ++++++++-------- .../MagicWE2/session/PluginSession.php | 4 +-- src/xenialdan/MagicWE2/session/Session.php | 26 +++++++++---------- .../MagicWE2/session/UserSession.php | 15 ++++++----- .../MagicWE2/task/AsyncActionTask.php | 9 ++++--- .../task/AsyncClipboardActionTask.php | 9 ++++--- src/xenialdan/MagicWE2/task/AsyncCopyTask.php | 9 ++++--- .../MagicWE2/task/AsyncCountTask.php | 9 ++++--- src/xenialdan/MagicWE2/task/AsyncFillTask.php | 9 ++++--- .../MagicWE2/task/AsyncPasteAssetTask.php | 9 ++++--- .../MagicWE2/task/AsyncPasteTask.php | 9 ++++--- .../MagicWE2/task/AsyncReplaceTask.php | 9 ++++--- .../MagicWE2/task/AsyncRevertTask.php | 9 ++++--- src/xenialdan/MagicWE2/task/MWEAsyncTask.php | 4 +-- src/xenialdan/MagicWE2/tool/Brush.php | 6 ++--- .../MagicWE2/tool/BrushProperties.php | 2 +- 18 files changed, 98 insertions(+), 86 deletions(-) diff --git a/plugin.yml b/plugin.yml index 77b3e85f..f4e7c9d7 100644 --- a/plugin.yml +++ b/plugin.yml @@ -1,7 +1,7 @@ --- name: MagicWE2 main: xenialdan\MagicWE2\Loader -version: 10.1.4 +version: 10.1.5 api: ["4.0.0"] php: [ "7.4", "8.0" ] softdepend: [ "DEVirion" ] diff --git a/src/xenialdan/MagicWE2/helper/SessionHelper.php b/src/xenialdan/MagicWE2/helper/SessionHelper.php index a2fac7ff..3b70bd24 100644 --- a/src/xenialdan/MagicWE2/helper/SessionHelper.php +++ b/src/xenialdan/MagicWE2/helper/SessionHelper.php @@ -16,7 +16,8 @@ use pocketmine\Server; use pocketmine\utils\AssumptionFailedError; use pocketmine\utils\TextFormat as TF; -use pocketmine\uuid\UUID; +use Ramsey\Uuid\Rfc4122\UuidV4; +use Ramsey\Uuid\UuidInterface; use RuntimeException; use xenialdan\MagicWE2\event\MWESessionLoadEvent; use xenialdan\MagicWE2\exception\SessionException; @@ -31,9 +32,9 @@ class SessionHelper { - /** @var Map */ + /** @var Map */ private static $userSessions; - /** @var Map */ + /** @var Map */ private static $pluginSessions; public static function init(): void @@ -134,7 +135,7 @@ public static function hasSession(Player $player): bool public static function getUserSession(Player $player): ?UserSession { if (self::$userSessions->isEmpty()) return null; - $filtered = self::$userSessions->filter(function (UUID $uuid, Session $session) use ($player) { + $filtered = self::$userSessions->filter(function (UuidInterface $uuid, Session $session) use ($player) { return $session instanceof UserSession && $session->getPlayer() === $player; }); if ($filtered->isEmpty()) return null; @@ -144,11 +145,11 @@ public static function getUserSession(Player $player): ?UserSession /** * TODO cleanup or optimize - * @param UUID $uuid + * @param UuidInterface $uuid * @return null|Session * @throws SessionException */ - public static function getSessionByUUID(UUID $uuid): ?Session + public static function getSessionByUUID(UuidInterface $uuid): ?Session { $v = null; if (self::$userSessions->hasKey($uuid)) { @@ -157,14 +158,14 @@ public static function getSessionByUUID(UUID $uuid): ?Session $v = self::$pluginSessions->get($uuid, null); } else { /* - * Sadly, this part is necessary. If you use UUID::fromString, the object "id" in the map does not match anymore + * Sadly, this part is necessary. If you use UuidInterface::fromString, the object "id" in the map does not match anymore */ - $userFiltered = self::$userSessions->filter(function (UUID $uuid2, Session $session) use ($uuid) { + $userFiltered = self::$userSessions->filter(function (UuidInterface $uuid2, Session $session) use ($uuid) { return $uuid2->equals($uuid); }); if (!$userFiltered->isEmpty()) $v = $userFiltered->values()->first(); else { - $pluginFiltered = self::$pluginSessions->filter(function (UUID $uuid2, Session $session) use ($uuid) { + $pluginFiltered = self::$pluginSessions->filter(function (UuidInterface $uuid2, Session $session) use ($uuid) { return $uuid2->equals($uuid); }); if (!$pluginFiltered->isEmpty()) $v = $pluginFiltered->values()->first(); @@ -213,7 +214,7 @@ public static function loadUserSession(Player $player): ?UserSession } $session = new UserSession($player); try { - $session->setUUID(UUID::fromString($data["uuid"])); + $session->setUUID(UuidV4::fromString($data["uuid"])); $session->setWandEnabled($data["wandEnabled"]); $session->setDebugToolEnabled($data["debugToolEnabled"]); $session->setWailaEnabled($data["wailaEnabled"]); diff --git a/src/xenialdan/MagicWE2/selection/Selection.php b/src/xenialdan/MagicWE2/selection/Selection.php index e722d195..445f78e0 100644 --- a/src/xenialdan/MagicWE2/selection/Selection.php +++ b/src/xenialdan/MagicWE2/selection/Selection.php @@ -10,9 +10,10 @@ use pocketmine\Server; use pocketmine\utils\AssumptionFailedError; use pocketmine\utils\TextFormat as TF; -use pocketmine\uuid\UUID; use pocketmine\world\Position; use pocketmine\world\World; +use Ramsey\Uuid\Uuid; +use Ramsey\Uuid\UuidInterface; use RuntimeException; use Serializable; use xenialdan\MagicWE2\event\MWESelectionChangeEvent; @@ -35,16 +36,16 @@ class Selection implements Serializable, JsonSerializable public $pos1; /** @var Vector3|null */ public $pos2; - /** @var UUID */ + /** @var UuidInterface */ public $uuid; - /** @var UUID */ + /** @var UuidInterface */ public $sessionUUID; /** @var Shape|null */ public $shape; /** * Selection constructor. - * @param UUID $sessionUUID + * @param UuidInterface $sessionUUID * @param World $world * @param ?int $minX * @param ?int $minY @@ -54,7 +55,7 @@ class Selection implements Serializable, JsonSerializable * @param ?int $maxZ * @param ?Shape $shape */ - public function __construct(UUID $sessionUUID, World $world, $minX = null, $minY = null, $minZ = null, $maxX = null, $maxY = null, $maxZ = null, ?Shape $shape = null) + public function __construct(UuidInterface $sessionUUID, World $world, $minX = null, $minY = null, $minZ = null, $maxX = null, $maxY = null, $maxZ = null, ?Shape $shape = null) { $this->sessionUUID = $sessionUUID; $this->worldId = $world->getId(); @@ -65,7 +66,7 @@ public function __construct(UUID $sessionUUID, World $world, $minX = null, $minY $this->pos2 = (new Vector3($maxX, $maxY, $maxZ))->floor(); } if ($shape !== null) $this->shape = $shape; - $this->setUUID(UUID::fromRandom()); + $this->setUUID(Uuid::uuid4()); } /** @@ -246,17 +247,17 @@ public function getSizeZ(): int } /** - * @param UUID $uuid + * @param UuidInterface $uuid */ - public function setUUID(UUID $uuid): void + public function setUUID(UuidInterface $uuid): void { $this->uuid = $uuid; } /** - * @return UUID + * @return UuidInterface */ - public function getUUID(): UUID + public function getUUID(): UuidInterface { return $this->uuid; } @@ -299,7 +300,7 @@ public function unserialize($serialized) $this->uuid, $this->sessionUUID, $this->shape - ] = unserialize($serialized/*, ['allowed_classes' => [__CLASS__, Vector3::class,UUID::class,Shape::class]]*/);//TODO test pm4 + ] = unserialize($serialized/*, ['allowed_classes' => [__CLASS__, Vector3::class,UuidInterface::class,Shape::class]]*/);//TODO test pm4 } /** diff --git a/src/xenialdan/MagicWE2/session/PluginSession.php b/src/xenialdan/MagicWE2/session/PluginSession.php index ad97b95a..32ce2ab3 100644 --- a/src/xenialdan/MagicWE2/session/PluginSession.php +++ b/src/xenialdan/MagicWE2/session/PluginSession.php @@ -6,7 +6,7 @@ use Ds\Deque; use pocketmine\plugin\Plugin; -use pocketmine\uuid\UUID; +use Ramsey\Uuid\Uuid; use xenialdan\MagicWE2\Loader; class PluginSession extends Session @@ -17,7 +17,7 @@ class PluginSession extends Session public function __construct(Plugin $plugin) { $this->plugin = $plugin; - $this->setUUID(UUID::fromRandom()); + $this->setUUID(Uuid::uuid4()); $this->undoHistory = new Deque(); $this->redoHistory = new Deque(); } diff --git a/src/xenialdan/MagicWE2/session/Session.php b/src/xenialdan/MagicWE2/session/Session.php index c3f6cf17..af415943 100644 --- a/src/xenialdan/MagicWE2/session/Session.php +++ b/src/xenialdan/MagicWE2/session/Session.php @@ -10,8 +10,8 @@ use pocketmine\lang\Language; use pocketmine\Server; use pocketmine\utils\TextFormat as TF; -use pocketmine\uuid\UUID; use pocketmine\world\World; +use Ramsey\Uuid\UuidInterface; use RuntimeException; use xenialdan\MagicWE2\clipboard\Clipboard; use xenialdan\MagicWE2\clipboard\RevertClipboard; @@ -23,12 +23,12 @@ abstract class Session { public const MAX_CLIPBOARDS = 5; public const MAX_HISTORY = 32; - /** @var UUID */ + /** @var UuidInterface */ private $uuid; //todo change to a list of objects with a pointer of the latest action /** @var Selection[] */ private $selections = []; - /** @var UUID|null */ + /** @var UuidInterface|null */ private $latestselection; //todo change to a list of objects with a pointer of the latest action /** @var Clipboard[] */ @@ -41,17 +41,17 @@ abstract class Session public $redoHistory; /** - * @return UUID + * @return UuidInterface */ - public function getUUID(): UUID + public function getUUID(): UuidInterface { return $this->uuid; } /** - * @param UUID $uuid + * @param UuidInterface $uuid */ - public function setUUID(UUID $uuid): void + public function setUUID(UuidInterface $uuid): void { $this->uuid = $uuid; } @@ -69,10 +69,10 @@ public function &addSelection(Selection $selection): ?Selection } /** - * @param UUID $uuid + * @param UuidInterface $uuid * @return null|Selection */ - public function &getSelectionByUUID(UUID $uuid): ?Selection + public function &getSelectionByUUID(UuidInterface $uuid): ?Selection { $selection = $this->selections[$uuid->toString()] ?? null; return $selection; @@ -119,17 +119,17 @@ public function setSelections($selections): void } /** - * @return UUID|null + * @return UuidInterface|null */ - public function getLatestSelectionUUID(): ?UUID + public function getLatestSelectionUUID(): ?UuidInterface { return $this->latestselection; } /** - * @param UUID $latestselection + * @param UuidInterface $latestselection */ - public function setLatestSelectionUUID(UUID $latestselection): void + public function setLatestSelectionUUID(UuidInterface $latestselection): void { $this->latestselection = $latestselection; } diff --git a/src/xenialdan/MagicWE2/session/UserSession.php b/src/xenialdan/MagicWE2/session/UserSession.php index 813145f1..c2a636d2 100644 --- a/src/xenialdan/MagicWE2/session/UserSession.php +++ b/src/xenialdan/MagicWE2/session/UserSession.php @@ -17,7 +17,8 @@ use pocketmine\nbt\tag\CompoundTag; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; -use pocketmine\uuid\UUID; +use Ramsey\Uuid\Uuid; +use Ramsey\Uuid\UuidInterface; use TypeError; use xenialdan\apibossbar\BossBar; use xenialdan\MagicWE2\API; @@ -236,7 +237,7 @@ public function getBrushFromItem(Item $item): Brush } /** @var BrushProperties $properties */ $properties = json_decode($entry->getString("properties"), false, 512, JSON_THROW_ON_ERROR); - $uuid = UUID::fromString($properties->uuid); + $uuid = Uuid::fromString($properties->uuid); $brush = $this->getBrush($uuid); if ($brush instanceof Brush) { return $brush; @@ -250,17 +251,17 @@ public function getBrushFromItem(Item $item): Brush /** * TODO exception for not a brush - * @param UUID $uuid + * @param UuidInterface $uuid * @return null|Brush */ - public function getBrush(UUID $uuid): ?Brush + public function getBrush(UuidInterface $uuid): ?Brush { return $this->brushes[$uuid->toString()] ?? null; } /** * TODO exception for not a brush - * @param Brush $brush UUID will be set automatically + * @param Brush $brush UuidInterface will be set automatically * @return void */ public function addBrush(Brush $brush): void @@ -270,7 +271,7 @@ public function addBrush(Brush $brush): void } /** - * @param Brush $brush UUID will be set automatically + * @param Brush $brush UuidInterface will be set automatically * @param bool $delete If true, it will be removed from the session brushes * @return void */ @@ -290,7 +291,7 @@ public function removeBrush(Brush $brush, bool $delete = false): void /** * TODO exception for not a brush - * @param Brush $brush UUID will be set automatically + * @param Brush $brush UuidInterface will be set automatically * @return void * @throws ActionNotFoundException * @throws InvalidArgumentException diff --git a/src/xenialdan/MagicWE2/task/AsyncActionTask.php b/src/xenialdan/MagicWE2/task/AsyncActionTask.php index 38241469..de79eab4 100644 --- a/src/xenialdan/MagicWE2/task/AsyncActionTask.php +++ b/src/xenialdan/MagicWE2/task/AsyncActionTask.php @@ -8,10 +8,11 @@ use pocketmine\player\Player; use pocketmine\utils\AssumptionFailedError; use pocketmine\utils\TextFormat as TF; -use pocketmine\uuid\UUID; use pocketmine\world\format\Chunk; use pocketmine\world\format\io\FastChunkSerializer; use pocketmine\world\World; +use Ramsey\Uuid\Uuid; +use Ramsey\Uuid\UuidInterface; use xenialdan\MagicWE2\API; use xenialdan\MagicWE2\clipboard\RevertClipboard; use xenialdan\MagicWE2\clipboard\SingleClipboard; @@ -48,14 +49,14 @@ class AsyncActionTask extends MWEAsyncTask /** * AsyncActionTask constructor. - * @param UUID $sessionUUID + * @param UuidInterface $sessionUUID * @param Selection $selection * @param TaskAction $action * @param string[] $touchedChunks serialized chunks * @param BlockPalette $newBlocks * @param BlockPalette $blockFilter */ - public function __construct(UUID $sessionUUID, Selection $selection, TaskAction $action, array $touchedChunks, BlockPalette $newBlocks, BlockPalette $blockFilter) + public function __construct(UuidInterface $sessionUUID, Selection $selection, TaskAction $action, array $touchedChunks, BlockPalette $newBlocks, BlockPalette $blockFilter) { $this->start = microtime(true); $this->sessionUUID = $sessionUUID->toString(); @@ -125,7 +126,7 @@ public function onRun(): void public function onCompletion(): void { try { - $session = SessionHelper::getSessionByUUID(UUID::fromString($this->sessionUUID)); + $session = SessionHelper::getSessionByUUID(Uuid::fromString($this->sessionUUID)); if ($session instanceof UserSession) $session->getBossBar()->hideFromAll(); } catch (SessionException $e) { Loader::getInstance()->getLogger()->logException($e); diff --git a/src/xenialdan/MagicWE2/task/AsyncClipboardActionTask.php b/src/xenialdan/MagicWE2/task/AsyncClipboardActionTask.php index 2481a4cc..d02042a5 100644 --- a/src/xenialdan/MagicWE2/task/AsyncClipboardActionTask.php +++ b/src/xenialdan/MagicWE2/task/AsyncClipboardActionTask.php @@ -7,7 +7,8 @@ use pocketmine\player\Player; use pocketmine\utils\AssumptionFailedError; use pocketmine\utils\TextFormat as TF; -use pocketmine\uuid\UUID; +use Ramsey\Uuid\Uuid; +use Ramsey\Uuid\UuidInterface; use xenialdan\MagicWE2\clipboard\SingleClipboard; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\BlockStatesParser; @@ -33,12 +34,12 @@ class AsyncClipboardActionTask extends MWEAsyncTask /** * AsyncClipboardActionTask constructor. - * @param UUID $sessionUUID + * @param UuidInterface $sessionUUID * @param Selection $selection * @param ClipboardAction $action * @param SingleClipboard $clipboard */ - public function __construct(UUID $sessionUUID, Selection $selection, ClipboardAction $action, SingleClipboard $clipboard) + public function __construct(UuidInterface $sessionUUID, Selection $selection, ClipboardAction $action, SingleClipboard $clipboard) { $this->start = microtime(true); $this->sessionUUID = $sessionUUID->toString(); @@ -97,7 +98,7 @@ public function onRun(): void public function onCompletion(): void { try { - $session = SessionHelper::getSessionByUUID(UUID::fromString($this->sessionUUID)); + $session = SessionHelper::getSessionByUUID(Uuid::fromString($this->sessionUUID)); if ($session instanceof UserSession) $session->getBossBar()->hideFromAll(); } catch (SessionException $e) { Loader::getInstance()->getLogger()->logException($e); diff --git a/src/xenialdan/MagicWE2/task/AsyncCopyTask.php b/src/xenialdan/MagicWE2/task/AsyncCopyTask.php index d0c73d9d..f2868f75 100644 --- a/src/xenialdan/MagicWE2/task/AsyncCopyTask.php +++ b/src/xenialdan/MagicWE2/task/AsyncCopyTask.php @@ -8,8 +8,9 @@ use pocketmine\math\Vector3; use pocketmine\utils\AssumptionFailedError; use pocketmine\utils\TextFormat as TF; -use pocketmine\uuid\UUID; use pocketmine\world\format\io\FastChunkSerializer; +use Ramsey\Uuid\Uuid; +use Ramsey\Uuid\UuidInterface; use xenialdan\MagicWE2\clipboard\SingleClipboard; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\AsyncChunkManager; @@ -37,12 +38,12 @@ class AsyncCopyTask extends MWEAsyncTask * AsyncCopyTask constructor. * @param Selection $selection * @param Vector3 $offset - * @param UUID $sessionUUID + * @param UuidInterface $sessionUUID * @param string[] $chunks serialized chunks * @param int $flags * @throws Exception */ - public function __construct(UUID $sessionUUID, Selection $selection, Vector3 $offset, array $chunks, int $flags) + public function __construct(UuidInterface $sessionUUID, Selection $selection, Vector3 $offset, array $chunks, int $flags) { $this->start = microtime(true); $this->chunks = serialize($chunks); @@ -113,7 +114,7 @@ private function copyBlocks(Selection $selection, AsyncChunkManager $manager, Si public function onCompletion(): void { try { - $session = SessionHelper::getSessionByUUID(UUID::fromString($this->sessionUUID)); + $session = SessionHelper::getSessionByUUID(Uuid::fromString($this->sessionUUID)); if ($session instanceof UserSession) $session->getBossBar()->hideFromAll(); $result = $this->getResult(); $copied = $result["copied"]; diff --git a/src/xenialdan/MagicWE2/task/AsyncCountTask.php b/src/xenialdan/MagicWE2/task/AsyncCountTask.php index 13cd8c8d..1471e67b 100644 --- a/src/xenialdan/MagicWE2/task/AsyncCountTask.php +++ b/src/xenialdan/MagicWE2/task/AsyncCountTask.php @@ -8,8 +8,9 @@ use pocketmine\block\BlockFactory; use pocketmine\utils\AssumptionFailedError; use pocketmine\utils\TextFormat as TF; -use pocketmine\uuid\UUID; use pocketmine\world\format\io\FastChunkSerializer; +use Ramsey\Uuid\Uuid; +use Ramsey\Uuid\UuidInterface; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\AsyncChunkManager; use xenialdan\MagicWE2\helper\BlockPalette; @@ -33,13 +34,13 @@ class AsyncCountTask extends MWEAsyncTask /** * AsyncCountTask constructor. * @param Selection $selection - * @param UUID $sessionUUID + * @param UuidInterface $sessionUUID * @param string[] $touchedChunks serialized chunks * @param BlockPalette $filterblocks * @param int $flags * @throws Exception */ - public function __construct(UUID $sessionUUID, Selection $selection, array $touchedChunks, BlockPalette $filterblocks, int $flags) + public function __construct(UuidInterface $sessionUUID, Selection $selection, array $touchedChunks, BlockPalette $filterblocks, int $flags) { $this->start = microtime(true); $this->touchedChunks = serialize($touchedChunks); @@ -118,7 +119,7 @@ private function countBlocks(Selection $selection, AsyncChunkManager $manager, B public function onCompletion(): void { try { - $session = SessionHelper::getSessionByUUID(UUID::fromString($this->sessionUUID)); + $session = SessionHelper::getSessionByUUID(Uuid::fromString($this->sessionUUID)); if ($session instanceof UserSession) $session->getBossBar()->hideFromAll(); $result = $this->getResult(); $counts = $result["counts"]; diff --git a/src/xenialdan/MagicWE2/task/AsyncFillTask.php b/src/xenialdan/MagicWE2/task/AsyncFillTask.php index 7d90ec24..9493f5f5 100644 --- a/src/xenialdan/MagicWE2/task/AsyncFillTask.php +++ b/src/xenialdan/MagicWE2/task/AsyncFillTask.php @@ -9,10 +9,11 @@ use pocketmine\block\Block; use pocketmine\utils\AssumptionFailedError; use pocketmine\utils\TextFormat as TF; -use pocketmine\uuid\UUID; use pocketmine\world\format\Chunk; use pocketmine\world\format\io\FastChunkSerializer; use pocketmine\world\World; +use Ramsey\Uuid\Uuid; +use Ramsey\Uuid\UuidInterface; use xenialdan\MagicWE2\API; use xenialdan\MagicWE2\clipboard\RevertClipboard; use xenialdan\MagicWE2\exception\SessionException; @@ -39,14 +40,14 @@ class AsyncFillTask extends MWEAsyncTask /** * AsyncFillTask constructor. - * @param UUID $sessionUUID + * @param UuidInterface $sessionUUID * @param Selection $selection * @param string[] $touchedChunks serialized chunks * @param BlockPalette $newBlocks * @param int $flags * @throws Exception */ - public function __construct(UUID $sessionUUID, Selection $selection, array $touchedChunks, BlockPalette $newBlocks, int $flags) + public function __construct(UuidInterface $sessionUUID, Selection $selection, array $touchedChunks, BlockPalette $newBlocks, int $flags) { $this->start = microtime(true); $this->sessionUUID = $sessionUUID->toString(); @@ -159,7 +160,7 @@ private function execute(Selection $selection, AsyncChunkManager $manager, Block public function onCompletion(): void { try { - $session = SessionHelper::getSessionByUUID(UUID::fromString($this->sessionUUID)); + $session = SessionHelper::getSessionByUUID(Uuid::fromString($this->sessionUUID)); if ($session instanceof UserSession) $session->getBossBar()->hideFromAll(); } catch (SessionException $e) { Loader::getInstance()->getLogger()->logException($e); diff --git a/src/xenialdan/MagicWE2/task/AsyncPasteAssetTask.php b/src/xenialdan/MagicWE2/task/AsyncPasteAssetTask.php index dd715662..c0b8a22f 100644 --- a/src/xenialdan/MagicWE2/task/AsyncPasteAssetTask.php +++ b/src/xenialdan/MagicWE2/task/AsyncPasteAssetTask.php @@ -10,10 +10,11 @@ use pocketmine\math\Vector3; use pocketmine\utils\AssumptionFailedError; use pocketmine\utils\TextFormat as TF; -use pocketmine\uuid\UUID; use pocketmine\world\format\Chunk; use pocketmine\world\format\io\FastChunkSerializer; use pocketmine\world\World; +use Ramsey\Uuid\Uuid; +use Ramsey\Uuid\UuidInterface; use xenialdan\libstructure\format\MCStructure; use xenialdan\MagicWE2\API; use xenialdan\MagicWE2\clipboard\RevertClipboard; @@ -43,14 +44,14 @@ class AsyncPasteAssetTask extends MWEAsyncTask /** * AsyncPasteTask constructor. - * @param UUID $sessionUUID + * @param UuidInterface $sessionUUID * @param Vector3 $target * @param Selection $selection * @param string[] $touchedChunks serialized chunks * @param Asset $asset * @throws Exception */ - public function __construct(UUID $sessionUUID, Vector3 $target, Selection $selection, array $touchedChunks, Asset $asset) + public function __construct(UuidInterface $sessionUUID, Vector3 $target, Selection $selection, array $touchedChunks, Asset $asset) { $this->start = microtime(true); $this->pasteVector = $selection->getShape()->getPasteVector();#->addVector($asset->getOrigin())->floor(); @@ -208,7 +209,7 @@ private function execute(AsyncChunkManager $manager, Asset $asset, ?int &$change public function onCompletion(): void { try { - $session = SessionHelper::getSessionByUUID(UUID::fromString($this->sessionUUID)); + $session = SessionHelper::getSessionByUUID(Uuid::fromString($this->sessionUUID)); if ($session instanceof UserSession) $session->getBossBar()->hideFromAll(); } catch (SessionException $e) { Loader::getInstance()->getLogger()->logException($e); diff --git a/src/xenialdan/MagicWE2/task/AsyncPasteTask.php b/src/xenialdan/MagicWE2/task/AsyncPasteTask.php index 04ee1638..1429d737 100644 --- a/src/xenialdan/MagicWE2/task/AsyncPasteTask.php +++ b/src/xenialdan/MagicWE2/task/AsyncPasteTask.php @@ -8,10 +8,11 @@ use pocketmine\math\Vector3; use pocketmine\utils\AssumptionFailedError; use pocketmine\utils\TextFormat as TF; -use pocketmine\uuid\UUID; use pocketmine\world\format\Chunk; use pocketmine\world\format\io\FastChunkSerializer; use pocketmine\world\World; +use Ramsey\Uuid\Uuid; +use Ramsey\Uuid\UuidInterface; use xenialdan\MagicWE2\API; use xenialdan\MagicWE2\clipboard\RevertClipboard; use xenialdan\MagicWE2\clipboard\SingleClipboard; @@ -37,13 +38,13 @@ class AsyncPasteTask extends MWEAsyncTask /** * AsyncPasteTask constructor. - * @param UUID $sessionUUID + * @param UuidInterface $sessionUUID * @param Selection $selection * @param string[] $touchedChunks serialized chunks * @param SingleClipboard $clipboard * @throws Exception */ - public function __construct(UUID $sessionUUID, Selection $selection, array $touchedChunks, SingleClipboard $clipboard) + public function __construct(UuidInterface $sessionUUID, Selection $selection, array $touchedChunks, SingleClipboard $clipboard) { $this->start = microtime(true); $this->offset = $selection->getShape()->getPasteVector()->addVector($clipboard->position)->floor(); @@ -149,7 +150,7 @@ private function execute(Selection $selection, AsyncChunkManager $manager, Singl public function onCompletion(): void { try { - $session = SessionHelper::getSessionByUUID(UUID::fromString($this->sessionUUID)); + $session = SessionHelper::getSessionByUUID(Uuid::fromString($this->sessionUUID)); if ($session instanceof UserSession) $session->getBossBar()->hideFromAll(); } catch (SessionException $e) { Loader::getInstance()->getLogger()->logException($e); diff --git a/src/xenialdan/MagicWE2/task/AsyncReplaceTask.php b/src/xenialdan/MagicWE2/task/AsyncReplaceTask.php index 8bb780ab..accf9056 100644 --- a/src/xenialdan/MagicWE2/task/AsyncReplaceTask.php +++ b/src/xenialdan/MagicWE2/task/AsyncReplaceTask.php @@ -9,10 +9,11 @@ use pocketmine\block\Block; use pocketmine\utils\AssumptionFailedError; use pocketmine\utils\TextFormat as TF; -use pocketmine\uuid\UUID; use pocketmine\world\format\Chunk; use pocketmine\world\format\io\FastChunkSerializer; use pocketmine\world\World; +use Ramsey\Uuid\Uuid; +use Ramsey\Uuid\UuidInterface; use xenialdan\MagicWE2\API; use xenialdan\MagicWE2\clipboard\RevertClipboard; use xenialdan\MagicWE2\exception\SessionException; @@ -40,14 +41,14 @@ class AsyncReplaceTask extends MWEAsyncTask /** * AsyncReplaceTask constructor. * @param Selection $selection - * @param UUID $sessionUUID + * @param UuidInterface $sessionUUID * @param string[] $touchedChunks serialized chunks * @param BlockPalette $replaceBlocks * @param BlockPalette $newBlocks * @param int $flags * @throws Exception */ - public function __construct(UUID $sessionUUID, Selection $selection, array $touchedChunks, BlockPalette $replaceBlocks, BlockPalette $newBlocks, int $flags) + public function __construct(UuidInterface $sessionUUID, Selection $selection, array $touchedChunks, BlockPalette $replaceBlocks, BlockPalette $newBlocks, int $flags) { $this->start = microtime(true); $this->sessionUUID = $sessionUUID->toString(); @@ -146,7 +147,7 @@ private function execute(Selection $selection, AsyncChunkManager $manager, Block public function onCompletion(): void { try { - $session = SessionHelper::getSessionByUUID(UUID::fromString($this->sessionUUID)); + $session = SessionHelper::getSessionByUUID(Uuid::fromString($this->sessionUUID)); if ($session instanceof UserSession) $session->getBossBar()->hideFromAll(); } catch (SessionException $e) { Loader::getInstance()->getLogger()->logException($e); diff --git a/src/xenialdan/MagicWE2/task/AsyncRevertTask.php b/src/xenialdan/MagicWE2/task/AsyncRevertTask.php index d98b1a58..c248edb8 100644 --- a/src/xenialdan/MagicWE2/task/AsyncRevertTask.php +++ b/src/xenialdan/MagicWE2/task/AsyncRevertTask.php @@ -7,8 +7,9 @@ use InvalidArgumentException; use pocketmine\utils\AssumptionFailedError; use pocketmine\utils\TextFormat as TF; -use pocketmine\uuid\UUID; use pocketmine\world\World; +use Ramsey\Uuid\Uuid; +use Ramsey\Uuid\UuidInterface; use xenialdan\MagicWE2\clipboard\RevertClipboard; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\AsyncChunkManager; @@ -29,11 +30,11 @@ class AsyncRevertTask extends MWEAsyncTask /** * AsyncRevertTask constructor. - * @param UUID $sessionUUID + * @param UuidInterface $sessionUUID * @param RevertClipboard $clipboard * @param int $type The type of clipboard pasting. */ - public function __construct(UUID $sessionUUID, RevertClipboard $clipboard, $type = self::TYPE_UNDO) + public function __construct(UuidInterface $sessionUUID, RevertClipboard $clipboard, $type = self::TYPE_UNDO) { $this->sessionUUID = $sessionUUID->toString(); $this->start = microtime(true); @@ -115,7 +116,7 @@ private function redoChunks(AsyncChunkManager $manager, RevertClipboard $clipboa public function onCompletion(): void { try { - $session = SessionHelper::getSessionByUUID(UUID::fromString($this->sessionUUID)); + $session = SessionHelper::getSessionByUUID(Uuid::fromString($this->sessionUUID)); if ($session instanceof UserSession) $session->getBossBar()->hideFromAll(); } catch (SessionException $e) { Loader::getInstance()->getLogger()->logException($e); diff --git a/src/xenialdan/MagicWE2/task/MWEAsyncTask.php b/src/xenialdan/MagicWE2/task/MWEAsyncTask.php index 6e696fee..5297ad72 100644 --- a/src/xenialdan/MagicWE2/task/MWEAsyncTask.php +++ b/src/xenialdan/MagicWE2/task/MWEAsyncTask.php @@ -5,8 +5,8 @@ use pocketmine\block\Block; use pocketmine\block\BlockFactory; use pocketmine\scheduler\AsyncTask; -use pocketmine\uuid\UUID; use pocketmine\world\Position; +use Ramsey\Uuid\Uuid; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\Progress; use xenialdan\MagicWE2\helper\SessionHelper; @@ -25,7 +25,7 @@ public function onProgressUpdate($progress): void $progress = new Progress($progress[0] / 100, $progress[1]); } try { - $session = SessionHelper::getSessionByUUID(UUID::fromString($this->sessionUUID)); + $session = SessionHelper::getSessionByUUID(Uuid::fromString($this->sessionUUID)); /** @var Progress $progress */ if ($session instanceof UserSession) $session->getBossBar()->setPercentage($progress->progress)->setSubTitle(str_replace("%", "%%%%", $progress->string . " | " . floor($progress->progress * 100) . "%")); else $session->sendMessage($progress->string . " | " . floor($progress->progress * 100) . "%");//TODO remove, debug diff --git a/src/xenialdan/MagicWE2/tool/Brush.php b/src/xenialdan/MagicWE2/tool/Brush.php index eff608bc..5b062e41 100644 --- a/src/xenialdan/MagicWE2/tool/Brush.php +++ b/src/xenialdan/MagicWE2/tool/Brush.php @@ -15,8 +15,8 @@ use pocketmine\player\Player; use pocketmine\utils\AssumptionFailedError; use pocketmine\utils\TextFormat as TF; -use pocketmine\uuid\UUID; use pocketmine\world\biome\BiomeRegistry; +use Ramsey\Uuid\Uuid; use ReflectionClass; use TypeError; use xenialdan\customui\elements\Dropdown; @@ -69,7 +69,7 @@ public function toItem(): Item { $item = VanillaItems::WOODEN_SHOVEL(); $item->addEnchantment(new EnchantmentInstance(Loader::$ench)); - $uuid = $this->properties->uuid ?? UUID::fromRandom()->toString(); + $uuid = $this->properties->uuid ?? Uuid::uuid4()->toString(); $this->properties->uuid = $uuid; $properties = json_encode($this->properties, JSON_THROW_ON_ERROR); if (!is_string($properties)) throw new InvalidArgumentException("Brush properties could not be decoded"); @@ -265,7 +265,7 @@ private function getExtradataForm(string $shapeClass): CustomForm if (!$session instanceof UserSession) { throw new SessionException(Loader::getInstance()->getLanguage()->translateString('error.nosession', [Loader::getInstance()->getName()])); } - $this->properties->uuid = UUID::fromRandom()->toString(); + $this->properties->uuid = Uuid::uuid4()->toString(); $session->addBrush($brush); $player->getInventory()->addItem($brush->toItem()); }); diff --git a/src/xenialdan/MagicWE2/tool/BrushProperties.php b/src/xenialdan/MagicWE2/tool/BrushProperties.php index a0dc3d99..d041be55 100644 --- a/src/xenialdan/MagicWE2/tool/BrushProperties.php +++ b/src/xenialdan/MagicWE2/tool/BrushProperties.php @@ -143,7 +143,7 @@ public function generateLore(): array TF::RESET . TF::BOLD . TF::GOLD . "Filter: " . TF::RESET . $this->filter, TF::RESET . TF::BOLD . TF::GOLD . "Biome: " . TF::RESET . $this->biomeId, TF::RESET . TF::BOLD . TF::GOLD . "Hollow: " . TF::RESET . ($this->hollow ? TF::GREEN . "Yes" : TF::RED . "No"), - //TF::GOLD . "UUID: {$this->uuid}", + //TF::GOLD . "UuidInterface: {$this->uuid}", ] ); } From fc3a760be988de0cab8ff4cf28e7ffceed1ab51a Mon Sep 17 00:00:00 2001 From: XenialDan Date: Fri, 23 Apr 2021 07:09:40 +0200 Subject: [PATCH 21/67] Update to PHP8 --- plugin.yml | 2 +- src/xenialdan/MagicWE2/API.php | 6 ++- src/xenialdan/MagicWE2/EventListener.php | 44 +++++++++++-------- src/xenialdan/MagicWE2/Loader.php | 24 +++++----- .../MagicWE2/clipboard/Clipboard.php | 4 +- .../MagicWE2/clipboard/RevertClipboard.php | 4 +- .../MagicWE2/clipboard/SingleClipboard.php | 8 ++-- .../MagicWE2/commands/DonateCommand.php | 2 + .../MagicWE2/commands/HelpCommand.php | 2 + .../MagicWE2/commands/InfoCommand.php | 2 + .../MagicWE2/commands/LanguageCommand.php | 2 + .../MagicWE2/commands/LimitCommand.php | 2 + .../MagicWE2/commands/ReportCommand.php | 2 + .../MagicWE2/commands/SetRangeCommand.php | 2 + .../MagicWE2/commands/TestCommand.php | 2 + .../MagicWE2/commands/VersionCommand.php | 2 + .../MagicWE2/commands/args/BlocksArgument.php | 4 ++ .../MagicWE2/commands/asset/AssetCommand.php | 2 + .../commands/biome/BiomeInfoCommand.php | 2 + .../commands/biome/BiomeListCommand.php | 3 ++ .../commands/biome/SetBiomeCommand.php | 2 + .../MagicWE2/commands/brush/BrushCommand.php | 2 + .../commands/brush/BrushNameCommand.php | 2 + .../clipboard/ClearClipboardCommand.php | 2 + .../commands/clipboard/CopyCommand.php | 2 + .../commands/clipboard/Cut2Command.php | 2 + .../commands/clipboard/CutCommand.php | 2 + .../commands/clipboard/FlipCommand.php | 2 + .../commands/clipboard/PasteCommand.php | 2 + .../commands/clipboard/RotateCommand.php | 4 +- .../debug/PlaceAllBlockstatesCommand.php | 2 + .../commands/generation/CylinderCommand.php | 4 +- .../commands/history/ClearhistoryCommand.php | 2 + .../MagicWE2/commands/history/RedoCommand.php | 2 + .../MagicWE2/commands/history/UndoCommand.php | 2 + .../commands/region/OverlayCommand.php | 2 + .../commands/region/ReplaceCommand.php | 2 + .../MagicWE2/commands/region/SetCommand.php | 2 + .../commands/selection/ChunkCommand.php | 2 + .../commands/selection/HPos1Command.php | 2 + .../commands/selection/HPos2Command.php | 2 + .../commands/selection/Pos1Command.php | 2 + .../commands/selection/Pos2Command.php | 2 + .../commands/selection/info/CountCommand.php | 2 + .../selection/info/ListChunksCommand.php | 2 + .../commands/selection/info/SizeCommand.php | 2 + .../MagicWE2/commands/tool/DebugCommand.php | 2 + .../commands/tool/ToggledebugCommand.php | 2 + .../commands/tool/TogglewandCommand.php | 2 + .../MagicWE2/commands/tool/WandCommand.php | 2 + .../commands/utility/CalculateCommand.php | 2 + .../commands/utility/ToggleWailaCommand.php | 2 + src/xenialdan/MagicWE2/event/MWEEditEvent.php | 6 +-- .../event/MWESelectionChangeEvent.php | 2 +- .../MagicWE2/event/MWESessionLoadEvent.php | 2 +- .../MagicWE2/helper/AsyncChunkManager.php | 6 +++ src/xenialdan/MagicWE2/helper/BlockEntry.php | 10 ++--- .../MagicWE2/helper/BlockPalette.php | 8 +--- src/xenialdan/MagicWE2/helper/BlockQuery.php | 11 +++-- .../MagicWE2/helper/BlockStatesEntry.php | 14 +++--- .../MagicWE2/helper/BlockStatesParser.php | 24 +++++----- src/xenialdan/MagicWE2/helper/Progress.php | 4 +- .../MagicWE2/helper/SessionHelper.php | 17 ++++--- .../MagicWE2/helper/StructureStore.php | 10 ++++- .../MagicWE2/helper/WeightedRandom.php | 8 ++-- .../MagicWE2/selection/Selection.php | 30 ++++++++----- .../MagicWE2/selection/shape/Cone.php | 17 ++++--- .../MagicWE2/selection/shape/Cube.php | 13 +++--- .../MagicWE2/selection/shape/Cuboid.php | 17 ++++--- .../MagicWE2/selection/shape/Custom.php | 13 +++--- .../MagicWE2/selection/shape/Cylinder.php | 15 +++---- .../MagicWE2/selection/shape/Ellipsoid.php | 17 ++++--- .../MagicWE2/selection/shape/Pyramid.php | 19 ++++---- .../MagicWE2/selection/shape/Shape.php | 19 ++++---- .../selection/shape/ShapeRegistry.php | 2 +- .../MagicWE2/selection/shape/Sphere.php | 13 +++--- .../MagicWE2/session/PluginSession.php | 2 +- src/xenialdan/MagicWE2/session/Session.php | 16 ++++--- .../MagicWE2/session/UserSession.php | 17 ++++--- src/xenialdan/MagicWE2/session/data/Asset.php | 2 + .../MagicWE2/task/AsyncActionTask.php | 22 +++++----- .../task/AsyncClipboardActionTask.php | 15 ++++--- src/xenialdan/MagicWE2/task/AsyncCopyTask.php | 11 ++--- .../MagicWE2/task/AsyncCountTask.php | 14 +++--- src/xenialdan/MagicWE2/task/AsyncFillTask.php | 19 ++++---- .../MagicWE2/task/AsyncPasteAssetTask.php | 29 ++++++------ .../MagicWE2/task/AsyncPasteTask.php | 19 ++++---- .../MagicWE2/task/AsyncReplaceTask.php | 21 ++++----- .../MagicWE2/task/AsyncRevertTask.php | 18 ++++---- src/xenialdan/MagicWE2/task/MWEAsyncTask.php | 4 +- .../MagicWE2/task/action/ActionRegistry.php | 2 +- .../MagicWE2/task/action/ClipboardAction.php | 7 ++- .../MagicWE2/task/action/CountAction.php | 10 ++--- .../MagicWE2/task/action/CutAction.php | 10 ++--- .../MagicWE2/task/action/FlipAction.php | 16 ++++--- .../MagicWE2/task/action/RotateAction.php | 15 ++++--- .../MagicWE2/task/action/SetBiomeAction.php | 6 +-- .../MagicWE2/task/action/SetBlockAction.php | 6 +-- .../MagicWE2/task/action/TaskAction.php | 13 +++--- .../MagicWE2/task/action/TestAction.php | 6 +-- .../MagicWE2/task/action/ThawAction.php | 6 +-- src/xenialdan/MagicWE2/tool/Brush.php | 2 +- .../MagicWE2/tool/BrushProperties.php | 22 +++++----- src/xenialdan/MagicWE2/tool/Flood.php | 26 +++++------ 104 files changed, 482 insertions(+), 360 deletions(-) diff --git a/plugin.yml b/plugin.yml index f4e7c9d7..c508bef6 100644 --- a/plugin.yml +++ b/plugin.yml @@ -3,7 +3,7 @@ name: MagicWE2 main: xenialdan\MagicWE2\Loader version: 10.1.5 api: ["4.0.0"] -php: [ "7.4", "8.0" ] +php: [ "8.0" ] softdepend: [ "DEVirion" ] authors: - XenialDan diff --git a/src/xenialdan/MagicWE2/API.php b/src/xenialdan/MagicWE2/API.php index 2d5fc913..1ec3c1bc 100644 --- a/src/xenialdan/MagicWE2/API.php +++ b/src/xenialdan/MagicWE2/API.php @@ -8,6 +8,7 @@ use InvalidArgumentException; use pocketmine\block\Block; use pocketmine\block\BlockFactory; +use pocketmine\block\utils\InvalidBlockStateException; use pocketmine\math\AxisAlignedBB; use pocketmine\math\Vector3; use pocketmine\nbt\tag\CompoundTag; @@ -77,7 +78,7 @@ class API //TODO Split into separate Class (SchematicStorage?) /** @var Clipboard[] */ - private static $schematics = [];//TODO + private static array $schematics = [];//TODO /** * @param Selection $selection @@ -441,8 +442,9 @@ public static function hasFlag(int $flags, int $check): bool * @param array $messages * @param bool $error * @return BlockPalette - * @throws InvalidArgumentException * @throws BlockQueryAlreadyParsedException + * @throws InvalidArgumentException + * @throws InvalidBlockStateException * @deprecated Use BlockPalette::fromString() */ public static function blockParser(string $fullstring, array &$messages, bool &$error): BlockPalette diff --git a/src/xenialdan/MagicWE2/EventListener.php b/src/xenialdan/MagicWE2/EventListener.php index 1c52a5ab..be5fcf70 100644 --- a/src/xenialdan/MagicWE2/EventListener.php +++ b/src/xenialdan/MagicWE2/EventListener.php @@ -7,6 +7,7 @@ use InvalidArgumentException; use InvalidStateException; use JsonException; +use OutOfBoundsException; use pocketmine\block\BlockFactory; use pocketmine\block\BlockLegacyIds; use pocketmine\entity\InvalidSkinException; @@ -27,8 +28,8 @@ use pocketmine\utils\TextFormat as TF; use pocketmine\world\Position; use RuntimeException; +use UnderflowException; use xenialdan\customui\windows\ModalForm; -use xenialdan\libstructure\StructureUI; use xenialdan\libstructure\tile\StructureBlockTile; use xenialdan\MagicWE2\event\MWESelectionChangeEvent; use xenialdan\MagicWE2\event\MWESessionLoadEvent; @@ -43,7 +44,7 @@ class EventListener implements Listener { /** @var Plugin */ - public $owner; + public Plugin $owner; public function __construct(Plugin $plugin) { @@ -52,7 +53,6 @@ public function __construct(Plugin $plugin) /** * @param PlayerJoinEvent $event - * @throws AssumptionFailedError * @throws InvalidSkinException * @throws JsonException * @throws RuntimeException @@ -73,20 +73,19 @@ public function onSessionLoad(MWESessionLoadEvent $event): void { Loader::getInstance()->wailaBossBar->addPlayer($event->getPlayer()); if (Loader::hasScoreboard()) { - try { - if (($session = $event->getSession()) instanceof UserSession && $session->isSidebarEnabled()) - /** @var UserSession $session */ - $session->sidebar->handleScoreboard($session); - } catch (InvalidArgumentException $e) { - Loader::getInstance()->getLogger()->logException($e); - } + $session = $event->getSession(); + if ($session instanceof UserSession && $session->isSidebarEnabled()) + /** @var UserSession $session */ + $session->sidebar->handleScoreboard($session); } } /** * @param PlayerQuitEvent $event - * @throws SessionException * @throws JsonException + * @throws OutOfBoundsException + * @throws SessionException + * @throws UnderflowException */ public function onLogout(PlayerQuitEvent $event): void { @@ -175,10 +174,12 @@ public function onBreak(BlockBreakEvent $event): void /** * TODO use tool classes * @param BlockBreakEvent $event + * @throws AssumptionFailedError * @throws Error - * @throws SessionException * @throws InvalidArgumentException - * @throws AssumptionFailedError + * @throws OutOfBoundsException + * @throws SessionException + * @throws UnderflowException */ private function onBreakBlock(BlockBreakEvent $event): void { @@ -213,11 +214,13 @@ private function onBreakBlock(BlockBreakEvent $event): void /** * TODO use tool classes * @param PlayerInteractEvent $event + * @throws AssumptionFailedError * @throws Error + * @throws InvalidArgumentException * @throws InvalidStateException + * @throws OutOfBoundsException * @throws SessionException - * @throws InvalidArgumentException - * @throws AssumptionFailedError + * @throws UnderflowException */ private function onRightClickBlock(PlayerInteractEvent $event): void { @@ -282,12 +285,14 @@ private function onRightClickBlock(PlayerInteractEvent $event): void /** * @param PlayerInteractEvent $event + * @throws AssumptionFailedError * @throws Error + * @throws InvalidArgumentException * @throws InvalidStateException + * @throws OutOfBoundsException * @throws SessionException - * @throws InvalidArgumentException * @throws UnexpectedTagTypeException - * @throws AssumptionFailedError + * @throws UnderflowException */ private function onLeftClickBlock(PlayerInteractEvent $event): void { @@ -393,8 +398,9 @@ public function onSelectionChange(MWESelectionChangeEvent $event): void /** * TODO use tool classes * @param PlayerItemHeldEvent $event + * @throws OutOfBoundsException * @throws SessionException - * @throws \OutOfBoundsException + * @throws UnderflowException */ public function onChangeSlot(PlayerItemHeldEvent $event): void { @@ -477,7 +483,7 @@ public static function sendOutline(Player $player, Position $target, Asset $asse public function onStructureBlockClick(PlayerInteractEvent $event): void { - $player = $event->getPlayer(); + //$player = $event->getPlayer(); $blockTouched = $event->getBlock(); if ($blockTouched->getId() === BlockLegacyIds::STRUCTURE_BLOCK) { var_dump("Clicked Structure Block", (string)$blockTouched); diff --git a/src/xenialdan/MagicWE2/Loader.php b/src/xenialdan/MagicWE2/Loader.php index 19fdd170..b95d3b33 100644 --- a/src/xenialdan/MagicWE2/Loader.php +++ b/src/xenialdan/MagicWE2/Loader.php @@ -84,27 +84,27 @@ class Loader extends PluginBase public const PREFIX_ASSETS = TF::RESET . TF::BOLD . TF::GOLD . "[Asset]" . TF::RESET . " "; public const PREFIX_FORM = TF::RESET . TF::BOLD . TF::DARK_PURPLE . "[MWE2]" . TF::RESET . " "; /** @var Loader|null */ - private static $instance; + private static ?Loader $instance; /** @var null|ShapeRegistry */ - public static $shapeRegistry; + public static ?ShapeRegistry $shapeRegistry; /** @var null|ActionRegistry */ - public static $actionRegistry; + public static ?ActionRegistry $actionRegistry; /** @var Enchantment */ - public static $ench; + public static Enchantment $ench; /** @var Language */ - private $baseLang; + private Language $baseLang; /** @var string[] Donator names */ - public $donators = []; + public array $donators = []; /** @var string */ - public $donatorData = ""; + public string $donatorData = ""; /** @var string */ - private static $rotPath; + private static string $rotPath; /** @var string */ - private static $doorRotPath; + private static string $doorRotPath; /** @var DiverseBossBar */#BossBar - public $wailaBossBar; + public DiverseBossBar $wailaBossBar; /** @var null|string */ - public static $scoreboardAPI; + public static ?string $scoreboardAPI; /** @var AssetCollection */ public static AssetCollection $assetCollection; @@ -158,7 +158,6 @@ public function onLoad(): void { self::$instance = $this; self::$ench = new Enchantment(self::FAKE_ENCH_ID, "", 0, ItemFlags::AXE, ItemFlags::NONE, 1); - /** @var EnchantmentIdMap $enchantmapinstance */ $enchantmapinstance = EnchantmentIdMap::getInstance(); $enchantmapinstance->register(self::FAKE_ENCH_ID, self::$ench); self::$shapeRegistry = new ShapeRegistry(); @@ -169,7 +168,6 @@ public function onLoad(): void self::$rotPath = $this->getFile() . "resources" . DIRECTORY_SEPARATOR . "rotation_flip_data.json"; self::$doorRotPath = $this->getFile() . "resources" . DIRECTORY_SEPARATOR . "door_data.json"; - /** @var BlockStatesParser $blockstateparserInstance */ $blockstateparserInstance = BlockStatesParser::getInstance(); $blockstateparserInstance::$rotPath = $this->getFile() . "resources" . DIRECTORY_SEPARATOR . "rotation_flip_data.json"; $blockstateparserInstance::$doorRotPath = $this->getFile() . "resources" . DIRECTORY_SEPARATOR . "door_data.json"; diff --git a/src/xenialdan/MagicWE2/clipboard/Clipboard.php b/src/xenialdan/MagicWE2/clipboard/Clipboard.php index c3ecca1f..e8f8b707 100644 --- a/src/xenialdan/MagicWE2/clipboard/Clipboard.php +++ b/src/xenialdan/MagicWE2/clipboard/Clipboard.php @@ -26,7 +26,7 @@ abstract class Clipboard implements Serializable public const FLIP_NORTH = 0x03; public const FLIP_SOUTH = 0x03; - public ?int $worldId; + public ?int $worldId = null; public string $customName = ""; /** @@ -36,7 +36,7 @@ abstract class Clipboard implements Serializable */ public static function getChunkManager(array $chunks): AsyncChunkManager { - $manager = new AsyncChunkManager(); + $manager = new AsyncChunkManager(0, World::Y_MAX); foreach ($chunks as $hash => $chunk) { World::getXZ($hash, $x, $z); $manager->setChunk($x, $z, $chunk); diff --git a/src/xenialdan/MagicWE2/clipboard/RevertClipboard.php b/src/xenialdan/MagicWE2/clipboard/RevertClipboard.php index 28543856..ff71554e 100644 --- a/src/xenialdan/MagicWE2/clipboard/RevertClipboard.php +++ b/src/xenialdan/MagicWE2/clipboard/RevertClipboard.php @@ -13,12 +13,12 @@ class RevertClipboard extends Clipboard * @var Chunk[] * @phpstan-var array */ - public $chunks = []; + public array $chunks = []; /** * @var array[] * @phpstan-var array */ - public $blocksAfter; + public array $blocksAfter; /** * RevertClipboard constructor. diff --git a/src/xenialdan/MagicWE2/clipboard/SingleClipboard.php b/src/xenialdan/MagicWE2/clipboard/SingleClipboard.php index 5ef5c624..330d13ec 100644 --- a/src/xenialdan/MagicWE2/clipboard/SingleClipboard.php +++ b/src/xenialdan/MagicWE2/clipboard/SingleClipboard.php @@ -13,11 +13,11 @@ class SingleClipboard extends Clipboard { /** @var BlockEntry[] */ - private $entries = []; + private array $entries = []; /** @var Selection */ - public $selection; + public Selection $selection; /** @var Vector3 */ - public $position; + public Vector3 $position; /** * SingleClipboard constructor. @@ -42,7 +42,7 @@ public function clear(): void * @param int|null $x * @param int|null $y * @param int|null $z - * @return Generator|BlockEntry[] + * @return Generator */ public function iterateEntries(?int &$x, ?int &$y, ?int &$z): Generator { diff --git a/src/xenialdan/MagicWE2/commands/DonateCommand.php b/src/xenialdan/MagicWE2/commands/DonateCommand.php index db3e865e..fa2ac7b6 100644 --- a/src/xenialdan/MagicWE2/commands/DonateCommand.php +++ b/src/xenialdan/MagicWE2/commands/DonateCommand.php @@ -10,6 +10,7 @@ use pocketmine\command\CommandSender; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; +use UnderflowException; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\SessionHelper; use xenialdan\MagicWE2\Loader; @@ -30,6 +31,7 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args + * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/HelpCommand.php b/src/xenialdan/MagicWE2/commands/HelpCommand.php index 6fa89cf6..29f2a792 100644 --- a/src/xenialdan/MagicWE2/commands/HelpCommand.php +++ b/src/xenialdan/MagicWE2/commands/HelpCommand.php @@ -13,6 +13,7 @@ use pocketmine\command\CommandSender; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; +use UnderflowException; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\SessionHelper; use xenialdan\MagicWE2\Loader; @@ -34,6 +35,7 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args + * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/InfoCommand.php b/src/xenialdan/MagicWE2/commands/InfoCommand.php index 074a598d..70d849cb 100644 --- a/src/xenialdan/MagicWE2/commands/InfoCommand.php +++ b/src/xenialdan/MagicWE2/commands/InfoCommand.php @@ -10,6 +10,7 @@ use pocketmine\command\CommandSender; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; +use UnderflowException; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\SessionHelper; use xenialdan\MagicWE2\Loader; @@ -30,6 +31,7 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args + * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/LanguageCommand.php b/src/xenialdan/MagicWE2/commands/LanguageCommand.php index 8e6701e2..bae4a54b 100644 --- a/src/xenialdan/MagicWE2/commands/LanguageCommand.php +++ b/src/xenialdan/MagicWE2/commands/LanguageCommand.php @@ -11,6 +11,7 @@ use pocketmine\command\CommandSender; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; +use UnderflowException; use xenialdan\customui\elements\Dropdown; use xenialdan\customui\elements\Label; use xenialdan\customui\windows\CustomForm; @@ -37,6 +38,7 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args + * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/LimitCommand.php b/src/xenialdan/MagicWE2/commands/LimitCommand.php index 0fd34061..7a1cc93d 100644 --- a/src/xenialdan/MagicWE2/commands/LimitCommand.php +++ b/src/xenialdan/MagicWE2/commands/LimitCommand.php @@ -12,6 +12,7 @@ use pocketmine\command\CommandSender; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; +use UnderflowException; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\SessionHelper; use xenialdan\MagicWE2\Loader; @@ -35,6 +36,7 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args + * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/ReportCommand.php b/src/xenialdan/MagicWE2/commands/ReportCommand.php index 1691b8b7..e532fe22 100644 --- a/src/xenialdan/MagicWE2/commands/ReportCommand.php +++ b/src/xenialdan/MagicWE2/commands/ReportCommand.php @@ -13,6 +13,7 @@ use pocketmine\command\ConsoleCommandSender; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; +use UnderflowException; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\SessionHelper; use xenialdan\MagicWE2\Loader; @@ -35,6 +36,7 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args + * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/SetRangeCommand.php b/src/xenialdan/MagicWE2/commands/SetRangeCommand.php index 60e1171d..776217bc 100644 --- a/src/xenialdan/MagicWE2/commands/SetRangeCommand.php +++ b/src/xenialdan/MagicWE2/commands/SetRangeCommand.php @@ -12,6 +12,7 @@ use pocketmine\command\CommandSender; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; +use UnderflowException; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\SessionHelper; use xenialdan\MagicWE2\Loader; @@ -35,6 +36,7 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args + * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/TestCommand.php b/src/xenialdan/MagicWE2/commands/TestCommand.php index f16dc71a..6ad99468 100644 --- a/src/xenialdan/MagicWE2/commands/TestCommand.php +++ b/src/xenialdan/MagicWE2/commands/TestCommand.php @@ -11,6 +11,7 @@ use pocketmine\player\Player; use pocketmine\Server; use pocketmine\utils\TextFormat as TF; +use UnderflowException; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\BlockPalette; use xenialdan\MagicWE2\helper\SessionHelper; @@ -35,6 +36,7 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args + * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/VersionCommand.php b/src/xenialdan/MagicWE2/commands/VersionCommand.php index b8166e60..8e6647c7 100644 --- a/src/xenialdan/MagicWE2/commands/VersionCommand.php +++ b/src/xenialdan/MagicWE2/commands/VersionCommand.php @@ -10,6 +10,7 @@ use pocketmine\command\CommandSender; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; +use UnderflowException; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\SessionHelper; use xenialdan\MagicWE2\Loader; @@ -30,6 +31,7 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args + * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/args/BlocksArgument.php b/src/xenialdan/MagicWE2/commands/args/BlocksArgument.php index e076c76a..594fc606 100644 --- a/src/xenialdan/MagicWE2/commands/args/BlocksArgument.php +++ b/src/xenialdan/MagicWE2/commands/args/BlocksArgument.php @@ -10,7 +10,9 @@ use pocketmine\command\CommandSender; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; +use UnderflowException; use xenialdan\MagicWE2\exception\BlockQueryAlreadyParsedException; +use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\BlockPalette; use xenialdan\MagicWE2\helper\SessionHelper; use xenialdan\MagicWE2\Loader; @@ -32,6 +34,8 @@ public function canParse(string $testString, CommandSender $sender): bool * @param CommandSender $sender * * @return BlockPalette + * @throws UnderflowException + * @throws SessionException */ public function parse(string $argument, CommandSender $sender) { diff --git a/src/xenialdan/MagicWE2/commands/asset/AssetCommand.php b/src/xenialdan/MagicWE2/commands/asset/AssetCommand.php index 7d9b0e98..90219e39 100644 --- a/src/xenialdan/MagicWE2/commands/asset/AssetCommand.php +++ b/src/xenialdan/MagicWE2/commands/asset/AssetCommand.php @@ -12,6 +12,7 @@ use pocketmine\command\CommandSender; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; +use UnderflowException; use xenialdan\customui\elements\Button; use xenialdan\customui\elements\Label; use xenialdan\customui\elements\Toggle; @@ -43,6 +44,7 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args + * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/biome/BiomeInfoCommand.php b/src/xenialdan/MagicWE2/commands/biome/BiomeInfoCommand.php index 99e09a86..3a8ac463 100644 --- a/src/xenialdan/MagicWE2/commands/biome/BiomeInfoCommand.php +++ b/src/xenialdan/MagicWE2/commands/biome/BiomeInfoCommand.php @@ -17,6 +17,7 @@ use pocketmine\world\biome\BiomeRegistry; use pocketmine\world\format\io\FastChunkSerializer; use ReflectionClass; +use UnderflowException; use xenialdan\MagicWE2\exception\SelectionException; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\SessionHelper; @@ -42,6 +43,7 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args + * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/biome/BiomeListCommand.php b/src/xenialdan/MagicWE2/commands/biome/BiomeListCommand.php index 41ad97ce..ef7bfa80 100644 --- a/src/xenialdan/MagicWE2/commands/biome/BiomeListCommand.php +++ b/src/xenialdan/MagicWE2/commands/biome/BiomeListCommand.php @@ -13,6 +13,7 @@ use pocketmine\world\biome\Biome; use pocketmine\world\biome\BiomeRegistry; use ReflectionClass; +use UnderflowException; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\SessionHelper; use xenialdan\MagicWE2\Loader; @@ -33,6 +34,8 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args + * @throws UnderflowException + * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/biome/SetBiomeCommand.php b/src/xenialdan/MagicWE2/commands/biome/SetBiomeCommand.php index d7d0219f..71d9256d 100644 --- a/src/xenialdan/MagicWE2/commands/biome/SetBiomeCommand.php +++ b/src/xenialdan/MagicWE2/commands/biome/SetBiomeCommand.php @@ -12,6 +12,7 @@ use pocketmine\command\CommandSender; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; +use UnderflowException; use xenialdan\MagicWE2\API; use xenialdan\MagicWE2\exception\SelectionException; use xenialdan\MagicWE2\exception\SessionException; @@ -38,6 +39,7 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args + * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/brush/BrushCommand.php b/src/xenialdan/MagicWE2/commands/brush/BrushCommand.php index 89d8d708..94c04cf7 100644 --- a/src/xenialdan/MagicWE2/commands/brush/BrushCommand.php +++ b/src/xenialdan/MagicWE2/commands/brush/BrushCommand.php @@ -11,6 +11,7 @@ use pocketmine\command\CommandSender; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; +use UnderflowException; use xenialdan\customui\elements\Button; use xenialdan\customui\elements\Label; use xenialdan\customui\elements\Toggle; @@ -39,6 +40,7 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args + * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/brush/BrushNameCommand.php b/src/xenialdan/MagicWE2/commands/brush/BrushNameCommand.php index 482a42ac..f2152886 100644 --- a/src/xenialdan/MagicWE2/commands/brush/BrushNameCommand.php +++ b/src/xenialdan/MagicWE2/commands/brush/BrushNameCommand.php @@ -12,6 +12,7 @@ use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; use TypeError; +use UnderflowException; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\SessionHelper; use xenialdan\MagicWE2\Loader; @@ -34,6 +35,7 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args + * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/clipboard/ClearClipboardCommand.php b/src/xenialdan/MagicWE2/commands/clipboard/ClearClipboardCommand.php index cc782867..8493ea48 100644 --- a/src/xenialdan/MagicWE2/commands/clipboard/ClearClipboardCommand.php +++ b/src/xenialdan/MagicWE2/commands/clipboard/ClearClipboardCommand.php @@ -10,6 +10,7 @@ use pocketmine\command\CommandSender; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; +use UnderflowException; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\SessionHelper; use xenialdan\MagicWE2\Loader; @@ -31,6 +32,7 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args + * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/clipboard/CopyCommand.php b/src/xenialdan/MagicWE2/commands/clipboard/CopyCommand.php index b006a33a..39c4823d 100644 --- a/src/xenialdan/MagicWE2/commands/clipboard/CopyCommand.php +++ b/src/xenialdan/MagicWE2/commands/clipboard/CopyCommand.php @@ -12,6 +12,7 @@ use pocketmine\command\CommandSender; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; +use UnderflowException; use xenialdan\MagicWE2\API; use xenialdan\MagicWE2\exception\SelectionException; use xenialdan\MagicWE2\exception\SessionException; @@ -36,6 +37,7 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args + * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/clipboard/Cut2Command.php b/src/xenialdan/MagicWE2/commands/clipboard/Cut2Command.php index 7dc16cec..ad9b1511 100644 --- a/src/xenialdan/MagicWE2/commands/clipboard/Cut2Command.php +++ b/src/xenialdan/MagicWE2/commands/clipboard/Cut2Command.php @@ -13,6 +13,7 @@ use pocketmine\player\Player; use pocketmine\Server; use pocketmine\utils\TextFormat as TF; +use UnderflowException; use xenialdan\MagicWE2\exception\SelectionException; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\BlockPalette; @@ -40,6 +41,7 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args + * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/clipboard/CutCommand.php b/src/xenialdan/MagicWE2/commands/clipboard/CutCommand.php index 16a56bc0..29810bd5 100644 --- a/src/xenialdan/MagicWE2/commands/clipboard/CutCommand.php +++ b/src/xenialdan/MagicWE2/commands/clipboard/CutCommand.php @@ -12,6 +12,7 @@ use pocketmine\command\CommandSender; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; +use UnderflowException; use xenialdan\MagicWE2\API; use xenialdan\MagicWE2\exception\SelectionException; use xenialdan\MagicWE2\exception\SessionException; @@ -37,6 +38,7 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args + * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/clipboard/FlipCommand.php b/src/xenialdan/MagicWE2/commands/clipboard/FlipCommand.php index 40fdc672..9e4a011c 100644 --- a/src/xenialdan/MagicWE2/commands/clipboard/FlipCommand.php +++ b/src/xenialdan/MagicWE2/commands/clipboard/FlipCommand.php @@ -12,6 +12,7 @@ use pocketmine\player\Player; use pocketmine\Server; use pocketmine\utils\TextFormat as TF; +use UnderflowException; use xenialdan\MagicWE2\clipboard\SingleClipboard; use xenialdan\MagicWE2\commands\args\MirrorAxisArgument; use xenialdan\MagicWE2\exception\SessionException; @@ -39,6 +40,7 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args + * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/clipboard/PasteCommand.php b/src/xenialdan/MagicWE2/commands/clipboard/PasteCommand.php index e3660ddd..3d840dbf 100644 --- a/src/xenialdan/MagicWE2/commands/clipboard/PasteCommand.php +++ b/src/xenialdan/MagicWE2/commands/clipboard/PasteCommand.php @@ -13,6 +13,7 @@ use pocketmine\player\Player; use pocketmine\utils\AssumptionFailedError; use pocketmine\utils\TextFormat as TF; +use UnderflowException; use xenialdan\MagicWE2\API; use xenialdan\MagicWE2\clipboard\SingleClipboard; use xenialdan\MagicWE2\exception\SelectionException; @@ -39,6 +40,7 @@ protected function prepare(): void * @param string $aliasUsed * @param mixed[] $args * @throws AssumptionFailedError + * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/clipboard/RotateCommand.php b/src/xenialdan/MagicWE2/commands/clipboard/RotateCommand.php index bb624bcf..1e3bdbe9 100644 --- a/src/xenialdan/MagicWE2/commands/clipboard/RotateCommand.php +++ b/src/xenialdan/MagicWE2/commands/clipboard/RotateCommand.php @@ -13,6 +13,7 @@ use pocketmine\player\Player; use pocketmine\Server; use pocketmine\utils\TextFormat as TF; +use UnderflowException; use xenialdan\MagicWE2\clipboard\SingleClipboard; use xenialdan\MagicWE2\commands\args\RotateAngleArgument; use xenialdan\MagicWE2\exception\SessionException; @@ -40,6 +41,7 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args + * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { @@ -57,7 +59,7 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo /** @var Player $sender */ try { $angle = (int)$args["angle"]; - $aroundOrigin = $args["aroundOrigin"] ?? true; + //$aroundOrigin = $args["aroundOrigin"] ?? true; $sender->sendMessage(Loader::PREFIX . $lang->translateString('command.rotate.try', [$angle])); $session = SessionHelper::getUserSession($sender); if (is_null($session)) { diff --git a/src/xenialdan/MagicWE2/commands/debug/PlaceAllBlockstatesCommand.php b/src/xenialdan/MagicWE2/commands/debug/PlaceAllBlockstatesCommand.php index a213c2a9..dee44ef2 100644 --- a/src/xenialdan/MagicWE2/commands/debug/PlaceAllBlockstatesCommand.php +++ b/src/xenialdan/MagicWE2/commands/debug/PlaceAllBlockstatesCommand.php @@ -10,6 +10,7 @@ use pocketmine\command\CommandSender; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; +use UnderflowException; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\BlockStatesParser; use xenialdan\MagicWE2\helper\SessionHelper; @@ -30,6 +31,7 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args + * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/generation/CylinderCommand.php b/src/xenialdan/MagicWE2/commands/generation/CylinderCommand.php index 500b49cc..a6fe6a0e 100644 --- a/src/xenialdan/MagicWE2/commands/generation/CylinderCommand.php +++ b/src/xenialdan/MagicWE2/commands/generation/CylinderCommand.php @@ -12,8 +12,8 @@ use InvalidArgumentException; use pocketmine\command\CommandSender; use pocketmine\player\Player; -use pocketmine\utils\AssumptionFailedError; use pocketmine\utils\TextFormat as TF; +use UnderflowException; use xenialdan\MagicWE2\API; use xenialdan\MagicWE2\commands\args\BlocksArgument; use xenialdan\MagicWE2\exception\SessionException; @@ -42,7 +42,7 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args - * @throws AssumptionFailedError + * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/history/ClearhistoryCommand.php b/src/xenialdan/MagicWE2/commands/history/ClearhistoryCommand.php index 6fd92d1e..211dc52a 100644 --- a/src/xenialdan/MagicWE2/commands/history/ClearhistoryCommand.php +++ b/src/xenialdan/MagicWE2/commands/history/ClearhistoryCommand.php @@ -10,6 +10,7 @@ use pocketmine\command\CommandSender; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; +use UnderflowException; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\SessionHelper; use xenialdan\MagicWE2\Loader; @@ -31,6 +32,7 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args + * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/history/RedoCommand.php b/src/xenialdan/MagicWE2/commands/history/RedoCommand.php index 937e5efd..5aca3343 100644 --- a/src/xenialdan/MagicWE2/commands/history/RedoCommand.php +++ b/src/xenialdan/MagicWE2/commands/history/RedoCommand.php @@ -10,6 +10,7 @@ use pocketmine\command\CommandSender; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; +use UnderflowException; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\SessionHelper; use xenialdan\MagicWE2\Loader; @@ -31,6 +32,7 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args + * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/history/UndoCommand.php b/src/xenialdan/MagicWE2/commands/history/UndoCommand.php index da8476dc..a0857188 100644 --- a/src/xenialdan/MagicWE2/commands/history/UndoCommand.php +++ b/src/xenialdan/MagicWE2/commands/history/UndoCommand.php @@ -10,6 +10,7 @@ use pocketmine\command\CommandSender; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; +use UnderflowException; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\SessionHelper; use xenialdan\MagicWE2\Loader; @@ -31,6 +32,7 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args + * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/region/OverlayCommand.php b/src/xenialdan/MagicWE2/commands/region/OverlayCommand.php index a8069582..cfa10393 100644 --- a/src/xenialdan/MagicWE2/commands/region/OverlayCommand.php +++ b/src/xenialdan/MagicWE2/commands/region/OverlayCommand.php @@ -11,6 +11,7 @@ use pocketmine\command\CommandSender; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; +use UnderflowException; use xenialdan\MagicWE2\commands\args\BlocksArgument; use xenialdan\MagicWE2\exception\SelectionException; use xenialdan\MagicWE2\exception\SessionException; @@ -35,6 +36,7 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args + * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/region/ReplaceCommand.php b/src/xenialdan/MagicWE2/commands/region/ReplaceCommand.php index bac9bf73..e56c94ca 100644 --- a/src/xenialdan/MagicWE2/commands/region/ReplaceCommand.php +++ b/src/xenialdan/MagicWE2/commands/region/ReplaceCommand.php @@ -12,6 +12,7 @@ use pocketmine\command\CommandSender; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; +use UnderflowException; use xenialdan\MagicWE2\API; use xenialdan\MagicWE2\commands\args\BlocksArgument; use xenialdan\MagicWE2\exception\SelectionException; @@ -39,6 +40,7 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args + * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/region/SetCommand.php b/src/xenialdan/MagicWE2/commands/region/SetCommand.php index bca8b276..24a14c76 100644 --- a/src/xenialdan/MagicWE2/commands/region/SetCommand.php +++ b/src/xenialdan/MagicWE2/commands/region/SetCommand.php @@ -12,6 +12,7 @@ use pocketmine\command\CommandSender; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; +use UnderflowException; use xenialdan\MagicWE2\API; use xenialdan\MagicWE2\commands\args\BlocksArgument; use xenialdan\MagicWE2\exception\SelectionException; @@ -38,6 +39,7 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args + * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/selection/ChunkCommand.php b/src/xenialdan/MagicWE2/commands/selection/ChunkCommand.php index 7aac45f6..6e39b406 100644 --- a/src/xenialdan/MagicWE2/commands/selection/ChunkCommand.php +++ b/src/xenialdan/MagicWE2/commands/selection/ChunkCommand.php @@ -14,6 +14,7 @@ use pocketmine\utils\TextFormat as TF; use pocketmine\world\Position; use pocketmine\world\World; +use UnderflowException; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\SessionHelper; use xenialdan\MagicWE2\Loader; @@ -36,6 +37,7 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args + * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/selection/HPos1Command.php b/src/xenialdan/MagicWE2/commands/selection/HPos1Command.php index bcfdcc69..af283cd5 100644 --- a/src/xenialdan/MagicWE2/commands/selection/HPos1Command.php +++ b/src/xenialdan/MagicWE2/commands/selection/HPos1Command.php @@ -11,6 +11,7 @@ use pocketmine\command\CommandSender; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; +use UnderflowException; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\SessionHelper; use xenialdan\MagicWE2\Loader; @@ -33,6 +34,7 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args + * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/selection/HPos2Command.php b/src/xenialdan/MagicWE2/commands/selection/HPos2Command.php index a217a941..d7c4b271 100644 --- a/src/xenialdan/MagicWE2/commands/selection/HPos2Command.php +++ b/src/xenialdan/MagicWE2/commands/selection/HPos2Command.php @@ -11,6 +11,7 @@ use pocketmine\command\CommandSender; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; +use UnderflowException; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\SessionHelper; use xenialdan\MagicWE2\Loader; @@ -33,6 +34,7 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args + * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/selection/Pos1Command.php b/src/xenialdan/MagicWE2/commands/selection/Pos1Command.php index b95a1bef..148d48c7 100644 --- a/src/xenialdan/MagicWE2/commands/selection/Pos1Command.php +++ b/src/xenialdan/MagicWE2/commands/selection/Pos1Command.php @@ -11,6 +11,7 @@ use pocketmine\command\CommandSender; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; +use UnderflowException; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\SessionHelper; use xenialdan\MagicWE2\Loader; @@ -33,6 +34,7 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args + * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/selection/Pos2Command.php b/src/xenialdan/MagicWE2/commands/selection/Pos2Command.php index d3e2d781..7b53c9ea 100644 --- a/src/xenialdan/MagicWE2/commands/selection/Pos2Command.php +++ b/src/xenialdan/MagicWE2/commands/selection/Pos2Command.php @@ -11,6 +11,7 @@ use pocketmine\command\CommandSender; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; +use UnderflowException; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\SessionHelper; use xenialdan\MagicWE2\Loader; @@ -33,6 +34,7 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args + * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/selection/info/CountCommand.php b/src/xenialdan/MagicWE2/commands/selection/info/CountCommand.php index ba220907..960616a6 100644 --- a/src/xenialdan/MagicWE2/commands/selection/info/CountCommand.php +++ b/src/xenialdan/MagicWE2/commands/selection/info/CountCommand.php @@ -13,6 +13,7 @@ use pocketmine\player\Player; use pocketmine\Server; use pocketmine\utils\TextFormat as TF; +use UnderflowException; use xenialdan\MagicWE2\commands\args\BlocksArgument; use xenialdan\MagicWE2\exception\SelectionException; use xenialdan\MagicWE2\exception\SessionException; @@ -41,6 +42,7 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args + * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/selection/info/ListChunksCommand.php b/src/xenialdan/MagicWE2/commands/selection/info/ListChunksCommand.php index c5de7b0d..59d3a216 100644 --- a/src/xenialdan/MagicWE2/commands/selection/info/ListChunksCommand.php +++ b/src/xenialdan/MagicWE2/commands/selection/info/ListChunksCommand.php @@ -12,6 +12,7 @@ use pocketmine\utils\TextFormat as TF; use pocketmine\world\format\io\FastChunkSerializer; use pocketmine\world\World; +use UnderflowException; use xenialdan\MagicWE2\exception\SelectionException; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\SessionHelper; @@ -33,6 +34,7 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args + * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/selection/info/SizeCommand.php b/src/xenialdan/MagicWE2/commands/selection/info/SizeCommand.php index 4c1e0b04..f99953a0 100644 --- a/src/xenialdan/MagicWE2/commands/selection/info/SizeCommand.php +++ b/src/xenialdan/MagicWE2/commands/selection/info/SizeCommand.php @@ -10,6 +10,7 @@ use pocketmine\command\CommandSender; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; +use UnderflowException; use xenialdan\MagicWE2\exception\SelectionException; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\SessionHelper; @@ -31,6 +32,7 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args + * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/tool/DebugCommand.php b/src/xenialdan/MagicWE2/commands/tool/DebugCommand.php index 1a0f544e..860b9153 100644 --- a/src/xenialdan/MagicWE2/commands/tool/DebugCommand.php +++ b/src/xenialdan/MagicWE2/commands/tool/DebugCommand.php @@ -15,6 +15,7 @@ use pocketmine\nbt\tag\CompoundTag; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; +use UnderflowException; use xenialdan\MagicWE2\API; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\SessionHelper; @@ -36,6 +37,7 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args + * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/tool/ToggledebugCommand.php b/src/xenialdan/MagicWE2/commands/tool/ToggledebugCommand.php index ddfa6c8b..60546d06 100644 --- a/src/xenialdan/MagicWE2/commands/tool/ToggledebugCommand.php +++ b/src/xenialdan/MagicWE2/commands/tool/ToggledebugCommand.php @@ -10,6 +10,7 @@ use pocketmine\command\CommandSender; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; +use UnderflowException; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\SessionHelper; use xenialdan\MagicWE2\Loader; @@ -29,6 +30,7 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args + * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/tool/TogglewandCommand.php b/src/xenialdan/MagicWE2/commands/tool/TogglewandCommand.php index 053e18d9..84a3a18e 100644 --- a/src/xenialdan/MagicWE2/commands/tool/TogglewandCommand.php +++ b/src/xenialdan/MagicWE2/commands/tool/TogglewandCommand.php @@ -10,6 +10,7 @@ use pocketmine\command\CommandSender; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; +use UnderflowException; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\SessionHelper; use xenialdan\MagicWE2\Loader; @@ -29,6 +30,7 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args + * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/tool/WandCommand.php b/src/xenialdan/MagicWE2/commands/tool/WandCommand.php index e9d7be49..d1cc3fd6 100644 --- a/src/xenialdan/MagicWE2/commands/tool/WandCommand.php +++ b/src/xenialdan/MagicWE2/commands/tool/WandCommand.php @@ -16,6 +16,7 @@ use pocketmine\nbt\tag\CompoundTag; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; +use UnderflowException; use xenialdan\MagicWE2\API; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\SessionHelper; @@ -37,6 +38,7 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args + * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/utility/CalculateCommand.php b/src/xenialdan/MagicWE2/commands/utility/CalculateCommand.php index d8687873..3ec5d2e4 100644 --- a/src/xenialdan/MagicWE2/commands/utility/CalculateCommand.php +++ b/src/xenialdan/MagicWE2/commands/utility/CalculateCommand.php @@ -12,6 +12,7 @@ use pocketmine\command\CommandSender; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; +use UnderflowException; use xenialdan\MagicWE2\API; use xenialdan\MagicWE2\exception\CalculationException; use xenialdan\MagicWE2\exception\SessionException; @@ -36,6 +37,7 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args + * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/utility/ToggleWailaCommand.php b/src/xenialdan/MagicWE2/commands/utility/ToggleWailaCommand.php index 691ea30f..850bde3f 100644 --- a/src/xenialdan/MagicWE2/commands/utility/ToggleWailaCommand.php +++ b/src/xenialdan/MagicWE2/commands/utility/ToggleWailaCommand.php @@ -10,6 +10,7 @@ use pocketmine\command\CommandSender; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; +use UnderflowException; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\SessionHelper; use xenialdan\MagicWE2\Loader; @@ -29,6 +30,7 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args + * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/event/MWEEditEvent.php b/src/xenialdan/MagicWE2/event/MWEEditEvent.php index 004b011e..cd075d2f 100644 --- a/src/xenialdan/MagicWE2/event/MWEEditEvent.php +++ b/src/xenialdan/MagicWE2/event/MWEEditEvent.php @@ -15,11 +15,11 @@ class MWEEditEvent extends MWEEvent implements Cancellable use CancellableTrait; /** @var Block[] */ - private $oldBlocks; + private array $oldBlocks; /** @var Block[] */ - private $newBlocks; + private array $newBlocks; /** @var null|Session */ - private $session; + private ?Session $session; /** * MWEEditEvent constructor. diff --git a/src/xenialdan/MagicWE2/event/MWESelectionChangeEvent.php b/src/xenialdan/MagicWE2/event/MWESelectionChangeEvent.php index 6fa42f2f..fad29fe1 100644 --- a/src/xenialdan/MagicWE2/event/MWESelectionChangeEvent.php +++ b/src/xenialdan/MagicWE2/event/MWESelectionChangeEvent.php @@ -19,7 +19,7 @@ class MWESelectionChangeEvent extends MWEEvent public const TYPE_SHAPE = 4; private Selection $selection; - private ?Session $session; + private ?Session $session = null; private int $type; public function __construct(Selection $selection, int $type) diff --git a/src/xenialdan/MagicWE2/event/MWESessionLoadEvent.php b/src/xenialdan/MagicWE2/event/MWESessionLoadEvent.php index 3bc922a2..3995844f 100644 --- a/src/xenialdan/MagicWE2/event/MWESessionLoadEvent.php +++ b/src/xenialdan/MagicWE2/event/MWESessionLoadEvent.php @@ -10,7 +10,7 @@ class MWESessionLoadEvent extends MWEEvent { /** @var Session */ - private $session; + private Session $session; /** * MWESessionLoadEvent constructor. diff --git a/src/xenialdan/MagicWE2/helper/AsyncChunkManager.php b/src/xenialdan/MagicWE2/helper/AsyncChunkManager.php index d05e0d1f..906b138c 100644 --- a/src/xenialdan/MagicWE2/helper/AsyncChunkManager.php +++ b/src/xenialdan/MagicWE2/helper/AsyncChunkManager.php @@ -4,6 +4,7 @@ use pocketmine\world\format\Chunk; use pocketmine\world\SimpleChunkManager; +use pocketmine\world\World; class AsyncChunkManager extends SimpleChunkManager { @@ -20,4 +21,9 @@ public function getChunks(): array { return $this->chunks; } + + public function getWorldHeight(): int + { + return World::Y_MAX; + } } \ No newline at end of file diff --git a/src/xenialdan/MagicWE2/helper/BlockEntry.php b/src/xenialdan/MagicWE2/helper/BlockEntry.php index 0f4de47c..56113fe4 100644 --- a/src/xenialdan/MagicWE2/helper/BlockEntry.php +++ b/src/xenialdan/MagicWE2/helper/BlockEntry.php @@ -12,9 +12,9 @@ class BlockEntry { /** @var int BlockFullId */ - public $fullId; + public int $fullId; /** @var CompoundTag|null */ - public $nbt; + public ?CompoundTag $nbt = null; /** * BlockEntry constructor. @@ -29,10 +29,10 @@ public function __construct(int $fullId, ?CompoundTag $nbt = null) public function validate(): bool { - /** @var BlockFactory $instance */ $instance = BlockFactory::getInstance(); $block = $instance->fromFullBlock($this->fullId); - [$id, $meta] = [$block->getId(), $block->getMeta()]; + //[$id, $meta] = [$block->getId(), $block->getMeta()]; + $id = $block->getId(); if ($id === BlockLegacyIds::INFO_UPDATE) { return false; } @@ -41,7 +41,6 @@ public function validate(): bool public function __toString() { - /** @var BlockFactory $instance */ $instance = BlockFactory::getInstance(); $block = $instance->fromFullBlock($this->fullId); $str = __CLASS__ . " " . $this->fullId . " [{$block->getId()}:{$block->getMeta()}]"; @@ -53,7 +52,6 @@ public function __toString() public function toBlock(): Block { - /** @var BlockFactory $instance */ $instance = BlockFactory::getInstance(); return $instance->fromFullBlock($this->fullId); } diff --git a/src/xenialdan/MagicWE2/helper/BlockPalette.php b/src/xenialdan/MagicWE2/helper/BlockPalette.php index 34e57bdd..f2941833 100644 --- a/src/xenialdan/MagicWE2/helper/BlockPalette.php +++ b/src/xenialdan/MagicWE2/helper/BlockPalette.php @@ -7,7 +7,6 @@ use Generator; use InvalidArgumentException; use JsonException; -use pocketmine\block\Block; use pocketmine\block\BlockFactory; use pocketmine\block\utils\InvalidBlockStateException; use xenialdan\MagicWE2\exception\BlockQueryAlreadyParsedException; @@ -65,13 +64,12 @@ public function addBlockQuery(BlockQuery $query): void /** * @param int $amount - * @return Generator|Block[] + * @return Generator * @throws InvalidArgumentException */ public function blocks(int $amount = 1): Generator { if ($amount < 1) throw new InvalidArgumentException('$amount must be greater than 0'); - /** @var BlockFactory $blockFactory */ $blockFactory = BlockFactory::getInstance(); /** @var BlockQuery $blockQuery */ foreach ($this->randomBlockQueries->generate($amount) as $blockQuery) {//TODO yield from? @@ -80,11 +78,10 @@ public function blocks(int $amount = 1): Generator } /** - * @return Generator|Block[] + * @return Generator */ public function palette(): Generator { - /** @var BlockFactory $blockFactory */ $blockFactory = BlockFactory::getInstance(); /** @var BlockQuery $blockQuery */ foreach ($this->randomBlockQueries->indexes() as $blockQuery) {//TODO yield from? @@ -123,7 +120,6 @@ public function encode(): string public static function decode(string $blocks): array { $e = []; - /** @var BlockFactory $blockFactory */ $blockFactory = BlockFactory::getInstance(); foreach (json_decode($blocks, true, 512, JSON_THROW_ON_ERROR) as $block) $e[] = $blockFactory->fromFullBlock($block); diff --git a/src/xenialdan/MagicWE2/helper/BlockQuery.php b/src/xenialdan/MagicWE2/helper/BlockQuery.php index 9d62bd15..5934a391 100644 --- a/src/xenialdan/MagicWE2/helper/BlockQuery.php +++ b/src/xenialdan/MagicWE2/helper/BlockQuery.php @@ -11,12 +11,12 @@ final class BlockQuery { public string $query; - public ?string $fullBlockQuery; - public ?string $blockId; - public ?string $blockStatesQuery; - public ?string $fullExtraQuery; + public ?string $fullBlockQuery = null; + public ?string $blockId = null; + public ?string $blockStatesQuery = null; + public ?string $fullExtraQuery = null; public float $weight;//TODO check which are optional - public ?int $blockFullId; + public ?int $blockFullId = null; /** * BlockQuery constructor. @@ -48,7 +48,6 @@ public function parse(bool $update = true): self { //calling methods should check with hasBlock() before parse() if (!$update && $this->hasBlock()) throw new BlockQueryAlreadyParsedException("FullBlockID is already parsed"); - /** @var BlockStatesParser $blockstateParser */ $blockstateParser = BlockStatesParser::getInstance(); $blockstateParser::fromString($this);//this should already set the blockFullId because it is a reference //var_dump($this->hasBlock() ? "Has block, " . $this->blockFullId : "Does not have block"); diff --git a/src/xenialdan/MagicWE2/helper/BlockStatesEntry.php b/src/xenialdan/MagicWE2/helper/BlockStatesEntry.php index 19fdc2c1..07af77a6 100644 --- a/src/xenialdan/MagicWE2/helper/BlockStatesEntry.php +++ b/src/xenialdan/MagicWE2/helper/BlockStatesEntry.php @@ -15,19 +15,20 @@ use pocketmine\utils\TextFormat; use RuntimeException; use Throwable; +use xenialdan\MagicWE2\exception\BlockQueryAlreadyParsedException; use xenialdan\MagicWE2\exception\InvalidBlockStateException; use xenialdan\MagicWE2\task\action\FlipAction; class BlockStatesEntry { /** @var string */ - public $blockIdentifier; + public string $blockIdentifier; /** @var CompoundTag */ - public $blockStates; + public CompoundTag $blockStates; /** @var string */ - public $blockFull; + public string $blockFull; /** @var Block|null */ - public $block; + public ?Block $block = null; /** * BlockStatesEntry constructor. @@ -63,8 +64,8 @@ public function __toString() * TODO hacky AF. clean up * @return Block * @throws InvalidArgumentException - * @throws RuntimeException - * @throws InvalidBlockStateException + * @throws \pocketmine\block\utils\InvalidBlockStateException + * @throws BlockQueryAlreadyParsedException */ public function toBlock(): Block { @@ -90,7 +91,6 @@ public function rotate(int $amount): BlockStatesEntry $block = $clone->toBlock(); $idMapName = str_replace("minecraft:", "", BlockStatesParser::getBlockIdMapName($block)); $key = $idMapName . ":" . $block->getMeta(); - /** @var BlockStatesParser $blockstateParser */ $blockstateParser = BlockStatesParser::getInstance(); if (strpos($idMapName, "_door") !== false) { $fromMap = $blockstateParser::getDoorRotationFlipMap()[$block->getMeta()] ?? null; diff --git a/src/xenialdan/MagicWE2/helper/BlockStatesParser.php b/src/xenialdan/MagicWE2/helper/BlockStatesParser.php index d1a3b0eb..840891dc 100644 --- a/src/xenialdan/MagicWE2/helper/BlockStatesParser.php +++ b/src/xenialdan/MagicWE2/helper/BlockStatesParser.php @@ -42,26 +42,26 @@ final class BlockStatesParser use SingletonTrait; /** @var string */ - public static $rotPath; + public static string $rotPath = ""; /** @var string */ - public static $doorRotPath; + public static string $doorRotPath = ""; /** @var R12ToCurrentBlockMapEntry[][] *///TODO check type correct? phpstan! - private static $legacyStateMap; + private static array $legacyStateMap; /** @var array */ - private static $aliasMap = []; + private static array $aliasMap = []; /** @var array */ - private static $rotationFlipMap = []; + private static array $rotationFlipMap = []; /** @var array */ - private static $doorRotationFlipMap = []; + private static array $doorRotationFlipMap = []; private function __construct() { -// $this->loadRotationAndFlipData(Loader::getRotFlipPath()); -// $this->loadDoorRotationAndFlipData(Loader::getDoorRotFlipPath()); - $this->loadRotationAndFlipData(self::$rotPath); - $this->loadDoorRotationAndFlipData(self::$doorRotPath); + $this->loadRotationAndFlipData(Loader::getRotFlipPath()); + $this->loadDoorRotationAndFlipData(Loader::getDoorRotFlipPath()); + //$this->loadRotationAndFlipData(self::$rotPath); + //$this->loadDoorRotationAndFlipData(self::$doorRotPath); $this->loadLegacyMappings(); } @@ -198,7 +198,6 @@ public static function fromString(BlockQuery $query): Block $namespacedSelectedBlockName = strpos($query->blockId, "minecraft:") === false ? "minecraft:" . $query->blockId : $query->blockId; $selectedBlockName = strtolower(str_replace("minecraft:", "", $namespacedSelectedBlockName));//TODO try to keep namespace "minecraft:" to support custom blocks - /** @var LegacyStringToItemParser $legacyStringToItemParser */ $legacyStringToItemParser = LegacyStringToItemParser::getInstance(); $block = $legacyStringToItemParser->parse($selectedBlockName)->getBlock(); //no states, just block @@ -269,7 +268,6 @@ public static function fromString(BlockQuery $query): Block foreach (self::$legacyStateMap[$namespacedSelectedBlockName] as $meta => $r12ToCurrentBlockMapEntry) { $clonedPrintedCompound = clone $r12ToCurrentBlockMapEntry->getBlockState()->getCompoundTag('states'); if ($clonedPrintedCompound->equals($finalStatesList)) { - /** @var BlockFactory $blockFactory */ $blockFactory = BlockFactory::getInstance(); $block = $blockFactory->get($block->getId(), $meta & 0xf); $blocks[] = $block; @@ -340,7 +338,6 @@ public static function printStates(BlockStatesEntry $entry, bool $skipDefaults): $blockIdentifier = $entry->blockIdentifier; $s = []; foreach ($printedCompound as $statesTagEntryName => $statesTagEntry) { - /** @var CompoundTag $defaultStatesNamedTag */ $defaultStatesNamedTag = self::getDefaultStates($blockIdentifier); $namedTag = $defaultStatesNamedTag->getTag($statesTagEntryName); if (!$namedTag instanceof ByteTag && !$namedTag instanceof StringTag && !$namedTag instanceof IntTag) { @@ -451,7 +448,6 @@ public static function runTests(): void } //return;//TODO //test flip+rotation - /** @noinspection PhpUnreachableStatementInspection */ // $tests2 = [ // #"minecraft:wooden_slab[wood_type=oak]", // #"minecraft:wooden_slab[wood_type=spruce,top_slot_bit=true]", diff --git a/src/xenialdan/MagicWE2/helper/Progress.php b/src/xenialdan/MagicWE2/helper/Progress.php index fc67e892..31f1669c 100644 --- a/src/xenialdan/MagicWE2/helper/Progress.php +++ b/src/xenialdan/MagicWE2/helper/Progress.php @@ -7,9 +7,9 @@ class Progress { /** @var float Percentage */ - public $progress = 0.0; + public float $progress = 0.0; /** @var string */ - public $string = ""; + public string $string = ""; /** * Progress constructor. diff --git a/src/xenialdan/MagicWE2/helper/SessionHelper.php b/src/xenialdan/MagicWE2/helper/SessionHelper.php index 3b70bd24..6deae164 100644 --- a/src/xenialdan/MagicWE2/helper/SessionHelper.php +++ b/src/xenialdan/MagicWE2/helper/SessionHelper.php @@ -8,17 +8,18 @@ use Exception; use InvalidArgumentException; use JsonException; +use OutOfBoundsException; use pocketmine\entity\InvalidSkinException; use pocketmine\entity\Skin; use pocketmine\math\Vector3; use pocketmine\player\Player; use pocketmine\plugin\Plugin; use pocketmine\Server; -use pocketmine\utils\AssumptionFailedError; use pocketmine\utils\TextFormat as TF; use Ramsey\Uuid\Rfc4122\UuidV4; use Ramsey\Uuid\UuidInterface; use RuntimeException; +use UnderflowException; use xenialdan\MagicWE2\event\MWESessionLoadEvent; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\Loader; @@ -33,9 +34,9 @@ class SessionHelper { /** @var Map */ - private static $userSessions; + private static Map $userSessions; /** @var Map */ - private static $pluginSessions; + private static Map $pluginSessions; public static function init(): void { @@ -68,6 +69,7 @@ public static function addSession(Session $session): void * @param Session $session * @param bool $save * @throws JsonException + * @throws OutOfBoundsException */ public static function destroySession(Session $session, bool $save = true): void { @@ -117,6 +119,7 @@ public static function createPluginSession(Plugin $plugin, bool $add = true): Pl /** * @param Player $player * @return bool + * @throws UnderflowException */ public static function hasSession(Player $player): bool { @@ -131,6 +134,7 @@ public static function hasSession(Player $player): bool * @param Player $player * @return null|UserSession * @throws SessionException + * @throws UnderflowException */ public static function getUserSession(Player $player): ?UserSession { @@ -148,6 +152,8 @@ public static function getUserSession(Player $player): ?UserSession * @param UuidInterface $uuid * @return null|Session * @throws SessionException + * @throws OutOfBoundsException + * @throws UnderflowException */ public static function getSessionByUUID(UuidInterface $uuid): ?Session { @@ -176,7 +182,7 @@ public static function getSessionByUUID(UuidInterface $uuid): ?Session } /** - * @return array|UserSession[] + * @return array */ public static function getUserSessions(): array { @@ -184,7 +190,7 @@ public static function getUserSessions(): array } /** - * @return array|PluginSession[] + * @return array */ public static function getPluginSessions(): array { @@ -194,7 +200,6 @@ public static function getPluginSessions(): array /** * @param Player $player * @return UserSession|null - * @throws AssumptionFailedError * @throws InvalidSkinException * @throws JsonException * @throws RuntimeException diff --git a/src/xenialdan/MagicWE2/helper/StructureStore.php b/src/xenialdan/MagicWE2/helper/StructureStore.php index 969f7192..3d3a9211 100644 --- a/src/xenialdan/MagicWE2/helper/StructureStore.php +++ b/src/xenialdan/MagicWE2/helper/StructureStore.php @@ -6,7 +6,10 @@ use BlockHorizons\libschematic\Schematic; use InvalidArgumentException; +use pocketmine\nbt\NbtDataException; +use pocketmine\nbt\UnexpectedTagTypeException; use pocketmine\utils\SingletonTrait; +use UnexpectedValueException; use xenialdan\libstructure\exception\StructureFileException; use xenialdan\libstructure\exception\StructureFormatException; use xenialdan\libstructure\format\MCStructure; @@ -19,11 +22,11 @@ final class StructureStore /** * @var MCStructure[] */ - private $structures; + private array $structures; /** * @var Schematic[] */ - private $schematics; + private array $schematics; /** @noinspection MkdirRaceConditionInspection */ public function __construct() @@ -38,6 +41,9 @@ public function __construct() * @throws InvalidArgumentException * @throws StructureFileException * @throws StructureFormatException + * @throws UnexpectedValueException + * @throws NbtDataException + * @throws UnexpectedTagTypeException */ public function loadStructure(string $filename, bool $override = true): MCStructure { diff --git a/src/xenialdan/MagicWE2/helper/WeightedRandom.php b/src/xenialdan/MagicWE2/helper/WeightedRandom.php index d55607b0..74dffb79 100644 --- a/src/xenialdan/MagicWE2/helper/WeightedRandom.php +++ b/src/xenialdan/MagicWE2/helper/WeightedRandom.php @@ -14,16 +14,16 @@ class WeightedRandom { /** @var float[] */ - private $probabilities = []; + private array $probabilities = []; /** @var int[] */ - private $aliases; + private array $aliases; /** @var Random */ - private $random; + private Random $random; /** @var mixed[] */ - protected $indexes = []; + protected array $indexes = []; /** * @param mixed $value diff --git a/src/xenialdan/MagicWE2/selection/Selection.php b/src/xenialdan/MagicWE2/selection/Selection.php index 445f78e0..e024374a 100644 --- a/src/xenialdan/MagicWE2/selection/Selection.php +++ b/src/xenialdan/MagicWE2/selection/Selection.php @@ -6,6 +6,7 @@ use Exception; use JsonSerializable; +use OutOfBoundsException; use pocketmine\math\Vector3; use pocketmine\Server; use pocketmine\utils\AssumptionFailedError; @@ -16,6 +17,7 @@ use Ramsey\Uuid\UuidInterface; use RuntimeException; use Serializable; +use UnderflowException; use xenialdan\MagicWE2\event\MWESelectionChangeEvent; use xenialdan\MagicWE2\exception\SelectionException; use xenialdan\MagicWE2\exception\SessionException; @@ -31,28 +33,28 @@ class Selection implements Serializable, JsonSerializable { /** @var int|null */ - public $worldId; + public ?int $worldId = null; /** @var Vector3|null */ - public $pos1; + public ?Vector3 $pos1 = null; /** @var Vector3|null */ - public $pos2; + public ?Vector3 $pos2 = null; /** @var UuidInterface */ - public $uuid; + public UuidInterface $uuid; /** @var UuidInterface */ - public $sessionUUID; + public UuidInterface $sessionUUID; /** @var Shape|null */ - public $shape; + public ?Shape $shape = null; /** * Selection constructor. * @param UuidInterface $sessionUUID * @param World $world - * @param ?int $minX - * @param ?int $minY - * @param ?int $minZ - * @param ?int $maxX - * @param ?int $maxY - * @param ?int $maxZ + * @param null $minX + * @param null $minY + * @param null $minZ + * @param null $maxX + * @param null $maxY + * @param null $maxZ * @param ?Shape $shape */ public function __construct(UuidInterface $sessionUUID, World $world, $minX = null, $minY = null, $minZ = null, $maxX = null, $maxY = null, $maxZ = null, ?Shape $shape = null) @@ -112,6 +114,8 @@ public function getPos1(): Position /** * @param Position $position * @throws AssumptionFailedError + * @throws OutOfBoundsException + * @throws UnderflowException */ public function setPos1(Position $position): void { @@ -153,6 +157,8 @@ public function getPos2(): Position /** * @param Position $position * @throws AssumptionFailedError + * @throws OutOfBoundsException + * @throws UnderflowException */ public function setPos2(Position $position): void { diff --git a/src/xenialdan/MagicWE2/selection/shape/Cone.php b/src/xenialdan/MagicWE2/selection/shape/Cone.php index fdcd4e2c..add07904 100644 --- a/src/xenialdan/MagicWE2/selection/shape/Cone.php +++ b/src/xenialdan/MagicWE2/selection/shape/Cone.php @@ -4,7 +4,6 @@ use Exception; use Generator; -use pocketmine\block\Block; use pocketmine\block\BlockLegacyIds; use pocketmine\math\AxisAlignedBB; use pocketmine\math\Vector2; @@ -18,11 +17,11 @@ class Cone extends Shape { /** @var int */ - public $height = 5; + public int $height = 5; /** @var int */ - public $diameter = 5; + public int $diameter = 5; /** @var bool */ - public $flipped = false; + public bool $flipped = false; /** * Cone constructor. @@ -44,10 +43,10 @@ public function __construct(Vector3 $pasteVector, int $height, int $diameter, bo * @param World|AsyncChunkManager $manager The world or AsyncChunkManager * @param BlockPalette $filterblocks If not empty, applying a filter on the block list * @param int $flags - * @return Generator|Block[] + * @return Generator * @throws Exception */ - public function getBlocks($manager, BlockPalette $filterblocks, int $flags = API::FLAG_BASE): Generator + public function getBlocks(AsyncChunkManager|World $manager, BlockPalette $filterblocks, int $flags = API::FLAG_BASE): Generator { $this->validateChunkManager($manager); $reducePerLayer = ($this->diameter / $this->height); @@ -84,10 +83,10 @@ public function getBlocks($manager, BlockPalette $filterblocks, int $flags = API * Returns a flat layer of all included x z positions in selection * @param World|AsyncChunkManager $manager The world or AsyncChunkManager * @param int $flags - * @return Generator|Vector2[] + * @return Generator * @throws Exception */ - public function getLayer($manager, int $flags = API::FLAG_BASE): Generator + public function getLayer(AsyncChunkManager|World $manager, int $flags = API::FLAG_BASE): Generator { $this->validateChunkManager($manager); $centerVec2 = new Vector2($this->getPasteVector()->getX(), $this->getPasteVector()->getZ()); @@ -106,7 +105,7 @@ public function getLayer($manager, int $flags = API::FLAG_BASE): Generator * @return string[] fastSerialized chunks * @throws Exception */ - public function getTouchedChunks($manager): array + public function getTouchedChunks(AsyncChunkManager|World $manager): array {//TODO optimize to remove "corner" chunks $this->validateChunkManager($manager); $maxX = ($this->getMaxVec3()->x + 1) >> 4; diff --git a/src/xenialdan/MagicWE2/selection/shape/Cube.php b/src/xenialdan/MagicWE2/selection/shape/Cube.php index acc3779e..d14dc8b8 100644 --- a/src/xenialdan/MagicWE2/selection/shape/Cube.php +++ b/src/xenialdan/MagicWE2/selection/shape/Cube.php @@ -4,7 +4,6 @@ use Exception; use Generator; -use pocketmine\block\Block; use pocketmine\block\BlockLegacyIds; use pocketmine\math\AxisAlignedBB; use pocketmine\math\Vector2; @@ -18,7 +17,7 @@ class Cube extends Shape { /** @var int */ - public $width = 5; + public int $width = 5; public function __construct(Vector3 $pasteVector, int $width) { @@ -31,10 +30,10 @@ public function __construct(Vector3 $pasteVector, int $width) * @param World|AsyncChunkManager $manager The world or AsyncChunkManager * @param BlockPalette $filterblocks If not empty, applying a filter on the block list * @param int $flags - * @return Generator|Block[] + * @return Generator * @throws Exception */ - public function getBlocks($manager, BlockPalette $filterblocks, int $flags = API::FLAG_BASE): Generator + public function getBlocks(AsyncChunkManager|World $manager, BlockPalette $filterblocks, int $flags = API::FLAG_BASE): Generator { $this->validateChunkManager($manager); for ($x = (int)floor($this->getMinVec3()->x), $rx = 0; $x <= floor($this->getMaxVec3()->x); $x++, $rx++) { @@ -62,10 +61,10 @@ public function getBlocks($manager, BlockPalette $filterblocks, int $flags = API * Returns a flat layer of all included x z positions in selection * @param World|AsyncChunkManager $manager The world or AsyncChunkManager * @param int $flags - * @return Generator|Vector2[] + * @return Generator * @throws Exception */ - public function getLayer($manager, int $flags = API::FLAG_BASE): Generator + public function getLayer(AsyncChunkManager|World $manager, int $flags = API::FLAG_BASE): Generator { $this->validateChunkManager($manager); for ($x = (int)floor($this->getMinVec3()->x); $x <= floor($this->getMaxVec3()->x); $x++) { @@ -80,7 +79,7 @@ public function getLayer($manager, int $flags = API::FLAG_BASE): Generator * @return string[] fastSerialized chunks * @throws Exception */ - public function getTouchedChunks($manager): array + public function getTouchedChunks(AsyncChunkManager|World $manager): array { $this->validateChunkManager($manager); $maxX = ($this->getMaxVec3()->x + 1) >> 4; diff --git a/src/xenialdan/MagicWE2/selection/shape/Cuboid.php b/src/xenialdan/MagicWE2/selection/shape/Cuboid.php index 6189615a..9e2ef363 100644 --- a/src/xenialdan/MagicWE2/selection/shape/Cuboid.php +++ b/src/xenialdan/MagicWE2/selection/shape/Cuboid.php @@ -4,7 +4,6 @@ use Exception; use Generator; -use pocketmine\block\Block; use pocketmine\block\BlockLegacyIds; use pocketmine\math\AxisAlignedBB; use pocketmine\math\Vector2; @@ -18,11 +17,11 @@ class Cuboid extends Shape { /** @var int */ - public $width = 5; + public int $width = 5; /** @var int */ - public $height = 5; + public int $height = 5; /** @var int */ - public $depth = 5; + public int $depth = 5; /** * Cuboid constructor. @@ -52,10 +51,10 @@ public static function constructFromPositions(Vector3 $pos1, Vector3 $pos2): sel * @param World|AsyncChunkManager $manager The world or AsyncChunkManager * @param BlockPalette $filterblocks If not empty, applying a filter on the block list * @param int $flags - * @return Generator|Block[] + * @return Generator * @throws Exception */ - public function getBlocks($manager, BlockPalette $filterblocks, int $flags = API::FLAG_BASE): Generator + public function getBlocks(AsyncChunkManager|World $manager, BlockPalette $filterblocks, int $flags = API::FLAG_BASE): Generator { $this->validateChunkManager($manager); for ($x = (int)floor($this->getMinVec3()->x); $x <= floor($this->getMaxVec3()->x); $x++) { @@ -84,10 +83,10 @@ public function getBlocks($manager, BlockPalette $filterblocks, int $flags = API * Returns a flat layer of all included x z positions in selection * @param World|AsyncChunkManager $manager The world or AsyncChunkManager * @param int $flags - * @return Generator|Vector2[] + * @return Generator * @throws Exception */ - public function getLayer($manager, int $flags = API::FLAG_BASE): Generator + public function getLayer(AsyncChunkManager|World $manager, int $flags = API::FLAG_BASE): Generator { $this->validateChunkManager($manager); for ($x = (int)floor($this->getMinVec3()->x); $x <= floor($this->getMaxVec3()->x); $x++) { @@ -102,7 +101,7 @@ public function getLayer($manager, int $flags = API::FLAG_BASE): Generator * @return string[] fastSerialized chunks * @throws Exception */ - public function getTouchedChunks($manager): array + public function getTouchedChunks(AsyncChunkManager|World $manager): array { $this->validateChunkManager($manager); $maxX = ($this->getMaxVec3()->x + 1) >> 4; diff --git a/src/xenialdan/MagicWE2/selection/shape/Custom.php b/src/xenialdan/MagicWE2/selection/shape/Custom.php index efbc0987..f4dea198 100644 --- a/src/xenialdan/MagicWE2/selection/shape/Custom.php +++ b/src/xenialdan/MagicWE2/selection/shape/Custom.php @@ -4,7 +4,6 @@ use Exception; use Generator; -use pocketmine\block\Block; use pocketmine\math\AxisAlignedBB; use pocketmine\math\Vector2; use pocketmine\math\Vector3; @@ -17,7 +16,7 @@ class Custom extends Shape { /** @var Vector3[] */ - public $positions = []; + public array $positions = []; /** * Custom constructor. @@ -35,10 +34,10 @@ public function __construct(Vector3 $pasteVector, array $positions) * @param World|AsyncChunkManager $manager The world or AsyncChunkManager * @param BlockPalette $filterblocks If not empty, applying a filter on the block list * @param int $flags - * @return Generator|Block[] + * @return Generator * @throws Exception */ - public function getBlocks($manager, BlockPalette $filterblocks, int $flags = API::FLAG_BASE): Generator + public function getBlocks(AsyncChunkManager|World $manager, BlockPalette $filterblocks, int $flags = API::FLAG_BASE): Generator { $this->validateChunkManager($manager); foreach ($this->positions as $position) { @@ -51,10 +50,10 @@ public function getBlocks($manager, BlockPalette $filterblocks, int $flags = API * Returns a flat layer of all included x z positions in selection * @param World|AsyncChunkManager $manager The world or AsyncChunkManager * @param int $flags - * @return Generator|Vector2[] + * @return Generator * @throws Exception */ - public function getLayer($manager, int $flags = API::FLAG_BASE): Generator + public function getLayer(AsyncChunkManager|World $manager, int $flags = API::FLAG_BASE): Generator { $this->validateChunkManager($manager); /* Mapping: $walked[$hash]=true */ @@ -72,7 +71,7 @@ public function getLayer($manager, int $flags = API::FLAG_BASE): Generator * @return string[] fastSerialized chunks * @throws Exception */ - public function getTouchedChunks($manager): array + public function getTouchedChunks(AsyncChunkManager|World $manager): array { $this->validateChunkManager($manager); $touchedChunks = []; diff --git a/src/xenialdan/MagicWE2/selection/shape/Cylinder.php b/src/xenialdan/MagicWE2/selection/shape/Cylinder.php index c5b7a947..6bb200a2 100644 --- a/src/xenialdan/MagicWE2/selection/shape/Cylinder.php +++ b/src/xenialdan/MagicWE2/selection/shape/Cylinder.php @@ -4,7 +4,6 @@ use Exception; use Generator; -use pocketmine\block\Block; use pocketmine\block\BlockLegacyIds; use pocketmine\math\AxisAlignedBB; use pocketmine\math\Vector2; @@ -18,9 +17,9 @@ class Cylinder extends Shape { /** @var int */ - public $height = 1; + public int $height = 1; /** @var int */ - public $diameter = 5; + public int $diameter = 5; /** * Cylinder constructor. @@ -40,10 +39,10 @@ public function __construct(Vector3 $pasteVector, int $height, int $diameter) * @param World|AsyncChunkManager $manager The world or AsyncChunkManager * @param BlockPalette $filterblocks If not empty, applying a filter on the block list * @param int $flags - * @return Generator|Block[] + * @return Generator * @throws Exception */ - public function getBlocks($manager, BlockPalette $filterblocks, int $flags = API::FLAG_BASE): Generator + public function getBlocks(AsyncChunkManager|World $manager, BlockPalette $filterblocks, int $flags = API::FLAG_BASE): Generator { $this->validateChunkManager($manager); $centerVec2 = new Vector2($this->getPasteVector()->getX(), $this->getPasteVector()->getZ()); @@ -75,10 +74,10 @@ public function getBlocks($manager, BlockPalette $filterblocks, int $flags = API * Returns a flat layer of all included x z positions in selection * @param World|AsyncChunkManager $manager The world or AsyncChunkManager * @param int $flags - * @return Generator|Vector2[] + * @return Generator * @throws Exception */ - public function getLayer($manager, int $flags = API::FLAG_BASE): Generator + public function getLayer(AsyncChunkManager|World $manager, int $flags = API::FLAG_BASE): Generator { $this->validateChunkManager($manager); $centerVec2 = new Vector2($this->getPasteVector()->getX(), $this->getPasteVector()->getZ()); @@ -97,7 +96,7 @@ public function getLayer($manager, int $flags = API::FLAG_BASE): Generator * @return string[] fastSerialized chunks * @throws Exception */ - public function getTouchedChunks($manager): array + public function getTouchedChunks(AsyncChunkManager|World $manager): array {//TODO optimize to remove "corner" chunks $this->validateChunkManager($manager); $maxX = ($this->getMaxVec3()->x + 1) >> 4; diff --git a/src/xenialdan/MagicWE2/selection/shape/Ellipsoid.php b/src/xenialdan/MagicWE2/selection/shape/Ellipsoid.php index 68cd59d3..10288234 100644 --- a/src/xenialdan/MagicWE2/selection/shape/Ellipsoid.php +++ b/src/xenialdan/MagicWE2/selection/shape/Ellipsoid.php @@ -4,7 +4,6 @@ use Exception; use Generator; -use pocketmine\block\Block; use pocketmine\block\BlockLegacyIds; use pocketmine\math\AxisAlignedBB; use pocketmine\math\Vector2; @@ -18,11 +17,11 @@ class Ellipsoid extends Shape { /** @var int */ - public $width = 5; + public int $width = 5; /** @var int */ - public $height = 5; + public int $height = 5; /** @var int */ - public $depth = 5; + public int $depth = 5; /** * Pyramid constructor. @@ -44,10 +43,10 @@ public function __construct(Vector3 $pasteVector, int $width, int $height, int $ * @param World|AsyncChunkManager $manager The world or AsyncChunkManager * @param BlockPalette $filterblocks If not empty, applying a filter on the block list * @param int $flags - * @return Generator|Block[] + * @return Generator * @throws Exception */ - public function getBlocks($manager, BlockPalette $filterblocks, int $flags = API::FLAG_BASE): Generator + public function getBlocks(AsyncChunkManager|World $manager, BlockPalette $filterblocks, int $flags = API::FLAG_BASE): Generator { $this->validateChunkManager($manager); $centerVec2 = new Vector2($this->getPasteVector()->getX(), $this->getPasteVector()->getZ()); @@ -94,10 +93,10 @@ public function getBlocks($manager, BlockPalette $filterblocks, int $flags = API * Returns a flat layer of all included x z positions in selection * @param World|AsyncChunkManager $manager The world or AsyncChunkManager * @param int $flags - * @return Generator|Vector2[] + * @return Generator * @throws Exception */ - public function getLayer($manager, int $flags = API::FLAG_BASE): Generator + public function getLayer(AsyncChunkManager|World $manager, int $flags = API::FLAG_BASE): Generator { $this->validateChunkManager($manager); $centerVec2 = new Vector2($this->getPasteVector()->getX(), $this->getPasteVector()->getZ()); @@ -125,7 +124,7 @@ public function getLayer($manager, int $flags = API::FLAG_BASE): Generator * @return string[] fastSerialized chunks * @throws Exception */ - public function getTouchedChunks($manager): array + public function getTouchedChunks(AsyncChunkManager|World $manager): array {//TODO optimize to remove "corner" chunks $this->validateChunkManager($manager); $maxX = ($this->getMaxVec3()->x + 1) >> 4; diff --git a/src/xenialdan/MagicWE2/selection/shape/Pyramid.php b/src/xenialdan/MagicWE2/selection/shape/Pyramid.php index 2a0cf42e..5c5acbbd 100644 --- a/src/xenialdan/MagicWE2/selection/shape/Pyramid.php +++ b/src/xenialdan/MagicWE2/selection/shape/Pyramid.php @@ -4,7 +4,6 @@ use Exception; use Generator; -use pocketmine\block\Block; use pocketmine\block\BlockLegacyIds; use pocketmine\math\AxisAlignedBB; use pocketmine\math\Vector2; @@ -18,13 +17,13 @@ class Pyramid extends Shape { /** @var int */ - public $width = 5; + public int $width = 5; /** @var int */ - public $height = 5; + public int $height = 5; /** @var int */ - public $depth = 5; + public int $depth = 5; /** @var bool */ - public $flipped = false; + public bool $flipped = false; /** * Pyramid constructor. @@ -48,10 +47,10 @@ public function __construct(Vector3 $pasteVector, int $width, int $height, int $ * @param World|AsyncChunkManager $manager The world or AsyncChunkManager * @param BlockPalette $filterblocks If not empty, applying a filter on the block list * @param int $flags - * @return Generator|Block[] + * @return Generator * @throws Exception */ - public function getBlocks($manager, BlockPalette $filterblocks, int $flags = API::FLAG_BASE): Generator + public function getBlocks(AsyncChunkManager|World $manager, BlockPalette $filterblocks, int $flags = API::FLAG_BASE): Generator { $this->validateChunkManager($manager); $reduceXPerLayer = -($this->width / $this->height); @@ -93,10 +92,10 @@ public function getBlocks($manager, BlockPalette $filterblocks, int $flags = API * Returns a flat layer of all included x z positions in selection * @param World|AsyncChunkManager $manager The world or AsyncChunkManager * @param int $flags - * @return Generator|Vector2[] + * @return Generator * @throws Exception */ - public function getLayer($manager, int $flags = API::FLAG_BASE): Generator + public function getLayer(AsyncChunkManager|World $manager, int $flags = API::FLAG_BASE): Generator { $this->validateChunkManager($manager); $centerVec2 = new Vector2($this->getPasteVector()->getX(), $this->getPasteVector()->getZ()); @@ -113,7 +112,7 @@ public function getLayer($manager, int $flags = API::FLAG_BASE): Generator * @return string[] fastSerialized chunks * @throws Exception */ - public function getTouchedChunks($manager): array + public function getTouchedChunks(AsyncChunkManager|World $manager): array {//TODO optimize to remove "corner" chunks $this->validateChunkManager($manager); $maxX = ($this->getMaxVec3()->x + 1) >> 4; diff --git a/src/xenialdan/MagicWE2/selection/shape/Shape.php b/src/xenialdan/MagicWE2/selection/shape/Shape.php index a0ee1b8d..a4e52257 100644 --- a/src/xenialdan/MagicWE2/selection/shape/Shape.php +++ b/src/xenialdan/MagicWE2/selection/shape/Shape.php @@ -5,11 +5,8 @@ use Exception; use Generator; use InvalidArgumentException; -use pocketmine\block\Block; use pocketmine\math\AxisAlignedBB; -use pocketmine\math\Vector2; use pocketmine\math\Vector3; -use pocketmine\world\ChunkManager; use pocketmine\world\format\Chunk; use pocketmine\world\World; use Serializable; @@ -20,7 +17,7 @@ abstract class Shape implements Serializable { /** @var null|Vector3 */ - public $pasteVector; + public ?Vector3 $pasteVector = null; public function getPasteVector(): ?Vector3 { @@ -39,7 +36,7 @@ public function setPasteVector(Vector3 $pasteVector): void */ public static function getChunkManager(array $chunks): AsyncChunkManager { - $manager = new AsyncChunkManager(); + $manager = new AsyncChunkManager(0, World::Y_MAX); foreach ($chunks as $hash => $chunk) { World::getXZ($hash, $chunkX, $chunkZ); $manager->setChunk($chunkX, $chunkZ, $chunk); @@ -63,26 +60,26 @@ abstract public function getTotalCount(): int; * @param World|AsyncChunkManager $manager The world or AsyncChunkManager * @param BlockPalette $filterblocks If not empty, applying a filter on the block list * @param int $flags - * @return Generator|Block[] + * @return Generator * @throws Exception */ - abstract public function getBlocks($manager, BlockPalette $filterblocks, int $flags = API::FLAG_BASE): Generator; + abstract public function getBlocks(AsyncChunkManager|World $manager, BlockPalette $filterblocks, int $flags = API::FLAG_BASE): Generator; /** * Returns a flat layer of all included x z positions in selection * @param World|AsyncChunkManager $manager The world or AsyncChunkManager * @param int $flags - * @return Generator|Vector2[] + * @return Generator * @throws Exception */ - abstract public function getLayer($manager, int $flags = API::FLAG_BASE): Generator; + abstract public function getLayer(AsyncChunkManager|World $manager, int $flags = API::FLAG_BASE): Generator; /** - * @param ChunkManager $manager + * @param World|AsyncChunkManager $manager * @return string[] fastSerialized chunks * @throws Exception */ - abstract public function getTouchedChunks(ChunkManager $manager): array; + abstract public function getTouchedChunks(AsyncChunkManager|World $manager): array; abstract public function getAABB(): AxisAlignedBB; diff --git a/src/xenialdan/MagicWE2/selection/shape/ShapeRegistry.php b/src/xenialdan/MagicWE2/selection/shape/ShapeRegistry.php index d6279fbc..a32cbc66 100644 --- a/src/xenialdan/MagicWE2/selection/shape/ShapeRegistry.php +++ b/src/xenialdan/MagicWE2/selection/shape/ShapeRegistry.php @@ -9,7 +9,7 @@ class ShapeRegistry//todo use SingletonTrait { /** @var string[] */ - private static $shapes = []; + private static array $shapes = []; public const CUBOID = "Cuboid"; public const CUBE = "Cube"; diff --git a/src/xenialdan/MagicWE2/selection/shape/Sphere.php b/src/xenialdan/MagicWE2/selection/shape/Sphere.php index c5b3951b..dd099ad4 100644 --- a/src/xenialdan/MagicWE2/selection/shape/Sphere.php +++ b/src/xenialdan/MagicWE2/selection/shape/Sphere.php @@ -4,7 +4,6 @@ use Exception; use Generator; -use pocketmine\block\Block; use pocketmine\block\BlockLegacyIds; use pocketmine\math\AxisAlignedBB; use pocketmine\math\Vector2; @@ -18,7 +17,7 @@ class Sphere extends Shape { /** @var int */ - public $diameter = 5; + public int $diameter = 5; /** * Sphere constructor. @@ -36,10 +35,10 @@ public function __construct(Vector3 $pasteVector, int $diameter) * @param World|AsyncChunkManager $manager The world or AsyncChunkManager * @param BlockPalette $filterblocks If not empty, applying a filter on the block list * @param int $flags - * @return Generator|Block[] + * @return Generator * @throws Exception */ - public function getBlocks($manager, BlockPalette $filterblocks, int $flags = API::FLAG_BASE): Generator + public function getBlocks(AsyncChunkManager|World $manager, BlockPalette $filterblocks, int $flags = API::FLAG_BASE): Generator { $this->validateChunkManager($manager); for ($x = (int)floor($this->pasteVector->x - $this->diameter / 2 - 1); $x <= floor($this->pasteVector->x + $this->diameter / 2 + 1); $x++) { @@ -69,10 +68,10 @@ public function getBlocks($manager, BlockPalette $filterblocks, int $flags = API * Returns a flat layer of all included x z positions in selection * @param World|AsyncChunkManager $manager The world or AsyncChunkManager * @param int $flags - * @return Generator|Vector2[] + * @return Generator * @throws Exception */ - public function getLayer($manager, int $flags = API::FLAG_BASE): Generator + public function getLayer(AsyncChunkManager|World $manager, int $flags = API::FLAG_BASE): Generator { $this->validateChunkManager($manager); $centerVec2 = new Vector2($this->getPasteVector()->getX(), $this->getPasteVector()->getZ()); @@ -91,7 +90,7 @@ public function getLayer($manager, int $flags = API::FLAG_BASE): Generator * @return string[] fastSerialized chunks * @throws Exception */ - public function getTouchedChunks($manager): array + public function getTouchedChunks(AsyncChunkManager|World $manager): array {//TODO optimize to remove "corner" chunks $this->validateChunkManager($manager); $maxX = ($this->getMaxVec3()->x + 1) >> 4; diff --git a/src/xenialdan/MagicWE2/session/PluginSession.php b/src/xenialdan/MagicWE2/session/PluginSession.php index 32ce2ab3..f519359e 100644 --- a/src/xenialdan/MagicWE2/session/PluginSession.php +++ b/src/xenialdan/MagicWE2/session/PluginSession.php @@ -12,7 +12,7 @@ class PluginSession extends Session { /** @var Plugin */ - private $plugin; + private Plugin $plugin; public function __construct(Plugin $plugin) { diff --git a/src/xenialdan/MagicWE2/session/Session.php b/src/xenialdan/MagicWE2/session/Session.php index af415943..70c8aa59 100644 --- a/src/xenialdan/MagicWE2/session/Session.php +++ b/src/xenialdan/MagicWE2/session/Session.php @@ -13,6 +13,7 @@ use pocketmine\world\World; use Ramsey\Uuid\UuidInterface; use RuntimeException; +use UnderflowException; use xenialdan\MagicWE2\clipboard\Clipboard; use xenialdan\MagicWE2\clipboard\RevertClipboard; use xenialdan\MagicWE2\Loader; @@ -24,21 +25,21 @@ abstract class Session public const MAX_CLIPBOARDS = 5; public const MAX_HISTORY = 32; /** @var UuidInterface */ - private $uuid; + private UuidInterface $uuid; //todo change to a list of objects with a pointer of the latest action /** @var Selection[] */ - private $selections = []; + private array $selections = []; /** @var UuidInterface|null */ - private $latestselection; + private ?UuidInterface $latestselection = null; //todo change to a list of objects with a pointer of the latest action /** @var Clipboard[] */ - private $clipboards = []; + private array $clipboards = []; /** @var int */ - private $currentClipboard = -1; + private int $currentClipboard = -1; /** @var Deque */ - public $undoHistory; + public Deque $undoHistory; /** @var Deque */ - public $redoHistory; + public Deque $redoHistory; /** * @return UuidInterface @@ -210,6 +211,7 @@ public function addClipboard(Clipboard $clipboard, bool $setAsCurrent = true): i /** * @param RevertClipboard $revertClipboard + * @throws UnderflowException */ public function addRevert(RevertClipboard $revertClipboard): void { diff --git a/src/xenialdan/MagicWE2/session/UserSession.php b/src/xenialdan/MagicWE2/session/UserSession.php index c2a636d2..bf1d7fe9 100644 --- a/src/xenialdan/MagicWE2/session/UserSession.php +++ b/src/xenialdan/MagicWE2/session/UserSession.php @@ -28,32 +28,31 @@ use xenialdan\MagicWE2\helper\Scoreboard; use xenialdan\MagicWE2\Loader; use xenialdan\MagicWE2\session\data\Asset; -use xenialdan\MagicWE2\session\data\BrushStore; use xenialdan\MagicWE2\tool\Brush; use xenialdan\MagicWE2\tool\BrushProperties; class UserSession extends Session implements JsonSerializable //TODO use JsonMapper { /** @var Player|null */ - private $player; + private ?Player $player = null; /** @var BossBar */ - private $bossBar; + private BossBar $bossBar; /** @var Scoreboard|null */ - public $sidebar; + public ?Scoreboard $sidebar = null; /** @var bool */ - private $wandEnabled = true; + private bool $wandEnabled = true; /** @var bool */ - private $debugToolEnabled = true; + private bool $debugToolEnabled = true; /** @var bool */ - private $wailaEnabled = true; + private bool $wailaEnabled = true; /** @var bool */ - private $sidebarEnabled = true;//TODO settings/commands + private bool $sidebarEnabled = true;//TODO settings/commands /** @var Map */ private Map $brushes; /** @var Map */ private Map $assets; /** @var Language|null */ - private $lang; + private ?Language $lang = null; public bool $displayOutline = false; public function __construct(Player $player) diff --git a/src/xenialdan/MagicWE2/session/data/Asset.php b/src/xenialdan/MagicWE2/session/data/Asset.php index c9317a02..f771772c 100644 --- a/src/xenialdan/MagicWE2/session/data/Asset.php +++ b/src/xenialdan/MagicWE2/session/data/Asset.php @@ -88,6 +88,7 @@ public function getOrigin(): Vector3 * @param bool $renew * @return Item * @throws InvalidArgumentException + * @throws UnexpectedValueException */ public function toItem(bool $renew = false): Item { @@ -116,6 +117,7 @@ public function toItem(bool $renew = false): Item /** * @return array + * @throws UnexpectedValueException */ private function generateLore(): array { diff --git a/src/xenialdan/MagicWE2/task/AsyncActionTask.php b/src/xenialdan/MagicWE2/task/AsyncActionTask.php index de79eab4..e9db96a0 100644 --- a/src/xenialdan/MagicWE2/task/AsyncActionTask.php +++ b/src/xenialdan/MagicWE2/task/AsyncActionTask.php @@ -3,7 +3,7 @@ namespace xenialdan\MagicWE2\task; use Exception; -use InvalidArgumentException; +use OutOfBoundsException; use pocketmine\math\Vector3; use pocketmine\player\Player; use pocketmine\utils\AssumptionFailedError; @@ -13,6 +13,7 @@ use pocketmine\world\World; use Ramsey\Uuid\Uuid; use Ramsey\Uuid\UuidInterface; +use UnderflowException; use xenialdan\MagicWE2\API; use xenialdan\MagicWE2\clipboard\RevertClipboard; use xenialdan\MagicWE2\clipboard\SingleClipboard; @@ -37,15 +38,15 @@ class AsyncActionTask extends MWEAsyncTask */ /** @var string */ - private $touchedChunks; + private string $touchedChunks; /** @var string */ - private $selection; + private string $selection; /** @var BlockPalette */ - private $blockFilter; + private BlockPalette $blockFilter; /** @var BlockPalette */ - private $newBlocks; + private BlockPalette $newBlocks; /** @var TaskAction */ - private $action; + private TaskAction $action; /** * AsyncActionTask constructor. @@ -55,6 +56,8 @@ class AsyncActionTask extends MWEAsyncTask * @param string[] $touchedChunks serialized chunks * @param BlockPalette $newBlocks * @param BlockPalette $blockFilter + * @throws OutOfBoundsException + * @throws UnderflowException */ public function __construct(UuidInterface $sessionUUID, Selection $selection, TaskAction $action, array $touchedChunks, BlockPalette $newBlocks, BlockPalette $blockFilter) { @@ -104,7 +107,7 @@ public function onRun(): void $oldBlocks->selection = $selection;//TODO test. Needed to add this so that //paste works after //cut2 #$oldBlocks = []; $messages = []; - $error = false; + //$error = false; /** @var Progress $progress */ foreach ($this->action->execute($this->sessionUUID, $selection, $manager, $changed, $this->newBlocks, $this->blockFilter, $oldBlocks, $messages) as $progress) { $this->publishProgress($progress); @@ -118,10 +121,9 @@ public function onRun(): void } /** - * @throws InvalidArgumentException * @throws AssumptionFailedError - * @throws Exception - * @throws Exception + * @throws OutOfBoundsException + * @throws UnderflowException */ public function onCompletion(): void { diff --git a/src/xenialdan/MagicWE2/task/AsyncClipboardActionTask.php b/src/xenialdan/MagicWE2/task/AsyncClipboardActionTask.php index d02042a5..a683ee66 100644 --- a/src/xenialdan/MagicWE2/task/AsyncClipboardActionTask.php +++ b/src/xenialdan/MagicWE2/task/AsyncClipboardActionTask.php @@ -3,12 +3,13 @@ namespace xenialdan\MagicWE2\task; use Exception; -use InvalidArgumentException; +use OutOfBoundsException; use pocketmine\player\Player; use pocketmine\utils\AssumptionFailedError; use pocketmine\utils\TextFormat as TF; use Ramsey\Uuid\Uuid; use Ramsey\Uuid\UuidInterface; +use UnderflowException; use xenialdan\MagicWE2\clipboard\SingleClipboard; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\BlockStatesParser; @@ -23,11 +24,11 @@ class AsyncClipboardActionTask extends MWEAsyncTask { /** @var string */ - private $selection; + private string $selection; /** @var ClipboardAction */ - private $action; + private ClipboardAction $action; /** @var string */ - private $clipboard; + private string $clipboard; private string $rotPath; private string $doorRotPath; @@ -38,6 +39,8 @@ class AsyncClipboardActionTask extends MWEAsyncTask * @param Selection $selection * @param ClipboardAction $action * @param SingleClipboard $clipboard + * @throws OutOfBoundsException + * @throws UnderflowException */ public function __construct(UuidInterface $sessionUUID, Selection $selection, ClipboardAction $action, SingleClipboard $clipboard) { @@ -91,9 +94,9 @@ public function onRun(): void } /** - * @throws InvalidArgumentException * @throws AssumptionFailedError - * @throws Exception + * @throws OutOfBoundsException + * @throws UnderflowException */ public function onCompletion(): void { diff --git a/src/xenialdan/MagicWE2/task/AsyncCopyTask.php b/src/xenialdan/MagicWE2/task/AsyncCopyTask.php index f2868f75..7559a2c4 100644 --- a/src/xenialdan/MagicWE2/task/AsyncCopyTask.php +++ b/src/xenialdan/MagicWE2/task/AsyncCopyTask.php @@ -3,7 +3,6 @@ namespace xenialdan\MagicWE2\task; use Exception; -use InvalidArgumentException; use pocketmine\block\Block; use pocketmine\math\Vector3; use pocketmine\utils\AssumptionFailedError; @@ -26,13 +25,13 @@ class AsyncCopyTask extends MWEAsyncTask { /** @var string */ - private $chunks; + private string $chunks; /** @var string */ - private $selection; + private string $selection; /** @var Vector3 */ - private $offset; + private Vector3 $offset; /** @var int */ - private $flags; + private int $flags; /** * AsyncCopyTask constructor. @@ -125,8 +124,6 @@ public function onCompletion(): void $session->addClipboard($clipboard); } catch (SessionException $e) { Loader::getInstance()->getLogger()->logException($e); - } catch (InvalidArgumentException $e) { - Loader::getInstance()->getLogger()->logException($e); } catch (AssumptionFailedError $e) { Loader::getInstance()->getLogger()->logException($e); } diff --git a/src/xenialdan/MagicWE2/task/AsyncCountTask.php b/src/xenialdan/MagicWE2/task/AsyncCountTask.php index 1471e67b..2c7f2f44 100644 --- a/src/xenialdan/MagicWE2/task/AsyncCountTask.php +++ b/src/xenialdan/MagicWE2/task/AsyncCountTask.php @@ -3,7 +3,7 @@ namespace xenialdan\MagicWE2\task; use Exception; -use InvalidArgumentException; +use OutOfBoundsException; use pocketmine\block\Block; use pocketmine\block\BlockFactory; use pocketmine\utils\AssumptionFailedError; @@ -11,6 +11,7 @@ use pocketmine\world\format\io\FastChunkSerializer; use Ramsey\Uuid\Uuid; use Ramsey\Uuid\UuidInterface; +use UnderflowException; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\AsyncChunkManager; use xenialdan\MagicWE2\helper\BlockPalette; @@ -23,13 +24,13 @@ class AsyncCountTask extends MWEAsyncTask { /** @var string */ - private $touchedChunks; + private string $touchedChunks; /** @var string */ - private $selection; + private string $selection; /** @var int */ - private $flags; + private int $flags; /** @var BlockPalette */ - private $filterblocks; + private BlockPalette $filterblocks; /** * AsyncCountTask constructor. @@ -113,8 +114,9 @@ private function countBlocks(Selection $selection, AsyncChunkManager $manager, B } /** - * @throws InvalidArgumentException * @throws AssumptionFailedError + * @throws OutOfBoundsException + * @throws UnderflowException */ public function onCompletion(): void { diff --git a/src/xenialdan/MagicWE2/task/AsyncFillTask.php b/src/xenialdan/MagicWE2/task/AsyncFillTask.php index 9493f5f5..6ffdf50a 100644 --- a/src/xenialdan/MagicWE2/task/AsyncFillTask.php +++ b/src/xenialdan/MagicWE2/task/AsyncFillTask.php @@ -6,6 +6,7 @@ use Generator; use InvalidArgumentException; use MultipleIterator; +use OutOfBoundsException; use pocketmine\block\Block; use pocketmine\utils\AssumptionFailedError; use pocketmine\utils\TextFormat as TF; @@ -14,6 +15,7 @@ use pocketmine\world\World; use Ramsey\Uuid\Uuid; use Ramsey\Uuid\UuidInterface; +use UnderflowException; use xenialdan\MagicWE2\API; use xenialdan\MagicWE2\clipboard\RevertClipboard; use xenialdan\MagicWE2\exception\SessionException; @@ -28,15 +30,15 @@ class AsyncFillTask extends MWEAsyncTask { /** @var string */ - private $touchedChunks; + private string $touchedChunks; /** @var string */ - private $selection; + private string $selection; /** @var int */ - private $flags; + private int $flags; ///** @var string */ //private $newBlocks; /** @var BlockPalette */ - private $newBlocks; + private BlockPalette $newBlocks; /** * AsyncFillTask constructor. @@ -101,9 +103,9 @@ public function onRun(): void * @param AsyncChunkManager $manager * @param BlockPalette $newBlocks * @param null|int $changed - * @return Generator|array[] + * @return Generator + * @throws InvalidArgumentException * @phpstan-return Generator - * @throws Exception */ private function execute(Selection $selection, AsyncChunkManager $manager, BlockPalette $newBlocks, ?int &$changed): Generator { @@ -152,10 +154,9 @@ private function execute(Selection $selection, AsyncChunkManager $manager, Block } /** - * @throws InvalidArgumentException * @throws AssumptionFailedError - * @throws Exception - * @throws Exception + * @throws OutOfBoundsException + * @throws UnderflowException */ public function onCompletion(): void { diff --git a/src/xenialdan/MagicWE2/task/AsyncPasteAssetTask.php b/src/xenialdan/MagicWE2/task/AsyncPasteAssetTask.php index c0b8a22f..937af19c 100644 --- a/src/xenialdan/MagicWE2/task/AsyncPasteAssetTask.php +++ b/src/xenialdan/MagicWE2/task/AsyncPasteAssetTask.php @@ -6,6 +6,7 @@ use Exception; use Generator; use InvalidArgumentException; +use OutOfBoundsException; use pocketmine\block\Block; use pocketmine\math\Vector3; use pocketmine\utils\AssumptionFailedError; @@ -15,6 +16,8 @@ use pocketmine\world\World; use Ramsey\Uuid\Uuid; use Ramsey\Uuid\UuidInterface; +use UnderflowException; +use UnexpectedValueException; use xenialdan\libstructure\format\MCStructure; use xenialdan\MagicWE2\API; use xenialdan\MagicWE2\clipboard\RevertClipboard; @@ -32,15 +35,15 @@ class AsyncPasteAssetTask extends MWEAsyncTask { /** @var string */ - private $touchedChunks; + private string $touchedChunks; /** @var Selection */ - private $selection; + private Selection $selection; /** @var string */ - private $asset; + private string $asset; + /** @var null|Vector3 */ + private ?Vector3 $pasteVector; /** @var Vector3 */ - private $pasteVector; - /** @var Vector3 */ - private $target; + private Vector3 $target; /** * AsyncPasteTask constructor. @@ -68,6 +71,8 @@ public function __construct(UuidInterface $sessionUUID, Vector3 $target, Selecti * * @return void * @throws InvalidArgumentException + * @throws UnexpectedValueException + * @throws OutOfBoundsException */ public function onRun(): void { @@ -80,9 +85,8 @@ public function onRun(): void $manager = Shape::getChunkManager($touchedChunks); unset($touchedChunks); - /** @var Selection $selection */ //$selection = unserialize($this->selection/*, ['allowed_classes' => [Selection::class]]*/);//TODO test pm4 - $selection = $this->selection; + //$selection = $this->selection; /** @var Asset $asset */ $asset = unserialize($this->asset/*, ['allowed_classes' => [SingleClipboard::class]]*/);//TODO test pm4 @@ -101,7 +105,8 @@ public function onRun(): void * @param null|int $changed * @return Generator * @throws InvalidArgumentException - * @throws \UnexpectedValueException + * @throws UnexpectedValueException + * @throws OutOfBoundsException * @phpstan-return Generator */ private function execute(AsyncChunkManager $manager, Asset $asset, ?int &$changed): Generator @@ -202,9 +207,8 @@ private function execute(AsyncChunkManager $manager, Asset $asset, ?int &$change /** * @throws AssumptionFailedError - * @throws InvalidArgumentException - * @throws Exception - * @throws Exception + * @throws OutOfBoundsException + * @throws UnderflowException */ public function onCompletion(): void { @@ -223,7 +227,6 @@ public function onCompletion(): void }, unserialize($this->touchedChunks/*, ['allowed_classes' => false]*/));//TODO test pm4 $oldBlocks = $result["oldBlocks"];//already data array $changed = $result["changed"]; - /** @var Selection $selection */ //$selection = unserialize($this->selection/*, ['allowed_classes' => [Selection::class]]*/);//TODO test pm4 $selection = $this->selection; $totalCount = $selection->getShape()->getTotalCount(); diff --git a/src/xenialdan/MagicWE2/task/AsyncPasteTask.php b/src/xenialdan/MagicWE2/task/AsyncPasteTask.php index 1429d737..6ea1d5e8 100644 --- a/src/xenialdan/MagicWE2/task/AsyncPasteTask.php +++ b/src/xenialdan/MagicWE2/task/AsyncPasteTask.php @@ -5,6 +5,7 @@ use Exception; use Generator; use InvalidArgumentException; +use OutOfBoundsException; use pocketmine\math\Vector3; use pocketmine\utils\AssumptionFailedError; use pocketmine\utils\TextFormat as TF; @@ -13,6 +14,7 @@ use pocketmine\world\World; use Ramsey\Uuid\Uuid; use Ramsey\Uuid\UuidInterface; +use UnderflowException; use xenialdan\MagicWE2\API; use xenialdan\MagicWE2\clipboard\RevertClipboard; use xenialdan\MagicWE2\clipboard\SingleClipboard; @@ -28,13 +30,13 @@ class AsyncPasteTask extends MWEAsyncTask { /** @var string */ - private $touchedChunks; + private string $touchedChunks; /** @var string */ - private $selection; + private string $selection; /** @var string */ - private $clipboard; + private string $clipboard; /** @var Vector3 */ - private $offset; + private Vector3 $offset; /** * AsyncPasteTask constructor. @@ -91,9 +93,9 @@ public function onRun(): void * @param AsyncChunkManager $manager * @param SingleClipboard $clipboard * @param null|int $changed - * @return Generator|array[] - * @phpstan-return Generator + * @return Generator * @throws InvalidArgumentException + * @phpstan-return Generator */ private function execute(Selection $selection, AsyncChunkManager $manager, SingleClipboard $clipboard, ?int &$changed): Generator { @@ -143,9 +145,8 @@ private function execute(Selection $selection, AsyncChunkManager $manager, Singl /** * @throws AssumptionFailedError - * @throws InvalidArgumentException - * @throws Exception - * @throws Exception + * @throws OutOfBoundsException + * @throws UnderflowException */ public function onCompletion(): void { diff --git a/src/xenialdan/MagicWE2/task/AsyncReplaceTask.php b/src/xenialdan/MagicWE2/task/AsyncReplaceTask.php index accf9056..5da1f730 100644 --- a/src/xenialdan/MagicWE2/task/AsyncReplaceTask.php +++ b/src/xenialdan/MagicWE2/task/AsyncReplaceTask.php @@ -6,6 +6,7 @@ use Generator; use InvalidArgumentException; use MultipleIterator; +use OutOfBoundsException; use pocketmine\block\Block; use pocketmine\utils\AssumptionFailedError; use pocketmine\utils\TextFormat as TF; @@ -14,6 +15,7 @@ use pocketmine\world\World; use Ramsey\Uuid\Uuid; use Ramsey\Uuid\UuidInterface; +use UnderflowException; use xenialdan\MagicWE2\API; use xenialdan\MagicWE2\clipboard\RevertClipboard; use xenialdan\MagicWE2\exception\SessionException; @@ -28,15 +30,15 @@ class AsyncReplaceTask extends MWEAsyncTask { /** @var string */ - private $touchedChunks; + private string $touchedChunks; /** @var string */ - private $selection; + private string $selection; /** @var int */ - private $flags; + private int $flags; /** @var BlockPalette */ - private $replaceBlocks; + private BlockPalette $replaceBlocks; /** @var BlockPalette */ - private $newBlocks; + private BlockPalette $newBlocks; /** * AsyncReplaceTask constructor. @@ -94,9 +96,9 @@ public function onRun(): void * @param BlockPalette $replaceBlocks * @param BlockPalette $newBlocks * @param null|int $changed - * @return Generator|array[] + * @return Generator + * @throws InvalidArgumentException * @phpstan-return Generator - * @throws Exception */ private function execute(Selection $selection, AsyncChunkManager $manager, BlockPalette $replaceBlocks, BlockPalette $newBlocks, ?int &$changed): Generator { @@ -139,10 +141,9 @@ private function execute(Selection $selection, AsyncChunkManager $manager, Block } /** - * @throws InvalidArgumentException * @throws AssumptionFailedError - * @throws Exception - * @throws Exception + * @throws OutOfBoundsException + * @throws UnderflowException */ public function onCompletion(): void { diff --git a/src/xenialdan/MagicWE2/task/AsyncRevertTask.php b/src/xenialdan/MagicWE2/task/AsyncRevertTask.php index c248edb8..9a7166e8 100644 --- a/src/xenialdan/MagicWE2/task/AsyncRevertTask.php +++ b/src/xenialdan/MagicWE2/task/AsyncRevertTask.php @@ -5,11 +5,13 @@ use Exception; use Generator; use InvalidArgumentException; +use OutOfBoundsException; use pocketmine\utils\AssumptionFailedError; use pocketmine\utils\TextFormat as TF; use pocketmine\world\World; use Ramsey\Uuid\Uuid; use Ramsey\Uuid\UuidInterface; +use UnderflowException; use xenialdan\MagicWE2\clipboard\RevertClipboard; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\AsyncChunkManager; @@ -24,9 +26,9 @@ class AsyncRevertTask extends MWEAsyncTask public const TYPE_REDO = 1; /** @var string */ - private $clipboard; + private string $clipboard; /** @var int */ - private $type; + private int $type; /** * AsyncRevertTask constructor. @@ -67,9 +69,9 @@ public function onRun(): void /** * @param AsyncChunkManager $manager * @param RevertClipboard $clipboard - * @return Generator|array[] - * @phpstan-return Generator + * @return Generator * @throws InvalidArgumentException + * @phpstan-return Generator */ private function undoChunks(AsyncChunkManager $manager, RevertClipboard $clipboard): Generator { @@ -89,9 +91,9 @@ private function undoChunks(AsyncChunkManager $manager, RevertClipboard $clipboa /** * @param AsyncChunkManager $manager * @param RevertClipboard $clipboard - * @return Generator|array[] - * @phpstan-return Generator + * @return Generator * @throws InvalidArgumentException + * @phpstan-return Generator */ private function redoChunks(AsyncChunkManager $manager, RevertClipboard $clipboard): Generator { @@ -109,9 +111,9 @@ private function redoChunks(AsyncChunkManager $manager, RevertClipboard $clipboa } /** - * @throws InvalidArgumentException * @throws AssumptionFailedError - * @throws Exception + * @throws OutOfBoundsException + * @throws UnderflowException */ public function onCompletion(): void { diff --git a/src/xenialdan/MagicWE2/task/MWEAsyncTask.php b/src/xenialdan/MagicWE2/task/MWEAsyncTask.php index 5297ad72..0ae1882f 100644 --- a/src/xenialdan/MagicWE2/task/MWEAsyncTask.php +++ b/src/xenialdan/MagicWE2/task/MWEAsyncTask.php @@ -15,9 +15,9 @@ abstract class MWEAsyncTask extends AsyncTask { /** @var string */ - public $sessionUUID; + public string $sessionUUID; /** @var float */ - public $start; + public float $start; public function onProgressUpdate($progress): void { diff --git a/src/xenialdan/MagicWE2/task/action/ActionRegistry.php b/src/xenialdan/MagicWE2/task/action/ActionRegistry.php index 0376b361..3f568368 100644 --- a/src/xenialdan/MagicWE2/task/action/ActionRegistry.php +++ b/src/xenialdan/MagicWE2/task/action/ActionRegistry.php @@ -9,7 +9,7 @@ class ActionRegistry { /** @var string[] */ - private static $actions = []; + private static array $actions = []; public function __construct() { diff --git a/src/xenialdan/MagicWE2/task/action/ClipboardAction.php b/src/xenialdan/MagicWE2/task/action/ClipboardAction.php index f3bfa02a..fdf36b29 100644 --- a/src/xenialdan/MagicWE2/task/action/ClipboardAction.php +++ b/src/xenialdan/MagicWE2/task/action/ClipboardAction.php @@ -7,19 +7,18 @@ use Generator; use pocketmine\math\Vector3; use xenialdan\MagicWE2\clipboard\SingleClipboard; -use xenialdan\MagicWE2\helper\Progress; use xenialdan\MagicWE2\selection\Selection; abstract class ClipboardAction { /** @var string */ - public $prefix = ""; + public string $prefix = ""; /** @var string */ public string $completionString = '{%name} succeed, took {%took}, {%changed} entries out of {%total} changed.'; /** @var bool */ public bool $addClipboard = false; /** @var null|Vector3 */ - public $clipboardVector; + public ?Vector3 $clipboardVector = null; /** * @param string $sessionUUID @@ -27,7 +26,7 @@ abstract class ClipboardAction * @param null|int $changed * @param SingleClipboard $clipboard * @param string[] $messages - * @return Generator|Progress[] + * @return Generator */ abstract public function execute(string $sessionUUID, Selection $selection, ?int &$changed, SingleClipboard $clipboard, array &$messages = []): Generator; diff --git a/src/xenialdan/MagicWE2/task/action/CountAction.php b/src/xenialdan/MagicWE2/task/action/CountAction.php index ec841ec8..a1c13dd3 100644 --- a/src/xenialdan/MagicWE2/task/action/CountAction.php +++ b/src/xenialdan/MagicWE2/task/action/CountAction.php @@ -4,8 +4,8 @@ namespace xenialdan\MagicWE2\task\action; -use Exception; use Generator; +use InvalidArgumentException; use pocketmine\block\BlockFactory; use pocketmine\utils\TextFormat as TF; use xenialdan\MagicWE2\clipboard\SingleClipboard; @@ -17,9 +17,9 @@ class CountAction extends TaskAction { /** @var bool */ - public $addRevert = false; + public bool $addRevert = false; /** @var string */ - public $completionString = '{%name} succeed, took {%took}, analyzed {%changed} blocks'; + public string $completionString = '{%name} succeed, took {%took}, analyzed {%changed} blocks'; public function __construct() { @@ -39,8 +39,8 @@ public static function getName(): string * @param BlockPalette $blockFilter * @param SingleClipboard $oldBlocksSingleClipboard blocks before the change * @param string[] $messages - * @return Generator|Progress[] - * @throws Exception + * @return Generator + * @throws InvalidArgumentException */ public function execute(string $sessionUUID, Selection $selection, AsyncChunkManager $manager, ?int &$changed, BlockPalette $newBlocks, BlockPalette $blockFilter, SingleClipboard $oldBlocksSingleClipboard, array &$messages = []): Generator { diff --git a/src/xenialdan/MagicWE2/task/action/CutAction.php b/src/xenialdan/MagicWE2/task/action/CutAction.php index a32b0d86..40d48859 100644 --- a/src/xenialdan/MagicWE2/task/action/CutAction.php +++ b/src/xenialdan/MagicWE2/task/action/CutAction.php @@ -4,8 +4,8 @@ namespace xenialdan\MagicWE2\task\action; -use Exception; use Generator; +use InvalidArgumentException; use pocketmine\block\Block; use xenialdan\MagicWE2\clipboard\SingleClipboard; use xenialdan\MagicWE2\helper\AsyncChunkManager; @@ -17,11 +17,11 @@ class CutAction extends TaskAction { /** @var string */ - public $completionString = '{%name} succeed, took {%took}, {%changed} blocks out of {%total} cut.'; + public string $completionString = '{%name} succeed, took {%took}, {%changed} blocks out of {%total} cut.'; # /** @var bool */ # public $addRevert = true; /** @var bool */ - public $addClipboard = true; + public bool $addClipboard = true; public function __construct() { @@ -41,8 +41,8 @@ public static function getName(): string * @param BlockPalette $blockFilter * @param SingleClipboard $oldBlocksSingleClipboard blocks before the change * @param string[] $messages - * @return Generator|Progress[] - * @throws Exception + * @return Generator + * @throws InvalidArgumentException */ public function execute(string $sessionUUID, Selection $selection, AsyncChunkManager $manager, ?int &$changed, BlockPalette $newBlocks, BlockPalette $blockFilter, SingleClipboard $oldBlocksSingleClipboard, array &$messages = []): Generator { diff --git a/src/xenialdan/MagicWE2/task/action/FlipAction.php b/src/xenialdan/MagicWE2/task/action/FlipAction.php index cd08b739..8726ea7f 100644 --- a/src/xenialdan/MagicWE2/task/action/FlipAction.php +++ b/src/xenialdan/MagicWE2/task/action/FlipAction.php @@ -4,11 +4,13 @@ namespace xenialdan\MagicWE2\task\action; -use Exception; use Generator; use InvalidArgumentException; use pocketmine\block\BlockFactory; +use RuntimeException; use xenialdan\MagicWE2\clipboard\SingleClipboard; +use xenialdan\MagicWE2\exception\BlockQueryAlreadyParsedException; +use xenialdan\MagicWE2\exception\InvalidBlockStateException; use xenialdan\MagicWE2\helper\BlockEntry; use xenialdan\MagicWE2\helper\BlockStatesParser; use xenialdan\MagicWE2\helper\Progress; @@ -25,7 +27,7 @@ class FlipAction extends ClipboardAction /** @var string */ public string $completionString = '{%name} succeed, took {%took}, flipped {%changed} blocks out of {%total}'; /** @var string */ - private $axis; + private string $axis; public function __construct(string $axis)//TODO use pm Axis { @@ -44,8 +46,12 @@ public static function getName(): string * @param null|int $changed * @param SingleClipboard $clipboard * @param string[] $messages - * @return Generator|Progress[] - * @throws Exception + * @return Generator + * @throws InvalidArgumentException + * @throws RuntimeException + * @throws \pocketmine\block\utils\InvalidBlockStateException + * @throws BlockQueryAlreadyParsedException + * @throws InvalidBlockStateException */ public function execute(string $sessionUUID, Selection $selection, ?int &$changed, SingleClipboard $clipboard, array &$messages = []): Generator { @@ -86,6 +92,6 @@ public function execute(string $sessionUUID, Selection $selection, ?int &$change $lastProgress = $progress; } } - $clipboard = $clonedClipboard; + //$clipboard = $clonedClipboard; } } \ No newline at end of file diff --git a/src/xenialdan/MagicWE2/task/action/RotateAction.php b/src/xenialdan/MagicWE2/task/action/RotateAction.php index 5dd52b09..3c6bc914 100644 --- a/src/xenialdan/MagicWE2/task/action/RotateAction.php +++ b/src/xenialdan/MagicWE2/task/action/RotateAction.php @@ -4,12 +4,14 @@ namespace xenialdan\MagicWE2\task\action; -use Exception; use Generator; use InvalidArgumentException; use pocketmine\block\BlockFactory; use pocketmine\math\Vector3; +use RuntimeException; use xenialdan\MagicWE2\clipboard\SingleClipboard; +use xenialdan\MagicWE2\exception\BlockQueryAlreadyParsedException; +use xenialdan\MagicWE2\exception\InvalidBlockStateException; use xenialdan\MagicWE2\helper\BlockEntry; use xenialdan\MagicWE2\helper\BlockStatesParser; use xenialdan\MagicWE2\helper\Progress; @@ -48,8 +50,12 @@ public static function getName(): string * @param null|int $changed * @param SingleClipboard $clipboard * @param string[] $messages - * @return Generator|Progress[] - * @throws Exception + * @return Generator + * @throws InvalidArgumentException + * @throws RuntimeException + * @throws \pocketmine\block\utils\InvalidBlockStateException + * @throws BlockQueryAlreadyParsedException + * @throws InvalidBlockStateException */ public function execute(string $sessionUUID, Selection $selection, ?int &$changed, SingleClipboard $clipboard, array &$messages = []): Generator { @@ -93,7 +99,6 @@ public function execute(string $sessionUUID, Selection $selection, ?int &$change } #var_dump("$newX $y $newZ"); $block1 = $blockEntry->toBlock(); - /** @var BlockStatesParser $instance */ $instance = BlockStatesParser::getInstance(); $blockStatesEntry = $instance::getStateByBlock($block1); $rotated = $blockStatesEntry->rotate($this->rotation); @@ -139,6 +144,6 @@ public function execute(string $sessionUUID, Selection $selection, ?int &$change } $clonedSelection->shape = (Cuboid::constructFromPositions($pos1, $pos2));//TODO figure out how to keep the shape (not always Cuboid) $clonedClipboard->selection = $clonedSelection; - $clipboard = $clonedClipboard; + //$clipboard = $clonedClipboard; } } \ No newline at end of file diff --git a/src/xenialdan/MagicWE2/task/action/SetBiomeAction.php b/src/xenialdan/MagicWE2/task/action/SetBiomeAction.php index 678194a3..97ad8bee 100644 --- a/src/xenialdan/MagicWE2/task/action/SetBiomeAction.php +++ b/src/xenialdan/MagicWE2/task/action/SetBiomeAction.php @@ -15,9 +15,9 @@ class SetBiomeAction extends TaskAction { /** @var bool */ - public $addRevert = false; + public bool $addRevert = false; /** @var int */ - private $biomeId; + private int $biomeId; public function __construct(int $biomeId) { @@ -38,7 +38,7 @@ public static function getName(): string * @param BlockPalette $blockFilter * @param SingleClipboard $oldBlocksSingleClipboard blocks before the change * @param string[] $messages - * @return Generator|Progress[] + * @return Generator * @throws Exception */ public function execute(string $sessionUUID, Selection $selection, AsyncChunkManager $manager, ?int &$changed, BlockPalette $newBlocks, BlockPalette $blockFilter, SingleClipboard $oldBlocksSingleClipboard, array &$messages = []): Generator diff --git a/src/xenialdan/MagicWE2/task/action/SetBlockAction.php b/src/xenialdan/MagicWE2/task/action/SetBlockAction.php index f1375769..e7696f2c 100644 --- a/src/xenialdan/MagicWE2/task/action/SetBlockAction.php +++ b/src/xenialdan/MagicWE2/task/action/SetBlockAction.php @@ -4,8 +4,8 @@ namespace xenialdan\MagicWE2\task\action; -use Exception; use Generator; +use InvalidArgumentException; use pocketmine\block\Block; use xenialdan\MagicWE2\clipboard\SingleClipboard; use xenialdan\MagicWE2\helper\AsyncChunkManager; @@ -35,8 +35,8 @@ public static function getName(): string * @param BlockPalette $blockFilter * @param SingleClipboard $oldBlocksSingleClipboard blocks before the change * @param string[] $messages - * @return Generator|Progress[] - * @throws Exception + * @return Generator + * @throws InvalidArgumentException */ public function execute(string $sessionUUID, Selection $selection, AsyncChunkManager $manager, ?int &$changed, BlockPalette $newBlocks, BlockPalette $blockFilter, SingleClipboard $oldBlocksSingleClipboard, array &$messages = []): Generator { diff --git a/src/xenialdan/MagicWE2/task/action/TaskAction.php b/src/xenialdan/MagicWE2/task/action/TaskAction.php index d99e25ca..1cc7a2a8 100644 --- a/src/xenialdan/MagicWE2/task/action/TaskAction.php +++ b/src/xenialdan/MagicWE2/task/action/TaskAction.php @@ -9,21 +9,20 @@ use xenialdan\MagicWE2\clipboard\SingleClipboard; use xenialdan\MagicWE2\helper\AsyncChunkManager; use xenialdan\MagicWE2\helper\BlockPalette; -use xenialdan\MagicWE2\helper\Progress; use xenialdan\MagicWE2\selection\Selection; abstract class TaskAction { /** @var string */ - public $prefix = ""; + public string $prefix = ""; /** @var bool */ - public $addRevert = true; + public bool $addRevert = true; /** @var string */ - public $completionString = '{%name} succeed, took {%took}, {%changed} blocks out of {%total} changed.'; + public string $completionString = '{%name} succeed, took {%took}, {%changed} blocks out of {%total} changed.'; /** @var bool */ - public $addClipboard = false; + public bool $addClipboard = false; /** @var null|Vector3 */ - public $clipboardVector; + public ?Vector3 $clipboardVector = null; //TODO add $flags and define available flags in child classes //public $flags //protected const AVAILABLE_FLAGS = [];(can be overwritten), access with static::AVAILABLE_FLAGS @@ -37,7 +36,7 @@ abstract class TaskAction * @param BlockPalette $blockFilter * @param SingleClipboard $oldBlocksSingleClipboard blocks before the change * @param string[] $messages - * @return Generator|Progress[] + * @return Generator */ abstract public function execute(string $sessionUUID, Selection $selection, AsyncChunkManager $manager, ?int &$changed, BlockPalette $newBlocks, BlockPalette $blockFilter, SingleClipboard $oldBlocksSingleClipboard, array &$messages = []): Generator; diff --git a/src/xenialdan/MagicWE2/task/action/TestAction.php b/src/xenialdan/MagicWE2/task/action/TestAction.php index 6603dee4..e85dfd30 100644 --- a/src/xenialdan/MagicWE2/task/action/TestAction.php +++ b/src/xenialdan/MagicWE2/task/action/TestAction.php @@ -16,9 +16,9 @@ class TestAction extends TaskAction { /** @var bool */ - public $addRevert = false; + public bool $addRevert = false; /** @var string */ - public $completionString = '{%name} succeed, took {%took}, tested {%changed} blocks'; + public string $completionString = '{%name} succeed, took {%took}, tested {%changed} blocks'; public function __construct() { @@ -38,7 +38,7 @@ public static function getName(): string * @param BlockPalette $blockFilter * @param SingleClipboard $oldBlocksSingleClipboard blocks before the change * @param string[] $messages - * @return Generator|Progress[] + * @return Generator * @throws Exception */ public function execute(string $sessionUUID, Selection $selection, AsyncChunkManager $manager, ?int &$changed, BlockPalette $newBlocks, BlockPalette $blockFilter, SingleClipboard $oldBlocksSingleClipboard, array &$messages = []): Generator diff --git a/src/xenialdan/MagicWE2/task/action/ThawAction.php b/src/xenialdan/MagicWE2/task/action/ThawAction.php index 6ac2559b..a2411b45 100644 --- a/src/xenialdan/MagicWE2/task/action/ThawAction.php +++ b/src/xenialdan/MagicWE2/task/action/ThawAction.php @@ -4,8 +4,8 @@ namespace xenialdan\MagicWE2\task\action; -use Exception; use Generator; +use InvalidArgumentException; use pocketmine\block\VanillaBlocks; use xenialdan\MagicWE2\clipboard\SingleClipboard; use xenialdan\MagicWE2\helper\AsyncChunkManager; @@ -35,8 +35,8 @@ public static function getName(): string * @param BlockPalette $blockFilter * @param SingleClipboard $oldBlocksSingleClipboard blocks before the change * @param string[] $messages - * @return Generator|Progress[] - * @throws Exception + * @return Generator + * @throws InvalidArgumentException */ public function execute(string $sessionUUID, Selection $selection, AsyncChunkManager $manager, ?int &$changed, BlockPalette $newBlocks, BlockPalette $blockFilter, SingleClipboard $oldBlocksSingleClipboard, array &$messages = []): Generator { diff --git a/src/xenialdan/MagicWE2/tool/Brush.php b/src/xenialdan/MagicWE2/tool/Brush.php index 5b062e41..2f5dc487 100644 --- a/src/xenialdan/MagicWE2/tool/Brush.php +++ b/src/xenialdan/MagicWE2/tool/Brush.php @@ -41,7 +41,7 @@ class Brush extends WETool public const TAG_BRUSH_PROPERTIES = "properties"; /** @var BrushProperties */ - public $properties; + public BrushProperties $properties; /** * Brush constructor. diff --git a/src/xenialdan/MagicWE2/tool/BrushProperties.php b/src/xenialdan/MagicWE2/tool/BrushProperties.php index d041be55..ce309c52 100644 --- a/src/xenialdan/MagicWE2/tool/BrushProperties.php +++ b/src/xenialdan/MagicWE2/tool/BrushProperties.php @@ -22,27 +22,27 @@ class BrushProperties implements JsonSerializable public const VERSION = 1; /** @var int */ - public $version = self::VERSION; + public int $version = self::VERSION; /** @var string */ - public $customName = ""; + public string $customName = ""; /** @var string */ - public $shape = Sphere::class; + public string $shape = Sphere::class; /** @var array */ - public $shapeProperties = []; + public array $shapeProperties = []; /** @var string */ - public $action = SetBlockAction::class; + public string $action = SetBlockAction::class; /** @var array */ - public $actionProperties = []; + public array $actionProperties = []; /** @var bool */ - public $hollow = false;//TODO consider moving into shape properties + public bool $hollow = false;//TODO consider moving into shape properties /** @var string */ - public $blocks = "stone"; + public string $blocks = "stone"; /** @var string */ - public $filter = ""; + public string $filter = ""; /** @var int */ - public $biomeId = BiomeIds::PLAINS; + public int $biomeId = BiomeIds::PLAINS; /** @var string */ - public $uuid; + public string $uuid; /** * Specify data which should be serialized to JSON diff --git a/src/xenialdan/MagicWE2/tool/Flood.php b/src/xenialdan/MagicWE2/tool/Flood.php index 5bfd3d7f..65bc62b2 100644 --- a/src/xenialdan/MagicWE2/tool/Flood.php +++ b/src/xenialdan/MagicWE2/tool/Flood.php @@ -19,13 +19,13 @@ class Flood extends WETool { /** @var int */ - private $limit; + private int $limit; /** @var Block[] */ - private $walked = []; + private array $walked = []; /** @var Block[] */ - private $nextToCheck = []; + private array $nextToCheck = []; /** @var int */ - private $y; + private int $y; /** * Square constructor. @@ -41,10 +41,10 @@ public function __construct(int $limit) * @param World|AsyncChunkManager $manager The world or AsyncChunkManager * @param BlockPalette $filterblocks If not empty, applying a filter on the block list * @param int $flags - * @return Generator|Block[] + * @return Generator * @throws Exception */ - public function getBlocks($manager, BlockPalette $filterblocks, int $flags = API::FLAG_BASE): Generator + public function getBlocks(AsyncChunkManager|World $manager, BlockPalette $filterblocks, int $flags = API::FLAG_BASE): Generator { $this->validateChunkManager($manager); $this->y = $this->getCenter()->getFloorY(); @@ -61,10 +61,10 @@ public function getBlocks($manager, BlockPalette $filterblocks, int $flags = API * Returns a flat layer of all included x z positions in selection * @param World|AsyncChunkManager $manager The world or AsyncChunkManager * @param int $flags - * @return Generator|Vector2[] + * @return Generator * @throws Exception */ - public function getLayer($manager, int $flags = API::FLAG_BASE): Generator + public function getLayer(AsyncChunkManager|World $manager, int $flags = API::FLAG_BASE): Generator { $this->validateChunkManager($manager); foreach ($this->getBlocks($manager, BlockPalette::CREATE()) as $block) { @@ -78,7 +78,7 @@ public function getLayer($manager, int $flags = API::FLAG_BASE): Generator * @throws InvalidArgumentException * @noinspection SlowArrayOperationsInLoopInspection */ - private function walk($manager): array + private function walk(AsyncChunkManager|World $manager): array { $this->validateChunkManager($manager); /** @var Block[] $walkTo */ @@ -98,10 +98,10 @@ private function walk($manager): array /** * @param World|AsyncChunkManager $manager * @param Vector3 $vector3 - * @return Generator|Block[] + * @return Generator * @throws InvalidArgumentException */ - private function getHorizontalSides($manager, Vector3 $vector3): Generator + private function getHorizontalSides(AsyncChunkManager|World $manager, Vector3 $vector3): Generator { $this->validateChunkManager($manager); foreach ([Facing::NORTH, Facing::SOUTH, Facing::WEST, Facing::EAST] as $vSide) { @@ -122,7 +122,7 @@ public function getTotalCount(): int * @return array * @throws InvalidArgumentException */ - public function getTouchedChunks($chunkManager): array + public function getTouchedChunks(AsyncChunkManager|World $chunkManager): array { $this->validateChunkManager($chunkManager); $maxRadius = sqrt($this->limit / M_PI); @@ -178,7 +178,7 @@ private function getCenter(): Vector3 */ public static function getChunkManager(array $chunks): AsyncChunkManager { - $manager = new AsyncChunkManager(); + $manager = new AsyncChunkManager(0, World::Y_MAX); foreach ($chunks as $hash => $chunk) { World::getXZ($hash, $x, $z); $manager->setChunk($x, $z, $chunk); From 582039b3379bc81de6a684b06d19debb08e60bde Mon Sep 17 00:00:00 2001 From: XenialDan Date: Fri, 23 Apr 2021 07:20:13 +0200 Subject: [PATCH 22/67] test --- phpstan.neon.dist | 1 + 1 file changed, 1 insertion(+) diff --git a/phpstan.neon.dist b/phpstan.neon.dist index ac2bc43a..a21554ce 100644 --- a/phpstan.neon.dist +++ b/phpstan.neon.dist @@ -18,5 +18,6 @@ parameters: - phar:///source/vendor/InvMenu.phar/src - phar:///source/vendor/libstructure.phar/src - phar:///source/vendor/ScoreFactory.phar/src + - /source/vendor excludes_analyse: - source/vendor \ No newline at end of file From d413ae43d6e99284cf001ab5b178f29b93668f18 Mon Sep 17 00:00:00 2001 From: XenialDan Date: Fri, 23 Apr 2021 12:24:56 +0200 Subject: [PATCH 23/67] phpstan works again --- phpstan.neon.dist | 2 +- .../MagicWE2/helper/BlockStatesEntry.php | 5 +-- .../MagicWE2/selection/Selection.php | 14 ++++---- .../MagicWE2/session/UserSession.php | 4 +-- src/xenialdan/MagicWE2/session/data/Asset.php | 9 ++---- .../MagicWE2/session/data/AssetCollection.php | 32 +++++++++++-------- 6 files changed, 32 insertions(+), 34 deletions(-) diff --git a/phpstan.neon.dist b/phpstan.neon.dist index a21554ce..47ca5562 100644 --- a/phpstan.neon.dist +++ b/phpstan.neon.dist @@ -11,6 +11,7 @@ parameters: - phar:///pocketmine/PocketMine-MP.phar/vendor/autoload.php scanDirectories: - /source/src + - /source/vendor - phar:///source/vendor/customui.phar/src - phar:///source/vendor/apibossbar.phar/src - phar:///source/vendor/Commando.phar/src @@ -18,6 +19,5 @@ parameters: - phar:///source/vendor/InvMenu.phar/src - phar:///source/vendor/libstructure.phar/src - phar:///source/vendor/ScoreFactory.phar/src - - /source/vendor excludes_analyse: - source/vendor \ No newline at end of file diff --git a/src/xenialdan/MagicWE2/helper/BlockStatesEntry.php b/src/xenialdan/MagicWE2/helper/BlockStatesEntry.php index 07af77a6..c749823e 100644 --- a/src/xenialdan/MagicWE2/helper/BlockStatesEntry.php +++ b/src/xenialdan/MagicWE2/helper/BlockStatesEntry.php @@ -42,10 +42,7 @@ public function __construct(string $blockIdentifier, CompoundTag $blockStates, ? $this->blockStates = $blockStates; $this->block = $block; try { - if ($this->blockStates !== null) - $this->blockFull = TextFormat::clean(BlockStatesParser::printStates($this, false)); - else - $this->blockFull = $this->blockIdentifier; + $this->blockFull = TextFormat::clean(BlockStatesParser::printStates($this, false)); } catch (Throwable $e) { GlobalLogger::get()->logException($e); $this->blockFull = $this->blockIdentifier; diff --git a/src/xenialdan/MagicWE2/selection/Selection.php b/src/xenialdan/MagicWE2/selection/Selection.php index e024374a..010abfbf 100644 --- a/src/xenialdan/MagicWE2/selection/Selection.php +++ b/src/xenialdan/MagicWE2/selection/Selection.php @@ -49,15 +49,15 @@ class Selection implements Serializable, JsonSerializable * Selection constructor. * @param UuidInterface $sessionUUID * @param World $world - * @param null $minX - * @param null $minY - * @param null $minZ - * @param null $maxX - * @param null $maxY - * @param null $maxZ + * @param ?int $minX + * @param ?int $minY + * @param ?int $minZ + * @param ?int $maxX + * @param ?int $maxY + * @param ?int $maxZ * @param ?Shape $shape */ - public function __construct(UuidInterface $sessionUUID, World $world, $minX = null, $minY = null, $minZ = null, $maxX = null, $maxY = null, $maxZ = null, ?Shape $shape = null) + public function __construct(UuidInterface $sessionUUID, World $world, ?int $minX = null, ?int $minY = null, ?int $minZ = null, ?int $maxX = null, ?int $maxY = null, ?int $maxZ = null, ?Shape $shape = null) { $this->sessionUUID = $sessionUUID; $this->worldId = $world->getId(); diff --git a/src/xenialdan/MagicWE2/session/UserSession.php b/src/xenialdan/MagicWE2/session/UserSession.php index bf1d7fe9..87b17ea8 100644 --- a/src/xenialdan/MagicWE2/session/UserSession.php +++ b/src/xenialdan/MagicWE2/session/UserSession.php @@ -47,9 +47,9 @@ class UserSession extends Session implements JsonSerializable //TODO use JsonMap private bool $wailaEnabled = true; /** @var bool */ private bool $sidebarEnabled = true;//TODO settings/commands - /** @var Map */ + /** @var Map */ private Map $brushes; - /** @var Map */ + /** @var Map */ private Map $assets; /** @var Language|null */ private ?Language $lang = null; diff --git a/src/xenialdan/MagicWE2/session/data/Asset.php b/src/xenialdan/MagicWE2/session/data/Asset.php index f771772c..20ffe4e4 100644 --- a/src/xenialdan/MagicWE2/session/data/Asset.php +++ b/src/xenialdan/MagicWE2/session/data/Asset.php @@ -66,14 +66,12 @@ public function getSize(): Vector3 if ($this->structure instanceof Schematic) return new Vector3($this->structure->getWidth(), $this->structure->getHeight(), $this->structure->getLength()); if ($this->structure instanceof MCStructure) return $this->structure->getSize(); if ($this->structure instanceof SingleClipboard) return new Vector3($this->structure->selection->getSizeX(), $this->structure->selection->getSizeY(), $this->structure->selection->getSizeZ()); - throw new UnexpectedValueException('Invalid class as Asset'); } public function getTotalCount(): int { if ($this->structure instanceof Schematic || $this->structure instanceof MCStructure) return $this->getSize()->getFloorX() * $this->getSize()->getFloorY() * $this->getSize()->getFloorZ(); if ($this->structure instanceof SingleClipboard) return $this->structure->getTotalCount(); - throw new UnexpectedValueException('Invalid class as Asset'); } public function getOrigin(): Vector3 @@ -81,7 +79,6 @@ public function getOrigin(): Vector3 if ($this->structure instanceof Schematic) return new Vector3(0, 0, 0); if ($this->structure instanceof MCStructure) return $this->structure->getStructureWorldOrigin(); if ($this->structure instanceof SingleClipboard) return $this->structure->position; - throw new UnexpectedValueException('Invalid class as Asset'); } /** @@ -156,7 +153,6 @@ public function toSchematic(): Schematic $schematic->setBlockArray($blocks); return $schematic; } - throw new PluginException("Wrong type"); } public function toMCStructure(): MCStructure @@ -225,7 +221,7 @@ public function getSettingForm(bool $new = true, array $errors = []): CustomForm $form->addLabel($value); } // Function - $form->setCallable(function (Player $player, $data) use ($form, $new) { + $form->setCallable(function (Player $player, $data) /*use ($form, $new)*/ { var_dump(__LINE__, $data); [$filename, $this->locked, $shared] = $data; var_dump($filename, $this->locked ? "true" : "false", $shared ? "true" : "false"); @@ -276,7 +272,8 @@ public function jsonSerialize() return [ 'filename' => $this->filename, 'displayname' => $this->displayname, - 'type' => $this->structure instanceof Schematic ? self::TYPE_SCHEMATIC : ($this->structure instanceof MCStructure ? self::TYPE_MCSTRUCTURE : ($this->structure instanceof SingleClipboard ? self::TYPE_CLIPBOARD : '')), + //'type' => $this->structure instanceof Schematic ? self::TYPE_SCHEMATIC : ($this->structure instanceof MCStructure ? self::TYPE_MCSTRUCTURE : ($this->structure instanceof SingleClipboard ? self::TYPE_CLIPBOARD : '')), + 'type' => $this->structure instanceof Schematic ? self::TYPE_SCHEMATIC : ($this->structure instanceof MCStructure ? self::TYPE_MCSTRUCTURE : self::TYPE_CLIPBOARD), 'locked' => $this->locked, 'owner' => $this->ownerXuid ?? 'none', 'shared' => $this->shared, diff --git a/src/xenialdan/MagicWE2/session/data/AssetCollection.php b/src/xenialdan/MagicWE2/session/data/AssetCollection.php index 82902f18..666f5585 100644 --- a/src/xenialdan/MagicWE2/session/data/AssetCollection.php +++ b/src/xenialdan/MagicWE2/session/data/AssetCollection.php @@ -15,7 +15,7 @@ final class AssetCollection { use SingletonTrait; - /** @var Map */ + /** @var Map */ public Map $assets; public function __construct() @@ -62,20 +62,24 @@ private function initFolders(): void { //Load mcstructure and schematic files and lock them to prevent editing $store = $this; - $schematicFiles = array_merge(glob(Loader::getInstance()->getDataFolder() . 'assets' . DIRECTORY_SEPARATOR . "*.mcstructure"), glob(Loader::getInstance()->getDataFolder() . 'assets' . DIRECTORY_SEPARATOR . "*.schematic"));//glob might return false - if ($schematicFiles !== false) - foreach ($schematicFiles as $file) { - ['basename' => $basename, 'extension' => $extension] = pathinfo($file); - Loader::getInstance()->getLogger()->debug(TF::GOLD . "Loading " . $basename); - try { - if ($extension === 'mcstructure') { - $store->assets->put($basename, new Asset($basename, StructureStore::getInstance()->loadStructure($basename), true, null, true)); - } else if ($extension === 'schematic') { - $store->assets->put($basename, new Asset($basename, StructureStore::getInstance()->loadSchematic($basename), true, null, true)); + $globStructure = glob(Loader::getInstance()->getDataFolder() . 'assets' . DIRECTORY_SEPARATOR . "*.mcstructure"); + $globSchematic = glob(Loader::getInstance()->getDataFolder() . 'assets' . DIRECTORY_SEPARATOR . "*.schematic"); + if($globStructure && $globSchematic) { + $schematicFiles = array_merge($globStructure, $globSchematic); + if ($schematicFiles !== false) + foreach ($schematicFiles as $file) { + ['basename' => $basename, 'extension' => $extension] = pathinfo($file); + Loader::getInstance()->getLogger()->debug(TF::GOLD . "Loading " . $basename); + try { + if ($extension === 'mcstructure') { + $store->assets->put($basename, new Asset($basename, StructureStore::getInstance()->loadStructure($basename), true, null, true)); + } else if ($extension === 'schematic') { + $store->assets->put($basename, new Asset($basename, StructureStore::getInstance()->loadSchematic($basename), true, null, true)); + } + } catch (StructureFileException $e) { + Loader::getInstance()->getLogger()->debug($e->getMessage()); } - } catch (StructureFileException $e) { - Loader::getInstance()->getLogger()->debug($e->getMessage()); } - } + } } } \ No newline at end of file From a7f90e4a44652e1ea603eec9641183729af7b7ca Mon Sep 17 00:00:00 2001 From: XenialDan Date: Fri, 23 Apr 2021 12:31:51 +0200 Subject: [PATCH 24/67] phpstan is rart with array access on Ds\Map --- src/xenialdan/MagicWE2/session/UserSession.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/xenialdan/MagicWE2/session/UserSession.php b/src/xenialdan/MagicWE2/session/UserSession.php index 87b17ea8..67dd8c55 100644 --- a/src/xenialdan/MagicWE2/session/UserSession.php +++ b/src/xenialdan/MagicWE2/session/UserSession.php @@ -255,7 +255,7 @@ public function getBrushFromItem(Item $item): Brush */ public function getBrush(UuidInterface $uuid): ?Brush { - return $this->brushes[$uuid->toString()] ?? null; + return $this->brushes->get($uuid->toString()); } /** @@ -265,7 +265,7 @@ public function getBrush(UuidInterface $uuid): ?Brush */ public function addBrush(Brush $brush): void { - $this->brushes[$brush->properties->uuid] = $brush; + $this->brushes->put($brush->properties->uuid, $brush); $this->sendMessage($this->getLanguage()->translateString('session.brush.added', [$brush->getName()])); } @@ -276,7 +276,7 @@ public function addBrush(Brush $brush): void */ public function removeBrush(Brush $brush, bool $delete = false): void { - if ($delete) unset($this->brushes[$brush->properties->uuid]); + if ($delete) $this->brushes->remove($brush->properties->uuid); foreach ($this->getPlayer()->getInventory()->getContents() as $slot => $item) { if (($entry = $item->getNamedTag()->getCompoundTag(API::TAG_MAGIC_WE_BRUSH)) instanceof CompoundTag) { if ($entry->getString("id") === $brush->properties->uuid) { @@ -300,7 +300,7 @@ public function removeBrush(Brush $brush, bool $delete = false): void */ public function replaceBrush(Brush $brush): void { - $this->brushes[$brush->properties->uuid] = $brush; + $this->brushes->put($brush->properties->uuid, $brush); $new = $brush->toItem(); foreach ($this->getPlayer()->getInventory()->getContents() as $slot => $item) { if (($entry = $item->getNamedTag()->getCompoundTag(API::TAG_MAGIC_WE_BRUSH)) instanceof CompoundTag) { From bd7de06689377385a6e7ff0b3af6264e3be0f030 Mon Sep 17 00:00:00 2001 From: XenialDan Date: Thu, 3 Jun 2021 12:32:52 +0200 Subject: [PATCH 25/67] save Signed-off-by: XenialDan --- plugin.yml | 4 + src/xenialdan/MagicWE2/Loader.php | 4 +- .../MagicWE2/commands/asset/AssetCommand.php | 2 +- .../commands/palette/PaletteCommand.php | 137 ++++++++++++++++++ .../MagicWE2/session/UserSession.php | 3 + .../session/data/PaletteCollection.php | 33 +++++ 6 files changed, 180 insertions(+), 3 deletions(-) create mode 100644 src/xenialdan/MagicWE2/commands/palette/PaletteCommand.php create mode 100644 src/xenialdan/MagicWE2/session/data/PaletteCollection.php diff --git a/plugin.yml b/plugin.yml index c508bef6..a548ce63 100644 --- a/plugin.yml +++ b/plugin.yml @@ -19,6 +19,10 @@ permissions: default: op we.command.donate: default: true + we.command.asset: + default: op + we.command.palette: + default: op we.command.language: default: op we.command.help: diff --git a/src/xenialdan/MagicWE2/Loader.php b/src/xenialdan/MagicWE2/Loader.php index b95d3b33..148753df 100644 --- a/src/xenialdan/MagicWE2/Loader.php +++ b/src/xenialdan/MagicWE2/Loader.php @@ -24,7 +24,7 @@ use xenialdan\apibossbar\DiverseBossBar; use xenialdan\customui\API as CustomUIAPI; use xenialdan\libstructure\PacketListener; -use xenialdan\MagicWE2\commands\asset\AssetCommand; +use xenialdan\MagicWE2\commands\asset\PaletteCommand; use xenialdan\MagicWE2\commands\biome\BiomeInfoCommand; use xenialdan\MagicWE2\commands\biome\BiomeListCommand; use xenialdan\MagicWE2\commands\biome\SetBiomeCommand; @@ -219,7 +219,7 @@ public function onEnable(): void new HPos2Command($this, "/hpos2", "Set position 2 to targeted block", ["/h2"]), new ChunkCommand($this, "/chunk", "Set the selection to your current chunk"), /* -- assets -- */ - new AssetCommand($this, "/asset", "Manage assets (schematics, structures, clipboard)"), + new PaletteCommand($this, "/asset", "Manage assets (schematics, structures, clipboard)"), /* -- tool -- */ new WandCommand($this, "/wand", "Gives you the selection wand"), new TogglewandCommand($this, "/togglewand", "Toggle the wand tool on/off", ["/toggleeditwand"]), diff --git a/src/xenialdan/MagicWE2/commands/asset/AssetCommand.php b/src/xenialdan/MagicWE2/commands/asset/AssetCommand.php index 90219e39..4217d88f 100644 --- a/src/xenialdan/MagicWE2/commands/asset/AssetCommand.php +++ b/src/xenialdan/MagicWE2/commands/asset/AssetCommand.php @@ -37,7 +37,7 @@ class AssetCommand extends BaseCommand protected function prepare(): void { #$this->registerSubCommand(new BrushNameCommand("name", "Get name or rename a brush")); - $this->setPermission("we.command.brush");//TODO perm + $this->setPermission("we.command.asset");//TODO perm } /** diff --git a/src/xenialdan/MagicWE2/commands/palette/PaletteCommand.php b/src/xenialdan/MagicWE2/commands/palette/PaletteCommand.php new file mode 100644 index 00000000..06b98f15 --- /dev/null +++ b/src/xenialdan/MagicWE2/commands/palette/PaletteCommand.php @@ -0,0 +1,137 @@ +registerSubCommand(new PaletteNameCommand("name", "Get name or rename a palette")); + $this->setPermission("we.command.palette"); + } + + /** + * @param CommandSender $sender + * @param string $aliasUsed + * @param mixed[] $args + * @throws UnderflowException + */ + public function onRun(CommandSender $sender, string $aliasUsed, array $args): void + { + $lang = Loader::getInstance()->getLanguage(); + if ($sender instanceof Player && SessionHelper::hasSession($sender)) { + try { + $lang = SessionHelper::getUserSession($sender)->getLanguage(); + } catch (SessionException $e) { + } + } + if (!$sender instanceof Player) { + $sender->sendMessage(TF::RED . $lang->translateString('error.runingame')); + return; + } + /** @var Player $sender */ + try { + $session = SessionHelper::getUserSession($sender); + if (!$session instanceof UserSession) { + throw new SessionException($lang->translateString('error.nosession', [Loader::getInstance()->getName()])); + } + $form = new SimpleForm(Loader::PREFIX_FORM . TF::BOLD . TF::DARK_PURPLE . $lang->translateString('ui.palette.title'), $lang->translateString('ui.palette.content')); + $form->addButton(new Button($lang->translateString('ui.palette.create'))); + $form->addButton(new Button($lang->translateString('ui.palette.get'))); + $form->addButton(new Button($lang->translateString('ui.palette.edithand'))); + $form->addButton(new Button($lang->translateString('ui.palette.viewhand'))); + $form->setCallable(function (Player $player, $data) use ($lang, $session) { + try { + switch ($data) { + case $lang->translateString('ui.palette.create'): + { + $brush = new Brush(new BrushProperties()); + if ($brush instanceof Brush) { + $player->sendForm($brush->getForm()); + } + break; + } + case $lang->translateString('ui.palette.get'): + { + $menu = InvMenu::create(InvMenu::TYPE_DOUBLE_CHEST); + foreach ($session->getBrushes() as $brush) { + $menu->getInventory()->addItem($brush->toItem()); + } + $menu->send($player, "Session brushes"); + break; + } + case $lang->translateString('ui.palette.edithand'): + { + //TODO + break; + } + case $lang->translateString('ui.palette.viewhand'): + { + $palettes = $session->palettes; + $menu = InvMenu::create(InvMenu::TYPE_DOUBLE_CHEST); + foreach ($palettes->getPalettes() as $palette) { + $menu->getInventory()->addItem($palette->toItem()); + } + $menu->send($player, "Palettes (" . count($palettes->getPalettes()) . ")"); + break; + } + } + return null; + } catch (Exception $error) { + $session->sendMessage(TF::RED . $lang->translateString('error')); + $session->sendMessage(TF::RED . $error->getMessage()); + } + }); + $sender->sendForm($form); + } catch (Exception $error) { + $sender->sendMessage(Loader::PREFIX . TF::RED . $lang->translateString('error.command-error')); + $sender->sendMessage(Loader::PREFIX . TF::RED . $error->getMessage()); + $sender->sendMessage($this->getUsage()); + } + } + + /** + * @param UIElement[] $elements + * @param array $data + * @return array + */ + public static function generateLore(array $elements, array $data): array//TODO remove? + { + $return = []; + foreach ($elements as $i => $element) { + if ($element instanceof Label) continue; + if ($element instanceof Toggle) { + $return[] = ($element->getText() . ": " . ($data[$i] ? "Yes" : "No")); + continue; + } + $return[] = ($element->getText() . ": " . $data[$i]); + } + return $return; + } +} diff --git a/src/xenialdan/MagicWE2/session/UserSession.php b/src/xenialdan/MagicWE2/session/UserSession.php index 67dd8c55..efad4338 100644 --- a/src/xenialdan/MagicWE2/session/UserSession.php +++ b/src/xenialdan/MagicWE2/session/UserSession.php @@ -28,6 +28,7 @@ use xenialdan\MagicWE2\helper\Scoreboard; use xenialdan\MagicWE2\Loader; use xenialdan\MagicWE2\session\data\Asset; +use xenialdan\MagicWE2\session\data\PaletteCollection; use xenialdan\MagicWE2\tool\Brush; use xenialdan\MagicWE2\tool\BrushProperties; @@ -51,6 +52,7 @@ class UserSession extends Session implements JsonSerializable //TODO use JsonMap private Map $brushes; /** @var Map */ private Map $assets; + public PaletteCollection $palettes; /** @var Language|null */ private ?Language $lang = null; public bool $displayOutline = false; @@ -69,6 +71,7 @@ public function __construct(Player $player) $this->redoHistory = new Deque(); $this->brushes = new Map(); $this->assets = new Map(); + $this->palettes = new PaletteCollection(); try { if (is_null($this->lang)) $this->lang = new Language(Language::FALLBACK_LANGUAGE, Loader::getInstance()->getLanguageFolder()); diff --git a/src/xenialdan/MagicWE2/session/data/PaletteCollection.php b/src/xenialdan/MagicWE2/session/data/PaletteCollection.php new file mode 100644 index 00000000..d6821821 --- /dev/null +++ b/src/xenialdan/MagicWE2/session/data/PaletteCollection.php @@ -0,0 +1,33 @@ + */ + public Map $palettes; + + public function __construct() + { + $this->palettes = new Map(); + //$this->initFolders(); + } + + /** @return BlockPalette[] */ + public function getPalettes(): array + { + return $this->palettes->values()->toArray(); + } + + private function initFolders(): void + { + } +} \ No newline at end of file From 4b1db3482bc2d5b111c8a30d9d758bd691a25203 Mon Sep 17 00:00:00 2001 From: XenialDan Date: Thu, 3 Jun 2021 12:44:35 +0200 Subject: [PATCH 26/67] Add missing null check in Scoreboard Signed-off-by: XenialDan --- src/xenialdan/MagicWE2/helper/Scoreboard.php | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/xenialdan/MagicWE2/helper/Scoreboard.php b/src/xenialdan/MagicWE2/helper/Scoreboard.php index 35964eab..9495f0b5 100644 --- a/src/xenialdan/MagicWE2/helper/Scoreboard.php +++ b/src/xenialdan/MagicWE2/helper/Scoreboard.php @@ -31,7 +31,10 @@ public function handleScoreboard(UserSession $session): void ScoreFactory::setScoreLine($player, ++$line, TF::GOLD . $session->getLanguage()->translateString("spacer", ["Selection"])); ScoreFactory::setScoreLine($player, ++$line, TF::BOLD . " Position: " . TF::RESET . API::vecToString($selection->getPos1()->asVector3()) . " » " . API::vecToString($selection->getPos2()->asVector3())); ScoreFactory::setScoreLine($player, ++$line, TF::BOLD . " World: " . TF::RESET . $selection->getWorld()->getFolderName()); - ScoreFactory::setScoreLine($player, ++$line, TF::BOLD . " Shape: " . TF::RESET . (new ReflectionClass($selection->shape))->getShortName()); + if ($selection->shape === null) + ScoreFactory::setScoreLine($player, ++$line, TF::BOLD . " Shape: " . TF::RESET . 'N/A'); + else + ScoreFactory::setScoreLine($player, ++$line, TF::BOLD . " Shape: " . TF::RESET . (new ReflectionClass($selection->shape))->getShortName()); ScoreFactory::setScoreLine($player, ++$line, TF::BOLD . " Size: " . TF::RESET . API::vecToString(new Vector3($selection->getSizeX(), $selection->getSizeY(), $selection->getSizeZ())) . " ({$selection->getShape()->getTotalCount()})"); ScoreFactory::setScoreLine($player, ++$line, TF::GOLD . $session->getLanguage()->translateString("spacer", ["Settings"])); @@ -48,7 +51,10 @@ public function handleScoreboard(UserSession $session): void if ($cb->customName !== "") ScoreFactory::setScoreLine($player, ++$line, TF::BOLD . " Name: " . TF::RESET . $cb->customName); if ($cb->selection instanceof Selection) { - ScoreFactory::setScoreLine($player, ++$line, TF::BOLD . " Shape: " . TF::RESET . (new ReflectionClass($cb->selection->shape))->getShortName()); + if ($cb->selection->shape === null) + ScoreFactory::setScoreLine($player, ++$line, TF::BOLD . " Shape: " . TF::RESET . 'N/A'); + else + ScoreFactory::setScoreLine($player, ++$line, TF::BOLD . " Shape: " . TF::RESET . (new ReflectionClass($cb->selection->shape))->getShortName()); ScoreFactory::setScoreLine($player, ++$line, TF::BOLD . " Size: " . TF::RESET . API::vecToString(new Vector3($cb->selection->getSizeX(), $cb->selection->getSizeY(), $cb->selection->getSizeZ())) . " ({$cb->getTotalCount()})"); } } From 7a94dd4062d4a7c1c022eb80fbeb8db4428d5104 Mon Sep 17 00:00:00 2001 From: XenialDan Date: Sun, 18 Jul 2021 07:44:19 +0200 Subject: [PATCH 27/67] Fix #231, improve getSession code Thanks @muqsit for the hint with UuidInterface as keys. > you probs should use the uuid string to map user sessions though > because if f.e., you get their uuid from database and create a new uuid containing the same value, it'll mismatch This should now work a lot better. Signed-off-by: XenialDan --- plugin.yml | 2 +- src/xenialdan/MagicWE2/API.php | 4 ++ src/xenialdan/MagicWE2/EventListener.php | 19 ++---- src/xenialdan/MagicWE2/Loader.php | 3 +- .../MagicWE2/commands/DonateCommand.php | 2 - .../MagicWE2/commands/HelpCommand.php | 2 - .../MagicWE2/commands/InfoCommand.php | 2 - .../MagicWE2/commands/LanguageCommand.php | 2 - .../MagicWE2/commands/LimitCommand.php | 2 - .../MagicWE2/commands/ReportCommand.php | 4 +- .../MagicWE2/commands/SetRangeCommand.php | 2 - .../MagicWE2/commands/TestCommand.php | 2 - .../MagicWE2/commands/VersionCommand.php | 2 - .../MagicWE2/commands/args/BlocksArgument.php | 6 +- .../MagicWE2/commands/asset/AssetCommand.php | 6 +- .../commands/biome/BiomeInfoCommand.php | 2 - .../commands/biome/BiomeListCommand.php | 3 - .../commands/biome/SetBiomeCommand.php | 2 - .../MagicWE2/commands/brush/BrushCommand.php | 2 - .../commands/brush/BrushNameCommand.php | 2 - .../clipboard/ClearClipboardCommand.php | 2 - .../commands/clipboard/CopyCommand.php | 2 - .../commands/clipboard/Cut2Command.php | 2 - .../commands/clipboard/CutCommand.php | 2 - .../commands/clipboard/FlipCommand.php | 2 - .../commands/clipboard/PasteCommand.php | 2 - .../commands/clipboard/RotateCommand.php | 2 - .../debug/PlaceAllBlockstatesCommand.php | 2 - .../commands/generation/CylinderCommand.php | 2 - .../commands/history/ClearhistoryCommand.php | 2 - .../MagicWE2/commands/history/RedoCommand.php | 2 - .../MagicWE2/commands/history/UndoCommand.php | 2 - .../commands/palette/PaletteCommand.php | 2 - .../commands/region/OverlayCommand.php | 2 - .../commands/region/ReplaceCommand.php | 2 - .../MagicWE2/commands/region/SetCommand.php | 2 - .../commands/selection/ChunkCommand.php | 2 - .../commands/selection/HPos1Command.php | 2 - .../commands/selection/HPos2Command.php | 2 - .../commands/selection/Pos1Command.php | 2 - .../commands/selection/Pos2Command.php | 2 - .../commands/selection/info/CountCommand.php | 2 - .../selection/info/ListChunksCommand.php | 2 - .../commands/selection/info/SizeCommand.php | 2 - .../MagicWE2/commands/tool/DebugCommand.php | 21 +++---- .../commands/tool/ToggledebugCommand.php | 2 - .../commands/tool/TogglewandCommand.php | 2 - .../MagicWE2/commands/tool/WandCommand.php | 23 +++---- .../commands/utility/CalculateCommand.php | 2 - .../commands/utility/ToggleWailaCommand.php | 2 - .../MagicWE2/helper/BlockPalette.php | 16 ++++- src/xenialdan/MagicWE2/helper/BlockQuery.php | 5 ++ .../MagicWE2/helper/BlockStatesEntry.php | 7 ++- .../MagicWE2/helper/BlockStatesParser.php | 31 +++++++--- .../MagicWE2/helper/SessionHelper.php | 62 ++++++------------- .../MagicWE2/helper/WeightedRandom.php | 8 +-- .../MagicWE2/selection/Selection.php | 6 -- .../MagicWE2/session/PluginSession.php | 6 +- src/xenialdan/MagicWE2/session/Session.php | 18 +++--- .../MagicWE2/session/UserSession.php | 32 +++++----- src/xenialdan/MagicWE2/session/data/Asset.php | 12 ++-- .../MagicWE2/session/data/AssetCollection.php | 25 ++++---- .../session/data/PaletteCollection.php | 8 +-- .../MagicWE2/task/AsyncActionTask.php | 6 -- .../task/AsyncClipboardActionTask.php | 6 -- .../MagicWE2/task/AsyncCountTask.php | 4 -- src/xenialdan/MagicWE2/task/AsyncFillTask.php | 12 ++-- .../MagicWE2/task/AsyncPasteAssetTask.php | 6 -- .../MagicWE2/task/AsyncPasteTask.php | 4 -- .../MagicWE2/task/AsyncReplaceTask.php | 4 -- .../MagicWE2/task/AsyncRevertTask.php | 4 -- 71 files changed, 160 insertions(+), 293 deletions(-) diff --git a/plugin.yml b/plugin.yml index a548ce63..020a9c5d 100644 --- a/plugin.yml +++ b/plugin.yml @@ -1,7 +1,7 @@ --- name: MagicWE2 main: xenialdan\MagicWE2\Loader -version: 10.1.5 +version: 10.1.6 api: ["4.0.0"] php: [ "8.0" ] softdepend: [ "DEVirion" ] diff --git a/src/xenialdan/MagicWE2/API.php b/src/xenialdan/MagicWE2/API.php index 1ec3c1bc..aa4ba0cb 100644 --- a/src/xenialdan/MagicWE2/API.php +++ b/src/xenialdan/MagicWE2/API.php @@ -9,9 +9,11 @@ use pocketmine\block\Block; use pocketmine\block\BlockFactory; use pocketmine\block\utils\InvalidBlockStateException; +use pocketmine\item\LegacyStringToItemParserException; use pocketmine\math\AxisAlignedBB; use pocketmine\math\Vector3; use pocketmine\nbt\tag\CompoundTag; +use pocketmine\nbt\UnexpectedTagTypeException; use pocketmine\player\Player; use pocketmine\Server; use pocketmine\utils\AssumptionFailedError; @@ -445,6 +447,8 @@ public static function hasFlag(int $flags, int $check): bool * @throws BlockQueryAlreadyParsedException * @throws InvalidArgumentException * @throws InvalidBlockStateException + * @throws LegacyStringToItemParserException + * @throws UnexpectedTagTypeException * @deprecated Use BlockPalette::fromString() */ public static function blockParser(string $fullstring, array &$messages, bool &$error): BlockPalette diff --git a/src/xenialdan/MagicWE2/EventListener.php b/src/xenialdan/MagicWE2/EventListener.php index be5fcf70..83be05a6 100644 --- a/src/xenialdan/MagicWE2/EventListener.php +++ b/src/xenialdan/MagicWE2/EventListener.php @@ -7,7 +7,6 @@ use InvalidArgumentException; use InvalidStateException; use JsonException; -use OutOfBoundsException; use pocketmine\block\BlockFactory; use pocketmine\block\BlockLegacyIds; use pocketmine\entity\InvalidSkinException; @@ -28,7 +27,6 @@ use pocketmine\utils\TextFormat as TF; use pocketmine\world\Position; use RuntimeException; -use UnderflowException; use xenialdan\customui\windows\ModalForm; use xenialdan\libstructure\tile\StructureBlockTile; use xenialdan\MagicWE2\event\MWESelectionChangeEvent; @@ -83,9 +81,7 @@ public function onSessionLoad(MWESessionLoadEvent $event): void /** * @param PlayerQuitEvent $event * @throws JsonException - * @throws OutOfBoundsException * @throws SessionException - * @throws UnderflowException */ public function onLogout(PlayerQuitEvent $event): void { @@ -139,6 +135,7 @@ public function onItemRightClick(PlayerItemUseEvent $event): void * @param BlockBreakEvent $event * @throws AssumptionFailedError * @throws Error + * @throws UnexpectedTagTypeException */ public function onBreak(BlockBreakEvent $event): void { @@ -177,9 +174,7 @@ public function onBreak(BlockBreakEvent $event): void * @throws AssumptionFailedError * @throws Error * @throws InvalidArgumentException - * @throws OutOfBoundsException * @throws SessionException - * @throws UnderflowException */ private function onBreakBlock(BlockBreakEvent $event): void { @@ -218,9 +213,8 @@ private function onBreakBlock(BlockBreakEvent $event): void * @throws Error * @throws InvalidArgumentException * @throws InvalidStateException - * @throws OutOfBoundsException * @throws SessionException - * @throws UnderflowException + * @throws UnexpectedTagTypeException */ private function onRightClickBlock(PlayerInteractEvent $event): void { @@ -263,7 +257,7 @@ private function onRightClickBlock(PlayerInteractEvent $event): void $tag = $event->getItem()->getNamedTag()->getCompoundTag(API::TAG_MAGIC_WE_ASSET); if ($tag !== null) { $filename = $tag->getString('filename'); - $asset = AssetCollection::getInstance()->assets->get($filename); + $asset = AssetCollection::getInstance()->assets[$filename]; $target = $event->getBlock()->getSide($event->getFace())->getPos(); if (API::placeAsset($target, $asset, $tag, $session)) { $event->getPlayer()->sendMessage("Asset placed!"); @@ -289,10 +283,8 @@ private function onRightClickBlock(PlayerInteractEvent $event): void * @throws Error * @throws InvalidArgumentException * @throws InvalidStateException - * @throws OutOfBoundsException * @throws SessionException * @throws UnexpectedTagTypeException - * @throws UnderflowException */ private function onLeftClickBlock(PlayerInteractEvent $event): void { @@ -398,9 +390,8 @@ public function onSelectionChange(MWESelectionChangeEvent $event): void /** * TODO use tool classes * @param PlayerItemHeldEvent $event - * @throws OutOfBoundsException * @throws SessionException - * @throws UnderflowException + * @throws UnexpectedTagTypeException */ public function onChangeSlot(PlayerItemHeldEvent $event): void { @@ -413,7 +404,7 @@ public function onChangeSlot(PlayerItemHeldEvent $event): void if (!$session instanceof UserSession) return; if ($item->getId() === ItemIds::SCAFFOLDING) { $filename = $tag->getString('filename'); - $asset = AssetCollection::getInstance()->assets->get($filename); + $asset = AssetCollection::getInstance()->assets[$filename]; var_dump($filename, $asset); #$assets = AssetCollection::getInstance()->getPlayerAssets($player->getXuid()); $session->displayOutline = true; diff --git a/src/xenialdan/MagicWE2/Loader.php b/src/xenialdan/MagicWE2/Loader.php index 148753df..c9b11f2a 100644 --- a/src/xenialdan/MagicWE2/Loader.php +++ b/src/xenialdan/MagicWE2/Loader.php @@ -24,7 +24,6 @@ use xenialdan\apibossbar\DiverseBossBar; use xenialdan\customui\API as CustomUIAPI; use xenialdan\libstructure\PacketListener; -use xenialdan\MagicWE2\commands\asset\PaletteCommand; use xenialdan\MagicWE2\commands\biome\BiomeInfoCommand; use xenialdan\MagicWE2\commands\biome\BiomeListCommand; use xenialdan\MagicWE2\commands\biome\SetBiomeCommand; @@ -219,7 +218,7 @@ public function onEnable(): void new HPos2Command($this, "/hpos2", "Set position 2 to targeted block", ["/h2"]), new ChunkCommand($this, "/chunk", "Set the selection to your current chunk"), /* -- assets -- */ - new PaletteCommand($this, "/asset", "Manage assets (schematics, structures, clipboard)"), + #new PaletteCommand($this, "/asset", "Manage assets (schematics, structures, clipboard)"), /* -- tool -- */ new WandCommand($this, "/wand", "Gives you the selection wand"), new TogglewandCommand($this, "/togglewand", "Toggle the wand tool on/off", ["/toggleeditwand"]), diff --git a/src/xenialdan/MagicWE2/commands/DonateCommand.php b/src/xenialdan/MagicWE2/commands/DonateCommand.php index fa2ac7b6..db3e865e 100644 --- a/src/xenialdan/MagicWE2/commands/DonateCommand.php +++ b/src/xenialdan/MagicWE2/commands/DonateCommand.php @@ -10,7 +10,6 @@ use pocketmine\command\CommandSender; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; -use UnderflowException; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\SessionHelper; use xenialdan\MagicWE2\Loader; @@ -31,7 +30,6 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args - * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/HelpCommand.php b/src/xenialdan/MagicWE2/commands/HelpCommand.php index 29f2a792..6fa89cf6 100644 --- a/src/xenialdan/MagicWE2/commands/HelpCommand.php +++ b/src/xenialdan/MagicWE2/commands/HelpCommand.php @@ -13,7 +13,6 @@ use pocketmine\command\CommandSender; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; -use UnderflowException; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\SessionHelper; use xenialdan\MagicWE2\Loader; @@ -35,7 +34,6 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args - * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/InfoCommand.php b/src/xenialdan/MagicWE2/commands/InfoCommand.php index 70d849cb..074a598d 100644 --- a/src/xenialdan/MagicWE2/commands/InfoCommand.php +++ b/src/xenialdan/MagicWE2/commands/InfoCommand.php @@ -10,7 +10,6 @@ use pocketmine\command\CommandSender; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; -use UnderflowException; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\SessionHelper; use xenialdan\MagicWE2\Loader; @@ -31,7 +30,6 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args - * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/LanguageCommand.php b/src/xenialdan/MagicWE2/commands/LanguageCommand.php index bae4a54b..8e6701e2 100644 --- a/src/xenialdan/MagicWE2/commands/LanguageCommand.php +++ b/src/xenialdan/MagicWE2/commands/LanguageCommand.php @@ -11,7 +11,6 @@ use pocketmine\command\CommandSender; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; -use UnderflowException; use xenialdan\customui\elements\Dropdown; use xenialdan\customui\elements\Label; use xenialdan\customui\windows\CustomForm; @@ -38,7 +37,6 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args - * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/LimitCommand.php b/src/xenialdan/MagicWE2/commands/LimitCommand.php index 7a1cc93d..0fd34061 100644 --- a/src/xenialdan/MagicWE2/commands/LimitCommand.php +++ b/src/xenialdan/MagicWE2/commands/LimitCommand.php @@ -12,7 +12,6 @@ use pocketmine\command\CommandSender; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; -use UnderflowException; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\SessionHelper; use xenialdan\MagicWE2\Loader; @@ -36,7 +35,6 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args - * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/ReportCommand.php b/src/xenialdan/MagicWE2/commands/ReportCommand.php index e532fe22..c5323e50 100644 --- a/src/xenialdan/MagicWE2/commands/ReportCommand.php +++ b/src/xenialdan/MagicWE2/commands/ReportCommand.php @@ -10,10 +10,9 @@ use Exception; use InvalidArgumentException; use pocketmine\command\CommandSender; -use pocketmine\command\ConsoleCommandSender; +use pocketmine\console\ConsoleCommandSender; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; -use UnderflowException; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\SessionHelper; use xenialdan\MagicWE2\Loader; @@ -36,7 +35,6 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args - * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/SetRangeCommand.php b/src/xenialdan/MagicWE2/commands/SetRangeCommand.php index 776217bc..60e1171d 100644 --- a/src/xenialdan/MagicWE2/commands/SetRangeCommand.php +++ b/src/xenialdan/MagicWE2/commands/SetRangeCommand.php @@ -12,7 +12,6 @@ use pocketmine\command\CommandSender; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; -use UnderflowException; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\SessionHelper; use xenialdan\MagicWE2\Loader; @@ -36,7 +35,6 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args - * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/TestCommand.php b/src/xenialdan/MagicWE2/commands/TestCommand.php index 6ad99468..f16dc71a 100644 --- a/src/xenialdan/MagicWE2/commands/TestCommand.php +++ b/src/xenialdan/MagicWE2/commands/TestCommand.php @@ -11,7 +11,6 @@ use pocketmine\player\Player; use pocketmine\Server; use pocketmine\utils\TextFormat as TF; -use UnderflowException; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\BlockPalette; use xenialdan\MagicWE2\helper\SessionHelper; @@ -36,7 +35,6 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args - * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/VersionCommand.php b/src/xenialdan/MagicWE2/commands/VersionCommand.php index 8e6647c7..b8166e60 100644 --- a/src/xenialdan/MagicWE2/commands/VersionCommand.php +++ b/src/xenialdan/MagicWE2/commands/VersionCommand.php @@ -10,7 +10,6 @@ use pocketmine\command\CommandSender; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; -use UnderflowException; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\SessionHelper; use xenialdan\MagicWE2\Loader; @@ -31,7 +30,6 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args - * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/args/BlocksArgument.php b/src/xenialdan/MagicWE2/commands/args/BlocksArgument.php index 594fc606..0ae0d7f0 100644 --- a/src/xenialdan/MagicWE2/commands/args/BlocksArgument.php +++ b/src/xenialdan/MagicWE2/commands/args/BlocksArgument.php @@ -8,9 +8,10 @@ use InvalidArgumentException as InvalidArgumentExceptionAlias; use pocketmine\block\utils\InvalidBlockStateException; use pocketmine\command\CommandSender; +use pocketmine\item\LegacyStringToItemParserException; +use pocketmine\nbt\UnexpectedTagTypeException; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; -use UnderflowException; use xenialdan\MagicWE2\exception\BlockQueryAlreadyParsedException; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\BlockPalette; @@ -34,8 +35,9 @@ public function canParse(string $testString, CommandSender $sender): bool * @param CommandSender $sender * * @return BlockPalette - * @throws UnderflowException * @throws SessionException + * @throws LegacyStringToItemParserException + * @throws UnexpectedTagTypeException */ public function parse(string $argument, CommandSender $sender) { diff --git a/src/xenialdan/MagicWE2/commands/asset/AssetCommand.php b/src/xenialdan/MagicWE2/commands/asset/AssetCommand.php index 4217d88f..386c474b 100644 --- a/src/xenialdan/MagicWE2/commands/asset/AssetCommand.php +++ b/src/xenialdan/MagicWE2/commands/asset/AssetCommand.php @@ -12,7 +12,6 @@ use pocketmine\command\CommandSender; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; -use UnderflowException; use xenialdan\customui\elements\Button; use xenialdan\customui\elements\Label; use xenialdan\customui\elements\Toggle; @@ -44,7 +43,6 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args - * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { @@ -106,7 +104,7 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo $form->setCallable(function (Player $player, $data) use (/*$lang, $session,*/ $store) { [$filename, $type] = $data; /** @var Asset $asset */ - $asset = $store->assets->get($filename); + $asset = $store->assets[$filename]; $player->sendMessage('Saving ' . (string)$asset); //TODO async, convert if ($type === Asset::TYPE_SCHEMATIC) { @@ -150,7 +148,7 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo $form->setCallable(function (Player $player, $data) use (/*$lang, $session,*/ $store) { [$filename] = $data; /** @var Asset $asset */ - $asset = $store->assets->get($filename); + $asset = $store->assets[$filename]; $player->sendForm($asset->getSettingForm()); }); $player->sendForm($form); diff --git a/src/xenialdan/MagicWE2/commands/biome/BiomeInfoCommand.php b/src/xenialdan/MagicWE2/commands/biome/BiomeInfoCommand.php index 3a8ac463..99e09a86 100644 --- a/src/xenialdan/MagicWE2/commands/biome/BiomeInfoCommand.php +++ b/src/xenialdan/MagicWE2/commands/biome/BiomeInfoCommand.php @@ -17,7 +17,6 @@ use pocketmine\world\biome\BiomeRegistry; use pocketmine\world\format\io\FastChunkSerializer; use ReflectionClass; -use UnderflowException; use xenialdan\MagicWE2\exception\SelectionException; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\SessionHelper; @@ -43,7 +42,6 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args - * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/biome/BiomeListCommand.php b/src/xenialdan/MagicWE2/commands/biome/BiomeListCommand.php index ef7bfa80..41ad97ce 100644 --- a/src/xenialdan/MagicWE2/commands/biome/BiomeListCommand.php +++ b/src/xenialdan/MagicWE2/commands/biome/BiomeListCommand.php @@ -13,7 +13,6 @@ use pocketmine\world\biome\Biome; use pocketmine\world\biome\BiomeRegistry; use ReflectionClass; -use UnderflowException; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\SessionHelper; use xenialdan\MagicWE2\Loader; @@ -34,8 +33,6 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args - * @throws UnderflowException - * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/biome/SetBiomeCommand.php b/src/xenialdan/MagicWE2/commands/biome/SetBiomeCommand.php index 71d9256d..d7d0219f 100644 --- a/src/xenialdan/MagicWE2/commands/biome/SetBiomeCommand.php +++ b/src/xenialdan/MagicWE2/commands/biome/SetBiomeCommand.php @@ -12,7 +12,6 @@ use pocketmine\command\CommandSender; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; -use UnderflowException; use xenialdan\MagicWE2\API; use xenialdan\MagicWE2\exception\SelectionException; use xenialdan\MagicWE2\exception\SessionException; @@ -39,7 +38,6 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args - * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/brush/BrushCommand.php b/src/xenialdan/MagicWE2/commands/brush/BrushCommand.php index 94c04cf7..89d8d708 100644 --- a/src/xenialdan/MagicWE2/commands/brush/BrushCommand.php +++ b/src/xenialdan/MagicWE2/commands/brush/BrushCommand.php @@ -11,7 +11,6 @@ use pocketmine\command\CommandSender; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; -use UnderflowException; use xenialdan\customui\elements\Button; use xenialdan\customui\elements\Label; use xenialdan\customui\elements\Toggle; @@ -40,7 +39,6 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args - * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/brush/BrushNameCommand.php b/src/xenialdan/MagicWE2/commands/brush/BrushNameCommand.php index f2152886..482a42ac 100644 --- a/src/xenialdan/MagicWE2/commands/brush/BrushNameCommand.php +++ b/src/xenialdan/MagicWE2/commands/brush/BrushNameCommand.php @@ -12,7 +12,6 @@ use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; use TypeError; -use UnderflowException; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\SessionHelper; use xenialdan\MagicWE2\Loader; @@ -35,7 +34,6 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args - * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/clipboard/ClearClipboardCommand.php b/src/xenialdan/MagicWE2/commands/clipboard/ClearClipboardCommand.php index 8493ea48..cc782867 100644 --- a/src/xenialdan/MagicWE2/commands/clipboard/ClearClipboardCommand.php +++ b/src/xenialdan/MagicWE2/commands/clipboard/ClearClipboardCommand.php @@ -10,7 +10,6 @@ use pocketmine\command\CommandSender; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; -use UnderflowException; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\SessionHelper; use xenialdan\MagicWE2\Loader; @@ -32,7 +31,6 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args - * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/clipboard/CopyCommand.php b/src/xenialdan/MagicWE2/commands/clipboard/CopyCommand.php index 39c4823d..b006a33a 100644 --- a/src/xenialdan/MagicWE2/commands/clipboard/CopyCommand.php +++ b/src/xenialdan/MagicWE2/commands/clipboard/CopyCommand.php @@ -12,7 +12,6 @@ use pocketmine\command\CommandSender; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; -use UnderflowException; use xenialdan\MagicWE2\API; use xenialdan\MagicWE2\exception\SelectionException; use xenialdan\MagicWE2\exception\SessionException; @@ -37,7 +36,6 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args - * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/clipboard/Cut2Command.php b/src/xenialdan/MagicWE2/commands/clipboard/Cut2Command.php index ad9b1511..7dc16cec 100644 --- a/src/xenialdan/MagicWE2/commands/clipboard/Cut2Command.php +++ b/src/xenialdan/MagicWE2/commands/clipboard/Cut2Command.php @@ -13,7 +13,6 @@ use pocketmine\player\Player; use pocketmine\Server; use pocketmine\utils\TextFormat as TF; -use UnderflowException; use xenialdan\MagicWE2\exception\SelectionException; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\BlockPalette; @@ -41,7 +40,6 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args - * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/clipboard/CutCommand.php b/src/xenialdan/MagicWE2/commands/clipboard/CutCommand.php index 29810bd5..16a56bc0 100644 --- a/src/xenialdan/MagicWE2/commands/clipboard/CutCommand.php +++ b/src/xenialdan/MagicWE2/commands/clipboard/CutCommand.php @@ -12,7 +12,6 @@ use pocketmine\command\CommandSender; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; -use UnderflowException; use xenialdan\MagicWE2\API; use xenialdan\MagicWE2\exception\SelectionException; use xenialdan\MagicWE2\exception\SessionException; @@ -38,7 +37,6 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args - * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/clipboard/FlipCommand.php b/src/xenialdan/MagicWE2/commands/clipboard/FlipCommand.php index 9e4a011c..40fdc672 100644 --- a/src/xenialdan/MagicWE2/commands/clipboard/FlipCommand.php +++ b/src/xenialdan/MagicWE2/commands/clipboard/FlipCommand.php @@ -12,7 +12,6 @@ use pocketmine\player\Player; use pocketmine\Server; use pocketmine\utils\TextFormat as TF; -use UnderflowException; use xenialdan\MagicWE2\clipboard\SingleClipboard; use xenialdan\MagicWE2\commands\args\MirrorAxisArgument; use xenialdan\MagicWE2\exception\SessionException; @@ -40,7 +39,6 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args - * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/clipboard/PasteCommand.php b/src/xenialdan/MagicWE2/commands/clipboard/PasteCommand.php index 3d840dbf..e3660ddd 100644 --- a/src/xenialdan/MagicWE2/commands/clipboard/PasteCommand.php +++ b/src/xenialdan/MagicWE2/commands/clipboard/PasteCommand.php @@ -13,7 +13,6 @@ use pocketmine\player\Player; use pocketmine\utils\AssumptionFailedError; use pocketmine\utils\TextFormat as TF; -use UnderflowException; use xenialdan\MagicWE2\API; use xenialdan\MagicWE2\clipboard\SingleClipboard; use xenialdan\MagicWE2\exception\SelectionException; @@ -40,7 +39,6 @@ protected function prepare(): void * @param string $aliasUsed * @param mixed[] $args * @throws AssumptionFailedError - * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/clipboard/RotateCommand.php b/src/xenialdan/MagicWE2/commands/clipboard/RotateCommand.php index 1e3bdbe9..e0c0461d 100644 --- a/src/xenialdan/MagicWE2/commands/clipboard/RotateCommand.php +++ b/src/xenialdan/MagicWE2/commands/clipboard/RotateCommand.php @@ -13,7 +13,6 @@ use pocketmine\player\Player; use pocketmine\Server; use pocketmine\utils\TextFormat as TF; -use UnderflowException; use xenialdan\MagicWE2\clipboard\SingleClipboard; use xenialdan\MagicWE2\commands\args\RotateAngleArgument; use xenialdan\MagicWE2\exception\SessionException; @@ -41,7 +40,6 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args - * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/debug/PlaceAllBlockstatesCommand.php b/src/xenialdan/MagicWE2/commands/debug/PlaceAllBlockstatesCommand.php index dee44ef2..a213c2a9 100644 --- a/src/xenialdan/MagicWE2/commands/debug/PlaceAllBlockstatesCommand.php +++ b/src/xenialdan/MagicWE2/commands/debug/PlaceAllBlockstatesCommand.php @@ -10,7 +10,6 @@ use pocketmine\command\CommandSender; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; -use UnderflowException; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\BlockStatesParser; use xenialdan\MagicWE2\helper\SessionHelper; @@ -31,7 +30,6 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args - * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/generation/CylinderCommand.php b/src/xenialdan/MagicWE2/commands/generation/CylinderCommand.php index a6fe6a0e..651c46ff 100644 --- a/src/xenialdan/MagicWE2/commands/generation/CylinderCommand.php +++ b/src/xenialdan/MagicWE2/commands/generation/CylinderCommand.php @@ -13,7 +13,6 @@ use pocketmine\command\CommandSender; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; -use UnderflowException; use xenialdan\MagicWE2\API; use xenialdan\MagicWE2\commands\args\BlocksArgument; use xenialdan\MagicWE2\exception\SessionException; @@ -42,7 +41,6 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args - * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/history/ClearhistoryCommand.php b/src/xenialdan/MagicWE2/commands/history/ClearhistoryCommand.php index 211dc52a..6fd92d1e 100644 --- a/src/xenialdan/MagicWE2/commands/history/ClearhistoryCommand.php +++ b/src/xenialdan/MagicWE2/commands/history/ClearhistoryCommand.php @@ -10,7 +10,6 @@ use pocketmine\command\CommandSender; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; -use UnderflowException; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\SessionHelper; use xenialdan\MagicWE2\Loader; @@ -32,7 +31,6 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args - * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/history/RedoCommand.php b/src/xenialdan/MagicWE2/commands/history/RedoCommand.php index 5aca3343..937e5efd 100644 --- a/src/xenialdan/MagicWE2/commands/history/RedoCommand.php +++ b/src/xenialdan/MagicWE2/commands/history/RedoCommand.php @@ -10,7 +10,6 @@ use pocketmine\command\CommandSender; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; -use UnderflowException; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\SessionHelper; use xenialdan\MagicWE2\Loader; @@ -32,7 +31,6 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args - * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/history/UndoCommand.php b/src/xenialdan/MagicWE2/commands/history/UndoCommand.php index a0857188..da8476dc 100644 --- a/src/xenialdan/MagicWE2/commands/history/UndoCommand.php +++ b/src/xenialdan/MagicWE2/commands/history/UndoCommand.php @@ -10,7 +10,6 @@ use pocketmine\command\CommandSender; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; -use UnderflowException; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\SessionHelper; use xenialdan\MagicWE2\Loader; @@ -32,7 +31,6 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args - * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/palette/PaletteCommand.php b/src/xenialdan/MagicWE2/commands/palette/PaletteCommand.php index 06b98f15..09525b05 100644 --- a/src/xenialdan/MagicWE2/commands/palette/PaletteCommand.php +++ b/src/xenialdan/MagicWE2/commands/palette/PaletteCommand.php @@ -11,7 +11,6 @@ use pocketmine\command\CommandSender; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; -use UnderflowException; use xenialdan\customui\elements\Button; use xenialdan\customui\elements\Label; use xenialdan\customui\elements\Toggle; @@ -40,7 +39,6 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args - * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/region/OverlayCommand.php b/src/xenialdan/MagicWE2/commands/region/OverlayCommand.php index cfa10393..a8069582 100644 --- a/src/xenialdan/MagicWE2/commands/region/OverlayCommand.php +++ b/src/xenialdan/MagicWE2/commands/region/OverlayCommand.php @@ -11,7 +11,6 @@ use pocketmine\command\CommandSender; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; -use UnderflowException; use xenialdan\MagicWE2\commands\args\BlocksArgument; use xenialdan\MagicWE2\exception\SelectionException; use xenialdan\MagicWE2\exception\SessionException; @@ -36,7 +35,6 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args - * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/region/ReplaceCommand.php b/src/xenialdan/MagicWE2/commands/region/ReplaceCommand.php index e56c94ca..bac9bf73 100644 --- a/src/xenialdan/MagicWE2/commands/region/ReplaceCommand.php +++ b/src/xenialdan/MagicWE2/commands/region/ReplaceCommand.php @@ -12,7 +12,6 @@ use pocketmine\command\CommandSender; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; -use UnderflowException; use xenialdan\MagicWE2\API; use xenialdan\MagicWE2\commands\args\BlocksArgument; use xenialdan\MagicWE2\exception\SelectionException; @@ -40,7 +39,6 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args - * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/region/SetCommand.php b/src/xenialdan/MagicWE2/commands/region/SetCommand.php index 24a14c76..bca8b276 100644 --- a/src/xenialdan/MagicWE2/commands/region/SetCommand.php +++ b/src/xenialdan/MagicWE2/commands/region/SetCommand.php @@ -12,7 +12,6 @@ use pocketmine\command\CommandSender; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; -use UnderflowException; use xenialdan\MagicWE2\API; use xenialdan\MagicWE2\commands\args\BlocksArgument; use xenialdan\MagicWE2\exception\SelectionException; @@ -39,7 +38,6 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args - * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/selection/ChunkCommand.php b/src/xenialdan/MagicWE2/commands/selection/ChunkCommand.php index 6e39b406..7aac45f6 100644 --- a/src/xenialdan/MagicWE2/commands/selection/ChunkCommand.php +++ b/src/xenialdan/MagicWE2/commands/selection/ChunkCommand.php @@ -14,7 +14,6 @@ use pocketmine\utils\TextFormat as TF; use pocketmine\world\Position; use pocketmine\world\World; -use UnderflowException; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\SessionHelper; use xenialdan\MagicWE2\Loader; @@ -37,7 +36,6 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args - * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/selection/HPos1Command.php b/src/xenialdan/MagicWE2/commands/selection/HPos1Command.php index af283cd5..bcfdcc69 100644 --- a/src/xenialdan/MagicWE2/commands/selection/HPos1Command.php +++ b/src/xenialdan/MagicWE2/commands/selection/HPos1Command.php @@ -11,7 +11,6 @@ use pocketmine\command\CommandSender; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; -use UnderflowException; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\SessionHelper; use xenialdan\MagicWE2\Loader; @@ -34,7 +33,6 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args - * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/selection/HPos2Command.php b/src/xenialdan/MagicWE2/commands/selection/HPos2Command.php index d7c4b271..a217a941 100644 --- a/src/xenialdan/MagicWE2/commands/selection/HPos2Command.php +++ b/src/xenialdan/MagicWE2/commands/selection/HPos2Command.php @@ -11,7 +11,6 @@ use pocketmine\command\CommandSender; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; -use UnderflowException; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\SessionHelper; use xenialdan\MagicWE2\Loader; @@ -34,7 +33,6 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args - * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/selection/Pos1Command.php b/src/xenialdan/MagicWE2/commands/selection/Pos1Command.php index 148d48c7..b95a1bef 100644 --- a/src/xenialdan/MagicWE2/commands/selection/Pos1Command.php +++ b/src/xenialdan/MagicWE2/commands/selection/Pos1Command.php @@ -11,7 +11,6 @@ use pocketmine\command\CommandSender; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; -use UnderflowException; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\SessionHelper; use xenialdan\MagicWE2\Loader; @@ -34,7 +33,6 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args - * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/selection/Pos2Command.php b/src/xenialdan/MagicWE2/commands/selection/Pos2Command.php index 7b53c9ea..d3e2d781 100644 --- a/src/xenialdan/MagicWE2/commands/selection/Pos2Command.php +++ b/src/xenialdan/MagicWE2/commands/selection/Pos2Command.php @@ -11,7 +11,6 @@ use pocketmine\command\CommandSender; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; -use UnderflowException; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\SessionHelper; use xenialdan\MagicWE2\Loader; @@ -34,7 +33,6 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args - * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/selection/info/CountCommand.php b/src/xenialdan/MagicWE2/commands/selection/info/CountCommand.php index 960616a6..ba220907 100644 --- a/src/xenialdan/MagicWE2/commands/selection/info/CountCommand.php +++ b/src/xenialdan/MagicWE2/commands/selection/info/CountCommand.php @@ -13,7 +13,6 @@ use pocketmine\player\Player; use pocketmine\Server; use pocketmine\utils\TextFormat as TF; -use UnderflowException; use xenialdan\MagicWE2\commands\args\BlocksArgument; use xenialdan\MagicWE2\exception\SelectionException; use xenialdan\MagicWE2\exception\SessionException; @@ -42,7 +41,6 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args - * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/selection/info/ListChunksCommand.php b/src/xenialdan/MagicWE2/commands/selection/info/ListChunksCommand.php index 59d3a216..c5de7b0d 100644 --- a/src/xenialdan/MagicWE2/commands/selection/info/ListChunksCommand.php +++ b/src/xenialdan/MagicWE2/commands/selection/info/ListChunksCommand.php @@ -12,7 +12,6 @@ use pocketmine\utils\TextFormat as TF; use pocketmine\world\format\io\FastChunkSerializer; use pocketmine\world\World; -use UnderflowException; use xenialdan\MagicWE2\exception\SelectionException; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\SessionHelper; @@ -34,7 +33,6 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args - * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/selection/info/SizeCommand.php b/src/xenialdan/MagicWE2/commands/selection/info/SizeCommand.php index f99953a0..4c1e0b04 100644 --- a/src/xenialdan/MagicWE2/commands/selection/info/SizeCommand.php +++ b/src/xenialdan/MagicWE2/commands/selection/info/SizeCommand.php @@ -10,7 +10,6 @@ use pocketmine\command\CommandSender; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; -use UnderflowException; use xenialdan\MagicWE2\exception\SelectionException; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\SessionHelper; @@ -32,7 +31,6 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args - * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/tool/DebugCommand.php b/src/xenialdan/MagicWE2/commands/tool/DebugCommand.php index 860b9153..bd92bcba 100644 --- a/src/xenialdan/MagicWE2/commands/tool/DebugCommand.php +++ b/src/xenialdan/MagicWE2/commands/tool/DebugCommand.php @@ -10,12 +10,10 @@ use InvalidArgumentException; use pocketmine\command\CommandSender; use pocketmine\item\enchantment\EnchantmentInstance; -use pocketmine\item\ItemFactory; -use pocketmine\item\ItemIds; +use pocketmine\item\VanillaItems; use pocketmine\nbt\tag\CompoundTag; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; -use UnderflowException; use xenialdan\MagicWE2\API; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\SessionHelper; @@ -37,7 +35,6 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args - * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { @@ -54,14 +51,14 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo } /** @var Player $sender */ try { - $item = ItemFactory::getInstance()->get(ItemIds::STICK); - $item->addEnchantment(new EnchantmentInstance(Loader::$ench)); - $item->setCustomName(Loader::PREFIX . TF::BOLD . TF::LIGHT_PURPLE . $lang->translateString('tool.debug')); - $item->setLore([ - TF::RESET . $lang->translateString('tool.debug.lore.1'), - TF::RESET . $lang->translateString('tool.debug.lore.2'), - TF::RESET . $lang->translateString('tool.debug.lore.3') - ]); + $item = VanillaItems::STICK() + ->addEnchantment(new EnchantmentInstance(Loader::$ench)) + ->setCustomName(Loader::PREFIX . TF::BOLD . TF::LIGHT_PURPLE . $lang->translateString('tool.debug')) + ->setLore([ + TF::RESET . $lang->translateString('tool.debug.lore.1'), + TF::RESET . $lang->translateString('tool.debug.lore.2'), + TF::RESET . $lang->translateString('tool.debug.lore.3') + ]); $item->getNamedTag()->setTag(API::TAG_MAGIC_WE, CompoundTag::create()); $sender->getInventory()->addItem($item); } catch (Exception $error) { diff --git a/src/xenialdan/MagicWE2/commands/tool/ToggledebugCommand.php b/src/xenialdan/MagicWE2/commands/tool/ToggledebugCommand.php index 60546d06..ddfa6c8b 100644 --- a/src/xenialdan/MagicWE2/commands/tool/ToggledebugCommand.php +++ b/src/xenialdan/MagicWE2/commands/tool/ToggledebugCommand.php @@ -10,7 +10,6 @@ use pocketmine\command\CommandSender; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; -use UnderflowException; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\SessionHelper; use xenialdan\MagicWE2\Loader; @@ -30,7 +29,6 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args - * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/tool/TogglewandCommand.php b/src/xenialdan/MagicWE2/commands/tool/TogglewandCommand.php index 84a3a18e..053e18d9 100644 --- a/src/xenialdan/MagicWE2/commands/tool/TogglewandCommand.php +++ b/src/xenialdan/MagicWE2/commands/tool/TogglewandCommand.php @@ -10,7 +10,6 @@ use pocketmine\command\CommandSender; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; -use UnderflowException; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\SessionHelper; use xenialdan\MagicWE2\Loader; @@ -30,7 +29,6 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args - * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/tool/WandCommand.php b/src/xenialdan/MagicWE2/commands/tool/WandCommand.php index d1cc3fd6..d8d92a5e 100644 --- a/src/xenialdan/MagicWE2/commands/tool/WandCommand.php +++ b/src/xenialdan/MagicWE2/commands/tool/WandCommand.php @@ -11,12 +11,10 @@ use pocketmine\command\CommandSender; use pocketmine\item\Durable; use pocketmine\item\enchantment\EnchantmentInstance; -use pocketmine\item\ItemFactory; -use pocketmine\item\ItemIds; +use pocketmine\item\VanillaItems; use pocketmine\nbt\tag\CompoundTag; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; -use UnderflowException; use xenialdan\MagicWE2\API; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\SessionHelper; @@ -38,7 +36,6 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args - * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { @@ -56,15 +53,15 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo /** @var Player $sender */ try { /** @var Durable $item */ - $item = ItemFactory::getInstance()->get(ItemIds::WOODEN_AXE); - $item->addEnchantment(new EnchantmentInstance(Loader::$ench)); - $item->setUnbreakable(true); - $item->setCustomName(Loader::PREFIX . TF::BOLD . TF::LIGHT_PURPLE . $lang->translateString('tool.wand')); - $item->setLore([ - TF::RESET . $lang->translateString('tool.wand.lore.1'), - TF::RESET . $lang->translateString('tool.wand.lore.2'), - TF::RESET . $lang->translateString('tool.wand.lore.3') - ]); + $item = VanillaItems::WOODEN_AXE() + ->addEnchantment(new EnchantmentInstance(Loader::$ench)) + ->setUnbreakable(true) + ->setCustomName(Loader::PREFIX . TF::BOLD . TF::LIGHT_PURPLE . $lang->translateString('tool.wand')) + ->setLore([ + TF::RESET . $lang->translateString('tool.wand.lore.1'), + TF::RESET . $lang->translateString('tool.wand.lore.2'), + TF::RESET . $lang->translateString('tool.wand.lore.3') + ]); $item->getNamedTag()->setTag(API::TAG_MAGIC_WE, CompoundTag::create()); if (!$sender->getInventory()->contains($item)) $sender->getInventory()->addItem($item); } catch (Exception $error) { diff --git a/src/xenialdan/MagicWE2/commands/utility/CalculateCommand.php b/src/xenialdan/MagicWE2/commands/utility/CalculateCommand.php index 3ec5d2e4..d8687873 100644 --- a/src/xenialdan/MagicWE2/commands/utility/CalculateCommand.php +++ b/src/xenialdan/MagicWE2/commands/utility/CalculateCommand.php @@ -12,7 +12,6 @@ use pocketmine\command\CommandSender; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; -use UnderflowException; use xenialdan\MagicWE2\API; use xenialdan\MagicWE2\exception\CalculationException; use xenialdan\MagicWE2\exception\SessionException; @@ -37,7 +36,6 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args - * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/commands/utility/ToggleWailaCommand.php b/src/xenialdan/MagicWE2/commands/utility/ToggleWailaCommand.php index 850bde3f..691ea30f 100644 --- a/src/xenialdan/MagicWE2/commands/utility/ToggleWailaCommand.php +++ b/src/xenialdan/MagicWE2/commands/utility/ToggleWailaCommand.php @@ -10,7 +10,6 @@ use pocketmine\command\CommandSender; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; -use UnderflowException; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\SessionHelper; use xenialdan\MagicWE2\Loader; @@ -30,7 +29,6 @@ protected function prepare(): void * @param CommandSender $sender * @param string $aliasUsed * @param mixed[] $args - * @throws UnderflowException */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { diff --git a/src/xenialdan/MagicWE2/helper/BlockPalette.php b/src/xenialdan/MagicWE2/helper/BlockPalette.php index f2941833..e5e1d787 100644 --- a/src/xenialdan/MagicWE2/helper/BlockPalette.php +++ b/src/xenialdan/MagicWE2/helper/BlockPalette.php @@ -9,6 +9,10 @@ use JsonException; use pocketmine\block\BlockFactory; use pocketmine\block\utils\InvalidBlockStateException; +use pocketmine\item\Item; +use pocketmine\item\LegacyStringToItemParserException; +use pocketmine\item\VanillaItems; +use pocketmine\nbt\UnexpectedTagTypeException; use xenialdan\MagicWE2\exception\BlockQueryAlreadyParsedException; class BlockPalette @@ -33,7 +37,12 @@ public function __construct(string $name = "") /** * @param string $blocksQuery * @return BlockPalette - * @throws InvalidArgumentException|BlockQueryAlreadyParsedException|InvalidBlockStateException + * @throws BlockQueryAlreadyParsedException + * @throws InvalidArgumentException + * @throws InvalidBlockStateException + * @throws LegacyStringToItemParserException + * @throws UnexpectedTagTypeException + * @throws \xenialdan\MagicWE2\exception\InvalidBlockStateException */ public static function fromString(string $blocksQuery): BlockPalette { @@ -131,4 +140,9 @@ public static function CREATE(): self return new self; } + public function toItem(): Item + { + return VanillaItems::EMERALD();//TODO placeholder + } + } \ No newline at end of file diff --git a/src/xenialdan/MagicWE2/helper/BlockQuery.php b/src/xenialdan/MagicWE2/helper/BlockQuery.php index 5934a391..32740839 100644 --- a/src/xenialdan/MagicWE2/helper/BlockQuery.php +++ b/src/xenialdan/MagicWE2/helper/BlockQuery.php @@ -6,6 +6,8 @@ use InvalidArgumentException; use pocketmine\block\utils\InvalidBlockStateException; +use pocketmine\item\LegacyStringToItemParserException; +use pocketmine\nbt\UnexpectedTagTypeException; use xenialdan\MagicWE2\exception\BlockQueryAlreadyParsedException; final class BlockQuery @@ -43,6 +45,9 @@ public function __construct(string $query, ?string $fullBlockQuery, ?string $blo * @throws BlockQueryAlreadyParsedException * @throws InvalidArgumentException * @throws InvalidBlockStateException + * @throws LegacyStringToItemParserException + * @throws UnexpectedTagTypeException + * @throws \xenialdan\MagicWE2\exception\InvalidBlockStateException */ public function parse(bool $update = true): self { diff --git a/src/xenialdan/MagicWE2/helper/BlockStatesEntry.php b/src/xenialdan/MagicWE2/helper/BlockStatesEntry.php index c749823e..7abe8de8 100644 --- a/src/xenialdan/MagicWE2/helper/BlockStatesEntry.php +++ b/src/xenialdan/MagicWE2/helper/BlockStatesEntry.php @@ -8,10 +8,12 @@ use InvalidArgumentException; use pocketmine\block\Block; use pocketmine\block\BlockFactory; +use pocketmine\item\LegacyStringToItemParserException; use pocketmine\nbt\tag\ByteTag; use pocketmine\nbt\tag\CompoundTag; use pocketmine\nbt\tag\IntTag; use pocketmine\nbt\tag\StringTag; +use pocketmine\nbt\UnexpectedTagTypeException; use pocketmine\utils\TextFormat; use RuntimeException; use Throwable; @@ -60,9 +62,12 @@ public function __toString() /** * TODO hacky AF. clean up * @return Block + * @throws BlockQueryAlreadyParsedException * @throws InvalidArgumentException + * @throws InvalidBlockStateException * @throws \pocketmine\block\utils\InvalidBlockStateException - * @throws BlockQueryAlreadyParsedException + * @throws LegacyStringToItemParserException + * @throws UnexpectedTagTypeException */ public function toBlock(): Block { diff --git a/src/xenialdan/MagicWE2/helper/BlockStatesParser.php b/src/xenialdan/MagicWE2/helper/BlockStatesParser.php index 840891dc..1b1495fc 100644 --- a/src/xenialdan/MagicWE2/helper/BlockStatesParser.php +++ b/src/xenialdan/MagicWE2/helper/BlockStatesParser.php @@ -16,15 +16,18 @@ use pocketmine\block\utils\BlockDataSerializer; use pocketmine\data\bedrock\LegacyBlockIdToStringIdMap; use pocketmine\item\LegacyStringToItemParser; +use pocketmine\item\LegacyStringToItemParserException; use pocketmine\math\Facing; use pocketmine\nbt\tag\ByteTag; use pocketmine\nbt\tag\CompoundTag; use pocketmine\nbt\tag\IntTag; use pocketmine\nbt\tag\StringTag; use pocketmine\nbt\UnexpectedTagTypeException; +use pocketmine\network\mcpe\convert\GlobalItemTypeDictionary; use pocketmine\network\mcpe\convert\R12ToCurrentBlockMapEntry; use pocketmine\network\mcpe\protocol\serializer\NetworkNbtSerializer; use pocketmine\network\mcpe\protocol\serializer\PacketSerializer; +use pocketmine\network\mcpe\protocol\serializer\PacketSerializerContext; use pocketmine\plugin\PluginException; use pocketmine\Server; use pocketmine\utils\AssumptionFailedError; @@ -33,8 +36,10 @@ use pocketmine\utils\TextFormat as TF; use pocketmine\world\Position; use RuntimeException; +use Webmozart\PathUtil\Path; use xenialdan\MagicWE2\exception\InvalidBlockStateException; use xenialdan\MagicWE2\Loader; +use function file_get_contents; use const pocketmine\RESOURCE_PATH; final class BlockStatesParser @@ -70,7 +75,7 @@ private function loadLegacyMappings(): void self::$legacyStateMap = []; $contents = file_get_contents(RESOURCE_PATH . "vanilla/r12_to_current_block_map.bin"); if ($contents === false) throw new PluginException("Can not get contents of r12_to_current_block_map"); - $legacyStateMapReader = new PacketSerializer($contents); + $legacyStateMapReader = PacketSerializer::decoder(file_get_contents(Path::join(RESOURCE_PATH, "vanilla", "r12_to_current_block_map.bin")), 0, new PacketSerializerContext(GlobalItemTypeDictionary::getInstance()->getDictionary())); $nbtReader = new NetworkNbtSerializer(); while (!$legacyStateMapReader->feof()) { $id = $legacyStateMapReader->getString(); @@ -142,7 +147,10 @@ public static function getDoorRotationFlipMap(): array * @param CompoundTag $states * @return Door * @throws InvalidArgumentException + * @throws InvalidBlockStateException + * @throws UnexpectedTagTypeException * @throws \pocketmine\block\utils\InvalidBlockStateException + * @throws LegacyStringToItemParserException */ private static function buildDoor(BlockQuery $query, CompoundTag $states): Door { @@ -180,6 +188,7 @@ public static function getBlockIdMapName(Block $block): ?string /** * @param string $blockIdentifier * @return CompoundTag + * @throws UnexpectedTagTypeException */ protected static function getDefaultStates(string $blockIdentifier): CompoundTag { @@ -190,7 +199,11 @@ protected static function getDefaultStates(string $blockIdentifier): CompoundTag * Parses a BlockQuery (acquired using BlockPalette::fromString()) to a block and sets the BlockQuery's blockFullId * @param BlockQuery $query * @return Block - * @throws InvalidArgumentException|\pocketmine\block\utils\InvalidBlockStateException + * @throws InvalidArgumentException + * @throws InvalidBlockStateException + * @throws UnexpectedTagTypeException + * @throws \pocketmine\block\utils\InvalidBlockStateException + * @throws LegacyStringToItemParserException * @noinspection PhpInternalEntityUsedInspection */ public static function fromString(BlockQuery $query): Block @@ -233,13 +246,9 @@ public static function fromString(BlockQuery $query): Block //change blockstate alias to blockstate name $stateName = $availableAliases[$stateName] ?? $stateName; //TODO maybe validate wrong states here? i.e. stone[type=wrongtype] => Exception, "wrongtype" is invalid value - try { - $tag = $finalStatesList->getTag($stateName); - } catch (UnexpectedTagTypeException $e) { - throw new InvalidBlockStateException("Default states for block '$query->blockId' do not contain Tag with name '$stateName'"); - } + $tag = $finalStatesList->getTag($stateName); if ($tag === null) { - throw new InvalidBlockStateException("Invalid state $stateName"); + throw new InvalidBlockStateException("Default states for block '$query->blockId' do not contain Tag with name '$stateName'"); } if ($tag instanceof StringTag) { $finalStatesList->setString($stateName, $value); @@ -330,7 +339,7 @@ public static function getStateByCompound(CompoundTag $compoundTag): ?BlockState * @param BlockStatesEntry $entry * @param bool $skipDefaults * @return string - * @throws RuntimeException + * @throws UnexpectedTagTypeException */ public static function printStates(BlockStatesEntry $entry, bool $skipDefaults): string { @@ -566,8 +575,9 @@ private static function doorEquals(int $currentoldDamage, CompoundTag $defaultSt /** * Generates an alias map for blockstates * Only call from main thread! - * @throws InvalidStateException * @throws AssumptionFailedError + * @throws InvalidStateException + * @throws UnexpectedTagTypeException * @internal * @noinspection PhpUnusedPrivateMethodInspection */ @@ -655,6 +665,7 @@ private static function generateBlockStateAliasMapJson(): void * Generates an alias map for blockstates * Only call from main thread! * @throws InvalidStateException + * @throws UnexpectedTagTypeException * @internal */ public static function generatePossibleStatesJson(): void diff --git a/src/xenialdan/MagicWE2/helper/SessionHelper.php b/src/xenialdan/MagicWE2/helper/SessionHelper.php index 6deae164..11011678 100644 --- a/src/xenialdan/MagicWE2/helper/SessionHelper.php +++ b/src/xenialdan/MagicWE2/helper/SessionHelper.php @@ -4,11 +4,9 @@ namespace xenialdan\MagicWE2\helper; -use Ds\Map; use Exception; use InvalidArgumentException; use JsonException; -use OutOfBoundsException; use pocketmine\entity\InvalidSkinException; use pocketmine\entity\Skin; use pocketmine\math\Vector3; @@ -19,7 +17,6 @@ use Ramsey\Uuid\Rfc4122\UuidV4; use Ramsey\Uuid\UuidInterface; use RuntimeException; -use UnderflowException; use xenialdan\MagicWE2\event\MWESessionLoadEvent; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\Loader; @@ -30,21 +27,22 @@ use xenialdan\MagicWE2\session\UserSession; use xenialdan\MagicWE2\tool\Brush; use xenialdan\MagicWE2\tool\BrushProperties; +use function array_filter; +use function array_values; +use function count; class SessionHelper { - /** @var Map */ - private static Map $userSessions; - /** @var Map */ - private static Map $pluginSessions; + /** @var array */ + private static array $userSessions = []; + /** @var array */ + private static array $pluginSessions = []; public static function init(): void { if (!@mkdir($concurrentDirectory = Loader::getInstance()->getDataFolder() . "sessions") && !is_dir($concurrentDirectory)) { throw new RuntimeException(sprintf('Directory "%s" was not created', $concurrentDirectory)); } - self::$userSessions = new Map(); - self::$pluginSessions = new Map(); } /** @@ -54,14 +52,14 @@ public static function init(): void public static function addSession(Session $session): void { if ($session instanceof UserSession) { - self::$userSessions->put($session->getUUID(), $session); + self::$userSessions[$session->getUUID()->toString()] = $session; if (!empty(Loader::getInstance()->donatorData) && (($player = $session->getPlayer())->hasPermission("we.donator") || in_array($player->getName(), Loader::getInstance()->donators))) { $oldSkin = $player->getSkin(); $newSkin = new Skin($oldSkin->getSkinId(), $oldSkin->getSkinData(), Loader::getInstance()->donatorData, $oldSkin->getGeometryName(), $oldSkin->getGeometryData()); $player->setSkin($newSkin); $player->sendSkin(); } - } else if ($session instanceof PluginSession) self::$pluginSessions->put($session->getUUID(), $session); + } else if ($session instanceof PluginSession) self::$pluginSessions[$session->getUUID()->toString()] = $session; } /** @@ -69,14 +67,13 @@ public static function addSession(Session $session): void * @param Session $session * @param bool $save * @throws JsonException - * @throws OutOfBoundsException */ public static function destroySession(Session $session, bool $save = true): void { if ($session instanceof UserSession) { $session->cleanupInventory(); - self::$userSessions->remove($session->getUUID()); - } else if ($session instanceof PluginSession) self::$pluginSessions->remove($session->getUUID()); + unset(self::$userSessions[$session->getUUID()->toString()]); + } else if ($session instanceof PluginSession) unset(self::$pluginSessions[($session->getUUID()->toString())]); if ($save && $session instanceof UserSession) { $session->save(); } @@ -119,7 +116,6 @@ public static function createPluginSession(Plugin $plugin, bool $add = true): Pl /** * @param Player $player * @return bool - * @throws UnderflowException */ public static function hasSession(Player $player): bool { @@ -134,17 +130,16 @@ public static function hasSession(Player $player): bool * @param Player $player * @return null|UserSession * @throws SessionException - * @throws UnderflowException */ public static function getUserSession(Player $player): ?UserSession { - if (self::$userSessions->isEmpty()) return null; - $filtered = self::$userSessions->filter(function (UuidInterface $uuid, Session $session) use ($player) { + if (count(self::$userSessions) === 0) return null; + $filtered = array_filter(self::$userSessions, function (Session $session) use ($player) { return $session instanceof UserSession && $session->getPlayer() === $player; }); - if ($filtered->isEmpty()) return null; + if (count($filtered) === 0) return null; if (count($filtered) > 1) throw new SessionException("Multiple sessions found for player {$player->getName()}. This should never happen!"); - return $filtered->values()->first(); + return array_values($filtered)[0]; } /** @@ -152,31 +147,10 @@ public static function getUserSession(Player $player): ?UserSession * @param UuidInterface $uuid * @return null|Session * @throws SessionException - * @throws OutOfBoundsException - * @throws UnderflowException */ public static function getSessionByUUID(UuidInterface $uuid): ?Session { - $v = null; - if (self::$userSessions->hasKey($uuid)) { - $v = self::$userSessions->get($uuid, null); - } else if (self::$pluginSessions->hasKey($uuid)) { - $v = self::$pluginSessions->get($uuid, null); - } else { - /* - * Sadly, this part is necessary. If you use UuidInterface::fromString, the object "id" in the map does not match anymore - */ - $userFiltered = self::$userSessions->filter(function (UuidInterface $uuid2, Session $session) use ($uuid) { - return $uuid2->equals($uuid); - }); - if (!$userFiltered->isEmpty()) $v = $userFiltered->values()->first(); - else { - $pluginFiltered = self::$pluginSessions->filter(function (UuidInterface $uuid2, Session $session) use ($uuid) { - return $uuid2->equals($uuid); - }); - if (!$pluginFiltered->isEmpty()) $v = $pluginFiltered->values()->first(); - } - } + $v = self::$userSessions[$uuid->toString()] ?? self::$pluginSessions[$uuid->toString()] ?? null; if (!$v instanceof Session) throw new SessionException("Session with uuid {$uuid->toString()} not found"); return $v; } @@ -186,7 +160,7 @@ public static function getSessionByUUID(UuidInterface $uuid): ?Session */ public static function getUserSessions(): array { - return self::$userSessions->values()->toArray(); + return self::$userSessions; } /** @@ -194,7 +168,7 @@ public static function getUserSessions(): array */ public static function getPluginSessions(): array { - return self::$pluginSessions->values()->toArray(); + return self::$pluginSessions; } /** diff --git a/src/xenialdan/MagicWE2/helper/WeightedRandom.php b/src/xenialdan/MagicWE2/helper/WeightedRandom.php index 74dffb79..4f3610a9 100644 --- a/src/xenialdan/MagicWE2/helper/WeightedRandom.php +++ b/src/xenialdan/MagicWE2/helper/WeightedRandom.php @@ -5,10 +5,10 @@ namespace xenialdan\MagicWE2\helper; -use Ds\Deque; use Generator; use pocketmine\utils\Binary; use pocketmine\utils\Random; +use SplDoublyLinkedList; class WeightedRandom { @@ -67,10 +67,8 @@ final public function setup(): void $probabilities = $this->probabilities; // Create two stacks to act as worklists as we populate the tables. - $small = new Deque(); - $small->allocate($probabilities_c); - $large = new Deque(); - $large->allocate($probabilities_c); + $small = new SplDoublyLinkedList(); + $large = new SplDoublyLinkedList(); // Populate the stacks with the input probabilities. for ($i = 0; $i < $probabilities_c; ++$i) { diff --git a/src/xenialdan/MagicWE2/selection/Selection.php b/src/xenialdan/MagicWE2/selection/Selection.php index 010abfbf..2eebd600 100644 --- a/src/xenialdan/MagicWE2/selection/Selection.php +++ b/src/xenialdan/MagicWE2/selection/Selection.php @@ -6,7 +6,6 @@ use Exception; use JsonSerializable; -use OutOfBoundsException; use pocketmine\math\Vector3; use pocketmine\Server; use pocketmine\utils\AssumptionFailedError; @@ -17,7 +16,6 @@ use Ramsey\Uuid\UuidInterface; use RuntimeException; use Serializable; -use UnderflowException; use xenialdan\MagicWE2\event\MWESelectionChangeEvent; use xenialdan\MagicWE2\exception\SelectionException; use xenialdan\MagicWE2\exception\SessionException; @@ -114,8 +112,6 @@ public function getPos1(): Position /** * @param Position $position * @throws AssumptionFailedError - * @throws OutOfBoundsException - * @throws UnderflowException */ public function setPos1(Position $position): void { @@ -157,8 +153,6 @@ public function getPos2(): Position /** * @param Position $position * @throws AssumptionFailedError - * @throws OutOfBoundsException - * @throws UnderflowException */ public function setPos2(Position $position): void { diff --git a/src/xenialdan/MagicWE2/session/PluginSession.php b/src/xenialdan/MagicWE2/session/PluginSession.php index f519359e..737b3bf0 100644 --- a/src/xenialdan/MagicWE2/session/PluginSession.php +++ b/src/xenialdan/MagicWE2/session/PluginSession.php @@ -4,9 +4,9 @@ namespace xenialdan\MagicWE2\session; -use Ds\Deque; use pocketmine\plugin\Plugin; use Ramsey\Uuid\Uuid; +use SplDoublyLinkedList; use xenialdan\MagicWE2\Loader; class PluginSession extends Session @@ -18,8 +18,8 @@ public function __construct(Plugin $plugin) { $this->plugin = $plugin; $this->setUUID(Uuid::uuid4()); - $this->undoHistory = new Deque(); - $this->redoHistory = new Deque(); + $this->undoHistory = new SplDoublyLinkedList(); + $this->redoHistory = new SplDoublyLinkedList(); } public function getPlugin(): Plugin diff --git a/src/xenialdan/MagicWE2/session/Session.php b/src/xenialdan/MagicWE2/session/Session.php index 70c8aa59..d1c31a3b 100644 --- a/src/xenialdan/MagicWE2/session/Session.php +++ b/src/xenialdan/MagicWE2/session/Session.php @@ -4,7 +4,6 @@ namespace xenialdan\MagicWE2\session; -use Ds\Deque; use Exception; use InvalidArgumentException; use pocketmine\lang\Language; @@ -13,7 +12,7 @@ use pocketmine\world\World; use Ramsey\Uuid\UuidInterface; use RuntimeException; -use UnderflowException; +use SplDoublyLinkedList; use xenialdan\MagicWE2\clipboard\Clipboard; use xenialdan\MagicWE2\clipboard\RevertClipboard; use xenialdan\MagicWE2\Loader; @@ -36,10 +35,10 @@ abstract class Session private array $clipboards = []; /** @var int */ private int $currentClipboard = -1; - /** @var Deque */ - public Deque $undoHistory; - /** @var Deque */ - public Deque $redoHistory; + /** @var SplDoublyLinkedList */ + public SplDoublyLinkedList $undoHistory; + /** @var SplDoublyLinkedList */ + public SplDoublyLinkedList $redoHistory; /** * @return UuidInterface @@ -211,11 +210,10 @@ public function addClipboard(Clipboard $clipboard, bool $setAsCurrent = true): i /** * @param RevertClipboard $revertClipboard - * @throws UnderflowException */ public function addRevert(RevertClipboard $revertClipboard): void { - $this->redoHistory->clear(); + $this->redoHistory = new SplDoublyLinkedList(); $this->undoHistory->push($revertClipboard); while ($this->undoHistory->count() > self::MAX_HISTORY) { $this->undoHistory->shift(); @@ -260,8 +258,8 @@ public function redo(): void public function clearHistory(): void { - $this->undoHistory->clear(); - $this->redoHistory->clear(); + $this->undoHistory = new SplDoublyLinkedList(); + $this->redoHistory = new SplDoublyLinkedList(); } public function clearClipboard(): void diff --git a/src/xenialdan/MagicWE2/session/UserSession.php b/src/xenialdan/MagicWE2/session/UserSession.php index efad4338..14183cf6 100644 --- a/src/xenialdan/MagicWE2/session/UserSession.php +++ b/src/xenialdan/MagicWE2/session/UserSession.php @@ -4,8 +4,6 @@ namespace xenialdan\MagicWE2\session; -use Ds\Deque; -use Ds\Map; use Exception; use InvalidArgumentException; use jackmd\scorefactory\ScoreFactory; @@ -15,10 +13,12 @@ use pocketmine\lang\Language; use pocketmine\lang\LanguageNotFoundException; use pocketmine\nbt\tag\CompoundTag; +use pocketmine\nbt\UnexpectedTagTypeException; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; use Ramsey\Uuid\Uuid; use Ramsey\Uuid\UuidInterface; +use SplDoublyLinkedList; use TypeError; use xenialdan\apibossbar\BossBar; use xenialdan\MagicWE2\API; @@ -48,10 +48,10 @@ class UserSession extends Session implements JsonSerializable //TODO use JsonMap private bool $wailaEnabled = true; /** @var bool */ private bool $sidebarEnabled = true;//TODO settings/commands - /** @var Map */ - private Map $brushes; - /** @var Map */ - private Map $assets; + /** @var array */ + private array $brushes = []; + /** @var array */ + private array $assets = []; public PaletteCollection $palettes; /** @var Language|null */ private ?Language $lang = null; @@ -67,10 +67,8 @@ public function __construct(Player $player) if (Loader::hasScoreboard()) { $this->sidebar = new Scoreboard(); } - $this->undoHistory = new Deque(); - $this->redoHistory = new Deque(); - $this->brushes = new Map(); - $this->assets = new Map(); + $this->undoHistory = new SplDoublyLinkedList(); + $this->redoHistory = new SplDoublyLinkedList(); $this->palettes = new PaletteCollection(); try { if (is_null($this->lang)) @@ -258,7 +256,7 @@ public function getBrushFromItem(Item $item): Brush */ public function getBrush(UuidInterface $uuid): ?Brush { - return $this->brushes->get($uuid->toString()); + return $this->brushes[$uuid->toString()]; } /** @@ -268,7 +266,7 @@ public function getBrush(UuidInterface $uuid): ?Brush */ public function addBrush(Brush $brush): void { - $this->brushes->put($brush->properties->uuid, $brush); + $this->brushes[$brush->properties->uuid] = $brush; $this->sendMessage($this->getLanguage()->translateString('session.brush.added', [$brush->getName()])); } @@ -276,10 +274,11 @@ public function addBrush(Brush $brush): void * @param Brush $brush UuidInterface will be set automatically * @param bool $delete If true, it will be removed from the session brushes * @return void + * @throws UnexpectedTagTypeException */ public function removeBrush(Brush $brush, bool $delete = false): void { - if ($delete) $this->brushes->remove($brush->properties->uuid); + if ($delete) unset($this->brushes[$brush->properties->uuid]); foreach ($this->getPlayer()->getInventory()->getContents() as $slot => $item) { if (($entry = $item->getNamedTag()->getCompoundTag(API::TAG_MAGIC_WE_BRUSH)) instanceof CompoundTag) { if ($entry->getString("id") === $brush->properties->uuid) { @@ -297,13 +296,14 @@ public function removeBrush(Brush $brush, bool $delete = false): void * @return void * @throws ActionNotFoundException * @throws InvalidArgumentException - * @throws ShapeNotFoundException * @throws JsonException + * @throws ShapeNotFoundException * @throws TypeError + * @throws UnexpectedTagTypeException */ public function replaceBrush(Brush $brush): void { - $this->brushes->put($brush->properties->uuid, $brush); + $this->brushes[$brush->properties->uuid] = $brush; $new = $brush->toItem(); foreach ($this->getPlayer()->getInventory()->getContents() as $slot => $item) { if (($entry = $item->getNamedTag()->getCompoundTag(API::TAG_MAGIC_WE_BRUSH)) instanceof CompoundTag) { @@ -319,7 +319,7 @@ public function replaceBrush(Brush $brush): void */ public function getBrushes(): array { - return $this->brushes->values()->toArray(); + return $this->brushes; } public function cleanupInventory(): void diff --git a/src/xenialdan/MagicWE2/session/data/Asset.php b/src/xenialdan/MagicWE2/session/data/Asset.php index 20ffe4e4..3ab4ecca 100644 --- a/src/xenialdan/MagicWE2/session/data/Asset.php +++ b/src/xenialdan/MagicWE2/session/data/Asset.php @@ -19,7 +19,6 @@ use pocketmine\utils\AssumptionFailedError; use pocketmine\utils\TextFormat as TF; use TypeError; -use UnexpectedValueException; use xenialdan\customui\windows\CustomForm; use xenialdan\libstructure\format\MCStructure; use xenialdan\MagicWE2\API; @@ -33,7 +32,7 @@ class Asset implements JsonSerializable { const TYPE_SCHEMATIC = 'schematic'; const TYPE_MCSTRUCTURE = 'structure'; - const TYPE_CLIPBOARD = 'clipboard';//TODO consider if this is even worth the efford, or instead just convert it to mcstructure before storing + const TYPE_CLIPBOARD = 'clipboard';//TODO consider if this is even worth the effort, or instead just convert it to mcstructure before storing public Schematic|SingleClipboard|MCStructure $structure; public string $filename;//used as identifier @@ -66,12 +65,14 @@ public function getSize(): Vector3 if ($this->structure instanceof Schematic) return new Vector3($this->structure->getWidth(), $this->structure->getHeight(), $this->structure->getLength()); if ($this->structure instanceof MCStructure) return $this->structure->getSize(); if ($this->structure instanceof SingleClipboard) return new Vector3($this->structure->selection->getSizeX(), $this->structure->selection->getSizeY(), $this->structure->selection->getSizeZ()); + throw new Exception("Unknown structure type"); } public function getTotalCount(): int { if ($this->structure instanceof Schematic || $this->structure instanceof MCStructure) return $this->getSize()->getFloorX() * $this->getSize()->getFloorY() * $this->getSize()->getFloorZ(); if ($this->structure instanceof SingleClipboard) return $this->structure->getTotalCount(); + throw new Exception("Unknown structure type"); } public function getOrigin(): Vector3 @@ -79,13 +80,13 @@ public function getOrigin(): Vector3 if ($this->structure instanceof Schematic) return new Vector3(0, 0, 0); if ($this->structure instanceof MCStructure) return $this->structure->getStructureWorldOrigin(); if ($this->structure instanceof SingleClipboard) return $this->structure->position; + throw new Exception("Unknown structure type"); } /** * @param bool $renew * @return Item * @throws InvalidArgumentException - * @throws UnexpectedValueException */ public function toItem(bool $renew = false): Item { @@ -114,7 +115,7 @@ public function toItem(bool $renew = false): Item /** * @return array - * @throws UnexpectedValueException + * @throws Exception */ private function generateLore(): array { @@ -153,6 +154,7 @@ public function toSchematic(): Schematic $schematic->setBlockArray($blocks); return $schematic; } + throw new Exception("Unknown structure type"); } public function toMCStructure(): MCStructure @@ -251,7 +253,7 @@ public function getSettingForm(bool $new = true, array $errors = []): CustomForm #print_r(AssetCollection::getInstance()->assets->values()->toArray()); #print_r(AssetCollection::getInstance()->assets->keys()->toArray()); #print_r(AssetCollection::getInstance()->getAssets()); - AssetCollection::getInstance()->assets->put($this->filename, $this);//overwrites + AssetCollection::getInstance()->assets[$this->filename] = $this;//overwrites $player->sendMessage("Asset stored in " . ($shared ? 'global' : 'private') . ' collection'); $player->sendMessage((string)$this); #$player->sendMessage((string)$this->toItem(true)); diff --git a/src/xenialdan/MagicWE2/session/data/AssetCollection.php b/src/xenialdan/MagicWE2/session/data/AssetCollection.php index 666f5585..f71d7d3b 100644 --- a/src/xenialdan/MagicWE2/session/data/AssetCollection.php +++ b/src/xenialdan/MagicWE2/session/data/AssetCollection.php @@ -4,46 +4,45 @@ namespace xenialdan\MagicWE2\session\data; -use Ds\Map; use pocketmine\utils\SingletonTrait; use pocketmine\utils\TextFormat as TF; use xenialdan\libstructure\exception\StructureFileException; use xenialdan\MagicWE2\helper\StructureStore; use xenialdan\MagicWE2\Loader; +use function array_filter; final class AssetCollection { use SingletonTrait; - /** @var Map */ - public Map $assets; + /** @var array */ + public array $assets = []; public function __construct() { - $this->assets = new Map(); $this->initFolders(); } /** @return Asset[] */ public function getAssets(): array { - return $this->assets->values()->toArray(); + return $this->assets; } /** @return Asset[] */ public function getUnlockedAssets(): array { - return $this->assets->filter(function (string $key, Asset $value) { + return array_filter($this->assets, function (Asset $value) { return !$value->locked; - })->values()->toArray(); + }); } /** @return Asset[] */ public function getSharedAssets(): array { - return $this->assets->filter(function (string $key, Asset $value) { + return array_filter($this->assets, function (Asset $value) { return $value->shared; - })->values()->toArray(); + }); } /** @@ -52,10 +51,10 @@ public function getSharedAssets(): array */ public function getPlayerAssets(?string $xuid = null): array { - return $this->assets->filter(function (string $key, Asset $value) use ($xuid) { + return array_filter($this->assets, function (string $key, Asset $value) use ($xuid) { if ($xuid === null) return $value->ownerXuid !== null; else return $value->ownerXuid === $xuid; - })->values()->toArray(); + }); } private function initFolders(): void @@ -72,9 +71,9 @@ private function initFolders(): void Loader::getInstance()->getLogger()->debug(TF::GOLD . "Loading " . $basename); try { if ($extension === 'mcstructure') { - $store->assets->put($basename, new Asset($basename, StructureStore::getInstance()->loadStructure($basename), true, null, true)); + $store->assets[$basename] = new Asset($basename, StructureStore::getInstance()->loadStructure($basename), true, null, true); } else if ($extension === 'schematic') { - $store->assets->put($basename, new Asset($basename, StructureStore::getInstance()->loadSchematic($basename), true, null, true)); + $store->assets[$basename] = new Asset($basename, StructureStore::getInstance()->loadSchematic($basename), true, null, true); } } catch (StructureFileException $e) { Loader::getInstance()->getLogger()->debug($e->getMessage()); diff --git a/src/xenialdan/MagicWE2/session/data/PaletteCollection.php b/src/xenialdan/MagicWE2/session/data/PaletteCollection.php index d6821821..c5e6402f 100644 --- a/src/xenialdan/MagicWE2/session/data/PaletteCollection.php +++ b/src/xenialdan/MagicWE2/session/data/PaletteCollection.php @@ -4,7 +4,6 @@ namespace xenialdan\MagicWE2\session\data; -use Ds\Map; use pocketmine\utils\SingletonTrait; use xenialdan\MagicWE2\helper\BlockPalette; @@ -12,19 +11,18 @@ final class PaletteCollection { use SingletonTrait; - /** @var Map */ - public Map $palettes; + /** @var array */ + public array $palettes; public function __construct() { - $this->palettes = new Map(); //$this->initFolders(); } /** @return BlockPalette[] */ public function getPalettes(): array { - return $this->palettes->values()->toArray(); + return $this->palettes; } private function initFolders(): void diff --git a/src/xenialdan/MagicWE2/task/AsyncActionTask.php b/src/xenialdan/MagicWE2/task/AsyncActionTask.php index e9db96a0..ac3c6da1 100644 --- a/src/xenialdan/MagicWE2/task/AsyncActionTask.php +++ b/src/xenialdan/MagicWE2/task/AsyncActionTask.php @@ -3,7 +3,6 @@ namespace xenialdan\MagicWE2\task; use Exception; -use OutOfBoundsException; use pocketmine\math\Vector3; use pocketmine\player\Player; use pocketmine\utils\AssumptionFailedError; @@ -13,7 +12,6 @@ use pocketmine\world\World; use Ramsey\Uuid\Uuid; use Ramsey\Uuid\UuidInterface; -use UnderflowException; use xenialdan\MagicWE2\API; use xenialdan\MagicWE2\clipboard\RevertClipboard; use xenialdan\MagicWE2\clipboard\SingleClipboard; @@ -56,8 +54,6 @@ class AsyncActionTask extends MWEAsyncTask * @param string[] $touchedChunks serialized chunks * @param BlockPalette $newBlocks * @param BlockPalette $blockFilter - * @throws OutOfBoundsException - * @throws UnderflowException */ public function __construct(UuidInterface $sessionUUID, Selection $selection, TaskAction $action, array $touchedChunks, BlockPalette $newBlocks, BlockPalette $blockFilter) { @@ -122,8 +118,6 @@ public function onRun(): void /** * @throws AssumptionFailedError - * @throws OutOfBoundsException - * @throws UnderflowException */ public function onCompletion(): void { diff --git a/src/xenialdan/MagicWE2/task/AsyncClipboardActionTask.php b/src/xenialdan/MagicWE2/task/AsyncClipboardActionTask.php index a683ee66..d882b660 100644 --- a/src/xenialdan/MagicWE2/task/AsyncClipboardActionTask.php +++ b/src/xenialdan/MagicWE2/task/AsyncClipboardActionTask.php @@ -3,13 +3,11 @@ namespace xenialdan\MagicWE2\task; use Exception; -use OutOfBoundsException; use pocketmine\player\Player; use pocketmine\utils\AssumptionFailedError; use pocketmine\utils\TextFormat as TF; use Ramsey\Uuid\Uuid; use Ramsey\Uuid\UuidInterface; -use UnderflowException; use xenialdan\MagicWE2\clipboard\SingleClipboard; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\BlockStatesParser; @@ -39,8 +37,6 @@ class AsyncClipboardActionTask extends MWEAsyncTask * @param Selection $selection * @param ClipboardAction $action * @param SingleClipboard $clipboard - * @throws OutOfBoundsException - * @throws UnderflowException */ public function __construct(UuidInterface $sessionUUID, Selection $selection, ClipboardAction $action, SingleClipboard $clipboard) { @@ -95,8 +91,6 @@ public function onRun(): void /** * @throws AssumptionFailedError - * @throws OutOfBoundsException - * @throws UnderflowException */ public function onCompletion(): void { diff --git a/src/xenialdan/MagicWE2/task/AsyncCountTask.php b/src/xenialdan/MagicWE2/task/AsyncCountTask.php index 2c7f2f44..063d5ab5 100644 --- a/src/xenialdan/MagicWE2/task/AsyncCountTask.php +++ b/src/xenialdan/MagicWE2/task/AsyncCountTask.php @@ -3,7 +3,6 @@ namespace xenialdan\MagicWE2\task; use Exception; -use OutOfBoundsException; use pocketmine\block\Block; use pocketmine\block\BlockFactory; use pocketmine\utils\AssumptionFailedError; @@ -11,7 +10,6 @@ use pocketmine\world\format\io\FastChunkSerializer; use Ramsey\Uuid\Uuid; use Ramsey\Uuid\UuidInterface; -use UnderflowException; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\AsyncChunkManager; use xenialdan\MagicWE2\helper\BlockPalette; @@ -115,8 +113,6 @@ private function countBlocks(Selection $selection, AsyncChunkManager $manager, B /** * @throws AssumptionFailedError - * @throws OutOfBoundsException - * @throws UnderflowException */ public function onCompletion(): void { diff --git a/src/xenialdan/MagicWE2/task/AsyncFillTask.php b/src/xenialdan/MagicWE2/task/AsyncFillTask.php index 6ffdf50a..359c3266 100644 --- a/src/xenialdan/MagicWE2/task/AsyncFillTask.php +++ b/src/xenialdan/MagicWE2/task/AsyncFillTask.php @@ -6,7 +6,6 @@ use Generator; use InvalidArgumentException; use MultipleIterator; -use OutOfBoundsException; use pocketmine\block\Block; use pocketmine\utils\AssumptionFailedError; use pocketmine\utils\TextFormat as TF; @@ -15,7 +14,6 @@ use pocketmine\world\World; use Ramsey\Uuid\Uuid; use Ramsey\Uuid\UuidInterface; -use UnderflowException; use xenialdan\MagicWE2\API; use xenialdan\MagicWE2\clipboard\RevertClipboard; use xenialdan\MagicWE2\exception\SessionException; @@ -53,8 +51,12 @@ public function __construct(UuidInterface $sessionUUID, Selection $selection, ar { $this->start = microtime(true); $this->sessionUUID = $sessionUUID->toString(); - $this->selection = igbinary_serialize($selection); - $this->touchedChunks = igbinary_serialize($touchedChunks); + $s1 = igbinary_serialize($selection); + if ($s1 === null) throw new Exception("Couldn't serialize selection"); + $s2 = igbinary_serialize($touchedChunks); + if ($s2 === null) throw new Exception("Couldn't serialize touched chunks"); + $this->selection = $s1; + $this->touchedChunks = $s2; //$this->newBlocks = BlockPalette::encode($newBlocks); $this->newBlocks = $newBlocks;//TODO check if serializes var_dump($this->newBlocks); @@ -155,8 +157,6 @@ private function execute(Selection $selection, AsyncChunkManager $manager, Block /** * @throws AssumptionFailedError - * @throws OutOfBoundsException - * @throws UnderflowException */ public function onCompletion(): void { diff --git a/src/xenialdan/MagicWE2/task/AsyncPasteAssetTask.php b/src/xenialdan/MagicWE2/task/AsyncPasteAssetTask.php index 937af19c..51647a27 100644 --- a/src/xenialdan/MagicWE2/task/AsyncPasteAssetTask.php +++ b/src/xenialdan/MagicWE2/task/AsyncPasteAssetTask.php @@ -16,8 +16,6 @@ use pocketmine\world\World; use Ramsey\Uuid\Uuid; use Ramsey\Uuid\UuidInterface; -use UnderflowException; -use UnexpectedValueException; use xenialdan\libstructure\format\MCStructure; use xenialdan\MagicWE2\API; use xenialdan\MagicWE2\clipboard\RevertClipboard; @@ -71,7 +69,6 @@ public function __construct(UuidInterface $sessionUUID, Vector3 $target, Selecti * * @return void * @throws InvalidArgumentException - * @throws UnexpectedValueException * @throws OutOfBoundsException */ public function onRun(): void @@ -105,7 +102,6 @@ public function onRun(): void * @param null|int $changed * @return Generator * @throws InvalidArgumentException - * @throws UnexpectedValueException * @throws OutOfBoundsException * @phpstan-return Generator */ @@ -207,8 +203,6 @@ private function execute(AsyncChunkManager $manager, Asset $asset, ?int &$change /** * @throws AssumptionFailedError - * @throws OutOfBoundsException - * @throws UnderflowException */ public function onCompletion(): void { diff --git a/src/xenialdan/MagicWE2/task/AsyncPasteTask.php b/src/xenialdan/MagicWE2/task/AsyncPasteTask.php index 6ea1d5e8..9a42708c 100644 --- a/src/xenialdan/MagicWE2/task/AsyncPasteTask.php +++ b/src/xenialdan/MagicWE2/task/AsyncPasteTask.php @@ -5,7 +5,6 @@ use Exception; use Generator; use InvalidArgumentException; -use OutOfBoundsException; use pocketmine\math\Vector3; use pocketmine\utils\AssumptionFailedError; use pocketmine\utils\TextFormat as TF; @@ -14,7 +13,6 @@ use pocketmine\world\World; use Ramsey\Uuid\Uuid; use Ramsey\Uuid\UuidInterface; -use UnderflowException; use xenialdan\MagicWE2\API; use xenialdan\MagicWE2\clipboard\RevertClipboard; use xenialdan\MagicWE2\clipboard\SingleClipboard; @@ -145,8 +143,6 @@ private function execute(Selection $selection, AsyncChunkManager $manager, Singl /** * @throws AssumptionFailedError - * @throws OutOfBoundsException - * @throws UnderflowException */ public function onCompletion(): void { diff --git a/src/xenialdan/MagicWE2/task/AsyncReplaceTask.php b/src/xenialdan/MagicWE2/task/AsyncReplaceTask.php index 5da1f730..71d2bc7c 100644 --- a/src/xenialdan/MagicWE2/task/AsyncReplaceTask.php +++ b/src/xenialdan/MagicWE2/task/AsyncReplaceTask.php @@ -6,7 +6,6 @@ use Generator; use InvalidArgumentException; use MultipleIterator; -use OutOfBoundsException; use pocketmine\block\Block; use pocketmine\utils\AssumptionFailedError; use pocketmine\utils\TextFormat as TF; @@ -15,7 +14,6 @@ use pocketmine\world\World; use Ramsey\Uuid\Uuid; use Ramsey\Uuid\UuidInterface; -use UnderflowException; use xenialdan\MagicWE2\API; use xenialdan\MagicWE2\clipboard\RevertClipboard; use xenialdan\MagicWE2\exception\SessionException; @@ -142,8 +140,6 @@ private function execute(Selection $selection, AsyncChunkManager $manager, Block /** * @throws AssumptionFailedError - * @throws OutOfBoundsException - * @throws UnderflowException */ public function onCompletion(): void { diff --git a/src/xenialdan/MagicWE2/task/AsyncRevertTask.php b/src/xenialdan/MagicWE2/task/AsyncRevertTask.php index 9a7166e8..c810fc4a 100644 --- a/src/xenialdan/MagicWE2/task/AsyncRevertTask.php +++ b/src/xenialdan/MagicWE2/task/AsyncRevertTask.php @@ -5,13 +5,11 @@ use Exception; use Generator; use InvalidArgumentException; -use OutOfBoundsException; use pocketmine\utils\AssumptionFailedError; use pocketmine\utils\TextFormat as TF; use pocketmine\world\World; use Ramsey\Uuid\Uuid; use Ramsey\Uuid\UuidInterface; -use UnderflowException; use xenialdan\MagicWE2\clipboard\RevertClipboard; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\AsyncChunkManager; @@ -112,8 +110,6 @@ private function redoChunks(AsyncChunkManager $manager, RevertClipboard $clipboa /** * @throws AssumptionFailedError - * @throws OutOfBoundsException - * @throws UnderflowException */ public function onCompletion(): void { From a92278cbe2c7f612d0f189e4dc238cadf4a286db Mon Sep 17 00:00:00 2001 From: XenialDan Date: Sun, 18 Jul 2021 10:09:30 +0200 Subject: [PATCH 28/67] Add //togglesidebar, Fix #226 Looks like it was lost in a git stash Signed-off-by: XenialDan --- plugin.yml | 2 + src/xenialdan/MagicWE2/Loader.php | 2 + .../commands/utility/ToggleSidebarCommand.php | 59 +++++++++++++++++++ 3 files changed, 63 insertions(+) create mode 100644 src/xenialdan/MagicWE2/commands/utility/ToggleSidebarCommand.php diff --git a/plugin.yml b/plugin.yml index 020a9c5d..d712b823 100644 --- a/plugin.yml +++ b/plugin.yml @@ -117,6 +117,8 @@ permissions: default: op we.command.utility.togglewaila: default: op + we.command.utility.togglesidebar: + default: op we.command.test: default: op ... diff --git a/src/xenialdan/MagicWE2/Loader.php b/src/xenialdan/MagicWE2/Loader.php index c9b11f2a..85be7618 100644 --- a/src/xenialdan/MagicWE2/Loader.php +++ b/src/xenialdan/MagicWE2/Loader.php @@ -64,6 +64,7 @@ use xenialdan\MagicWE2\commands\tool\TogglewandCommand; use xenialdan\MagicWE2\commands\tool\WandCommand; use xenialdan\MagicWE2\commands\utility\CalculateCommand; +use xenialdan\MagicWE2\commands\utility\ToggleSidebarCommand; use xenialdan\MagicWE2\commands\utility\ToggleWailaCommand; use xenialdan\MagicWE2\commands\VersionCommand; use xenialdan\MagicWE2\exception\ActionRegistryException; @@ -303,6 +304,7 @@ public function onEnable(): void //new ThawCommand($this,"/thaw", "Thaws blocks in the selection"), new CalculateCommand($this, "/calculate", "Evaluate a mathematical expression", ["/calc", "/eval", "/evaluate", "/solve"]), new ToggleWailaCommand($this, "/togglewaila", "Toggle the What Am I Looking At utility", ["/waila", "/wyla"]), + new ToggleSidebarCommand($this, "/togglesidebar", "Toggle the sidebar", ["/sidebar"]), /* -- debugging -- */ new PlaceAllBlockstatesCommand($this, "/placeallblockstates", "Place all blockstates similar to Java debug worlds"), ]); diff --git a/src/xenialdan/MagicWE2/commands/utility/ToggleSidebarCommand.php b/src/xenialdan/MagicWE2/commands/utility/ToggleSidebarCommand.php new file mode 100644 index 00000000..739e094f --- /dev/null +++ b/src/xenialdan/MagicWE2/commands/utility/ToggleSidebarCommand.php @@ -0,0 +1,59 @@ +setPermission("we.command.utility.togglesidebar"); + } + + /** + * @param CommandSender $sender + * @param string $aliasUsed + * @param mixed[] $args + */ + public function onRun(CommandSender $sender, string $aliasUsed, array $args): void + { + $lang = Loader::getInstance()->getLanguage(); + if ($sender instanceof Player && SessionHelper::hasSession($sender)) { + try { + $lang = SessionHelper::getUserSession($sender)->getLanguage(); + } catch (SessionException $e) { + } + } + if (!$sender instanceof Player) { + $sender->sendMessage(TF::RED . $lang->translateString('error.runingame')); + return; + } + /** @var Player $sender */ + try { + $session = SessionHelper::getUserSession($sender); + if (is_null($session)) { + throw new SessionException($lang->translateString('error.nosession', [Loader::getInstance()->getName()])); + } + $sender->sendMessage($session->setSidebarEnabled(!$session->isSidebarEnabled())); + } catch (Exception $error) { + $sender->sendMessage(Loader::PREFIX . TF::RED . $lang->translateString('error.command-error')); + $sender->sendMessage(Loader::PREFIX . TF::RED . $error->getMessage()); + $sender->sendMessage($this->getUsage()); + } + } +} From 79d6fba873e2399e82c23354e09f0dcba859f7c4 Mon Sep 17 00:00:00 2001 From: Adam Matthew Date: Wed, 21 Jul 2021 03:42:50 +0800 Subject: [PATCH 29/67] [phpstan skip] --- .github/workflows/main.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 5432c0cd..737b0b18 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -4,6 +4,7 @@ on: [push, pull_request] jobs: phpstan: + if: "!contains(github.event.head_commit.message, '[phpstan skip]')" runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 From e218eaff11ce307e421f0fd08803fa415887e030 Mon Sep 17 00:00:00 2001 From: Adam Matthew Date: Wed, 21 Jul 2021 03:44:21 +0800 Subject: [PATCH 30/67] Include PocketMine-MP.phar --- phpstan.neon.dist | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/phpstan.neon.dist b/phpstan.neon.dist index 47ca5562..1a8f66c1 100644 --- a/phpstan.neon.dist +++ b/phpstan.neon.dist @@ -19,5 +19,6 @@ parameters: - phar:///source/vendor/InvMenu.phar/src - phar:///source/vendor/libstructure.phar/src - phar:///source/vendor/ScoreFactory.phar/src + - phar:///pocketmine/PocketMine-MP.phar excludes_analyse: - - source/vendor \ No newline at end of file + - source/vendor From 23ad659465006099b9f2b58cce6729589f2a8dd5 Mon Sep 17 00:00:00 2001 From: XenialDan Date: Sun, 25 Jul 2021 17:12:38 +0200 Subject: [PATCH 31/67] Fix #232 Signed-off-by: XenialDan --- src/xenialdan/MagicWE2/helper/BlockStatesParser.php | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/xenialdan/MagicWE2/helper/BlockStatesParser.php b/src/xenialdan/MagicWE2/helper/BlockStatesParser.php index 1b1495fc..03130662 100644 --- a/src/xenialdan/MagicWE2/helper/BlockStatesParser.php +++ b/src/xenialdan/MagicWE2/helper/BlockStatesParser.php @@ -39,6 +39,7 @@ use Webmozart\PathUtil\Path; use xenialdan\MagicWE2\exception\InvalidBlockStateException; use xenialdan\MagicWE2\Loader; +use function array_key_exists; use function file_get_contents; use const pocketmine\RESOURCE_PATH; @@ -305,6 +306,9 @@ public static function getStateByBlock(Block $block): ?BlockStatesEntry $name = self::getBlockIdMapName($block); if ($name === null) return null; $damage = $block->getMeta(); + if(!array_key_exists($name,self::$legacyStateMap)){ + return null; + } $blockStates = clone self::$legacyStateMap[$name][$damage]->getBlockState()->getCompoundTag('states'); if ($blockStates === null) return null; return new BlockStatesEntry($name, $blockStates, $block); From a80106355838509d1195535daa9b7dc6e6bffb64 Mon Sep 17 00:00:00 2001 From: XenialDan Date: Sun, 25 Jul 2021 17:20:37 +0200 Subject: [PATCH 32/67] Add more null checks BlockStatesParser::getStateByBlock() Signed-off-by: XenialDan --- src/xenialdan/MagicWE2/helper/BlockStatesParser.php | 10 +++++++--- src/xenialdan/MagicWE2/task/action/FlipAction.php | 8 ++++++-- src/xenialdan/MagicWE2/task/action/RotateAction.php | 8 ++++++-- 3 files changed, 19 insertions(+), 7 deletions(-) diff --git a/src/xenialdan/MagicWE2/helper/BlockStatesParser.php b/src/xenialdan/MagicWE2/helper/BlockStatesParser.php index 03130662..ce539e86 100644 --- a/src/xenialdan/MagicWE2/helper/BlockStatesParser.php +++ b/src/xenialdan/MagicWE2/helper/BlockStatesParser.php @@ -450,9 +450,13 @@ public static function runTests(): void foreach (BlockPalette::fromString($test)->palette() as $block) { assert($block instanceof Block); $blockStatesEntry = self::getStateByBlock($block); - Server::getInstance()->getLogger()->debug(TF::LIGHT_PURPLE . self::printStates($blockStatesEntry, true)); - Server::getInstance()->getLogger()->debug(TF::LIGHT_PURPLE . self::printStates($blockStatesEntry, false)); - Server::getInstance()->getLogger()->debug(TF::LIGHT_PURPLE . "Final block: " . TF::AQUA . $block); + if($blockStatesEntry !== null) { + Server::getInstance()->getLogger()->debug(TF::LIGHT_PURPLE . self::printStates($blockStatesEntry, true)); + Server::getInstance()->getLogger()->debug(TF::LIGHT_PURPLE . self::printStates($blockStatesEntry, false)); + Server::getInstance()->getLogger()->debug(TF::LIGHT_PURPLE . "Final block: " . TF::AQUA . $block); + }else{ + Server::getInstance()->getLogger()->debug(TF::LIGHT_PURPLE . "Final block: " . TF::AQUA . $block); + } } } catch (Exception $e) { Server::getInstance()->getLogger()->debug($e->getMessage()); diff --git a/src/xenialdan/MagicWE2/task/action/FlipAction.php b/src/xenialdan/MagicWE2/task/action/FlipAction.php index 8726ea7f..a37a73c6 100644 --- a/src/xenialdan/MagicWE2/task/action/FlipAction.php +++ b/src/xenialdan/MagicWE2/task/action/FlipAction.php @@ -77,8 +77,12 @@ public function execute(string $sessionUUID, Selection $selection, ?int &$change #var_dump("$x $y $z"); $block1 = $blockEntry->toBlock(); $blockStatesEntry = BlockStatesParser::getInstance()::getStateByBlock($block1); - $mirrored = $blockStatesEntry->mirror($this->axis); - $block = $mirrored->toBlock(); + if($blockStatesEntry === null){ + $block = $block1; + }else{ + $mirrored = $blockStatesEntry->mirror($this->axis); + $block = $mirrored->toBlock(); + } $entry = BlockEntry::fromBlock($block); //var_dump($blockStatesEntry->__toString(), $mirrored->__toString(), $block); /** @var int $x */ diff --git a/src/xenialdan/MagicWE2/task/action/RotateAction.php b/src/xenialdan/MagicWE2/task/action/RotateAction.php index 3c6bc914..de55d735 100644 --- a/src/xenialdan/MagicWE2/task/action/RotateAction.php +++ b/src/xenialdan/MagicWE2/task/action/RotateAction.php @@ -101,8 +101,12 @@ public function execute(string $sessionUUID, Selection $selection, ?int &$change $block1 = $blockEntry->toBlock(); $instance = BlockStatesParser::getInstance(); $blockStatesEntry = $instance::getStateByBlock($block1); - $rotated = $blockStatesEntry->rotate($this->rotation); - $block = $rotated->toBlock(); + if ($blockStatesEntry === null) { + $block = $block1; + } else { + $rotated = $blockStatesEntry->rotate($this->rotation); + $block = $rotated->toBlock(); + } $entry = BlockEntry::fromBlock($block); #var_dump($blockStatesEntry->__toString(), $rotated->__toString(), $entry); /** @var int $y */ From 9c1ad768025af09be20b11536ef8aa5dfbd1d85a Mon Sep 17 00:00:00 2001 From: XenialDan Date: Sun, 25 Jul 2021 18:28:59 +0200 Subject: [PATCH 33/67] Move brushes, assets and palettes into collections Signed-off-by: XenialDan --- plugin.yml | 2 +- src/xenialdan/MagicWE2/EventListener.php | 11 +- src/xenialdan/MagicWE2/Loader.php | 3 +- .../MagicWE2/commands/asset/AssetCommand.php | 10 +- .../MagicWE2/commands/brush/BrushCommand.php | 4 +- .../commands/brush/BrushNameCommand.php | 4 +- .../commands/palette/PaletteCommand.php | 6 +- .../MagicWE2/helper/SessionHelper.php | 2 +- .../MagicWE2/session/UserSession.php | 132 +++-------------- src/xenialdan/MagicWE2/session/data/Asset.php | 6 +- .../MagicWE2/session/data/AssetCollection.php | 20 ++- .../MagicWE2/session/data/BrushCollection.php | 135 ++++++++++++++++++ .../session/data/PaletteCollection.php | 20 +-- src/xenialdan/MagicWE2/tool/Brush.php | 4 +- 14 files changed, 208 insertions(+), 151 deletions(-) create mode 100644 src/xenialdan/MagicWE2/session/data/BrushCollection.php diff --git a/plugin.yml b/plugin.yml index d712b823..37f9253e 100644 --- a/plugin.yml +++ b/plugin.yml @@ -1,7 +1,7 @@ --- name: MagicWE2 main: xenialdan\MagicWE2\Loader -version: 10.1.6 +version: 10.1.7 api: ["4.0.0"] php: [ "8.0" ] softdepend: [ "DEVirion" ] diff --git a/src/xenialdan/MagicWE2/EventListener.php b/src/xenialdan/MagicWE2/EventListener.php index 83be05a6..03f3cc25 100644 --- a/src/xenialdan/MagicWE2/EventListener.php +++ b/src/xenialdan/MagicWE2/EventListener.php @@ -35,7 +35,6 @@ use xenialdan\MagicWE2\helper\SessionHelper; use xenialdan\MagicWE2\selection\Selection; use xenialdan\MagicWE2\session\data\Asset; -use xenialdan\MagicWE2\session\data\AssetCollection; use xenialdan\MagicWE2\session\UserSession; use xenialdan\MagicWE2\tool\Brush; @@ -257,7 +256,7 @@ private function onRightClickBlock(PlayerInteractEvent $event): void $tag = $event->getItem()->getNamedTag()->getCompoundTag(API::TAG_MAGIC_WE_ASSET); if ($tag !== null) { $filename = $tag->getString('filename'); - $asset = AssetCollection::getInstance()->assets[$filename]; + $asset = Loader::$assetCollection->assets[$filename];//TODO allow private assets again $target = $event->getBlock()->getSide($event->getFace())->getPos(); if (API::placeAsset($target, $asset, $tag, $session)) { $event->getPlayer()->sendMessage("Asset placed!"); @@ -342,7 +341,7 @@ private function onRightClickAir(PlayerItemUseEvent $event): void $session = SessionHelper::getUserSession($event->getPlayer()); if (!$session instanceof UserSession) return; $target = $event->getPlayer()->getTargetBlock(Loader::getInstance()->getToolDistance()); - $brush = $session->getBrushFromItem($event->getItem()); + $brush = $session->getBrushes()->getBrushFromItem($event->getItem()); var_dump(json_encode($brush, JSON_THROW_ON_ERROR)); if ($brush instanceof Brush && !is_null($target)) {// && has perms API::createBrush($target, $brush, $session); @@ -360,13 +359,13 @@ public function onDropItem(PlayerDropItemEvent $event): void $event->cancel(); $session = SessionHelper::getUserSession($event->getPlayer()); if (!$session instanceof UserSession) return; - $brush = $session->getBrushFromItem($event->getItem()); + $brush = $session->getBrushes()->getBrushFromItem($event->getItem()); if ($brush instanceof Brush) { $form = new ModalForm(TF::BOLD . $brush->getName(), TF::RED . "Delete" . TF::WHITE . " brush from session or " . TF::GREEN . "remove" . TF::WHITE . " from Inventory?" . TF::EOL . implode(TF::EOL, $event->getItem()->getLore()), TF::BOLD . TF::DARK_RED . "Delete", TF::BOLD . TF::DARK_GREEN . "Remove"); $form->setCallable(function (Player $player, $data) use ($session, $brush) { - $session->removeBrush($brush, $data); + $session->getBrushes()->removeBrush($brush, $data); }); $event->getPlayer()->sendForm($form); } @@ -404,7 +403,7 @@ public function onChangeSlot(PlayerItemHeldEvent $event): void if (!$session instanceof UserSession) return; if ($item->getId() === ItemIds::SCAFFOLDING) { $filename = $tag->getString('filename'); - $asset = AssetCollection::getInstance()->assets[$filename]; + $asset = Loader::$assetCollection->assets[$filename];//TODO allow private assets again var_dump($filename, $asset); #$assets = AssetCollection::getInstance()->getPlayerAssets($player->getXuid()); $session->displayOutline = true; diff --git a/src/xenialdan/MagicWE2/Loader.php b/src/xenialdan/MagicWE2/Loader.php index 85be7618..09b11505 100644 --- a/src/xenialdan/MagicWE2/Loader.php +++ b/src/xenialdan/MagicWE2/Loader.php @@ -74,6 +74,7 @@ use xenialdan\MagicWE2\helper\SessionHelper; use xenialdan\MagicWE2\selection\shape\ShapeRegistry; use xenialdan\MagicWE2\session\data\AssetCollection; +use xenialdan\MagicWE2\session\PluginSession; use xenialdan\MagicWE2\session\UserSession; use xenialdan\MagicWE2\task\action\ActionRegistry; @@ -180,7 +181,7 @@ public function onLoad(): void $blockstateparserInstance->setAliasMap(json_decode($fileGetContents, true, 512, JSON_THROW_ON_ERROR)); //$blockstateparserInstance::runTests();//TODO REMOVE, DEBUG!!!!!!! - self::$assetCollection = new AssetCollection(); + self::$assetCollection = new AssetCollection(new PluginSession($this)); } /** diff --git a/src/xenialdan/MagicWE2/commands/asset/AssetCommand.php b/src/xenialdan/MagicWE2/commands/asset/AssetCommand.php index 386c474b..a6e49c64 100644 --- a/src/xenialdan/MagicWE2/commands/asset/AssetCommand.php +++ b/src/xenialdan/MagicWE2/commands/asset/AssetCommand.php @@ -24,7 +24,6 @@ use xenialdan\MagicWE2\helper\SessionHelper; use xenialdan\MagicWE2\Loader; use xenialdan\MagicWE2\session\data\Asset; -use xenialdan\MagicWE2\session\data\AssetCollection; use xenialdan\MagicWE2\session\UserSession; class AssetCommand extends BaseCommand @@ -71,7 +70,7 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo $form->addButton(new Button($lang->translateString('ui.asset.save'))); $form->setCallable(function (Player $player, $data) use ($lang, $session) { try { - $store = AssetCollection::getInstance(); + $store = Loader::$assetCollection;//TODO allow private assets again switch ($data) { case $lang->translateString('ui.asset.create.fromclipboard'): { @@ -141,7 +140,7 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo //dropdown type $form = new CustomForm(Loader::PREFIX_FORM . TF::BOLD . TF::DARK_PURPLE . $lang->translateString('ui.asset.select')); $options = []; - foreach (AssetCollection::getInstance()->getAssets() as $asset) { + foreach (Loader::$assetCollection->getAll() as $asset) {//TODO allow private assets again $options[$asset->filename] = $asset->filename; } $form->addDropdown("Asset", array_values($options)); @@ -157,7 +156,7 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo case $lang->translateString('ui.asset.global'): { $menu = InvMenu::create(InvMenu::TYPE_DOUBLE_CHEST); - #$store = Loader::$assetCollection; + $store = Loader::$assetCollection; foreach ($store->getSharedAssets() as $asset) { $menu->getInventory()->addItem($asset->toItem()); } @@ -167,8 +166,7 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo case $lang->translateString('ui.asset.private'): { $menu = InvMenu::create(InvMenu::TYPE_DOUBLE_CHEST); - #$store = Loader::$assetCollection; - $store = AssetCollection::getInstance(); + $store = $session->getAssets(); $playerAssets = $store->getPlayerAssets($player->getXuid()); var_dump(array_keys($playerAssets), array_keys($store->getPlayerAssets())); foreach ($playerAssets as $key => $asset) { diff --git a/src/xenialdan/MagicWE2/commands/brush/BrushCommand.php b/src/xenialdan/MagicWE2/commands/brush/BrushCommand.php index 89d8d708..b0255f65 100644 --- a/src/xenialdan/MagicWE2/commands/brush/BrushCommand.php +++ b/src/xenialdan/MagicWE2/commands/brush/BrushCommand.php @@ -77,7 +77,7 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo case $lang->translateString('ui.brush.getsession'): { $menu = InvMenu::create(InvMenu::TYPE_DOUBLE_CHEST); - foreach ($session->getBrushes() as $brush) { + foreach ($session->getBrushes()->getAll() as $brush) { $menu->getInventory()->addItem($brush->toItem()); } $menu->send($player, "Session brushes"); @@ -85,7 +85,7 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo } case $lang->translateString('ui.brush.edithand'): { - $brush = $session->getBrushFromItem($player->getInventory()->getItemInHand()); + $brush = $session->getBrushes()->getBrushFromItem($player->getInventory()->getItemInHand()); if ($brush instanceof Brush) { $player->sendForm($brush->getForm(false)); } diff --git a/src/xenialdan/MagicWE2/commands/brush/BrushNameCommand.php b/src/xenialdan/MagicWE2/commands/brush/BrushNameCommand.php index 482a42ac..518529c6 100644 --- a/src/xenialdan/MagicWE2/commands/brush/BrushNameCommand.php +++ b/src/xenialdan/MagicWE2/commands/brush/BrushNameCommand.php @@ -54,7 +54,7 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo if (!$session instanceof UserSession) { throw new SessionException($lang->translateString('error.nosession', [Loader::getInstance()->getName()])); } - $brush = $session->getBrushFromItem($sender->getInventory()->getItemInHand()); + $brush = $session->getBrushes()->getBrushFromItem($sender->getInventory()->getItemInHand()); if ($brush instanceof Brush) { if (empty($args["name"])) { $sender->sendMessage($brush->getName()); @@ -62,7 +62,7 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo } $brush->properties->setCustomName((string)$args["name"]); $session->sendMessage(TF::GREEN . $lang->translateString('command.brushname.set', [$brush->getName()])); - $session->replaceBrush($brush); + $session->getBrushes()->replaceBrush($brush); } } catch (Exception | TypeError $error) { $sender->sendMessage(Loader::PREFIX . TF::RED . $lang->translateString('error.command-error')); diff --git a/src/xenialdan/MagicWE2/commands/palette/PaletteCommand.php b/src/xenialdan/MagicWE2/commands/palette/PaletteCommand.php index 09525b05..47579ffc 100644 --- a/src/xenialdan/MagicWE2/commands/palette/PaletteCommand.php +++ b/src/xenialdan/MagicWE2/commands/palette/PaletteCommand.php @@ -91,12 +91,12 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo } case $lang->translateString('ui.palette.viewhand'): { - $palettes = $session->palettes; + $palettes = $session->getPalettes(); $menu = InvMenu::create(InvMenu::TYPE_DOUBLE_CHEST); - foreach ($palettes->getPalettes() as $palette) { + foreach ($palettes->getAll() as $palette) { $menu->getInventory()->addItem($palette->toItem()); } - $menu->send($player, "Palettes (" . count($palettes->getPalettes()) . ")"); + $menu->send($player, "Palettes (" . count($palettes->getAll()) . ")"); break; } } diff --git a/src/xenialdan/MagicWE2/helper/SessionHelper.php b/src/xenialdan/MagicWE2/helper/SessionHelper.php index 11011678..b0e4e2c4 100644 --- a/src/xenialdan/MagicWE2/helper/SessionHelper.php +++ b/src/xenialdan/MagicWE2/helper/SessionHelper.php @@ -203,7 +203,7 @@ public static function loadUserSession(Player $player): ?UserSession try { $properties = BrushProperties::fromJson($brushJson["properties"]); $brush = new Brush($properties); - $session->addBrush($brush); + $session->getBrushes()->addBrush($brush); } catch (InvalidArgumentException $e) { continue; } diff --git a/src/xenialdan/MagicWE2/session/UserSession.php b/src/xenialdan/MagicWE2/session/UserSession.php index 14183cf6..024cce93 100644 --- a/src/xenialdan/MagicWE2/session/UserSession.php +++ b/src/xenialdan/MagicWE2/session/UserSession.php @@ -4,33 +4,21 @@ namespace xenialdan\MagicWE2\session; -use Exception; -use InvalidArgumentException; use jackmd\scorefactory\ScoreFactory; -use JsonException; use JsonSerializable; -use pocketmine\item\Item; use pocketmine\lang\Language; use pocketmine\lang\LanguageNotFoundException; use pocketmine\nbt\tag\CompoundTag; -use pocketmine\nbt\UnexpectedTagTypeException; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; -use Ramsey\Uuid\Uuid; -use Ramsey\Uuid\UuidInterface; use SplDoublyLinkedList; -use TypeError; use xenialdan\apibossbar\BossBar; use xenialdan\MagicWE2\API; -use xenialdan\MagicWE2\exception\ActionNotFoundException; -use xenialdan\MagicWE2\exception\BrushException; -use xenialdan\MagicWE2\exception\ShapeNotFoundException; use xenialdan\MagicWE2\helper\Scoreboard; use xenialdan\MagicWE2\Loader; -use xenialdan\MagicWE2\session\data\Asset; +use xenialdan\MagicWE2\session\data\AssetCollection; +use xenialdan\MagicWE2\session\data\BrushCollection; use xenialdan\MagicWE2\session\data\PaletteCollection; -use xenialdan\MagicWE2\tool\Brush; -use xenialdan\MagicWE2\tool\BrushProperties; class UserSession extends Session implements JsonSerializable //TODO use JsonMapper { @@ -48,11 +36,9 @@ class UserSession extends Session implements JsonSerializable //TODO use JsonMap private bool $wailaEnabled = true; /** @var bool */ private bool $sidebarEnabled = true;//TODO settings/commands - /** @var array */ - private array $brushes = []; - /** @var array */ - private array $assets = []; - public PaletteCollection $palettes; + private BrushCollection $brushes; + private AssetCollection $assets; + private PaletteCollection $palettes; /** @var Language|null */ private ?Language $lang = null; public bool $displayOutline = false; @@ -69,7 +55,9 @@ public function __construct(Player $player) } $this->undoHistory = new SplDoublyLinkedList(); $this->redoHistory = new SplDoublyLinkedList(); - $this->palettes = new PaletteCollection(); + $this->brushes = new BrushCollection($this); + $this->assets = new AssetCollection($this); + $this->palettes = new PaletteCollection($this); try { if (is_null($this->lang)) $this->lang = new Language(Language::FALLBACK_LANGUAGE, Loader::getInstance()->getLanguageFolder()); @@ -222,104 +210,19 @@ public function getBossBar(): BossBar return $this->bossBar; } - /** - * TODO exception for not a brush - * @param Item $item - * @return Brush - * @throws Exception - */ - public function getBrushFromItem(Item $item): Brush - { - if ((($entry = $item->getNamedTag()->getCompoundTag(API::TAG_MAGIC_WE_BRUSH))) instanceof CompoundTag) { - $version = $entry->getInt("version", 0); - if ($version !== BrushProperties::VERSION) { - throw new BrushException("Brush can not be restored - version mismatch"); - } - /** @var BrushProperties $properties */ - $properties = json_decode($entry->getString("properties"), false, 512, JSON_THROW_ON_ERROR); - $uuid = Uuid::fromString($properties->uuid); - $brush = $this->getBrush($uuid); - if ($brush instanceof Brush) { - return $brush; - } - $brush = new Brush($properties); - $this->addBrush($brush); - return $brush; - } - throw new BrushException("The item is not a valid brush!"); - } - - /** - * TODO exception for not a brush - * @param UuidInterface $uuid - * @return null|Brush - */ - public function getBrush(UuidInterface $uuid): ?Brush - { - return $this->brushes[$uuid->toString()]; - } - - /** - * TODO exception for not a brush - * @param Brush $brush UuidInterface will be set automatically - * @return void - */ - public function addBrush(Brush $brush): void - { - $this->brushes[$brush->properties->uuid] = $brush; - $this->sendMessage($this->getLanguage()->translateString('session.brush.added', [$brush->getName()])); - } - - /** - * @param Brush $brush UuidInterface will be set automatically - * @param bool $delete If true, it will be removed from the session brushes - * @return void - * @throws UnexpectedTagTypeException - */ - public function removeBrush(Brush $brush, bool $delete = false): void + public function getBrushes(): BrushCollection { - if ($delete) unset($this->brushes[$brush->properties->uuid]); - foreach ($this->getPlayer()->getInventory()->getContents() as $slot => $item) { - if (($entry = $item->getNamedTag()->getCompoundTag(API::TAG_MAGIC_WE_BRUSH)) instanceof CompoundTag) { - if ($entry->getString("id") === $brush->properties->uuid) { - $this->getPlayer()->getInventory()->clear($slot); - } - } - } - if ($delete) $this->sendMessage($this->getLanguage()->translateString('session.brush.deleted', [$brush->getName(), $brush->properties->uuid])); - else $this->sendMessage($this->getLanguage()->translateString('session.brush.removed', [$brush->getName(), $brush->properties->uuid])); + return $this->brushes; } - /** - * TODO exception for not a brush - * @param Brush $brush UuidInterface will be set automatically - * @return void - * @throws ActionNotFoundException - * @throws InvalidArgumentException - * @throws JsonException - * @throws ShapeNotFoundException - * @throws TypeError - * @throws UnexpectedTagTypeException - */ - public function replaceBrush(Brush $brush): void + public function getAssets(): AssetCollection { - $this->brushes[$brush->properties->uuid] = $brush; - $new = $brush->toItem(); - foreach ($this->getPlayer()->getInventory()->getContents() as $slot => $item) { - if (($entry = $item->getNamedTag()->getCompoundTag(API::TAG_MAGIC_WE_BRUSH)) instanceof CompoundTag) { - if ($entry->getString("id") === $brush->properties->uuid) { - $this->getPlayer()->getInventory()->setItem($slot, $new); - } - } - } + return $this->assets; } - /** - * @return Brush[] - */ - public function getBrushes(): array + public function getPalettes(): PaletteCollection { - return $this->brushes; + return $this->palettes; } public function cleanupInventory(): void @@ -351,7 +254,9 @@ public function __toString() " Current: " . $this->getCurrentClipboardIndex() . " Undos: " . count($this->undoHistory) . " Redos: " . count($this->redoHistory) . - " Brushes: " . count($this->brushes); + " Brushes: " . count($this->brushes->brushes) . + " Assets: " . count($this->assets->assets) . + " Palettes: " . count($this->palettes->palettes); } public function sendMessage(string $message): void @@ -374,7 +279,8 @@ public function jsonSerialize() "debugToolEnabled" => $this->debugToolEnabled, "wailaEnabled" => $this->wailaEnabled, "sidebarEnabled" => $this->sidebarEnabled, - "brushes" => $this->brushes, + "brushes" => $this->brushes->brushes, + //todo assets, palettes "latestSelection" => $this->getLatestSelection(), "currentClipboard" => $this->getCurrentClipboard(), "language" => $this->getLanguage()->getLang() diff --git a/src/xenialdan/MagicWE2/session/data/Asset.php b/src/xenialdan/MagicWE2/session/data/Asset.php index 3ab4ecca..ae278b47 100644 --- a/src/xenialdan/MagicWE2/session/data/Asset.php +++ b/src/xenialdan/MagicWE2/session/data/Asset.php @@ -253,7 +253,11 @@ public function getSettingForm(bool $new = true, array $errors = []): CustomForm #print_r(AssetCollection::getInstance()->assets->values()->toArray()); #print_r(AssetCollection::getInstance()->assets->keys()->toArray()); #print_r(AssetCollection::getInstance()->getAssets()); - AssetCollection::getInstance()->assets[$this->filename] = $this;//overwrites + if($shared){ + Loader::$assetCollection->assets[$this->filename] = $this;//overwrites + }else{ + $session->getAssets()->assets[$this->filename] = $this;//overwrites + } $player->sendMessage("Asset stored in " . ($shared ? 'global' : 'private') . ' collection'); $player->sendMessage((string)$this); #$player->sendMessage((string)$this->toItem(true)); diff --git a/src/xenialdan/MagicWE2/session/data/AssetCollection.php b/src/xenialdan/MagicWE2/session/data/AssetCollection.php index f71d7d3b..dfdc62d3 100644 --- a/src/xenialdan/MagicWE2/session/data/AssetCollection.php +++ b/src/xenialdan/MagicWE2/session/data/AssetCollection.php @@ -4,27 +4,35 @@ namespace xenialdan\MagicWE2\session\data; -use pocketmine\utils\SingletonTrait; use pocketmine\utils\TextFormat as TF; use xenialdan\libstructure\exception\StructureFileException; use xenialdan\MagicWE2\helper\StructureStore; use xenialdan\MagicWE2\Loader; +use xenialdan\MagicWE2\session\Session; use function array_filter; final class AssetCollection { - use SingletonTrait; - /** @var array */ public array $assets = []; + private Session $session; - public function __construct() + public function __construct(Session $session) { + $this->session = $session; $this->initFolders(); } + /** + * @return Session + */ + public function getSession(): Session + { + return $this->session; + } + /** @return Asset[] */ - public function getAssets(): array + public function getAll(): array { return $this->assets; } @@ -40,6 +48,7 @@ public function getUnlockedAssets(): array /** @return Asset[] */ public function getSharedAssets(): array { + //TODO remove return array_filter($this->assets, function (Asset $value) { return $value->shared; }); @@ -51,6 +60,7 @@ public function getSharedAssets(): array */ public function getPlayerAssets(?string $xuid = null): array { + //TODO remove return array_filter($this->assets, function (string $key, Asset $value) use ($xuid) { if ($xuid === null) return $value->ownerXuid !== null; else return $value->ownerXuid === $xuid; diff --git a/src/xenialdan/MagicWE2/session/data/BrushCollection.php b/src/xenialdan/MagicWE2/session/data/BrushCollection.php new file mode 100644 index 00000000..9cd45be2 --- /dev/null +++ b/src/xenialdan/MagicWE2/session/data/BrushCollection.php @@ -0,0 +1,135 @@ + */ + public array $brushes; + private UserSession $session; + + public function __construct(UserSession $session) + { + $this->session = $session; + } + + /** + * @return UserSession + */ + public function getSession(): UserSession + { + return $this->session; + } + + /** @return Brush[] */ + public function getAll(): array + { + return $this->brushes; + } + + /** + * TODO exception for not a brush + * @param Item $item + * @return Brush + * @throws Exception + */ + public function getBrushFromItem(Item $item): Brush + { + if ((($entry = $item->getNamedTag()->getCompoundTag(API::TAG_MAGIC_WE_BRUSH))) instanceof CompoundTag) { + $version = $entry->getInt("version", 0); + if ($version !== BrushProperties::VERSION) { + throw new BrushException("Brush can not be restored - version mismatch"); + } + /** @var BrushProperties $properties */ + $properties = json_decode($entry->getString("properties"), false, 512, JSON_THROW_ON_ERROR); + $brush = $this->getBrush($properties->uuid); + if ($brush instanceof Brush) { + return $brush; + } + $brush = new Brush($properties); + $this->addBrush($brush); + return $brush; + } + throw new BrushException("The item is not a valid brush!"); + } + + public function getBrush(string $id): ?Brush + { + return $this->brushes[$id];//TODO allow finding by custom name + } + + /** + * TODO exception for not a brush + * @param Brush $brush UuidInterface will be set automatically + * @return void + */ + public function addBrush(Brush $brush): void + { + $this->brushes[$brush->properties->uuid] = $brush; + $this->getSession()->sendMessage($this->getSession()->getLanguage()->translateString('session.brush.added', [$brush->getName()])); + } + + /** + * @param Brush $brush UuidInterface will be set automatically + * @param bool $delete If true, it will be removed from the session brushes + * @return void + * @throws UnexpectedTagTypeException + */ + public function removeBrush(Brush $brush, bool $delete = false): void + { + if ($delete) unset($this->brushes[$brush->properties->uuid]); + foreach ($this->getSession()->getPlayer()->getInventory()->getContents() as $slot => $item) { + if (($entry = $item->getNamedTag()->getCompoundTag(API::TAG_MAGIC_WE_BRUSH)) instanceof CompoundTag) { + if ($entry->getString("id") === $brush->properties->uuid) { + $this->getSession()->getPlayer()->getInventory()->clear($slot); + } + } + } + if ($delete) $this->getSession()->sendMessage($this->getSession()->getLanguage()->translateString('session.brush.deleted', [$brush->getName(), $brush->properties->uuid])); + else $this->getSession()->sendMessage($this->getSession()->getLanguage()->translateString('session.brush.removed', [$brush->getName(), $brush->properties->uuid])); + } + + /** + * TODO exception for not a brush + * @param Brush $brush UuidInterface will be set automatically + * @return void + * @throws ActionNotFoundException + * @throws InvalidArgumentException + * @throws JsonException + * @throws ShapeNotFoundException + * @throws TypeError + * @throws UnexpectedTagTypeException + */ + public function replaceBrush(Brush $brush): void + { + $this->brushes[$brush->properties->uuid] = $brush; + $new = $brush->toItem(); + foreach ($this->getSession()->getPlayer()->getInventory()->getContents() as $slot => $item) { + if (($entry = $item->getNamedTag()->getCompoundTag(API::TAG_MAGIC_WE_BRUSH)) instanceof CompoundTag) { + if ($entry->getString("id") === $brush->properties->uuid) { + $this->getSession()->getPlayer()->getInventory()->setItem($slot, $new); + } + } + } + } +} \ No newline at end of file diff --git a/src/xenialdan/MagicWE2/session/data/PaletteCollection.php b/src/xenialdan/MagicWE2/session/data/PaletteCollection.php index c5e6402f..6ac31229 100644 --- a/src/xenialdan/MagicWE2/session/data/PaletteCollection.php +++ b/src/xenialdan/MagicWE2/session/data/PaletteCollection.php @@ -4,28 +4,32 @@ namespace xenialdan\MagicWE2\session\data; -use pocketmine\utils\SingletonTrait; use xenialdan\MagicWE2\helper\BlockPalette; +use xenialdan\MagicWE2\session\UserSession; final class PaletteCollection { - use SingletonTrait; /** @var array */ public array $palettes; + private UserSession $session; - public function __construct() + public function __construct(UserSession $session) { - //$this->initFolders(); + $this->session = $session; } - /** @return BlockPalette[] */ - public function getPalettes(): array + /** + * @return UserSession + */ + public function getSession(): UserSession { - return $this->palettes; + return $this->session; } - private function initFolders(): void + /** @return BlockPalette[] */ + public function getAll(): array { + return $this->palettes; } } \ No newline at end of file diff --git a/src/xenialdan/MagicWE2/tool/Brush.php b/src/xenialdan/MagicWE2/tool/Brush.php index 2f5dc487..50578cf4 100644 --- a/src/xenialdan/MagicWE2/tool/Brush.php +++ b/src/xenialdan/MagicWE2/tool/Brush.php @@ -223,7 +223,7 @@ public function getForm(bool $new = true, array $errors = []): CustomForm throw new SessionException(Loader::getInstance()->getLanguage()->translateString('error.nosession', [Loader::getInstance()->getName()])); } if (!$new) { - $session->replaceBrush($brush); + $session->getBrushes()->replaceBrush($brush); } else { $player->sendForm($this->getExtradataForm($this->properties->shape)); } @@ -266,7 +266,7 @@ private function getExtradataForm(string $shapeClass): CustomForm throw new SessionException(Loader::getInstance()->getLanguage()->translateString('error.nosession', [Loader::getInstance()->getName()])); } $this->properties->uuid = Uuid::uuid4()->toString(); - $session->addBrush($brush); + $session->getBrushes()->addBrush($brush); $player->getInventory()->addItem($brush->toItem()); }); return $form; From 2db269d57beaf6aa656587ae72cf70a92c12085b Mon Sep 17 00:00:00 2001 From: XenialDan Date: Sun, 25 Jul 2021 19:08:47 +0200 Subject: [PATCH 34/67] Replace getBlockArrayAt with getBlockFullId Signed-off-by: XenialDan --- src/xenialdan/MagicWE2/EventListener.php | 1 + src/xenialdan/MagicWE2/helper/AsyncChunkManager.php | 5 +++-- src/xenialdan/MagicWE2/helper/BlockStatesParser.php | 1 + src/xenialdan/MagicWE2/selection/shape/Shape.php | 4 +++- src/xenialdan/MagicWE2/session/data/Asset.php | 1 + src/xenialdan/MagicWE2/task/AsyncCopyTask.php | 1 + src/xenialdan/MagicWE2/task/AsyncCountTask.php | 4 ++-- src/xenialdan/MagicWE2/task/AsyncFillTask.php | 3 ++- src/xenialdan/MagicWE2/task/AsyncPasteAssetTask.php | 12 +++--------- src/xenialdan/MagicWE2/task/AsyncPasteTask.php | 4 +--- src/xenialdan/MagicWE2/task/AsyncReplaceTask.php | 3 ++- src/xenialdan/MagicWE2/task/action/CountAction.php | 8 ++++---- src/xenialdan/MagicWE2/task/action/CutAction.php | 3 ++- .../MagicWE2/task/action/SetBlockAction.php | 3 ++- 14 files changed, 28 insertions(+), 25 deletions(-) diff --git a/src/xenialdan/MagicWE2/EventListener.php b/src/xenialdan/MagicWE2/EventListener.php index 03f3cc25..102c1369 100644 --- a/src/xenialdan/MagicWE2/EventListener.php +++ b/src/xenialdan/MagicWE2/EventListener.php @@ -442,6 +442,7 @@ public static function sendOutline(Player $player, Position $target, Asset $asse $minComponents = new Vector3($ix, $iy, $iz); $maxComponents = new Vector3($ax, $ay, $az); + /** @noinspection PhpDeprecationInspection */ $block = BlockFactory::getInstance()->get(BlockLegacyIds::STRUCTURE_BLOCK, 0/*StructureEditorData::TYPE_SAVE*/); var_dump((string)$block); $target->world->setBlock($target->asVector3(), $block); diff --git a/src/xenialdan/MagicWE2/helper/AsyncChunkManager.php b/src/xenialdan/MagicWE2/helper/AsyncChunkManager.php index 906b138c..daebe88a 100644 --- a/src/xenialdan/MagicWE2/helper/AsyncChunkManager.php +++ b/src/xenialdan/MagicWE2/helper/AsyncChunkManager.php @@ -9,9 +9,10 @@ class AsyncChunkManager extends SimpleChunkManager { - public function getBlockArrayAt(int $x, int $y, int $z): array//TODO replace with getFullBlock + public function getBlockFullIdAt(int $x, int $y, int $z): int { - return [$this->getBlockAt($x, $y, $z)->getId(), $this->getBlockAt($x, $y, $z)->getMeta()]; + /** @noinspection PhpInternalEntityUsedInspection */ + return $this->getBlockAt($x, $y, $z)->getFullId(); } /** diff --git a/src/xenialdan/MagicWE2/helper/BlockStatesParser.php b/src/xenialdan/MagicWE2/helper/BlockStatesParser.php index ce539e86..85f5b12c 100644 --- a/src/xenialdan/MagicWE2/helper/BlockStatesParser.php +++ b/src/xenialdan/MagicWE2/helper/BlockStatesParser.php @@ -279,6 +279,7 @@ public static function fromString(BlockQuery $query): Block $clonedPrintedCompound = clone $r12ToCurrentBlockMapEntry->getBlockState()->getCompoundTag('states'); if ($clonedPrintedCompound->equals($finalStatesList)) { $blockFactory = BlockFactory::getInstance(); + /** @noinspection PhpDeprecationInspection */ $block = $blockFactory->get($block->getId(), $meta & 0xf); $blocks[] = $block; } diff --git a/src/xenialdan/MagicWE2/selection/shape/Shape.php b/src/xenialdan/MagicWE2/selection/shape/Shape.php index a4e52257..5e894068 100644 --- a/src/xenialdan/MagicWE2/selection/shape/Shape.php +++ b/src/xenialdan/MagicWE2/selection/shape/Shape.php @@ -5,6 +5,7 @@ use Exception; use Generator; use InvalidArgumentException; +use pocketmine\block\Block; use pocketmine\math\AxisAlignedBB; use pocketmine\math\Vector3; use pocketmine\world\format\Chunk; @@ -60,8 +61,9 @@ abstract public function getTotalCount(): int; * @param World|AsyncChunkManager $manager The world or AsyncChunkManager * @param BlockPalette $filterblocks If not empty, applying a filter on the block list * @param int $flags - * @return Generator + * @return Generator|Block[] * @throws Exception + * @noinspection PhpDocSignatureInspection */ abstract public function getBlocks(AsyncChunkManager|World $manager, BlockPalette $filterblocks, int $flags = API::FLAG_BASE): Generator; diff --git a/src/xenialdan/MagicWE2/session/data/Asset.php b/src/xenialdan/MagicWE2/session/data/Asset.php index ae278b47..def4dcca 100644 --- a/src/xenialdan/MagicWE2/session/data/Asset.php +++ b/src/xenialdan/MagicWE2/session/data/Asset.php @@ -91,6 +91,7 @@ public function getOrigin(): Vector3 public function toItem(bool $renew = false): Item { if ($this->item !== null && !$renew) return $this->item; + /** @noinspection PhpDeprecationInspection */ $item = ItemFactory::getInstance()->get(ItemIds::SCAFFOLDING); $item->addEnchantment(new EnchantmentInstance(Loader::$ench)); try { diff --git a/src/xenialdan/MagicWE2/task/AsyncCopyTask.php b/src/xenialdan/MagicWE2/task/AsyncCopyTask.php index 7559a2c4..d7cfd57d 100644 --- a/src/xenialdan/MagicWE2/task/AsyncCopyTask.php +++ b/src/xenialdan/MagicWE2/task/AsyncCopyTask.php @@ -98,6 +98,7 @@ private function copyBlocks(Selection $selection, AsyncChunkManager $manager, Si foreach ($selection->getShape()->getBlocks($manager, BlockPalette::CREATE(), $this->flags) as $block) { #var_dump("copy chunk X: " . ($block->getX() >> 4) . " Y: " . ($block->getY() >> 4)); $newv3 = $block->getPos()->subtractVector($min)->floor(); + /** @noinspection PhpInternalEntityUsedInspection */ $clipboard->addEntry($newv3->getFloorX(), $newv3->getFloorY(), $newv3->getFloorZ(), new BlockEntry($block->getFullId()));//TODO test tiles #var_dump("copied selection block", $block); $i++; diff --git a/src/xenialdan/MagicWE2/task/AsyncCountTask.php b/src/xenialdan/MagicWE2/task/AsyncCountTask.php index 063d5ab5..9f5064af 100644 --- a/src/xenialdan/MagicWE2/task/AsyncCountTask.php +++ b/src/xenialdan/MagicWE2/task/AsyncCountTask.php @@ -97,8 +97,8 @@ private function countBlocks(Selection $selection, AsyncChunkManager $manager, B } } BlockFactory::getInstance(); - $block1 = $manager->getBlockArrayAt($block->getPos()->getFloorX(), $block->getPos()->getFloorY(), $block->getPos()->getFloorZ()); - $tostring = (BlockFactory::getInstance()->get($block1[0], $block1[1]))->getName() . " " . $block1[0] . ":" . $block1[1]; + $block1 = $manager->getBlockAt($block->getPos()->getFloorX(), $block->getPos()->getFloorY(), $block->getPos()->getFloorZ()); + $tostring = $block1->getName() . " " . $block1->getId(). ":" . $block1->getMeta(); if (!array_key_exists($tostring, $counts)) $counts[$tostring] = 0; $counts[$tostring]++; $changed++; diff --git a/src/xenialdan/MagicWE2/task/AsyncFillTask.php b/src/xenialdan/MagicWE2/task/AsyncFillTask.php index 359c3266..1516dc04 100644 --- a/src/xenialdan/MagicWE2/task/AsyncFillTask.php +++ b/src/xenialdan/MagicWE2/task/AsyncFillTask.php @@ -142,7 +142,8 @@ private function execute(Selection $selection, AsyncChunkManager $manager, Block yield self::singleBlockToData(API::setComponents($manager->getBlockAt($block->getPos()->getFloorX(), $block->getPos()->getFloorY(), $block->getPos()->getFloorZ()), (int)$block->getPos()->x, (int)$block->getPos()->y, (int)$block->getPos()->z)); #yield $block;//backup $manager->setBlockAt($block->getPos()->getFloorX(), $block->getPos()->getFloorY(), $block->getPos()->getFloorZ(), $new); - if ($manager->getBlockArrayAt($block->getPos()->getFloorX(), $block->getPos()->getFloorY(), $block->getPos()->getFloorZ()) !== [$block->getId(), $block->getMeta()]) { + /** @noinspection PhpInternalEntityUsedInspection */ + if ($manager->getBlockFullIdAt($block->getPos()->getFloorX(), $block->getPos()->getFloorY(), $block->getPos()->getFloorZ()) !== $block->getFullId()) { $changed++; } /// diff --git a/src/xenialdan/MagicWE2/task/AsyncPasteAssetTask.php b/src/xenialdan/MagicWE2/task/AsyncPasteAssetTask.php index 51647a27..f3ece916 100644 --- a/src/xenialdan/MagicWE2/task/AsyncPasteAssetTask.php +++ b/src/xenialdan/MagicWE2/task/AsyncPasteAssetTask.php @@ -132,9 +132,7 @@ private function execute(AsyncChunkManager $manager, Asset $asset, ?int &$change $new = $block; yield self::singleBlockToData(API::setComponents($manager->getBlockAt((int)$x, (int)$y, (int)$z), (int)$x, (int)$y, (int)$z)); $manager->setBlockAt((int)$x, (int)$y, (int)$z, $new); - if ($manager->getBlockArrayAt((int)$x, (int)$y, (int)$z) !== [$manager->getBlockAt((int)$x, (int)$y, (int)$z)->getId(), $manager->getBlockAt((int)$x, (int)$y, (int)$z)->getMeta()]) {//TODO remove? Just useless waste imo - $changed++; - } + $changed++; /// $i++; $progress = floor($i / $blockCount * 100); @@ -161,9 +159,7 @@ private function execute(AsyncChunkManager $manager, Asset $asset, ?int &$change $new = $entry->toBlock(); yield self::singleBlockToData(API::setComponents($manager->getBlockAt((int)$v->x, (int)$v->y, (int)$v->z), (int)$v->x, (int)$v->y, (int)$v->z)); $manager->setBlockAt((int)$v->x, (int)$v->y, (int)$v->z, $new); - if ($manager->getBlockArrayAt((int)$v->x, (int)$v->y, (int)$v->z) !== [$manager->getBlockAt((int)$v->x, (int)$v->y, (int)$v->z)->getId(), $manager->getBlockAt((int)$v->x, (int)$v->y, (int)$v->z)->getMeta()]) {//TODO remove? Just useless waste imo - $changed++; - } + $changed++; /// $i++; $progress = floor($i / $blockCount * 100); @@ -187,9 +183,7 @@ private function execute(AsyncChunkManager $manager, Asset $asset, ?int &$change $new = $block; yield self::singleBlockToData(API::setComponents($manager->getBlockAt($x, $y, $z), (int)$x, (int)$y, (int)$z)); $manager->setBlockAt($x, $y, $z, $new); - if ($manager->getBlockArrayAt($x, $y, $z) !== [$manager->getBlockAt($x, $y, $z)->getId(), $manager->getBlockAt($x, $y, $z)->getMeta()]) {//TODO remove? Just useless waste imo - $changed++; - } + $changed++; /// $i++; $progress = floor($i / $blockCount * 100); diff --git a/src/xenialdan/MagicWE2/task/AsyncPasteTask.php b/src/xenialdan/MagicWE2/task/AsyncPasteTask.php index 9a42708c..9b011b12 100644 --- a/src/xenialdan/MagicWE2/task/AsyncPasteTask.php +++ b/src/xenialdan/MagicWE2/task/AsyncPasteTask.php @@ -128,9 +128,7 @@ private function execute(Selection $selection, AsyncChunkManager $manager, Singl #var_dump("old", $old, "new", $new); yield self::singleBlockToData(API::setComponents($manager->getBlockAt($x, $y, $z), (int)$x, (int)$y, (int)$z)); $manager->setBlockAt($x, $y, $z, $new); - if ($manager->getBlockArrayAt($x, $y, $z) !== [$manager->getBlockAt($x, $y, $z)->getId(), $manager->getBlockAt($x, $y, $z)->getMeta()]) {//TODO remove? Just useless waste imo - $changed++; - } + $changed++; /// $i++; $progress = floor($i / $blockCount * 100); diff --git a/src/xenialdan/MagicWE2/task/AsyncReplaceTask.php b/src/xenialdan/MagicWE2/task/AsyncReplaceTask.php index 71d2bc7c..b4696315 100644 --- a/src/xenialdan/MagicWE2/task/AsyncReplaceTask.php +++ b/src/xenialdan/MagicWE2/task/AsyncReplaceTask.php @@ -125,7 +125,8 @@ private function execute(Selection $selection, AsyncChunkManager $manager, Block if ($new->getId() === $block->getId() && $new->getMeta() === $block->getMeta()) continue;//skip same blocks yield self::singleBlockToData(API::setComponents($manager->getBlockAt($block->getPos()->getFloorX(), $block->getPos()->getFloorY(), $block->getPos()->getFloorZ()), (int)$block->getPos()->x, (int)$block->getPos()->y, (int)$block->getPos()->z)); $manager->setBlockAt($block->getPos()->getFloorX(), $block->getPos()->getFloorY(), $block->getPos()->getFloorZ(), $new); - if ($manager->getBlockArrayAt($block->getPos()->getFloorX(), $block->getPos()->getFloorY(), $block->getPos()->getFloorZ()) !== [$block->getId(), $block->getMeta()]) { + /** @noinspection PhpInternalEntityUsedInspection */ + if ($manager->getBlockFullIdAt($block->getPos()->getFloorX(), $block->getPos()->getFloorY(), $block->getPos()->getFloorZ()) !== $block->getFullId()) { $changed++; } /// diff --git a/src/xenialdan/MagicWE2/task/action/CountAction.php b/src/xenialdan/MagicWE2/task/action/CountAction.php index a1c13dd3..369c3377 100644 --- a/src/xenialdan/MagicWE2/task/action/CountAction.php +++ b/src/xenialdan/MagicWE2/task/action/CountAction.php @@ -4,8 +4,8 @@ namespace xenialdan\MagicWE2\task\action; +use Exception; use Generator; -use InvalidArgumentException; use pocketmine\block\BlockFactory; use pocketmine\utils\TextFormat as TF; use xenialdan\MagicWE2\clipboard\SingleClipboard; @@ -40,7 +40,7 @@ public static function getName(): string * @param SingleClipboard $oldBlocksSingleClipboard blocks before the change * @param string[] $messages * @return Generator - * @throws InvalidArgumentException + * @throws Exception */ public function execute(string $sessionUUID, Selection $selection, AsyncChunkManager $manager, ?int &$changed, BlockPalette $newBlocks, BlockPalette $blockFilter, SingleClipboard $oldBlocksSingleClipboard, array &$messages = []): Generator { @@ -51,8 +51,8 @@ public function execute(string $sessionUUID, Selection $selection, AsyncChunkMan $counts = []; BlockFactory::getInstance(); foreach ($selection->getShape()->getBlocks($manager, $newBlocks) as $block) { - $block1 = $manager->getBlockArrayAt($block->getPos()->getFloorX(), $block->getPos()->getFloorY(), $block->getPos()->getFloorZ()); - $tostring = (BlockFactory::getInstance()->get($block1[0], $block1[1]))->getName() . " " . $block1[0] . ":" . $block1[1]; + $block1 = $manager->getBlockAt($block->getPos()->getFloorX(), $block->getPos()->getFloorY(), $block->getPos()->getFloorZ()); + $tostring = $block1->getName() . " " . $block1->getId() . ":" . $block1->getMeta(); if (!array_key_exists($tostring, $counts)) $counts[$tostring] = 0; $counts[$tostring]++; $changed++; diff --git a/src/xenialdan/MagicWE2/task/action/CutAction.php b/src/xenialdan/MagicWE2/task/action/CutAction.php index 40d48859..79093793 100644 --- a/src/xenialdan/MagicWE2/task/action/CutAction.php +++ b/src/xenialdan/MagicWE2/task/action/CutAction.php @@ -60,7 +60,8 @@ public function execute(string $sessionUUID, Selection $selection, AsyncChunkMan $newv3 = $block->getPos()->subtractVector($min)->floor();//TODO check if only used for clipboard $oldBlocksSingleClipboard->addEntry($newv3->getFloorX(), $newv3->getFloorY(), $newv3->getFloorZ(), BlockEntry::fromBlock($block)); $manager->setBlockAt($block->getPos()->getFloorX(), $block->getPos()->getFloorY(), $block->getPos()->getFloorZ(), $new); - if ($manager->getBlockArrayAt($block->getPos()->getFloorX(), $block->getPos()->getFloorY(), $block->getPos()->getFloorZ()) !== [$block->getId(), $block->getMeta()]) { + /** @noinspection PhpInternalEntityUsedInspection */ + if ($manager->getBlockFullIdAt($block->getPos()->getFloorX(), $block->getPos()->getFloorY(), $block->getPos()->getFloorZ()) !== $block->getFullId()) { $changed++; } $i++; diff --git a/src/xenialdan/MagicWE2/task/action/SetBlockAction.php b/src/xenialdan/MagicWE2/task/action/SetBlockAction.php index e7696f2c..d1dee59a 100644 --- a/src/xenialdan/MagicWE2/task/action/SetBlockAction.php +++ b/src/xenialdan/MagicWE2/task/action/SetBlockAction.php @@ -52,7 +52,8 @@ public function execute(string $sessionUUID, Selection $selection, AsyncChunkMan #$oldBlocks[] = API::setComponents($manager->getBlockAt($block->getPos()->getFloorX(), $block->getPos()->getFloorY(), $block->getPos()->getFloorZ()),$block->x, $block->y, $block->z); $oldBlocksSingleClipboard->addEntry($block->getPos()->getFloorX(), $block->getPos()->getFloorY(), $block->getPos()->getFloorZ(), BlockEntry::fromBlock($block)); $manager->setBlockAt($block->getPos()->getFloorX(), $block->getPos()->getFloorY(), $block->getPos()->getFloorZ(), $new); - if ($manager->getBlockArrayAt($block->getPos()->getFloorX(), $block->getPos()->getFloorY(), $block->getPos()->getFloorZ()) !== [$block->getId(), $block->getMeta()]) { + /** @noinspection PhpInternalEntityUsedInspection */ + if ($manager->getBlockFullIdAt($block->getPos()->getFloorX(), $block->getPos()->getFloorY(), $block->getPos()->getFloorZ()) !== $block->getFullId()) { $changed++; } $i++; From 8e8178467366223f3f27b59d2b4ec3de0e66d812 Mon Sep 17 00:00:00 2001 From: XenialDan Date: Sun, 25 Jul 2021 19:14:33 +0200 Subject: [PATCH 35/67] Fix #228 Signed-off-by: XenialDan --- src/xenialdan/MagicWE2/session/UserSession.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/xenialdan/MagicWE2/session/UserSession.php b/src/xenialdan/MagicWE2/session/UserSession.php index 024cce93..ec64e225 100644 --- a/src/xenialdan/MagicWE2/session/UserSession.php +++ b/src/xenialdan/MagicWE2/session/UserSession.php @@ -19,6 +19,7 @@ use xenialdan\MagicWE2\session\data\AssetCollection; use xenialdan\MagicWE2\session\data\BrushCollection; use xenialdan\MagicWE2\session\data\PaletteCollection; +use function mkdir; class UserSession extends Session implements JsonSerializable //TODO use JsonMapper { @@ -289,6 +290,7 @@ public function jsonSerialize() public function save(): void { + @mkdir(Loader::getInstance()->getDataFolder() . "sessions",0777,true); file_put_contents(Loader::getInstance()->getDataFolder() . "sessions" . DIRECTORY_SEPARATOR . $this->getPlayer()->getName() . ".json", json_encode($this, JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT) From 53d1c0fb3d3fa8ef906fbe558c3493650c559198 Mon Sep 17 00:00:00 2001 From: XenialDan Date: Sun, 25 Jul 2021 20:14:09 +0200 Subject: [PATCH 36/67] Implement some PaletteCommand functionality Signed-off-by: XenialDan --- .../commands/palette/PaletteCommand.php | 73 +++++++------------ .../MagicWE2/helper/BlockPalette.php | 22 +++++- src/xenialdan/MagicWE2/helper/BlockQuery.php | 6 +- 3 files changed, 50 insertions(+), 51 deletions(-) diff --git a/src/xenialdan/MagicWE2/commands/palette/PaletteCommand.php b/src/xenialdan/MagicWE2/commands/palette/PaletteCommand.php index 47579ffc..5cd37423 100644 --- a/src/xenialdan/MagicWE2/commands/palette/PaletteCommand.php +++ b/src/xenialdan/MagicWE2/commands/palette/PaletteCommand.php @@ -8,20 +8,19 @@ use Exception; use InvalidArgumentException; use muqsit\invmenu\InvMenu; +use pocketmine\block\Block; use pocketmine\command\CommandSender; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; +use Ramsey\Uuid\Uuid; use xenialdan\customui\elements\Button; -use xenialdan\customui\elements\Label; -use xenialdan\customui\elements\Toggle; -use xenialdan\customui\elements\UIElement; use xenialdan\customui\windows\SimpleForm; use xenialdan\MagicWE2\exception\SessionException; +use xenialdan\MagicWE2\helper\BlockPalette; use xenialdan\MagicWE2\helper\SessionHelper; use xenialdan\MagicWE2\Loader; use xenialdan\MagicWE2\session\UserSession; -use xenialdan\MagicWE2\tool\Brush; -use xenialdan\MagicWE2\tool\BrushProperties; +use function array_filter; class PaletteCommand extends BaseCommand { @@ -60,43 +59,42 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo throw new SessionException($lang->translateString('error.nosession', [Loader::getInstance()->getName()])); } $form = new SimpleForm(Loader::PREFIX_FORM . TF::BOLD . TF::DARK_PURPLE . $lang->translateString('ui.palette.title'), $lang->translateString('ui.palette.content')); - $form->addButton(new Button($lang->translateString('ui.palette.create'))); + $form->addButton(new Button($lang->translateString('ui.palette.fromhotbar'))); + $form->addButton(new Button($lang->translateString('ui.palette.frominventory'))); $form->addButton(new Button($lang->translateString('ui.palette.get'))); - $form->addButton(new Button($lang->translateString('ui.palette.edithand'))); - $form->addButton(new Button($lang->translateString('ui.palette.viewhand'))); $form->setCallable(function (Player $player, $data) use ($lang, $session) { try { switch ($data) { - case $lang->translateString('ui.palette.create'): - { - $brush = new Brush(new BrushProperties()); - if ($brush instanceof Brush) { - $player->sendForm($brush->getForm()); - } - break; - } case $lang->translateString('ui.palette.get'): { $menu = InvMenu::create(InvMenu::TYPE_DOUBLE_CHEST); - foreach ($session->getBrushes() as $brush) { - $menu->getInventory()->addItem($brush->toItem()); + foreach ($session->getPalettes()->getAll() as $palette) { + $menu->getInventory()->addItem($palette->toItem()); } - $menu->send($player, "Session brushes"); + $menu->send($player, "Session palettes"); break; } - case $lang->translateString('ui.palette.edithand'): + case $lang->translateString('ui.palette.fromhotbar'): { - //TODO + /** @var Block[] $blocks */ + $blocks = []; + for ($i = 0; $i <= $player->getInventory()->getHotbarSize(); $i++) { + if (($item = $player->getInventory()->getHotbarSlotItem($i)) instanceof Block) $blocks[] = $item; + } + $palette = BlockPalette::fromBlocks($blocks); + $session->getPalettes()->palettes[Uuid::uuid4()->toString()] = $palette; + $session->sendMessage(TF::GREEN . $lang->translateString('Created palette from hotbar')); break; } - case $lang->translateString('ui.palette.viewhand'): + case $lang->translateString('ui.palette.frominventory'): { - $palettes = $session->getPalettes(); - $menu = InvMenu::create(InvMenu::TYPE_DOUBLE_CHEST); - foreach ($palettes->getAll() as $palette) { - $menu->getInventory()->addItem($palette->toItem()); - } - $menu->send($player, "Palettes (" . count($palettes->getAll()) . ")"); + /** @var Block[] $blocks */ + $blocks = array_filter($player->getInventory()->getContents(), function ($item): bool { + return $item instanceof Block; + });//TODO check if this works, what about items that are blocks + $palette = BlockPalette::fromBlocks($blocks); + $session->getPalettes()->palettes[Uuid::uuid4()->toString()] = $palette; + $session->sendMessage(TF::GREEN . $lang->translateString('Created palette from inventory')); break; } } @@ -113,23 +111,4 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo $sender->sendMessage($this->getUsage()); } } - - /** - * @param UIElement[] $elements - * @param array $data - * @return array - */ - public static function generateLore(array $elements, array $data): array//TODO remove? - { - $return = []; - foreach ($elements as $i => $element) { - if ($element instanceof Label) continue; - if ($element instanceof Toggle) { - $return[] = ($element->getText() . ": " . ($data[$i] ? "Yes" : "No")); - continue; - } - $return[] = ($element->getText() . ": " . $data[$i]); - } - return $return; - } } diff --git a/src/xenialdan/MagicWE2/helper/BlockPalette.php b/src/xenialdan/MagicWE2/helper/BlockPalette.php index e5e1d787..bc28438b 100644 --- a/src/xenialdan/MagicWE2/helper/BlockPalette.php +++ b/src/xenialdan/MagicWE2/helper/BlockPalette.php @@ -7,6 +7,7 @@ use Generator; use InvalidArgumentException; use JsonException; +use pocketmine\block\Block; use pocketmine\block\BlockFactory; use pocketmine\block\utils\InvalidBlockStateException; use pocketmine\item\Item; @@ -57,7 +58,26 @@ public static function fromString(string $blocksQuery): BlockPalette $blockMatch += [null, null, null]; $extraMatch += [null, null]; [[$fullBlockQuery, $blockId, $blockStatesQuery], [$fullExtraQuery, $weight]] = [$blockMatch, $extraMatch]; - $palette->addBlockQuery((new BlockQuery($query, $fullBlockQuery, $blockId, $blockStatesQuery, $fullExtraQuery, $weight))->parse()); + $palette->addBlockQuery((new BlockQuery($query, $fullBlockQuery, $blockId, $blockStatesQuery, $fullExtraQuery, (float)$weight))->parse()); + } + $palette->randomBlockQueries->setup(); + + return $palette; + } + + /** + * @param Block[] $blocks + * @return BlockPalette + */ + public static function fromBlocks(array $blocks): BlockPalette + { + $palette = self::CREATE(); + foreach ($blocks as $block) { + //TODO this really isn't optimal.. + $state = BlockStatesParser::getStateByBlock($block); + if ($state !== null) { + $palette->addBlockQuery(new BlockQuery($state->blockFull, null, null, null, null, 100)); + }//TODO exceptions } $palette->randomBlockQueries->setup(); diff --git a/src/xenialdan/MagicWE2/helper/BlockQuery.php b/src/xenialdan/MagicWE2/helper/BlockQuery.php index 32740839..c9e3c266 100644 --- a/src/xenialdan/MagicWE2/helper/BlockQuery.php +++ b/src/xenialdan/MagicWE2/helper/BlockQuery.php @@ -27,16 +27,16 @@ final class BlockQuery * @param string|null $blockId * @param string|null $blockStatesQuery * @param string|null $fullExtraQuery - * @param string|null $weight + * @param float|null $weight */ - public function __construct(string $query, ?string $fullBlockQuery, ?string $blockId, ?string $blockStatesQuery, ?string $fullExtraQuery, ?string $weight) + public function __construct(string $query, ?string $fullBlockQuery, ?string $blockId, ?string $blockStatesQuery, ?string $fullExtraQuery, ?float $weight = 100) { $this->query = $query; $this->fullBlockQuery = $fullBlockQuery; $this->blockId = $blockId; $this->blockStatesQuery = $blockStatesQuery; $this->fullExtraQuery = $fullExtraQuery; - $this->weight = (float)($weight ?? "100") / 100; + $this->weight = (float)$weight / 100; } /** From 4541909cbc791ad570cce376d1df6fea8fec9b22 Mon Sep 17 00:00:00 2001 From: XenialDan Date: Sun, 25 Jul 2021 21:15:03 +0200 Subject: [PATCH 37/67] Fix logic in PaletteCommand Signed-off-by: XenialDan --- .../MagicWE2/commands/palette/PaletteCommand.php | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/xenialdan/MagicWE2/commands/palette/PaletteCommand.php b/src/xenialdan/MagicWE2/commands/palette/PaletteCommand.php index 5cd37423..ab258007 100644 --- a/src/xenialdan/MagicWE2/commands/palette/PaletteCommand.php +++ b/src/xenialdan/MagicWE2/commands/palette/PaletteCommand.php @@ -20,7 +20,6 @@ use xenialdan\MagicWE2\helper\SessionHelper; use xenialdan\MagicWE2\Loader; use xenialdan\MagicWE2\session\UserSession; -use function array_filter; class PaletteCommand extends BaseCommand { @@ -79,7 +78,7 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo /** @var Block[] $blocks */ $blocks = []; for ($i = 0; $i <= $player->getInventory()->getHotbarSize(); $i++) { - if (($item = $player->getInventory()->getHotbarSlotItem($i)) instanceof Block) $blocks[] = $item; + if (($block = $player->getInventory()->getHotbarSlotItem($i)->getBlock()) instanceof Block) $blocks[] = $block; } $palette = BlockPalette::fromBlocks($blocks); $session->getPalettes()->palettes[Uuid::uuid4()->toString()] = $palette; @@ -89,9 +88,10 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo case $lang->translateString('ui.palette.frominventory'): { /** @var Block[] $blocks */ - $blocks = array_filter($player->getInventory()->getContents(), function ($item): bool { - return $item instanceof Block; - });//TODO check if this works, what about items that are blocks + $blocks = []; + foreach ($player->getInventory()->getContents() as $block) { + if (($block = $block->getBlock()) instanceof Block) $blocks[] = $block; + } $palette = BlockPalette::fromBlocks($blocks); $session->getPalettes()->palettes[Uuid::uuid4()->toString()] = $palette; $session->sendMessage(TF::GREEN . $lang->translateString('Created palette from inventory')); From 49386a617f4bb208fcb8fe6d718bd1ebcaa114de Mon Sep 17 00:00:00 2001 From: XenialDan Date: Mon, 26 Jul 2021 11:44:17 +0200 Subject: [PATCH 38/67] Implement basic palette items + command functionality Signed-off-by: XenialDan --- src/xenialdan/MagicWE2/API.php | 1 + src/xenialdan/MagicWE2/Loader.php | 7 ++- .../commands/palette/PaletteCommand.php | 39 ++++++++++++-- .../MagicWE2/exception/PaletteException.php | 10 ++++ .../MagicWE2/helper/BlockPalette.php | 51 ++++++++++++++----- .../MagicWE2/session/data/BrushCollection.php | 2 +- .../session/data/PaletteCollection.php | 44 +++++++++++++++- 7 files changed, 135 insertions(+), 19 deletions(-) create mode 100644 src/xenialdan/MagicWE2/exception/PaletteException.php diff --git a/src/xenialdan/MagicWE2/API.php b/src/xenialdan/MagicWE2/API.php index aa4ba0cb..a7aa67d3 100644 --- a/src/xenialdan/MagicWE2/API.php +++ b/src/xenialdan/MagicWE2/API.php @@ -77,6 +77,7 @@ class API public const TAG_MAGIC_WE = "MagicWE"; public const TAG_MAGIC_WE_BRUSH = "MagicWEBrush"; public const TAG_MAGIC_WE_ASSET = "MagicWEAsset"; + public const TAG_MAGIC_WE_PALETTE = "MagicWEPalette"; //TODO Split into separate Class (SchematicStorage?) /** @var Clipboard[] */ diff --git a/src/xenialdan/MagicWE2/Loader.php b/src/xenialdan/MagicWE2/Loader.php index 09b11505..45f2f043 100644 --- a/src/xenialdan/MagicWE2/Loader.php +++ b/src/xenialdan/MagicWE2/Loader.php @@ -45,6 +45,7 @@ use xenialdan\MagicWE2\commands\InfoCommand; use xenialdan\MagicWE2\commands\LanguageCommand; use xenialdan\MagicWE2\commands\LimitCommand; +use xenialdan\MagicWE2\commands\palette\PaletteCommand; use xenialdan\MagicWE2\commands\region\ReplaceCommand; use xenialdan\MagicWE2\commands\region\SetCommand; use xenialdan\MagicWE2\commands\ReportCommand; @@ -83,6 +84,8 @@ class Loader extends PluginBase public const FAKE_ENCH_ID = 201; public const PREFIX = TF::RESET . TF::BOLD . TF::GOLD . "[MagicWE2]" . TF::RESET . " "; public const PREFIX_ASSETS = TF::RESET . TF::BOLD . TF::GOLD . "[Asset]" . TF::RESET . " "; + public const PREFIX_BRUSH = TF::RESET . TF::BOLD . TF::GOLD . "[Brush]" . TF::RESET . " "; + public const PREFIX_PALETTE = TF::RESET . TF::BOLD . TF::GOLD . "[Palette]" . TF::RESET . " "; public const PREFIX_FORM = TF::RESET . TF::BOLD . TF::DARK_PURPLE . "[MWE2]" . TF::RESET . " "; /** @var Loader|null */ private static ?Loader $instance; @@ -220,7 +223,9 @@ public function onEnable(): void new HPos2Command($this, "/hpos2", "Set position 2 to targeted block", ["/h2"]), new ChunkCommand($this, "/chunk", "Set the selection to your current chunk"), /* -- assets -- */ - #new PaletteCommand($this, "/asset", "Manage assets (schematics, structures, clipboard)"), + #new AssetCommand($this, "/asset", "Manage assets (schematics, structures, clipboard)"), + /* -- palette -- */ + new PaletteCommand($this, "/palette", "Manage block palettes"), /* -- tool -- */ new WandCommand($this, "/wand", "Gives you the selection wand"), new TogglewandCommand($this, "/togglewand", "Toggle the wand tool on/off", ["/toggleeditwand"]), diff --git a/src/xenialdan/MagicWE2/commands/palette/PaletteCommand.php b/src/xenialdan/MagicWE2/commands/palette/PaletteCommand.php index ab258007..dc9e0761 100644 --- a/src/xenialdan/MagicWE2/commands/palette/PaletteCommand.php +++ b/src/xenialdan/MagicWE2/commands/palette/PaletteCommand.php @@ -2,24 +2,29 @@ declare(strict_types=1); -namespace xenialdan\MagicWE2\commands\brush; +namespace xenialdan\MagicWE2\commands\palette; use CortexPE\Commando\BaseCommand; use Exception; use InvalidArgumentException; use muqsit\invmenu\InvMenu; +use muqsit\invmenu\transaction\InvMenuTransaction; +use muqsit\invmenu\transaction\InvMenuTransactionResult; use pocketmine\block\Block; +use pocketmine\block\BlockLegacyIds; use pocketmine\command\CommandSender; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; use Ramsey\Uuid\Uuid; use xenialdan\customui\elements\Button; use xenialdan\customui\windows\SimpleForm; +use xenialdan\MagicWE2\exception\PaletteException; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\BlockPalette; use xenialdan\MagicWE2\helper\SessionHelper; use xenialdan\MagicWE2\Loader; use xenialdan\MagicWE2\session\UserSession; +use function var_dump; class PaletteCommand extends BaseCommand { @@ -61,14 +66,15 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo $form->addButton(new Button($lang->translateString('ui.palette.fromhotbar'))); $form->addButton(new Button($lang->translateString('ui.palette.frominventory'))); $form->addButton(new Button($lang->translateString('ui.palette.get'))); + $form->addButton(new Button($lang->translateString('ui.palette.modify'))); $form->setCallable(function (Player $player, $data) use ($lang, $session) { try { switch ($data) { case $lang->translateString('ui.palette.get'): { $menu = InvMenu::create(InvMenu::TYPE_DOUBLE_CHEST); - foreach ($session->getPalettes()->getAll() as $palette) { - $menu->getInventory()->addItem($palette->toItem()); + foreach ($session->getPalettes()->getAll() as $id => $palette) { + $menu->getInventory()->addItem($palette->toItem($id)); } $menu->send($player, "Session palettes"); break; @@ -78,7 +84,7 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo /** @var Block[] $blocks */ $blocks = []; for ($i = 0; $i <= $player->getInventory()->getHotbarSize(); $i++) { - if (($block = $player->getInventory()->getHotbarSlotItem($i)->getBlock()) instanceof Block) $blocks[] = $block; + if (($block = $player->getInventory()->getHotbarSlotItem($i)->getBlock()) instanceof Block && $block->getId() !== BlockLegacyIds::AIR) $blocks[] = $block; } $palette = BlockPalette::fromBlocks($blocks); $session->getPalettes()->palettes[Uuid::uuid4()->toString()] = $palette; @@ -97,6 +103,31 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo $session->sendMessage(TF::GREEN . $lang->translateString('Created palette from inventory')); break; } + case $lang->translateString('ui.palette.modify'): + { + $menu = InvMenu::create(InvMenu::TYPE_DOUBLE_CHEST); + foreach ($session->getPalettes()->getAll() as $id => $palette) { + $menu->getInventory()->addItem($palette->toItem($id)); + } + $menu->setListener(function (InvMenuTransaction $transaction) use ($session): InvMenuTransactionResult { + //todo functionality + $player = $transaction->getPlayer(); + $itemClicked = $transaction->getItemClicked(); + $itemClickedWith = $transaction->getItemClickedWith(); + $action = $transaction->getAction(); + $inv_transaction = $transaction->getTransaction(); + try { + $palette = $session->getPalettes()->getPaletteFromItem($itemClicked); + } catch (PaletteException $e) { + $session->sendMessage($e->getMessage()); + Loader::getInstance()->getLogger()->logException($e); + } + var_dump($player, $itemClicked, $itemClickedWith, $action, $inv_transaction, $itemClicked->getLore(), $palette); + return $transaction->continue(); + }); + $menu->send($player, "Select a palette to modify"); + break; + } } return null; } catch (Exception $error) { diff --git a/src/xenialdan/MagicWE2/exception/PaletteException.php b/src/xenialdan/MagicWE2/exception/PaletteException.php new file mode 100644 index 00000000..6b1b0633 --- /dev/null +++ b/src/xenialdan/MagicWE2/exception/PaletteException.php @@ -0,0 +1,10 @@ +randomBlockQueries->generate($this->randomBlockQueries->count()) as $blockQuery) - $e[] = $blockQuery->blockFullId; - return json_encode($e, JSON_THROW_ON_ERROR); + foreach ($this->randomBlockQueries->indexes() as $blockQuery)//TODO check if this isn't random + { + $e[] = $blockQuery->query . '%' . $blockQuery->weight; + } + return $e; } /** * @param string $blocks * @return array + * @throws BlockQueryAlreadyParsedException + * @throws InvalidArgumentException + * @throws InvalidBlockStateException * @throws JsonException + * @throws LegacyStringToItemParserException + * @throws UnexpectedTagTypeException */ - public static function decode(string $blocks): array + public static function fromStringArray(string $blocks): array { $e = []; - $blockFactory = BlockFactory::getInstance(); - foreach (json_decode($blocks, true, 512, JSON_THROW_ON_ERROR) as $block) - $e[] = $blockFactory->fromFullBlock($block); + foreach (json_decode($blocks, true, 512, JSON_THROW_ON_ERROR) as $query) { + $q = new BlockQuery($query, null, null, null, null); + $q->parse(true);//TODO the weight might not be parsed + $e[] = $q; + } return $e; } @@ -160,9 +174,22 @@ public static function CREATE(): self return new self; } - public function toItem(): Item + public function toItem(string $id): Item { - return VanillaItems::EMERALD();//TODO placeholder + $item = VanillaItems::BLUE_DYE();//placeholder. Maybe make it the most used item or replace with bundles + $item->addEnchantment(new EnchantmentInstance(Loader::$ench)); + $item->getNamedTag()->setTag(API::TAG_MAGIC_WE_PALETTE, + CompoundTag::create() + ->setString("id", $id) + ); + $item->setCustomName(Loader::PREFIX . TF::BOLD . TF::LIGHT_PURPLE . "Palette $id"); + $lines = []; + $blocks = $this->toStringArray(); + $lines[] = TF::RESET . TF::BOLD . TF::GOLD . "Blocks: "; + foreach ($blocks as $block) + $lines[] = TF::RESET . $block; + $item->setLore($lines); + return $item; } } \ No newline at end of file diff --git a/src/xenialdan/MagicWE2/session/data/BrushCollection.php b/src/xenialdan/MagicWE2/session/data/BrushCollection.php index 9cd45be2..23fb68da 100644 --- a/src/xenialdan/MagicWE2/session/data/BrushCollection.php +++ b/src/xenialdan/MagicWE2/session/data/BrushCollection.php @@ -25,7 +25,7 @@ final class BrushCollection { /** @var array */ - public array $brushes; + public array $brushes = []; private UserSession $session; public function __construct(UserSession $session) diff --git a/src/xenialdan/MagicWE2/session/data/PaletteCollection.php b/src/xenialdan/MagicWE2/session/data/PaletteCollection.php index 6ac31229..33430e91 100644 --- a/src/xenialdan/MagicWE2/session/data/PaletteCollection.php +++ b/src/xenialdan/MagicWE2/session/data/PaletteCollection.php @@ -4,14 +4,20 @@ namespace xenialdan\MagicWE2\session\data; +use pocketmine\item\Item; +use pocketmine\nbt\tag\CompoundTag; +use pocketmine\nbt\UnexpectedTagTypeException; +use xenialdan\MagicWE2\API; +use xenialdan\MagicWE2\exception\PaletteException; use xenialdan\MagicWE2\helper\BlockPalette; use xenialdan\MagicWE2\session\UserSession; +use function json_encode; final class PaletteCollection { /** @var array */ - public array $palettes; + public array $palettes = []; private UserSession $session; public function __construct(UserSession $session) @@ -32,4 +38,40 @@ public function getAll(): array { return $this->palettes; } + + public function getPalette(string $id): ?BlockPalette + { + return $this->palettes[$id];//TODO allow finding by custom name + } + + public function toJson(): string + { + //TODO + $queries = []; + foreach ($this->getAll() as $id => $palette) { + $queries[$id] = $palette->toStringArray(); + } + return json_encode( + $queries + ); + } + + /** + * @param Item $item + * @return BlockPalette + * @throws PaletteException + * @throws UnexpectedTagTypeException + */ + public function getPaletteFromItem(Item $item): BlockPalette + { + if ((($entry = $item->getNamedTag()->getCompoundTag(API::TAG_MAGIC_WE_PALETTE))) instanceof CompoundTag) { + $id = $entry->getString("id");//todo check if not found + $brush = $this->getPalette($id); + if ($brush instanceof BlockPalette) { + return $brush; + } + throw new PaletteException("No palette with the id $id could be found!"); + } + throw new PaletteException("The item is not a valid palette!"); + } } \ No newline at end of file From 26c36d540d27c512fc081eae599e5586b7c0d073 Mon Sep 17 00:00:00 2001 From: XenialDan Date: Mon, 26 Jul 2021 13:30:45 +0200 Subject: [PATCH 39/67] Add COMMANDS.MD, add setting for developer commands Signed-off-by: XenialDan --- COMMANDS.MD | 51 ++++++++++ README.md | 25 +---- plugin.yml | 2 +- resources/config.yml | 5 +- src/xenialdan/MagicWE2/Loader.php | 13 ++- .../debug/GenerateCommandsMDCommand.php | 95 +++++++++++++++++++ .../debug/PlaceAllBlockstatesCommand.php | 2 +- .../TestAPICommand.php} | 6 +- 8 files changed, 165 insertions(+), 34 deletions(-) create mode 100644 COMMANDS.MD create mode 100644 src/xenialdan/MagicWE2/commands/debug/GenerateCommandsMDCommand.php rename src/xenialdan/MagicWE2/commands/{TestCommand.php => debug/TestAPICommand.php} (96%) diff --git a/COMMANDS.MD b/COMMANDS.MD new file mode 100644 index 00000000..539c484b --- /dev/null +++ b/COMMANDS.MD @@ -0,0 +1,51 @@ +# Commands +This list is automatically generated. If you have noticed an error, please create an issue. + +| Command | Description | Usage | Alias | +|---|---|---|---| +| `//pos1` | Set position 1 | `//pos1 ` | `//1` | +| `//pos2` | Set position 2 | `//pos2 ` | `//2` | +| `//hpos1` | Set position 1 to targeted block | `//hpos1 ` | `//h1` | +| `//hpos2` | Set position 2 to targeted block | `//hpos2 ` | `//h2` | +| `//chunk` | Set the selection to your current chunk | `//chunk ` | | +| `//palette` | Manage block palettes | `//palette ` | | +| `//wand` | Gives you the selection wand | `//wand ` | | +| `//togglewand` | Toggle the wand tool on/off | `//togglewand ` | `//toggleeditwand` | +| `//debug` | Gives you the debug stick, which gives information about the clicked block | `//debug ` | | +| `//toggledebug` | Toggle the debug stick on/off | `//toggledebug ` | | +| `//size` | Get information about the selection | `//size ` | | +| `//count` | Counts the number of blocks matching a mask in selection | `//count [blocks:string] [flags:text]` | `//analyze` | +| `//listchunks` | List chunks that your selection includes | `//listchunks ` | | +| `//set` | Fill a selection with the specified blocks | `//set [flags:text]` | | +| `//replace` | Replace blocks in an area with other blocks | `//replace [flags:text]` | | +| `//cylinder` | Create a cylinder | `//cylinder [height:int] [flags:text]` | `//cyl` | +| `//copy` | Copy the selection to the clipboard | `//copy [flags:text]` | | +| `//paste` | Paste the clipboard's contents | `//paste [flags:text]` | | +| `//cut` | Cut the selection to the clipboard | `//cut [flags:text]` | | +| `//cut2` | Cut the selection to the clipboard - the new way | `//cut2 [flags:text]` | | +| `//clearclipboard` | Clear your clipboard | `//clearclipboard ` | | +| `//flip` | Flip the contents of the clipboard across the origin | `//flip ` | `//mirror` | +| `//rotate` | Rotate the contents of the clipboard around the origin | `//rotate [aroundOrigin:bool]` | | +| `//undo` | Rolls back the last action | `//undo ` | | +| `//redo` | Applies the last undo action again | `//redo ` | | +| `//clearhistory` | Clear your history | `//clearhistory ` | | +| `//setrange` | Set tool range | `//setrange [range:int]` | `//toolrange` | +| `//limit` | Set the block change limit. Use -1 to disable | `//limit [limit:int]` | | +| `//help` | MagicWE help command | `//help [command:string]` | `//?, //mwe, //wehelp` | +| `//version` | MagicWE version | `//version ` | `//ver` | +| `//info` | Information about MagicWE | `//info ` | | +| `//report` | Report a bug to GitHub | `//report [title:text]` | `//bug, //github` | +| `//donate` | Donate to support development of MagicWE! | `//donate ` | `//support, //paypal` | +| `//language` | Set your language | `//language [language:string]` | `//lang` | +| `//biomelist` | Gets all biomes available | `//biomelist ` | `//biomels` | +| `//biomeinfo` | Get the biome of the targeted block | `//biomeinfo [flags:text]` | | +| `//setbiome` | Sets the biome of your current block or region | `//setbiome ` | | +| `//calculate` | Evaluate a mathematical expression | `//calculate ` | `//calc, //eval, //evaluate, //solve` | +| `//togglewaila` | Toggle the What Am I Looking At utility | `//togglewaila ` | `//waila, //wyla` | +| `//togglesidebar` | Toggle the sidebar | `//togglesidebar ` | `//sidebar` | +| `//placeallblockstates` | Place all blockstates similar to Java debug worlds | `//placeallblockstates ` | | +| `//testapi` | Internal command for testing API methods | `//testapi ` | | +| `//generatecommandsmd` | Generates the commands.md file | `//generatecommandsmd ` | | +| `//brush` | Opens the brush tool menu | `//brush` | | +| `//brush name` | Get name or rename a brush | `/brush name [name:string]` | | +| `//flood` | Opens the flood fill tool menu | `//flood ` | `//floodfill` | \ No newline at end of file diff --git a/README.md b/README.md index 46480129..41c0f3f3 100644 --- a/README.md +++ b/README.md @@ -33,29 +33,8 @@ Jokes aside, here is a list of pros: --> ## Commands -| Command | Alias | Description | Usage | -| --- | --- | --- | --- | -| `//pos1` | `//1` | `Select first position` | `//pos1` | -| `//pos2` | `//2` | `Select second position` | `//pos2` | -| `//set` | `//fill` | `Fill an area with the specified blocks` | `//set [flags:text]` | -| `//replace` | | `Replace blocks in an area with other blocks` | `//replace [flags:text]` | -| `//copy` | | `Copy an area into a clipboard` | `//copy [flags:text]` | -| `//paste` | | `Paste your clipboard` | `//paste [flags:text]` | -| `//wand` | | `Gives you the selection wand` | `//wand` | -| `//togglewand` | | `Toggle the wand tool on/off` | `//togglewand` | -| `//undo` | | `Rolls back the last action` | `//undo` | -| `//redo` | | `Applies the last undo action again` | `//redo` | -| `//debug` | | `Gives you the debug stick, which gives information about the clicked block` | `//debug` | -| `//toggledebug` | | `Toggle the debug stick on/off` | `//toggledebug` | -| `//cylinder` | `//cyl` | `Create a cylinder` | `//cylinder [height:int] [flags:text]` | -| `//count` | `//analyze` | `Count blocks in selection` | `//count [blocks:string] [flags:text]` | -| `//help` | `//?,//mwe,//wehelp` | `MagicWE help command` | `//help [command:string]` | -| `//version` | `//ver` | `MagicWE version` | `//version` | -| `//info` | | `Information about MagicWE` | `//info` | -| `//report` | `//bug,//github` | `Report a bug to GitHub` | `//report [title:text]` | -| `//donate` | `//support,//paypal` | `Donate to support development of MagicWE!` | `//donate` | -| `//brush` | | `Opens the brush tool menu` | `//brush` | -| `//flood` | | `Opens the flood tool menu` | `//flood` | + +You can find a list of commands here: [COMMANDS.MD](https://github.com/thebigsmileXD/MagicWE2/blob/palette-preview/COMMANDS.MD) ## Planned features - Saved sessions (saved brushes and clipboards) diff --git a/plugin.yml b/plugin.yml index 37f9253e..bca9593b 100644 --- a/plugin.yml +++ b/plugin.yml @@ -119,6 +119,6 @@ permissions: default: op we.command.utility.togglesidebar: default: op - we.command.test: + we.command.debug: default: op ... diff --git a/resources/config.yml b/resources/config.yml index 3ed2f82a..29584703 100644 --- a/resources/config.yml +++ b/resources/config.yml @@ -4,6 +4,9 @@ # Available languages (ISO639-2): # eng, ara, cat, ces, chi, dan, deu, ell, epo, esp, est, fre, geo, hin, ind, ita, jpn, kor, lit, mar, mas, nld, nor, pol, por, rom, rus, slo, swa, swe, tgl, tha, zho language: eng -show-startup-icon: false +# Enables special commands for testing API features +developer-commands: false +# Maximum amount of blocks that can be edited at once. Set to -1 to disable limit: -1 +# Maximum raytraced distance for ranged tools. Default 100 tool-range: 100 diff --git a/src/xenialdan/MagicWE2/Loader.php b/src/xenialdan/MagicWE2/Loader.php index 45f2f043..147112c5 100644 --- a/src/xenialdan/MagicWE2/Loader.php +++ b/src/xenialdan/MagicWE2/Loader.php @@ -35,7 +35,9 @@ use xenialdan\MagicWE2\commands\clipboard\FlipCommand; use xenialdan\MagicWE2\commands\clipboard\PasteCommand; use xenialdan\MagicWE2\commands\clipboard\RotateCommand; +use xenialdan\MagicWE2\commands\debug\GenerateCommandsMDCommand; use xenialdan\MagicWE2\commands\debug\PlaceAllBlockstatesCommand; +use xenialdan\MagicWE2\commands\debug\TestAPICommand; use xenialdan\MagicWE2\commands\DonateCommand; use xenialdan\MagicWE2\commands\generation\CylinderCommand; use xenialdan\MagicWE2\commands\HelpCommand; @@ -58,7 +60,6 @@ use xenialdan\MagicWE2\commands\selection\Pos1Command; use xenialdan\MagicWE2\commands\selection\Pos2Command; use xenialdan\MagicWE2\commands\SetRangeCommand; -use xenialdan\MagicWE2\commands\TestCommand; use xenialdan\MagicWE2\commands\tool\DebugCommand; use xenialdan\MagicWE2\commands\tool\FloodCommand; use xenialdan\MagicWE2\commands\tool\ToggledebugCommand; @@ -208,8 +209,7 @@ public function onEnable(): void { $lang = $this->getConfig()->get("language", Language::FALLBACK_LANGUAGE); $this->baseLang = new Language((string)$lang, $this->getFile() . "resources" . DIRECTORY_SEPARATOR . "lang" . DIRECTORY_SEPARATOR); - if ($this->getConfig()->get("show-startup-icon", false)) $this->showStartupIcon(); - //$this->loadDonator(); + $registerDeveloperCommands = $this->getConfig()->get("developer-commands", false); $this->getLogger()->warning("WARNING! Commands and their permissions changed! Make sure to update your permission sets!"); if (!InvMenuHandler::isRegistered()) InvMenuHandler::register($this); if (!PacketListener::isRegistered()) PacketListener::register($this); @@ -288,7 +288,6 @@ public function onEnable(): void //new TogglePlaceCommand($this,"/toggleplace", "Switch between your position and pos1 for placement"), //new SearchItemCommand($this,"/searchitem", "Search for an item"), //new RangeCommand($this,"/range", "Set the brush range"), - new TestCommand($this, "/test", "test action"),//TODO REMOVE new SetRangeCommand($this, "/setrange", "Set tool range", ["/toolrange"]), new LimitCommand($this, "/limit", "Set the block change limit. Use -1 to disable"), new HelpCommand($this, "/help", "MagicWE help command", ["/?", "/mwe", "/wehelp"]),//Blame MCPE for client side /help shit! only the aliases work @@ -311,8 +310,12 @@ public function onEnable(): void new CalculateCommand($this, "/calculate", "Evaluate a mathematical expression", ["/calc", "/eval", "/evaluate", "/solve"]), new ToggleWailaCommand($this, "/togglewaila", "Toggle the What Am I Looking At utility", ["/waila", "/wyla"]), new ToggleSidebarCommand($this, "/togglesidebar", "Toggle the sidebar", ["/sidebar"]), - /* -- debugging -- */ + ]); + if ($registerDeveloperCommands) $this->getServer()->getCommandMap()->registerAll("MagicWE2", [ + /* -- developer commands -- */ new PlaceAllBlockstatesCommand($this, "/placeallblockstates", "Place all blockstates similar to Java debug worlds"), + new TestAPICommand($this, "/testapi", "Internal command for testing API methods"), + new GenerateCommandsMDCommand($this, "/generatecommandsmd", "Generates the commands.md file"), ]); if (class_exists(CustomUIAPI::class)) { $this->getLogger()->notice("CustomUI found, can use ui-based commands"); diff --git a/src/xenialdan/MagicWE2/commands/debug/GenerateCommandsMDCommand.php b/src/xenialdan/MagicWE2/commands/debug/GenerateCommandsMDCommand.php new file mode 100644 index 00000000..8c558290 --- /dev/null +++ b/src/xenialdan/MagicWE2/commands/debug/GenerateCommandsMDCommand.php @@ -0,0 +1,95 @@ +setPermission("we.command.debug"); + } + + /** + * @param CommandSender $sender + * @param string $aliasUsed + * @param mixed[] $args + */ + public function onRun(CommandSender $sender, string $aliasUsed, array $args): void + { + $lang = Loader::getInstance()->getLanguage(); + try { + $cmds = []; + foreach (array_filter(Loader::getInstance()->getServer()->getCommandMap()->getCommands(), static function (Command $command) use ($sender) { + return strpos($command->getName(), "/") !== false; + }) as $cmd) { + /** @var Command $cmd */ + $cmds[$cmd->getName()] = $cmd; + } + $lines = [ + '| Command | Description | Usage | Alias |', + '|---|---|---|---|' + ]; + /** @var BaseCommand $command */ + foreach ($cmds as $command) { + $aliasStr = ''; + if (!empty(($aliases = $command->getAliases()))) { + foreach ($aliases as $i => $alias) { + $aliases[$i] = "/" . $alias; + } + $aliasStr = '`' . implode(", ", $aliases) . '`'; + } + $usage = $command->getUsage(); + //subcommand hack + $subCommands = $command->getSubCommands(); + if (count($subCommands) > 0) { + $pos = stripos($usage, " \n"); + if ($pos !== false) $usage = substr($usage, 0, $pos); + } + $lines[] = "| `/{$command->getName()}` | {$command->getDescription()} | `$usage` | $aliasStr |"; + foreach ($subCommands as $subCommand) { + $aliasStr = ''; + if (!empty(($aliases = $subCommand->getAliases()))) { + foreach ($aliases as $i => $alias) { + $aliases[$i] = "/" . $alias; + } + $aliasStr = '`' . implode(", ", $aliases) . '`'; + } + $lines[] = "| `/{$command->getName()} {$subCommand->getName()}` | {$subCommand->getDescription()} | `{$command->getName()} {$subCommand->getUsageMessage()}` | $aliasStr |"; + } + } + $path = Loader::getInstance()->getDataFolder() . 'COMMANDS.MD'; + file_put_contents($path, '# Commands +This list is automatically generated. If you have noticed an error, please create an issue. + +' . implode(' +', $lines), LOCK_EX); + } catch (Exception $error) { + Loader::getInstance()->getLogger()->logException($error); + $sender->sendMessage(Loader::PREFIX . TF::RED . $lang->translateString('error.command-error')); + $sender->sendMessage(Loader::PREFIX . TF::RED . $error->getMessage()); + $sender->sendMessage($this->getUsage()); + } + } +} diff --git a/src/xenialdan/MagicWE2/commands/debug/PlaceAllBlockstatesCommand.php b/src/xenialdan/MagicWE2/commands/debug/PlaceAllBlockstatesCommand.php index a213c2a9..8ae0ce2e 100644 --- a/src/xenialdan/MagicWE2/commands/debug/PlaceAllBlockstatesCommand.php +++ b/src/xenialdan/MagicWE2/commands/debug/PlaceAllBlockstatesCommand.php @@ -23,7 +23,7 @@ class PlaceAllBlockstatesCommand extends BaseCommand */ protected function prepare(): void { - $this->setPermission("we.command.test"); + $this->setPermission("we.command.debug"); } /** diff --git a/src/xenialdan/MagicWE2/commands/TestCommand.php b/src/xenialdan/MagicWE2/commands/debug/TestAPICommand.php similarity index 96% rename from src/xenialdan/MagicWE2/commands/TestCommand.php rename to src/xenialdan/MagicWE2/commands/debug/TestAPICommand.php index f16dc71a..0ad1ade4 100644 --- a/src/xenialdan/MagicWE2/commands/TestCommand.php +++ b/src/xenialdan/MagicWE2/commands/debug/TestAPICommand.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace xenialdan\MagicWE2\commands; +namespace xenialdan\MagicWE2\commands\debug; use CortexPE\Commando\BaseCommand; use Exception; @@ -19,7 +19,7 @@ use xenialdan\MagicWE2\task\action\TestAction; use xenialdan\MagicWE2\task\AsyncActionTask; -class TestCommand extends BaseCommand +class TestAPICommand extends BaseCommand { /** @@ -28,7 +28,7 @@ class TestCommand extends BaseCommand */ protected function prepare(): void { - $this->setPermission("we.command.test"); + $this->setPermission("we.command.debug"); } /** From 33dd946855764c0bac157adcd135b9a7a536a738 Mon Sep 17 00:00:00 2001 From: XenialDan Date: Fri, 1 Oct 2021 00:15:51 +0200 Subject: [PATCH 40/67] Palette from selection Signed-off-by: XenialDan --- .../commands/palette/PaletteCommand.php | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/src/xenialdan/MagicWE2/commands/palette/PaletteCommand.php b/src/xenialdan/MagicWE2/commands/palette/PaletteCommand.php index dc9e0761..ccea1a35 100644 --- a/src/xenialdan/MagicWE2/commands/palette/PaletteCommand.php +++ b/src/xenialdan/MagicWE2/commands/palette/PaletteCommand.php @@ -23,6 +23,7 @@ use xenialdan\MagicWE2\helper\BlockPalette; use xenialdan\MagicWE2\helper\SessionHelper; use xenialdan\MagicWE2\Loader; +use xenialdan\MagicWE2\selection\Selection; use xenialdan\MagicWE2\session\UserSession; use function var_dump; @@ -65,6 +66,7 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo $form = new SimpleForm(Loader::PREFIX_FORM . TF::BOLD . TF::DARK_PURPLE . $lang->translateString('ui.palette.title'), $lang->translateString('ui.palette.content')); $form->addButton(new Button($lang->translateString('ui.palette.fromhotbar'))); $form->addButton(new Button($lang->translateString('ui.palette.frominventory'))); + $form->addButton(new Button($lang->translateString('ui.palette.fromselection'))); $form->addButton(new Button($lang->translateString('ui.palette.get'))); $form->addButton(new Button($lang->translateString('ui.palette.modify'))); $form->setCallable(function (Player $player, $data) use ($lang, $session) { @@ -103,6 +105,22 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo $session->sendMessage(TF::GREEN . $lang->translateString('Created palette from inventory')); break; } + case $lang->translateString('ui.palette.fromselection'): + { + /** @var Block[] $blocks */ + $blocks = []; + $selection = $session->getLatestSelection(); + if (!$selection instanceof Selection) { + $session->sendMessage(TF::RED . $lang->translateString('No selection'));//todo string + } + foreach ($selection as $block) { + if (($block = $block->getBlock()) instanceof Block) $blocks[] = $block; + } + $palette = BlockPalette::fromBlocks($blocks); + $session->getPalettes()->palettes[Uuid::uuid4()->toString()] = $palette; + $session->sendMessage(TF::GREEN . $lang->translateString('Created palette from inventory')); + break; + } case $lang->translateString('ui.palette.modify'): { $menu = InvMenu::create(InvMenu::TYPE_DOUBLE_CHEST); From cacedf7d850dbdede5ca2afe08c4b1d14280986c Mon Sep 17 00:00:00 2001 From: XenialDan Date: Thu, 23 Sep 2021 22:14:37 +0200 Subject: [PATCH 41/67] getPos -> getPosition & minor cleanups --- src/xenialdan/MagicWE2/API.php | 8 ++-- src/xenialdan/MagicWE2/EventListener.php | 20 +++++----- src/xenialdan/MagicWE2/Loader.php | 38 +------------------ .../MagicWE2/clipboard/RevertClipboard.php | 7 ++-- .../MagicWE2/clipboard/SingleClipboard.php | 7 ++-- .../commands/biome/BiomeInfoCommand.php | 2 +- .../MagicWE2/commands/brush/BrushCommand.php | 4 +- .../commands/selection/HPos1Command.php | 2 +- .../commands/selection/HPos2Command.php | 2 +- .../MagicWE2/helper/BlockStatesParser.php | 6 +-- .../MagicWE2/helper/SessionHelper.php | 2 +- .../MagicWE2/selection/Selection.php | 9 ++--- .../MagicWE2/selection/shape/Cone.php | 2 +- .../MagicWE2/selection/shape/Cube.php | 4 +- .../MagicWE2/selection/shape/Cuboid.php | 4 +- .../MagicWE2/selection/shape/Cylinder.php | 2 +- .../MagicWE2/selection/shape/Ellipsoid.php | 2 +- .../MagicWE2/selection/shape/Pyramid.php | 2 +- .../MagicWE2/selection/shape/Shape.php | 7 ++-- .../MagicWE2/selection/shape/Sphere.php | 2 +- src/xenialdan/MagicWE2/task/AsyncCopyTask.php | 2 +- .../MagicWE2/task/AsyncCountTask.php | 12 +++--- src/xenialdan/MagicWE2/task/AsyncFillTask.php | 22 +++++------ .../MagicWE2/task/AsyncPasteAssetTask.php | 12 +++--- .../MagicWE2/task/AsyncReplaceTask.php | 14 +++---- .../MagicWE2/task/AsyncRevertTask.php | 4 +- src/xenialdan/MagicWE2/task/MWEAsyncTask.php | 10 ++--- .../MagicWE2/task/action/CountAction.php | 2 +- .../MagicWE2/task/action/CutAction.php | 8 ++-- .../MagicWE2/task/action/SetBlockAction.php | 8 ++-- .../MagicWE2/task/action/TestAction.php | 2 +- .../MagicWE2/task/action/ThawAction.php | 8 ++-- src/xenialdan/MagicWE2/tool/Flood.php | 6 +-- 33 files changed, 99 insertions(+), 143 deletions(-) diff --git a/src/xenialdan/MagicWE2/API.php b/src/xenialdan/MagicWE2/API.php index a7aa67d3..e4528913 100644 --- a/src/xenialdan/MagicWE2/API.php +++ b/src/xenialdan/MagicWE2/API.php @@ -312,8 +312,8 @@ public static function createBrush(Block $target, Brush $brush, Session $session { $shapeClass = $brush->properties->shape; /** @var Shape $shape */ - $shape = new $shapeClass($target->getPos()->asVector3(), ...array_values($brush->properties->shapeProperties)); - $selection = new Selection($session->getUUID(), $target->getPos()->getWorld()); + $shape = new $shapeClass($target->getPosition()->asVector3(), ...array_values($brush->properties->shapeProperties)); + $selection = new Selection($session->getUUID(), $target->getPosition()->getWorld()); $selection->setShape($shape); $actionClass = $brush->properties->action; //TODO remove hack @@ -333,7 +333,6 @@ public static function createBrush(Block $target, Brush $brush, Session $session */ public static function floodArea(Block $target, CompoundTag $settings, Session $session, int $flags = self::FLAG_BASE): bool { //TODO - if (!$settings instanceof CompoundTag) return false; $session->sendMessage(TF::RED . "TEMPORARILY DISABLED!"); return false;/* $shape = ShapeRegistry::getShape($target->getWorld(), ShapeRegistry::TYPE_FLOOD, self::compoundToArray($settings)); @@ -345,7 +344,6 @@ public static function floodArea(Block $target, CompoundTag $settings, Session $ public static function placeAsset(Position $target, Asset $asset, CompoundTag $settings, UserSession $session): bool { - if (!$settings instanceof CompoundTag) return false; #$start = clone $target->asVector3()->floor()->addVector($asset->getOrigin())->floor();//start pos of paste//TODO if using rotate, this fails #$end = $start->addVector($asset->getSize()->subtractVector($asset->getOrigin()));//add size @@ -557,7 +555,7 @@ public static function compoundToArray(CompoundTag $compoundTag): array */ public static function setComponents(Block $block, int $x, int $y, int $z): Block { - [$block->getPos()->x, $block->getPos()->y, $block->getPos()->z] = [$x, $y, $z]; + [$block->getPosition()->x, $block->getPosition()->y, $block->getPosition()->z] = [$x, $y, $z]; return $block; } diff --git a/src/xenialdan/MagicWE2/EventListener.php b/src/xenialdan/MagicWE2/EventListener.php index 102c1369..1736f160 100644 --- a/src/xenialdan/MagicWE2/EventListener.php +++ b/src/xenialdan/MagicWE2/EventListener.php @@ -186,11 +186,11 @@ private function onBreakBlock(BlockBreakEvent $event): void $session->sendMessage(TF::RED . $session->getLanguage()->translateString("tool.wand.disabled")); break; } - $selection = $session->getLatestSelection() ?? $session->addSelection(new Selection($session->getUUID(), $event->getBlock()->getPos()->getWorld())); // TODO check if the selection inside of the session updates + $selection = $session->getLatestSelection() ?? $session->addSelection(new Selection($session->getUUID(), $event->getBlock()->getPosition()->getWorld())); // TODO check if the selection inside of the session updates if (is_null($selection)) { throw new Error("No selection created - Check the console for errors"); } - $selection->setPos1(new Position($event->getBlock()->getPos()->x, $event->getBlock()->getPos()->y, $event->getBlock()->getPos()->z, $event->getBlock()->getPos()->getWorld())); + $selection->setPos1(new Position($event->getBlock()->getPosition()->x, $event->getBlock()->getPosition()->y, $event->getBlock()->getPosition()->z, $event->getBlock()->getPosition()->getWorld())); break; } case ItemIds::STICK: @@ -228,11 +228,11 @@ private function onRightClickBlock(PlayerInteractEvent $event): void $session->sendMessage(TF::RED . $session->getLanguage()->translateString("tool.wand.disabled")); break; } - $selection = $session->getLatestSelection() ?? $session->addSelection(new Selection($session->getUUID(), $event->getBlock()->getPos()->getWorld())); // TODO check if the selection inside of the session updates + $selection = $session->getLatestSelection() ?? $session->addSelection(new Selection($session->getUUID(), $event->getBlock()->getPosition()->getWorld())); // TODO check if the selection inside of the session updates if (is_null($selection)) { throw new Error("No selection created - Check the console for errors"); } - $selection->setPos2(new Position($event->getBlock()->getPos()->x, $event->getBlock()->getPos()->y, $event->getBlock()->getPos()->z, $event->getBlock()->getPos()->getWorld())); + $selection->setPos2(new Position($event->getBlock()->getPosition()->x, $event->getBlock()->getPosition()->y, $event->getBlock()->getPosition()->z, $event->getBlock()->getPosition()->getWorld())); break; } case ItemIds::STICK: @@ -257,7 +257,7 @@ private function onRightClickBlock(PlayerInteractEvent $event): void if ($tag !== null) { $filename = $tag->getString('filename'); $asset = Loader::$assetCollection->assets[$filename];//TODO allow private assets again - $target = $event->getBlock()->getSide($event->getFace())->getPos(); + $target = $event->getBlock()->getSide($event->getFace())->getPosition(); if (API::placeAsset($target, $asset, $tag, $session)) { $event->getPlayer()->sendMessage("Asset placed!"); } else { @@ -298,11 +298,11 @@ private function onLeftClickBlock(PlayerInteractEvent $event): void $session->sendMessage(TF::RED . $session->getLanguage()->translateString("tool.wand.disabled")); break; } - $selection = $session->getLatestSelection() ?? $session->addSelection(new Selection($session->getUUID(), $event->getBlock()->getPos()->getWorld())); // TODO check if the selection inside of the session updates + $selection = $session->getLatestSelection() ?? $session->addSelection(new Selection($session->getUUID(), $event->getBlock()->getPosition()->getWorld())); // TODO check if the selection inside of the session updates if (is_null($selection)) { throw new Error("No selection created - Check the console for errors"); } - $selection->setPos1(new Position($event->getBlock()->getPos()->x, $event->getBlock()->getPos()->y, $event->getBlock()->getPos()->z, $event->getBlock()->getPos()->getWorld())); + $selection->setPos1(new Position($event->getBlock()->getPosition()->x, $event->getBlock()->getPosition()->y, $event->getBlock()->getPosition()->z, $event->getBlock()->getPosition()->getWorld())); break; } case ItemIds::STICK: @@ -409,7 +409,7 @@ public function onChangeSlot(PlayerItemHeldEvent $event): void $session->displayOutline = true; #foreach ($assets as $asset) { $backwards = $player->getDirectionVector()->normalize()->multiply(-1); - $target = $player->getTargetBlock(10)->getPos(); + $target = $player->getTargetBlock(10)->getPosition(); $target->addVector($backwards);//this selects the block before raytrace $target->subtract(0, 1, 0);//one block down $target = Position::fromObject($target, $player->getWorld()); @@ -478,7 +478,7 @@ public function onStructureBlockClick(PlayerInteractEvent $event): void $blockTouched = $event->getBlock(); if ($blockTouched->getId() === BlockLegacyIds::STRUCTURE_BLOCK) { var_dump("Clicked Structure Block", (string)$blockTouched); - $tile = $blockTouched->getPos()->getWorld()->getTile($blockTouched->getPos()->asVector3()); + $tile = $blockTouched->getPosition()->getWorld()->getTile($blockTouched->getPosition()->asVector3()); if ($tile instanceof StructureBlockTile) { var_dump("Is Structure Block Tile", $tile->getSpawnCompound()->toString()); // $item = $player->getInventory()->getItemInHand(); @@ -492,7 +492,7 @@ public function onStructureBlockClick(PlayerInteractEvent $event): void // $inventory = $tile->getInventory(); // $pk = new StructureBlockUpdatePacket(); // $pk->structureEditorData = $tile->getStructureEditorData($asset); -// [$pk->x, $pk->y, $pk->z] = [$blockTouched->getPos()->getFloorX(), $blockTouched->getPos()->getFloorY(), $blockTouched->getPos()->getFloorZ()]; +// [$pk->x, $pk->y, $pk->z] = [$blockTouched->getPosition()->getFloorX(), $blockTouched->getPosition()->getFloorY(), $blockTouched->getPosition()->getFloorZ()]; // $pk->isPowered = false; // $player->getNetworkSession()->sendDataPacket($pk); // $tile->sendInventory($player); diff --git a/src/xenialdan/MagicWE2/Loader.php b/src/xenialdan/MagicWE2/Loader.php index 147112c5..53d93127 100644 --- a/src/xenialdan/MagicWE2/Loader.php +++ b/src/xenialdan/MagicWE2/Loader.php @@ -162,7 +162,7 @@ public static function hasScoreboard(): bool public function onLoad(): void { self::$instance = $this; - self::$ench = new Enchantment(self::FAKE_ENCH_ID, "", 0, ItemFlags::AXE, ItemFlags::NONE, 1); + self::$ench = new Enchantment("", 0, ItemFlags::AXE, ItemFlags::NONE, 1); $enchantmapinstance = EnchantmentIdMap::getInstance(); $enchantmapinstance->register(self::FAKE_ENCH_ID, self::$ench); self::$shapeRegistry = new ShapeRegistry(); @@ -354,7 +354,7 @@ public function onEnable(): void if ($stateEntry instanceof BlockStatesEntry) { $sub = implode("," . TF::EOL, explode(",", BlockStatesParser::printStates($stateEntry, false))); } - $distancePercentage = round(floor($block->getPos()->distance($player->getEyePos())) / 10, 1); + $distancePercentage = round(floor($block->getPosition()->distance($player->getEyePos())) / 10, 1); Loader::getInstance()->wailaBossBar->setTitleFor([$player], $title)->setSubTitleFor([$player], $sub)->setPercentage($distancePercentage); } else Loader::getInstance()->wailaBossBar->hideFrom([$player]); @@ -418,40 +418,6 @@ public static function getInfo(): array ]; } - private function showStartupIcon(): void - { - $colorAxe = TF::BOLD . TF::DARK_PURPLE; - $colorAxeStem = TF::LIGHT_PURPLE; - $colorAxeSky = TF::LIGHT_PURPLE; - $colorAxeFill = TF::GOLD; - $axe = [ - " {$colorAxe}####{$colorAxeSky} ", - " {$colorAxe}##{$colorAxeFill}####{$colorAxe}##{$colorAxeSky} ", - " {$colorAxe}##{$colorAxeFill}######{$colorAxe}##{$colorAxeSky} ", - " {$colorAxe}##{$colorAxeFill}########{$colorAxe}####{$colorAxeSky} ", - " {$colorAxe}##{$colorAxeFill}######{$colorAxe}##{$colorAxeStem}##{$colorAxe}##{$colorAxeSky} ", - " {$colorAxe}######{$colorAxeStem}##{$colorAxe}##{$colorAxeFill}##{$colorAxe}##", - " {$colorAxe}##{$colorAxeStem}##{$colorAxe}##{$colorAxeFill}####{$colorAxe}##", - " {$colorAxe}##{$colorAxeStem}##{$colorAxe}## {$colorAxe}####{$colorAxeSky} ", - " {$colorAxe}##{$colorAxeStem}##{$colorAxe}##{$colorAxeSky} ", - " {$colorAxe}##{$colorAxeStem}##{$colorAxe}##{$colorAxeSky} ", - " {$colorAxe}##{$colorAxeStem}##{$colorAxe}##{$colorAxeSky} ", - " {$colorAxe}##{$colorAxeStem}##{$colorAxe}##{$colorAxeSky} ", - "{$colorAxe}##{$colorAxeStem}##{$colorAxe}##{$colorAxeSky} MagicWE v.2", - "{$colorAxe}####{$colorAxeSky} by XenialDan"]; - foreach (array_map(static function ($line) { - return preg_replace_callback( - '/ +(?getLogger()->info($axeMsg); - } - /** * Returns the path to the language files folder. * diff --git a/src/xenialdan/MagicWE2/clipboard/RevertClipboard.php b/src/xenialdan/MagicWE2/clipboard/RevertClipboard.php index ff71554e..fcc20c35 100644 --- a/src/xenialdan/MagicWE2/clipboard/RevertClipboard.php +++ b/src/xenialdan/MagicWE2/clipboard/RevertClipboard.php @@ -56,20 +56,19 @@ public function serialize() /** * Constructs the object * @link http://php.net/manual/en/serializable.unserialize.php - * @param string $serialized

+ * @param string $data

* The string representation of the object. *

* @return void * @since 5.1.0 - * @noinspection PhpMissingParamTypeInspection */ - public function unserialize($serialized) + public function unserialize($data) { [ $this->worldId, $chunks, $this->blocksAfter - ] = unserialize($serialized/*, ['allowed_classes' => [__CLASS__]]*/);//TODO test pm4 + ] = unserialize($data/*, ['allowed_classes' => [__CLASS__]]*/);//TODO test pm4 foreach ($chunks as $hash => $chunk) $this->chunks[$hash] = FastChunkSerializer::deserialize($chunk); } diff --git a/src/xenialdan/MagicWE2/clipboard/SingleClipboard.php b/src/xenialdan/MagicWE2/clipboard/SingleClipboard.php index 330d13ec..c4fc318b 100644 --- a/src/xenialdan/MagicWE2/clipboard/SingleClipboard.php +++ b/src/xenialdan/MagicWE2/clipboard/SingleClipboard.php @@ -76,20 +76,19 @@ public function serialize() /** * Constructs the object * @link https://php.net/manual/en/serializable.unserialize.php - * @param string $serialized

+ * @param string $data

* The string representation of the object. *

* @return void * @since 5.1 - * @noinspection PhpMissingParamTypeInspection */ - public function unserialize($serialized) + public function unserialize($data) { // TODO: Implement unserialize() method. [ $this->entries, $this->selection, $this->position - ] = unserialize($serialized/*, ['allowed_classes' => [BlockEntry::class, Selection::class, Vector3::class]]*/); + ] = unserialize($data/*, ['allowed_classes' => [BlockEntry::class, Selection::class, Vector3::class]]*/); } } \ No newline at end of file diff --git a/src/xenialdan/MagicWE2/commands/biome/BiomeInfoCommand.php b/src/xenialdan/MagicWE2/commands/biome/BiomeInfoCommand.php index 99e09a86..a23fb808 100644 --- a/src/xenialdan/MagicWE2/commands/biome/BiomeInfoCommand.php +++ b/src/xenialdan/MagicWE2/commands/biome/BiomeInfoCommand.php @@ -76,7 +76,7 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo $sender->sendMessage(Loader::PREFIX . TF::RED . $lang->translateString('error.notarget')); return; } - $biomeId = $target->getPos()->getWorld()->getOrLoadChunkAtPosition($target->getPos())->getBiomeId($target->getPos()->getX() % 16, $target->getPos()->getZ() % 16); + $biomeId = $target->getPosition()->getWorld()->getOrLoadChunkAtPosition($target->getPosition())->getBiomeId($target->getPosition()->getX() % 16, $target->getPosition()->getZ() % 16); $session->sendMessage(TF::DARK_AQUA . $lang->translateString('command.biomeinfo.attarget')); $session->sendMessage(TF::AQUA . "ID: $biomeId Name: " . $biomeNames[$biomeId]); } diff --git a/src/xenialdan/MagicWE2/commands/brush/BrushCommand.php b/src/xenialdan/MagicWE2/commands/brush/BrushCommand.php index b0255f65..646b9de6 100644 --- a/src/xenialdan/MagicWE2/commands/brush/BrushCommand.php +++ b/src/xenialdan/MagicWE2/commands/brush/BrushCommand.php @@ -69,9 +69,7 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo case $lang->translateString('ui.brush.create'): { $brush = new Brush(new BrushProperties()); - if ($brush instanceof Brush) { - $player->sendForm($brush->getForm()); - } + $player->sendForm($brush->getForm()); break; } case $lang->translateString('ui.brush.getsession'): diff --git a/src/xenialdan/MagicWE2/commands/selection/HPos1Command.php b/src/xenialdan/MagicWE2/commands/selection/HPos1Command.php index bcfdcc69..cfe2d435 100644 --- a/src/xenialdan/MagicWE2/commands/selection/HPos1Command.php +++ b/src/xenialdan/MagicWE2/commands/selection/HPos1Command.php @@ -62,7 +62,7 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo $sender->sendMessage(Loader::PREFIX . TF::RED . $lang->translateString('error.notarget')); return; } - $selection->setPos1($target->getPos()); + $selection->setPos1($target->getPosition()); } catch (Exception $error) { $sender->sendMessage(Loader::PREFIX . TF::RED . $lang->translateString('error.command-error')); $sender->sendMessage(Loader::PREFIX . TF::RED . $error->getMessage()); diff --git a/src/xenialdan/MagicWE2/commands/selection/HPos2Command.php b/src/xenialdan/MagicWE2/commands/selection/HPos2Command.php index a217a941..e103ac1b 100644 --- a/src/xenialdan/MagicWE2/commands/selection/HPos2Command.php +++ b/src/xenialdan/MagicWE2/commands/selection/HPos2Command.php @@ -62,7 +62,7 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo $sender->sendMessage(Loader::PREFIX . TF::RED . $lang->translateString('error.notarget')); return; } - $selection->setPos2($target->getPos()); + $selection->setPos2($target->getPosition()); } catch (Exception $error) { $sender->sendMessage(Loader::PREFIX . TF::RED . $lang->translateString('error.command-error')); $sender->sendMessage(Loader::PREFIX . TF::RED . $error->getMessage()); diff --git a/src/xenialdan/MagicWE2/helper/BlockStatesParser.php b/src/xenialdan/MagicWE2/helper/BlockStatesParser.php index 85f5b12c..36c2eb7e 100644 --- a/src/xenialdan/MagicWE2/helper/BlockStatesParser.php +++ b/src/xenialdan/MagicWE2/helper/BlockStatesParser.php @@ -451,13 +451,11 @@ public static function runTests(): void foreach (BlockPalette::fromString($test)->palette() as $block) { assert($block instanceof Block); $blockStatesEntry = self::getStateByBlock($block); - if($blockStatesEntry !== null) { + if ($blockStatesEntry !== null) { Server::getInstance()->getLogger()->debug(TF::LIGHT_PURPLE . self::printStates($blockStatesEntry, true)); Server::getInstance()->getLogger()->debug(TF::LIGHT_PURPLE . self::printStates($blockStatesEntry, false)); - Server::getInstance()->getLogger()->debug(TF::LIGHT_PURPLE . "Final block: " . TF::AQUA . $block); - }else{ - Server::getInstance()->getLogger()->debug(TF::LIGHT_PURPLE . "Final block: " . TF::AQUA . $block); } + Server::getInstance()->getLogger()->debug(TF::LIGHT_PURPLE . "Final block: " . TF::AQUA . $block); } } catch (Exception $e) { Server::getInstance()->getLogger()->debug($e->getMessage()); diff --git a/src/xenialdan/MagicWE2/helper/SessionHelper.php b/src/xenialdan/MagicWE2/helper/SessionHelper.php index b0e4e2c4..79b3955c 100644 --- a/src/xenialdan/MagicWE2/helper/SessionHelper.php +++ b/src/xenialdan/MagicWE2/helper/SessionHelper.php @@ -232,7 +232,7 @@ public static function loadUserSession(Player $player): ?UserSession $latestSelection["pos2"]["z"], $shape ?? null ); - if ($selection instanceof Selection && $selection->isValid()) { + if ($selection->isValid()) { $session->addSelection($selection); } } diff --git a/src/xenialdan/MagicWE2/selection/Selection.php b/src/xenialdan/MagicWE2/selection/Selection.php index 2eebd600..79dbb84c 100644 --- a/src/xenialdan/MagicWE2/selection/Selection.php +++ b/src/xenialdan/MagicWE2/selection/Selection.php @@ -283,16 +283,15 @@ public function serialize() /** * Constructs the object * @link http://php.net/manual/en/serializable.unserialize.php - * @param string $serialized

+ * @param string $data

* The string representation of the object. *

* @return void * @since 5.1.0 - * @noinspection PhpMissingParamTypeInspection */ - public function unserialize($serialized) + public function unserialize($data) { - var_dump($serialized); + var_dump($data); [ $this->worldId, $this->pos1, @@ -300,7 +299,7 @@ public function unserialize($serialized) $this->uuid, $this->sessionUUID, $this->shape - ] = unserialize($serialized/*, ['allowed_classes' => [__CLASS__, Vector3::class,UuidInterface::class,Shape::class]]*/);//TODO test pm4 + ] = unserialize($data/*, ['allowed_classes' => [__CLASS__, Vector3::class,UuidInterface::class,Shape::class]]*/);//TODO test pm4 } /** diff --git a/src/xenialdan/MagicWE2/selection/shape/Cone.php b/src/xenialdan/MagicWE2/selection/shape/Cone.php index add07904..63508695 100644 --- a/src/xenialdan/MagicWE2/selection/shape/Cone.php +++ b/src/xenialdan/MagicWE2/selection/shape/Cone.php @@ -66,7 +66,7 @@ public function getBlocks(AsyncChunkManager|World $manager, BlockPalette $filter if (API::hasFlag($flags, API::FLAG_KEEP_BLOCKS) && $block->getId() !== BlockLegacyIds::AIR) continue; if (API::hasFlag($flags, API::FLAG_KEEP_AIR) && $block->getId() === BlockLegacyIds::AIR) continue; - if ($block->getPos()->y >= World::Y_MAX || $block->getPos()->y < 0) continue;//TODO fuufufufuuu EDIT: And.. fufufu is what? + if ($block->getPosition()->y >= World::Y_MAX || $block->getPosition()->y < 0) continue;//TODO fuufufufuuu EDIT: And.. fufufu is what? if ($filterblocks->empty()) yield $block; else { foreach ($filterblocks->palette() as $filterblock) { diff --git a/src/xenialdan/MagicWE2/selection/shape/Cube.php b/src/xenialdan/MagicWE2/selection/shape/Cube.php index d14dc8b8..66f56609 100644 --- a/src/xenialdan/MagicWE2/selection/shape/Cube.php +++ b/src/xenialdan/MagicWE2/selection/shape/Cube.php @@ -43,8 +43,8 @@ public function getBlocks(AsyncChunkManager|World $manager, BlockPalette $filter if (API::hasFlag($flags, API::FLAG_KEEP_BLOCKS) && $block->getId() !== BlockLegacyIds::AIR) continue; if (API::hasFlag($flags, API::FLAG_KEEP_AIR) && $block->getId() === BlockLegacyIds::AIR) continue; - if ($block->getPos()->y >= World::Y_MAX || $block->getPos()->y < 0) continue;//TODO check for removal because relative might be at other y - if (API::hasFlag($flags, API::FLAG_HOLLOW) && ($block->getPos()->x > $this->getMinVec3()->getX() && $block->getPos()->x < $this->getMaxVec3()->getX()) && ($block->getPos()->y > $this->getMinVec3()->getY() && $block->getPos()->y < $this->getMaxVec3()->getY()) && ($block->getPos()->z > $this->getMinVec3()->getZ() && $block->getPos()->z < $this->getMaxVec3()->getZ())) continue; + if ($block->getPosition()->y >= World::Y_MAX || $block->getPosition()->y < 0) continue;//TODO check for removal because relative might be at other y + if (API::hasFlag($flags, API::FLAG_HOLLOW) && ($block->getPosition()->x > $this->getMinVec3()->getX() && $block->getPosition()->x < $this->getMaxVec3()->getX()) && ($block->getPosition()->y > $this->getMinVec3()->getY() && $block->getPosition()->y < $this->getMaxVec3()->getY()) && ($block->getPosition()->z > $this->getMinVec3()->getZ() && $block->getPosition()->z < $this->getMaxVec3()->getZ())) continue; if ($filterblocks->empty()) yield $block; else { foreach ($filterblocks->palette() as $filterblock) { diff --git a/src/xenialdan/MagicWE2/selection/shape/Cuboid.php b/src/xenialdan/MagicWE2/selection/shape/Cuboid.php index 9e2ef363..8e1ccc9b 100644 --- a/src/xenialdan/MagicWE2/selection/shape/Cuboid.php +++ b/src/xenialdan/MagicWE2/selection/shape/Cuboid.php @@ -65,8 +65,8 @@ public function getBlocks(AsyncChunkManager|World $manager, BlockPalette $filter if (API::hasFlag($flags, API::FLAG_KEEP_BLOCKS) && $block->getId() !== BlockLegacyIds::AIR) continue; if (API::hasFlag($flags, API::FLAG_KEEP_AIR) && $block->getId() === BlockLegacyIds::AIR) continue; - if ($block->getPos()->y >= World::Y_MAX || $block->getPos()->y < 0) continue;//TODO check for removal because relative might be at other y - if (API::hasFlag($flags, API::FLAG_HOLLOW) && ($block->getPos()->x > $this->getMinVec3()->getX() && $block->getPos()->x < $this->getMaxVec3()->getX()) && ($block->getPos()->y > $this->getMinVec3()->getY() && $block->getPos()->y < $this->getMaxVec3()->getY()) && ($block->getPos()->z > $this->getMinVec3()->getZ() && $block->getPos()->z < $this->getMaxVec3()->getZ())) continue; + if ($block->getPosition()->y >= World::Y_MAX || $block->getPosition()->y < 0) continue;//TODO check for removal because relative might be at other y + if (API::hasFlag($flags, API::FLAG_HOLLOW) && ($block->getPosition()->x > $this->getMinVec3()->getX() && $block->getPosition()->x < $this->getMaxVec3()->getX()) && ($block->getPosition()->y > $this->getMinVec3()->getY() && $block->getPosition()->y < $this->getMaxVec3()->getY()) && ($block->getPosition()->z > $this->getMinVec3()->getZ() && $block->getPosition()->z < $this->getMaxVec3()->getZ())) continue; if ($filterblocks->empty()) yield $block; else { foreach ($filterblocks->palette() as $filterblock) { diff --git a/src/xenialdan/MagicWE2/selection/shape/Cylinder.php b/src/xenialdan/MagicWE2/selection/shape/Cylinder.php index 6bb200a2..9dd26b0d 100644 --- a/src/xenialdan/MagicWE2/selection/shape/Cylinder.php +++ b/src/xenialdan/MagicWE2/selection/shape/Cylinder.php @@ -57,7 +57,7 @@ public function getBlocks(AsyncChunkManager|World $manager, BlockPalette $filter if (API::hasFlag($flags, API::FLAG_KEEP_BLOCKS) && $block->getId() !== BlockLegacyIds::AIR) continue; if (API::hasFlag($flags, API::FLAG_KEEP_AIR) && $block->getId() === BlockLegacyIds::AIR) continue; - if ($block->getPos()->y >= World::Y_MAX || $block->getPos()->y < 0) continue;//TODO fuufufufuuu + if ($block->getPosition()->y >= World::Y_MAX || $block->getPosition()->y < 0) continue;//TODO fuufufufuuu if ($filterblocks->empty()) yield $block; else { foreach ($filterblocks->palette() as $filterblock) { diff --git a/src/xenialdan/MagicWE2/selection/shape/Ellipsoid.php b/src/xenialdan/MagicWE2/selection/shape/Ellipsoid.php index 10288234..51272cbf 100644 --- a/src/xenialdan/MagicWE2/selection/shape/Ellipsoid.php +++ b/src/xenialdan/MagicWE2/selection/shape/Ellipsoid.php @@ -76,7 +76,7 @@ public function getBlocks(AsyncChunkManager|World $manager, BlockPalette $filter if (API::hasFlag($flags, API::FLAG_KEEP_BLOCKS) && $block->getId() !== BlockLegacyIds::AIR) continue; if (API::hasFlag($flags, API::FLAG_KEEP_AIR) && $block->getId() === BlockLegacyIds::AIR) continue; - if ($block->getPos()->y >= World::Y_MAX || $block->getPos()->y < 0) continue;//TODO fuufufufuuu + if ($block->getPosition()->y >= World::Y_MAX || $block->getPosition()->y < 0) continue;//TODO fuufufufuuu if ($filterblocks->empty()) yield $block; else { foreach ($filterblocks->palette() as $filterblock) { diff --git a/src/xenialdan/MagicWE2/selection/shape/Pyramid.php b/src/xenialdan/MagicWE2/selection/shape/Pyramid.php index 5c5acbbd..4d98b619 100644 --- a/src/xenialdan/MagicWE2/selection/shape/Pyramid.php +++ b/src/xenialdan/MagicWE2/selection/shape/Pyramid.php @@ -75,7 +75,7 @@ public function getBlocks(AsyncChunkManager|World $manager, BlockPalette $filter if (API::hasFlag($flags, API::FLAG_KEEP_BLOCKS) && $block->getId() !== BlockLegacyIds::AIR) continue; if (API::hasFlag($flags, API::FLAG_KEEP_AIR) && $block->getId() === BlockLegacyIds::AIR) continue; - if ($block->getPos()->y >= World::Y_MAX || $block->getPos()->y < 0) continue;//TODO fuufufufuuu + if ($block->getPosition()->y >= World::Y_MAX || $block->getPosition()->y < 0) continue;//TODO fuufufufuuu if ($filterblocks->empty()) yield $block; else { foreach ($filterblocks->palette() as $filterblock) { diff --git a/src/xenialdan/MagicWE2/selection/shape/Shape.php b/src/xenialdan/MagicWE2/selection/shape/Shape.php index 5e894068..ab9d029f 100644 --- a/src/xenialdan/MagicWE2/selection/shape/Shape.php +++ b/src/xenialdan/MagicWE2/selection/shape/Shape.php @@ -122,16 +122,15 @@ public function serialize() /** * Constructs the object * @link http://php.net/manual/en/serializable.unserialize.php - * @param string $serialized

+ * @param string $data

* The string representation of the object. *

* @return void * @since 5.1.0 - * @noinspection PhpMissingParamTypeInspection */ - public function unserialize($serialized) + public function unserialize($data) { - $unserialize = unserialize($serialized/*, ['allowed_classes' => [__CLASS__]]*/);//TODO test pm4 + $unserialize = unserialize($data/*, ['allowed_classes' => [__CLASS__]]*/);//TODO test pm4 array_walk($unserialize, function ($value, $key) { $this->$key = $value; }); diff --git a/src/xenialdan/MagicWE2/selection/shape/Sphere.php b/src/xenialdan/MagicWE2/selection/shape/Sphere.php index dd099ad4..fd52a85e 100644 --- a/src/xenialdan/MagicWE2/selection/shape/Sphere.php +++ b/src/xenialdan/MagicWE2/selection/shape/Sphere.php @@ -51,7 +51,7 @@ public function getBlocks(AsyncChunkManager|World $manager, BlockPalette $filter if (API::hasFlag($flags, API::FLAG_KEEP_BLOCKS) && $block->getId() !== BlockLegacyIds::AIR) continue; if (API::hasFlag($flags, API::FLAG_KEEP_AIR) && $block->getId() === BlockLegacyIds::AIR) continue; - if ($block->getPos()->y >= World::Y_MAX || $block->getPos()->y < 0) continue;//TODO fufufufuuu + if ($block->getPosition()->y >= World::Y_MAX || $block->getPosition()->y < 0) continue;//TODO fufufufuuu if ($filterblocks->empty()) yield $block; else { foreach ($filterblocks->palette() as $filterblock) { diff --git a/src/xenialdan/MagicWE2/task/AsyncCopyTask.php b/src/xenialdan/MagicWE2/task/AsyncCopyTask.php index d7cfd57d..53196926 100644 --- a/src/xenialdan/MagicWE2/task/AsyncCopyTask.php +++ b/src/xenialdan/MagicWE2/task/AsyncCopyTask.php @@ -97,7 +97,7 @@ private function copyBlocks(Selection $selection, AsyncChunkManager $manager, Si /** @var Block $block */ foreach ($selection->getShape()->getBlocks($manager, BlockPalette::CREATE(), $this->flags) as $block) { #var_dump("copy chunk X: " . ($block->getX() >> 4) . " Y: " . ($block->getY() >> 4)); - $newv3 = $block->getPos()->subtractVector($min)->floor(); + $newv3 = $block->getPosition()->subtractVector($min)->floor(); /** @noinspection PhpInternalEntityUsedInspection */ $clipboard->addEntry($newv3->getFloorX(), $newv3->getFloorY(), $newv3->getFloorZ(), new BlockEntry($block->getFullId()));//TODO test tiles #var_dump("copied selection block", $block); diff --git a/src/xenialdan/MagicWE2/task/AsyncCountTask.php b/src/xenialdan/MagicWE2/task/AsyncCountTask.php index 9f5064af..21ed9a65 100644 --- a/src/xenialdan/MagicWE2/task/AsyncCountTask.php +++ b/src/xenialdan/MagicWE2/task/AsyncCountTask.php @@ -88,17 +88,17 @@ private function countBlocks(Selection $selection, AsyncChunkManager $manager, B $counts = []; /** @var Block $block */ foreach ($selection->getShape()->getBlocks($manager, $filterblocks, $this->flags) as $block) { - if (is_null($lastchunkx) || ($block->getPos()->x >> 4 !== $lastchunkx && $block->getPos()->z >> 4 !== $lastchunkz)) { - $lastchunkx = $block->getPos()->x >> 4; - $lastchunkz = $block->getPos()->z >> 4; - if (is_null($manager->getChunk($block->getPos()->x >> 4, $block->getPos()->z >> 4))) { + if (is_null($lastchunkx) || ($block->getPosition()->x >> 4 !== $lastchunkx && $block->getPosition()->z >> 4 !== $lastchunkz)) { + $lastchunkx = $block->getPosition()->x >> 4; + $lastchunkz = $block->getPosition()->z >> 4; + if (is_null($manager->getChunk($block->getPosition()->x >> 4, $block->getPosition()->z >> 4))) { #print PHP_EOL . "Not found: " . strval($block->x >> 4) . ":" . strval($block->z >> 4) . PHP_EOL; continue; } } BlockFactory::getInstance(); - $block1 = $manager->getBlockAt($block->getPos()->getFloorX(), $block->getPos()->getFloorY(), $block->getPos()->getFloorZ()); - $tostring = $block1->getName() . " " . $block1->getId(). ":" . $block1->getMeta(); + $block1 = $manager->getBlockAt($block->getPosition()->getFloorX(), $block->getPosition()->getFloorY(), $block->getPosition()->getFloorZ()); + $tostring = $block1->getName() . " " . $block1->getId() . ":" . $block1->getMeta(); if (!array_key_exists($tostring, $counts)) $counts[$tostring] = 0; $counts[$tostring]++; $changed++; diff --git a/src/xenialdan/MagicWE2/task/AsyncFillTask.php b/src/xenialdan/MagicWE2/task/AsyncFillTask.php index 1516dc04..2feae586 100644 --- a/src/xenialdan/MagicWE2/task/AsyncFillTask.php +++ b/src/xenialdan/MagicWE2/task/AsyncFillTask.php @@ -129,21 +129,21 @@ private function execute(Selection $selection, AsyncChunkManager $manager, Block $rel = $block->subtract($selection->shape->getPasteVector()); $block = API::setComponents($block,$rel->x,$rel->y,$rel->z);//TODO COPY TO ALL TASKS }*/ - if (is_null($lastchunkx) || ($block->getPos()->x >> 4 !== $lastchunkx && $block->getPos()->z >> 4 !== $lastchunkz)) { - $lastchunkx = $block->getPos()->x >> 4; - $lastchunkz = $block->getPos()->z >> 4; - if (is_null($manager->getChunk($block->getPos()->x >> 4, $block->getPos()->z >> 4))) { + if (is_null($lastchunkx) || ($block->getPosition()->x >> 4 !== $lastchunkx && $block->getPosition()->z >> 4 !== $lastchunkz)) { + $lastchunkx = $block->getPosition()->x >> 4; + $lastchunkz = $block->getPosition()->z >> 4; + if (is_null($manager->getChunk($block->getPosition()->x >> 4, $block->getPosition()->z >> 4))) { #print PHP_EOL . "Not found: " . strval($block->x >> 4) . ":" . strval($block->z >> 4) . PHP_EOL; continue; } } if ($new->getId() === $block->getId() && $new->getMeta() === $block->getMeta()) continue;//skip same blocks//TODO better method - #yield self::undoBlockHackToArray($manager->getBlockAt($block->getPos()->getFloorX(), $block->getPos()->getFloorY(), $block->getPos()->getFloorZ()),$block->getPos()); - yield self::singleBlockToData(API::setComponents($manager->getBlockAt($block->getPos()->getFloorX(), $block->getPos()->getFloorY(), $block->getPos()->getFloorZ()), (int)$block->getPos()->x, (int)$block->getPos()->y, (int)$block->getPos()->z)); + #yield self::undoBlockHackToArray($manager->getBlockAt($block->getPosition()->getFloorX(), $block->getPosition()->getFloorY(), $block->getPosition()->getFloorZ()),$block->getPosition()); + yield self::singleBlockToData(API::setComponents($manager->getBlockAt($block->getPosition()->getFloorX(), $block->getPosition()->getFloorY(), $block->getPosition()->getFloorZ()), (int)$block->getPosition()->x, (int)$block->getPosition()->y, (int)$block->getPosition()->z)); #yield $block;//backup - $manager->setBlockAt($block->getPos()->getFloorX(), $block->getPos()->getFloorY(), $block->getPos()->getFloorZ(), $new); + $manager->setBlockAt($block->getPosition()->getFloorX(), $block->getPosition()->getFloorY(), $block->getPosition()->getFloorZ(), $new); /** @noinspection PhpInternalEntityUsedInspection */ - if ($manager->getBlockFullIdAt($block->getPos()->getFloorX(), $block->getPos()->getFloorY(), $block->getPos()->getFloorZ()) !== $block->getFullId()) { + if ($manager->getBlockFullIdAt($block->getPosition()->getFloorX(), $block->getPosition()->getFloorY(), $block->getPosition()->getFloorZ()) !== $block->getFullId()) { $changed++; } /// @@ -183,9 +183,9 @@ public function onCompletion(): void // */ // foreach ($oldBlocks as [$fullId, $pos]) { // $b = BlockFactory::getInstance()->fromFullBlock($fullId); -// $b->getPos()->x = $pos->x; -// $b->getPos()->y = $pos->y; -// $b->getPos()->z = $pos->z; +// $b->getPosition()->x = $pos->x; +// $b->getPosition()->y = $pos->y; +// $b->getPosition()->z = $pos->z; // $oldBlocks2[] = $b; // } // var_dump($oldBlocks2); diff --git a/src/xenialdan/MagicWE2/task/AsyncPasteAssetTask.php b/src/xenialdan/MagicWE2/task/AsyncPasteAssetTask.php index f3ece916..36e419f2 100644 --- a/src/xenialdan/MagicWE2/task/AsyncPasteAssetTask.php +++ b/src/xenialdan/MagicWE2/task/AsyncPasteAssetTask.php @@ -117,10 +117,10 @@ private function execute(AsyncChunkManager $manager, Asset $asset, ?int &$change if ($structure instanceof MCStructure) { /** @var Block $block */ foreach ($structure->blocks() as $block) {// [0,0,0 -> sizex,sizey,sizez] - #var_dump($block->getPos()->asVector3(), $this->pasteVector, $this->selection); - $pos = $block->getPos()->addVector($this->target)->subtract($asset->getSize()->getX() / 2, 0, $asset->getSize()->getZ() / 2); - [$block->getPos()->x, $block->getPos()->y, $block->getPos()->z] = [$x, $y, $z] = [$pos->getX(), $pos->getY(), $pos->getZ()]; - #var_dump($block->getPos()->asVector3()); + #var_dump($block->getPosition()->asVector3(), $this->pasteVector, $this->selection); + $pos = $block->getPosition()->addVector($this->target)->subtract($asset->getSize()->getX() / 2, 0, $asset->getSize()->getZ() / 2); + [$block->getPosition()->x, $block->getPosition()->y, $block->getPosition()->z] = [$x, $y, $z] = [$pos->getX(), $pos->getY(), $pos->getZ()]; + #var_dump($block->getPosition()->asVector3()); if (($x >> 4 !== $lastchunkx && $z >> 4 !== $lastchunkz) || is_null($lastchunkx)) { $lastchunkx = $x >> 4; $lastchunkz = $z >> 4; @@ -170,8 +170,8 @@ private function execute(AsyncChunkManager $manager, Asset $asset, ?int &$change } } else if ($structure instanceof Schematic) { foreach ($structure->blocks() as $block) { - $pos = $block->getPos()->addVector($this->target)->subtract($asset->getSize()->getX() / 2, 0, $asset->getSize()->getZ() / 2); - [$block->getPos()->x, $block->getPos()->y, $block->getPos()->z] = [$x, $y, $z] = [$pos->getX(), $pos->getY(), $pos->getZ()]; + $pos = $block->getPosition()->addVector($this->target)->subtract($asset->getSize()->getX() / 2, 0, $asset->getSize()->getZ() / 2); + [$block->getPosition()->x, $block->getPosition()->y, $block->getPosition()->z] = [$x, $y, $z] = [$pos->getX(), $pos->getY(), $pos->getZ()]; if (($x >> 4 !== $lastchunkx && $z >> 4 !== $lastchunkz) || is_null($lastchunkx)) { $lastchunkx = $x >> 4; $lastchunkz = $z >> 4; diff --git a/src/xenialdan/MagicWE2/task/AsyncReplaceTask.php b/src/xenialdan/MagicWE2/task/AsyncReplaceTask.php index b4696315..ab927d49 100644 --- a/src/xenialdan/MagicWE2/task/AsyncReplaceTask.php +++ b/src/xenialdan/MagicWE2/task/AsyncReplaceTask.php @@ -114,19 +114,19 @@ private function execute(Selection $selection, AsyncChunkManager $manager, Block * @var Block $block * @var Block $new */ - if (is_null($lastchunkx) || ($block->getPos()->x >> 4 !== $lastchunkx && $block->getPos()->z >> 4 !== $lastchunkz)) { - $lastchunkx = $block->getPos()->x >> 4; - $lastchunkz = $block->getPos()->z >> 4; - if (is_null($manager->getChunk($block->getPos()->x >> 4, $block->getPos()->z >> 4))) { + if (is_null($lastchunkx) || ($block->getPosition()->x >> 4 !== $lastchunkx && $block->getPosition()->z >> 4 !== $lastchunkz)) { + $lastchunkx = $block->getPosition()->x >> 4; + $lastchunkz = $block->getPosition()->z >> 4; + if (is_null($manager->getChunk($block->getPosition()->x >> 4, $block->getPosition()->z >> 4))) { #print PHP_EOL . "Not found: " . strval($block->x >> 4) . ":" . strval($block->z >> 4) . PHP_EOL; continue; } } if ($new->getId() === $block->getId() && $new->getMeta() === $block->getMeta()) continue;//skip same blocks - yield self::singleBlockToData(API::setComponents($manager->getBlockAt($block->getPos()->getFloorX(), $block->getPos()->getFloorY(), $block->getPos()->getFloorZ()), (int)$block->getPos()->x, (int)$block->getPos()->y, (int)$block->getPos()->z)); - $manager->setBlockAt($block->getPos()->getFloorX(), $block->getPos()->getFloorY(), $block->getPos()->getFloorZ(), $new); + yield self::singleBlockToData(API::setComponents($manager->getBlockAt($block->getPosition()->getFloorX(), $block->getPosition()->getFloorY(), $block->getPosition()->getFloorZ()), (int)$block->getPosition()->x, (int)$block->getPosition()->y, (int)$block->getPosition()->z)); + $manager->setBlockAt($block->getPosition()->getFloorX(), $block->getPosition()->getFloorY(), $block->getPosition()->getFloorZ(), $new); /** @noinspection PhpInternalEntityUsedInspection */ - if ($manager->getBlockFullIdAt($block->getPos()->getFloorX(), $block->getPos()->getFloorY(), $block->getPos()->getFloorZ()) !== $block->getFullId()) { + if ($manager->getBlockFullIdAt($block->getPosition()->getFloorX(), $block->getPosition()->getFloorY(), $block->getPosition()->getFloorZ()) !== $block->getFullId()) { $changed++; } /// diff --git a/src/xenialdan/MagicWE2/task/AsyncRevertTask.php b/src/xenialdan/MagicWE2/task/AsyncRevertTask.php index c810fc4a..ad3eff4a 100644 --- a/src/xenialdan/MagicWE2/task/AsyncRevertTask.php +++ b/src/xenialdan/MagicWE2/task/AsyncRevertTask.php @@ -80,7 +80,7 @@ private function undoChunks(AsyncChunkManager $manager, RevertClipboard $clipboa foreach ($clipboard->blocksAfter as $block) { yield $block; $block = self::singleDataToBlock($block);//turn data into real block - $manager->setBlockAt($block->getPos()->getFloorX(), $block->getPos()->getFloorY(), $block->getPos()->getFloorZ(), $block); + $manager->setBlockAt($block->getPosition()->getFloorX(), $block->getPosition()->getFloorY(), $block->getPosition()->getFloorZ(), $block); $changed++; $this->publishProgress([$changed / $count, "Reverted $changed blocks out of $count"]); } @@ -102,7 +102,7 @@ private function redoChunks(AsyncChunkManager $manager, RevertClipboard $clipboa foreach ($clipboard->blocksAfter as $block) { yield $block; $block = self::singleDataToBlock($block);//turn data into real block - $manager->setBlockAt($block->getPos()->getFloorX(), $block->getPos()->getFloorY(), $block->getPos()->getFloorZ(), $block); + $manager->setBlockAt($block->getPosition()->getFloorX(), $block->getPosition()->getFloorY(), $block->getPosition()->getFloorZ(), $block); $changed++; $this->publishProgress([$changed / $count, "Redone $changed blocks out of $count"]); } diff --git a/src/xenialdan/MagicWE2/task/MWEAsyncTask.php b/src/xenialdan/MagicWE2/task/MWEAsyncTask.php index 0ae1882f..d1767b99 100644 --- a/src/xenialdan/MagicWE2/task/MWEAsyncTask.php +++ b/src/xenialdan/MagicWE2/task/MWEAsyncTask.php @@ -48,7 +48,7 @@ public function generateTookString(): string public static function singleBlockToData(Block $block, ?Position $position = null): array { /** @noinspection PhpInternalEntityUsedInspection */ - return [$block->getFullId(), $position ?? $block->getPos()]; + return [$block->getFullId(), $position ?? $block->getPosition()]; } /** @@ -74,10 +74,10 @@ protected static function singleDataToBlock(array $data): Block $block = BlockFactory::getInstance()->fromFullBlock($data[0]); /** @var Position $pos */ $pos = $data[1]; - $block->getPos()->world = $pos->world; - $block->getPos()->x = $pos->x; - $block->getPos()->y = $pos->y; - $block->getPos()->z = $pos->z; + $block->getPosition()->world = $pos->world; + $block->getPosition()->x = $pos->x; + $block->getPosition()->y = $pos->y; + $block->getPosition()->z = $pos->z; return $block; } diff --git a/src/xenialdan/MagicWE2/task/action/CountAction.php b/src/xenialdan/MagicWE2/task/action/CountAction.php index 369c3377..dd6b5085 100644 --- a/src/xenialdan/MagicWE2/task/action/CountAction.php +++ b/src/xenialdan/MagicWE2/task/action/CountAction.php @@ -51,7 +51,7 @@ public function execute(string $sessionUUID, Selection $selection, AsyncChunkMan $counts = []; BlockFactory::getInstance(); foreach ($selection->getShape()->getBlocks($manager, $newBlocks) as $block) { - $block1 = $manager->getBlockAt($block->getPos()->getFloorX(), $block->getPos()->getFloorY(), $block->getPos()->getFloorZ()); + $block1 = $manager->getBlockAt($block->getPosition()->getFloorX(), $block->getPosition()->getFloorY(), $block->getPosition()->getFloorZ()); $tostring = $block1->getName() . " " . $block1->getId() . ":" . $block1->getMeta(); if (!array_key_exists($tostring, $counts)) $counts[$tostring] = 0; $counts[$tostring]++; diff --git a/src/xenialdan/MagicWE2/task/action/CutAction.php b/src/xenialdan/MagicWE2/task/action/CutAction.php index 79093793..3e712ccf 100644 --- a/src/xenialdan/MagicWE2/task/action/CutAction.php +++ b/src/xenialdan/MagicWE2/task/action/CutAction.php @@ -56,12 +56,12 @@ public function execute(string $sessionUUID, Selection $selection, AsyncChunkMan /** @var Block $new */ $new = $newBlocks->blocks(1)->current();//TODO Merged iterator if ($new->getId() === $block->getId() && $new->getMeta() === $block->getMeta()) continue;//skip same blocks - #$oldBlocks[] = API::setComponents($manager->getBlockAt($block->getPos()->getFloorX(), $block->getPos()->getFloorY(), $block->getPos()->getFloorZ()),$block->x, $block->y, $block->z); - $newv3 = $block->getPos()->subtractVector($min)->floor();//TODO check if only used for clipboard + #$oldBlocks[] = API::setComponents($manager->getBlockAt($block->getPosition()->getFloorX(), $block->getPosition()->getFloorY(), $block->getPosition()->getFloorZ()),$block->x, $block->y, $block->z); + $newv3 = $block->getPosition()->subtractVector($min)->floor();//TODO check if only used for clipboard $oldBlocksSingleClipboard->addEntry($newv3->getFloorX(), $newv3->getFloorY(), $newv3->getFloorZ(), BlockEntry::fromBlock($block)); - $manager->setBlockAt($block->getPos()->getFloorX(), $block->getPos()->getFloorY(), $block->getPos()->getFloorZ(), $new); + $manager->setBlockAt($block->getPosition()->getFloorX(), $block->getPosition()->getFloorY(), $block->getPosition()->getFloorZ(), $new); /** @noinspection PhpInternalEntityUsedInspection */ - if ($manager->getBlockFullIdAt($block->getPos()->getFloorX(), $block->getPos()->getFloorY(), $block->getPos()->getFloorZ()) !== $block->getFullId()) { + if ($manager->getBlockFullIdAt($block->getPosition()->getFloorX(), $block->getPosition()->getFloorY(), $block->getPosition()->getFloorZ()) !== $block->getFullId()) { $changed++; } $i++; diff --git a/src/xenialdan/MagicWE2/task/action/SetBlockAction.php b/src/xenialdan/MagicWE2/task/action/SetBlockAction.php index d1dee59a..8fe7e6b4 100644 --- a/src/xenialdan/MagicWE2/task/action/SetBlockAction.php +++ b/src/xenialdan/MagicWE2/task/action/SetBlockAction.php @@ -49,11 +49,11 @@ public function execute(string $sessionUUID, Selection $selection, AsyncChunkMan /** @var Block $new */ $new = $newBlocks->blocks(1)->current();//TODO merge iterator if ($new->getId() === $block->getId() && $new->getMeta() === $block->getMeta()) continue;//skip same blocks - #$oldBlocks[] = API::setComponents($manager->getBlockAt($block->getPos()->getFloorX(), $block->getPos()->getFloorY(), $block->getPos()->getFloorZ()),$block->x, $block->y, $block->z); - $oldBlocksSingleClipboard->addEntry($block->getPos()->getFloorX(), $block->getPos()->getFloorY(), $block->getPos()->getFloorZ(), BlockEntry::fromBlock($block)); - $manager->setBlockAt($block->getPos()->getFloorX(), $block->getPos()->getFloorY(), $block->getPos()->getFloorZ(), $new); + #$oldBlocks[] = API::setComponents($manager->getBlockAt($block->getPosition()->getFloorX(), $block->getPosition()->getFloorY(), $block->getPosition()->getFloorZ()),$block->x, $block->y, $block->z); + $oldBlocksSingleClipboard->addEntry($block->getPosition()->getFloorX(), $block->getPosition()->getFloorY(), $block->getPosition()->getFloorZ(), BlockEntry::fromBlock($block)); + $manager->setBlockAt($block->getPosition()->getFloorX(), $block->getPosition()->getFloorY(), $block->getPosition()->getFloorZ(), $new); /** @noinspection PhpInternalEntityUsedInspection */ - if ($manager->getBlockFullIdAt($block->getPos()->getFloorX(), $block->getPos()->getFloorY(), $block->getPos()->getFloorZ()) !== $block->getFullId()) { + if ($manager->getBlockFullIdAt($block->getPosition()->getFloorX(), $block->getPosition()->getFloorY(), $block->getPosition()->getFloorZ()) !== $block->getFullId()) { $changed++; } $i++; diff --git a/src/xenialdan/MagicWE2/task/action/TestAction.php b/src/xenialdan/MagicWE2/task/action/TestAction.php index e85dfd30..5697af07 100644 --- a/src/xenialdan/MagicWE2/task/action/TestAction.php +++ b/src/xenialdan/MagicWE2/task/action/TestAction.php @@ -50,7 +50,7 @@ public function execute(string $sessionUUID, Selection $selection, AsyncChunkMan BlockFactory::getInstance(); foreach ($selection->getShape()->getBlocks($manager, $blockFilter) as $block) { $changed++; - $messages[] = $block->getPos()->asVector3()->__toString() . " " . $block->getName(); + $messages[] = $block->getPosition()->asVector3()->__toString() . " " . $block->getName(); $progress = new Progress($changed / $count, "$changed/$count"); if (floor($progress->progress * 100) > floor($lastProgress->progress * 100)) { yield $progress; diff --git a/src/xenialdan/MagicWE2/task/action/ThawAction.php b/src/xenialdan/MagicWE2/task/action/ThawAction.php index a2411b45..ecb3b0bc 100644 --- a/src/xenialdan/MagicWE2/task/action/ThawAction.php +++ b/src/xenialdan/MagicWE2/task/action/ThawAction.php @@ -51,10 +51,10 @@ public function execute(string $sessionUUID, Selection $selection, AsyncChunkMan foreach ($blockFilterA as $ib => $blockF) { foreach ($selection->getShape()->getBlocks($manager, BlockPalette::CREATE()) as $block) {//TODO merged generator iterating blocks and newblocks $new = clone $newBlocksA[$ib]; - #$oldBlocks[] = API::setComponents($manager->getBlockAt($block->getPos()->getFloorX(), $block->getPos()->getFloorY(), $block->getPos()->getFloorZ()),$block->x, $block->y, $block->z); - $oldBlocksSingleClipboard->addEntry($block->getPos()->getFloorX(), $block->getPos()->getFloorY(), $block->getPos()->getFloorZ(), BlockEntry::fromBlock($block)); - $manager->setBlockAt($block->getPos()->getFloorX(), $block->getPos()->getFloorY(), $block->getPos()->getFloorZ(), $new); - if ($manager->getBlockAt($block->getPos()->getFloorX(), $block->getPos()->getFloorY(), $block->getPos()->getFloorZ())->getId() !== $block->getId()) { + #$oldBlocks[] = API::setComponents($manager->getBlockAt($block->getPosition()->getFloorX(), $block->getPosition()->getFloorY(), $block->getPosition()->getFloorZ()),$block->x, $block->y, $block->z); + $oldBlocksSingleClipboard->addEntry($block->getPosition()->getFloorX(), $block->getPosition()->getFloorY(), $block->getPosition()->getFloorZ(), BlockEntry::fromBlock($block)); + $manager->setBlockAt($block->getPosition()->getFloorX(), $block->getPosition()->getFloorY(), $block->getPosition()->getFloorZ(), $new); + if ($manager->getBlockAt($block->getPosition()->getFloorX(), $block->getPosition()->getFloorY(), $block->getPosition()->getFloorZ())->getId() !== $block->getId()) { $changed++; } $i++; diff --git a/src/xenialdan/MagicWE2/tool/Flood.php b/src/xenialdan/MagicWE2/tool/Flood.php index 65bc62b2..6721e1cf 100644 --- a/src/xenialdan/MagicWE2/tool/Flood.php +++ b/src/xenialdan/MagicWE2/tool/Flood.php @@ -68,7 +68,7 @@ public function getLayer(AsyncChunkManager|World $manager, int $flags = API::FLA { $this->validateChunkManager($manager); foreach ($this->getBlocks($manager, BlockPalette::CREATE()) as $block) { - yield new Vector2($block->getPos()->x, $block->getPos()->z); + yield new Vector2($block->getPosition()->x, $block->getPosition()->z); } } @@ -84,9 +84,9 @@ private function walk(AsyncChunkManager|World $manager): array /** @var Block[] $walkTo */ $walkTo = []; foreach ($this->nextToCheck as $next) { - $sides = iterator_to_array($this->getHorizontalSides($manager, $next->getPos())); + $sides = iterator_to_array($this->getHorizontalSides($manager, $next->getPosition())); $walkTo = array_merge($walkTo, array_filter($sides, function (Block $side) use ($walkTo) { - return $side->getId() === 0 && !in_array($side, $walkTo, true) && !in_array($side, $this->walked, true) && !in_array($side, $this->nextToCheck, true) && $side->getPos()->distanceSquared($this->getCenter()) <= ($this->limit / M_PI); + return $side->getId() === 0 && !in_array($side, $walkTo, true) && !in_array($side, $this->walked, true) && !in_array($side, $this->nextToCheck, true) && $side->getPosition()->distanceSquared($this->getCenter()) <= ($this->limit / M_PI); })); } $this->walked = array_merge($this->walked, $walkTo); From 1af1e6ff876ffd61edc6f3825183c662b55e24ac Mon Sep 17 00:00:00 2001 From: XenialDan Date: Fri, 1 Oct 2021 01:23:58 +0200 Subject: [PATCH 42/67] Use FormAPI virion --- .poggit.yml | 6 +++--- phpstan.neon.dist | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.poggit.yml b/.poggit.yml index a55289ea..719e0da5 100644 --- a/.poggit.yml +++ b/.poggit.yml @@ -12,9 +12,9 @@ projects: libs: - src: BlockHorizons/libschematic/libschematic version: ^2.0.1 - - src: thebigsmilexd/customui/customui - version: ^4.0.0 - branch: PM4 + - src: WolvesFortress/FormAPI/libFormAPI + version: ^1.3.0 + branch: pm4 - src: thebigsmilexd/apibossbar/apibossbar version: ^0.1.4 branch: PM4 diff --git a/phpstan.neon.dist b/phpstan.neon.dist index 1a8f66c1..168f84a0 100644 --- a/phpstan.neon.dist +++ b/phpstan.neon.dist @@ -12,7 +12,7 @@ parameters: scanDirectories: - /source/src - /source/vendor - - phar:///source/vendor/customui.phar/src + - phar:///source/vendor/libFormAPI.phar/src - phar:///source/vendor/apibossbar.phar/src - phar:///source/vendor/Commando.phar/src - phar:///source/vendor/libschematic.phar/src From 31a6abbc89d63046c2cdb3b5dfa419e4267e1a33 Mon Sep 17 00:00:00 2001 From: XenialDan Date: Fri, 1 Oct 2021 02:41:46 +0200 Subject: [PATCH 43/67] Step 1 of migrating to FormAPI --- resources/parsepoggit.php | 2 +- src/xenialdan/MagicWE2/API.php | 8 +- src/xenialdan/MagicWE2/EventListener.php | 18 +-- src/xenialdan/MagicWE2/Loader.php | 13 +- .../MagicWE2/clipboard/RevertClipboard.php | 7 +- .../MagicWE2/clipboard/SingleClipboard.php | 2 +- .../MagicWE2/commands/DonateCommand.php | 5 - .../MagicWE2/commands/HelpCommand.php | 7 +- .../MagicWE2/commands/InfoCommand.php | 5 - .../MagicWE2/commands/LanguageCommand.php | 24 ++-- .../MagicWE2/commands/LimitCommand.php | 5 - .../MagicWE2/commands/ReportCommand.php | 5 - .../MagicWE2/commands/SetRangeCommand.php | 5 - .../MagicWE2/commands/VersionCommand.php | 5 - .../MagicWE2/commands/args/BlocksArgument.php | 2 +- .../commands/args/LanguageArgument.php | 2 +- .../commands/args/MirrorAxisArgument.php | 2 +- .../commands/args/RotateAngleArgument.php | 2 +- .../MagicWE2/commands/asset/AssetCommand.php | 98 ++++++------- .../commands/biome/BiomeInfoCommand.php | 5 - .../commands/biome/BiomeListCommand.php | 5 - .../commands/biome/SetBiomeCommand.php | 5 - .../MagicWE2/commands/brush/BrushCommand.php | 46 ++---- .../commands/brush/BrushNameCommand.php | 5 - .../clipboard/ClearClipboardCommand.php | 5 - .../commands/clipboard/CopyCommand.php | 5 - .../commands/clipboard/Cut2Command.php | 5 - .../commands/clipboard/CutCommand.php | 5 - .../commands/clipboard/FlipCommand.php | 5 - .../commands/clipboard/PasteCommand.php | 7 - .../commands/clipboard/RotateCommand.php | 5 - .../debug/GenerateCommandsMDCommand.php | 8 +- .../debug/PlaceAllBlockstatesCommand.php | 5 - .../commands/debug/TestAPICommand.php | 5 - .../commands/generation/CylinderCommand.php | 5 - .../commands/history/ClearhistoryCommand.php | 5 - .../MagicWE2/commands/history/RedoCommand.php | 5 - .../MagicWE2/commands/history/UndoCommand.php | 5 - .../commands/palette/PaletteCommand.php | 32 ++--- .../commands/region/OverlayCommand.php | 5 - .../commands/region/ReplaceCommand.php | 5 - .../MagicWE2/commands/region/SetCommand.php | 5 - .../commands/selection/ChunkCommand.php | 5 - .../commands/selection/HPos1Command.php | 5 - .../commands/selection/HPos2Command.php | 5 - .../commands/selection/Pos1Command.php | 5 - .../commands/selection/Pos2Command.php | 5 - .../commands/selection/info/CountCommand.php | 9 +- .../selection/info/ListChunksCommand.php | 7 +- .../commands/selection/info/SizeCommand.php | 5 - .../MagicWE2/commands/tool/DebugCommand.php | 5 - .../MagicWE2/commands/tool/FloodCommand.php | 5 - .../commands/tool/ToggledebugCommand.php | 5 - .../commands/tool/TogglewandCommand.php | 5 - .../MagicWE2/commands/tool/WandCommand.php | 5 - .../commands/utility/CalculateCommand.php | 9 +- .../commands/utility/ToggleSidebarCommand.php | 5 - .../commands/utility/ToggleWailaCommand.php | 5 - .../MagicWE2/helper/BlockPalette.php | 2 +- .../MagicWE2/helper/BlockStatesEntry.php | 4 +- .../MagicWE2/helper/BlockStatesParser.php | 21 +-- .../MagicWE2/helper/SessionHelper.php | 2 +- .../MagicWE2/helper/WeightedRandom.php | 4 +- .../MagicWE2/selection/Selection.php | 6 +- .../MagicWE2/selection/shape/Shape.php | 4 +- src/xenialdan/MagicWE2/session/Session.php | 5 +- .../MagicWE2/session/UserSession.php | 4 +- src/xenialdan/MagicWE2/session/data/Asset.php | 27 ++-- .../MagicWE2/task/AsyncActionTask.php | 2 +- src/xenialdan/MagicWE2/task/AsyncCopyTask.php | 4 +- src/xenialdan/MagicWE2/task/AsyncFillTask.php | 5 +- .../MagicWE2/task/AsyncPasteAssetTask.php | 5 +- .../MagicWE2/task/AsyncPasteTask.php | 5 +- .../MagicWE2/task/AsyncReplaceTask.php | 5 +- .../MagicWE2/task/AsyncRevertTask.php | 7 +- .../MagicWE2/task/action/CutAction.php | 4 +- .../MagicWE2/task/action/SetBlockAction.php | 4 +- .../MagicWE2/task/action/ThawAction.php | 2 +- src/xenialdan/MagicWE2/tool/Brush.php | 136 ++++++++++-------- .../MagicWE2/tool/BrushProperties.php | 4 +- src/xenialdan/MagicWE2/tool/Flood.php | 4 +- 81 files changed, 252 insertions(+), 509 deletions(-) diff --git a/resources/parsepoggit.php b/resources/parsepoggit.php index af2892f5..588c5e9b 100644 --- a/resources/parsepoggit.php +++ b/resources/parsepoggit.php @@ -16,7 +16,7 @@ $version = $lib["version"] ?? "*"; $branch = $lib["branch"] ?? ":default"; - $urls[] = "https://poggit.pmmp.io/v.dl/{$src}/{$version}?branch={$branch}"; + $urls[] = "https://poggit.pmmp.io/v.dl/$src/$version?branch=$branch"; } } diff --git a/src/xenialdan/MagicWE2/API.php b/src/xenialdan/MagicWE2/API.php index e4528913..57c335c9 100644 --- a/src/xenialdan/MagicWE2/API.php +++ b/src/xenialdan/MagicWE2/API.php @@ -463,7 +463,7 @@ public static function blockParser(string $fullstring, array &$messages, bool &$ * @return float|int * @throws CalculationException */ - public static function evalAsMath(string $str) + public static function evalAsMath(string $str): float|int { $error = false; $div_mul = false; @@ -473,12 +473,12 @@ public static function evalAsMath(string $str) $str = preg_replace('/[^\d.+\-*\/]/', '', $str); $str = rtrim(trim($str, '/*+'), '-'); - if ((strpos($str, '/') !== false || strpos($str, '*') !== false)) { + if ((str_contains($str, '/') || str_contains($str, '*'))) { $div_mul = true; $operators = ['*', '/']; while (!$error && !empty($operators)) { $operator = array_pop($operators); - while ($operator !== null && strpos($str, $operator) !== false) { + while ($operator !== null && str_contains($str, $operator)) { $regex = '/([\d\.]+)\\' . $operator . '(\-?[\d\.]+)/'; preg_match($regex, $str, $matches); if (isset($matches[1], $matches[2])) { @@ -501,7 +501,7 @@ public static function evalAsMath(string $str) } } - if (!$error && (strpos($str, '+') !== false || strpos($str, '-') !== false)) { + if (!$error && (str_contains($str, '+') || str_contains($str, '-'))) { $add_sub = true; preg_match_all('/([\d.]+|[+\-])/', $str, $matches); if (isset($matches[0])) { diff --git a/src/xenialdan/MagicWE2/EventListener.php b/src/xenialdan/MagicWE2/EventListener.php index 1736f160..22113c33 100644 --- a/src/xenialdan/MagicWE2/EventListener.php +++ b/src/xenialdan/MagicWE2/EventListener.php @@ -6,6 +6,7 @@ use Exception; use InvalidArgumentException; use InvalidStateException; +use jojoe77777\FormAPI\ModalForm; use JsonException; use pocketmine\block\BlockFactory; use pocketmine\block\BlockLegacyIds; @@ -27,7 +28,6 @@ use pocketmine\utils\TextFormat as TF; use pocketmine\world\Position; use RuntimeException; -use xenialdan\customui\windows\ModalForm; use xenialdan\libstructure\tile\StructureBlockTile; use xenialdan\MagicWE2\event\MWESelectionChangeEvent; use xenialdan\MagicWE2\event\MWESessionLoadEvent; @@ -361,12 +361,15 @@ public function onDropItem(PlayerDropItemEvent $event): void if (!$session instanceof UserSession) return; $brush = $session->getBrushes()->getBrushFromItem($event->getItem()); if ($brush instanceof Brush) { - $form = new ModalForm(TF::BOLD . $brush->getName(), TF::RED . - "Delete" . TF::WHITE . " brush from session or " . TF::GREEN . "remove" . TF::WHITE . " from Inventory?" . TF::EOL . - implode(TF::EOL, $event->getItem()->getLore()), TF::BOLD . TF::DARK_RED . "Delete", TF::BOLD . TF::DARK_GREEN . "Remove"); - $form->setCallable(function (Player $player, $data) use ($session, $brush) { + $form = (new ModalForm(function (Player $player, $data) use ($session, $brush) { $session->getBrushes()->removeBrush($brush, $data); - }); + })) + ->setTitle(TF::BOLD . $brush->getName()) + ->setContent(TF::RED . + "Delete" . TF::WHITE . " brush from session or " . TF::GREEN . "remove" . TF::WHITE . " from Inventory?" . TF::EOL . + implode(TF::EOL, $event->getItem()->getLore())) + ->setButton1(TF::BOLD . TF::DARK_RED . "Delete") + ->setButton2(TF::BOLD . TF::DARK_GREEN . "Remove"); $event->getPlayer()->sendForm($form); } } else if (!is_null($event->getItem()->getNamedTag()->getCompoundTag(API::TAG_MAGIC_WE))) { @@ -414,7 +417,7 @@ public function onChangeSlot(PlayerItemHeldEvent $event): void $target->subtract(0, 1, 0);//one block down $target = Position::fromObject($target, $player->getWorld()); if (/*$session->displayOutline && */ self::sendOutline($player, $target, $asset, $session)) { - $player->sendMessage("Added asset outline for {$asset->filename}!"); + $player->sendMessage("Added asset outline for $asset->filename!"); } else { $player->sendMessage("Did not add asset outline!"); } @@ -442,7 +445,6 @@ public static function sendOutline(Player $player, Position $target, Asset $asse $minComponents = new Vector3($ix, $iy, $iz); $maxComponents = new Vector3($ax, $ay, $az); - /** @noinspection PhpDeprecationInspection */ $block = BlockFactory::getInstance()->get(BlockLegacyIds::STRUCTURE_BLOCK, 0/*StructureEditorData::TYPE_SAVE*/); var_dump((string)$block); $target->world->setBlock($target->asVector3(), $block); diff --git a/src/xenialdan/MagicWE2/Loader.php b/src/xenialdan/MagicWE2/Loader.php index 53d93127..a669be58 100644 --- a/src/xenialdan/MagicWE2/Loader.php +++ b/src/xenialdan/MagicWE2/Loader.php @@ -6,6 +6,7 @@ use InvalidArgumentException; use jackmd\scorefactory\ScoreFactory; +use jojoe77777\FormAPI\FormAPI; use JsonException; use muqsit\invmenu\InvMenuHandler; use pocketmine\block\Block; @@ -22,7 +23,6 @@ use pocketmine\utils\TextFormat as TF; use RuntimeException; use xenialdan\apibossbar\DiverseBossBar; -use xenialdan\customui\API as CustomUIAPI; use xenialdan\libstructure\PacketListener; use xenialdan\MagicWE2\commands\biome\BiomeInfoCommand; use xenialdan\MagicWE2\commands\biome\BiomeListCommand; @@ -158,6 +158,7 @@ public static function hasScoreboard(): bool * @throws RuntimeException * @throws JsonException * @throws AssumptionFailedError + * @throws InvalidArgumentException */ public function onLoad(): void { @@ -317,8 +318,8 @@ public function onEnable(): void new TestAPICommand($this, "/testapi", "Internal command for testing API methods"), new GenerateCommandsMDCommand($this, "/generatecommandsmd", "Generates the commands.md file"), ]); - if (class_exists(CustomUIAPI::class)) { - $this->getLogger()->notice("CustomUI found, can use ui-based commands"); + if (class_exists(FormAPI::class)) { + $this->getLogger()->notice("FormAPI found, can use ui-based commands"); $this->getServer()->getCommandMap()->registerAll("MagicWE2", [ /* -- brush -- */ new BrushCommand($this, "/brush", "Opens the brush tool menu"), @@ -326,7 +327,7 @@ public function onEnable(): void new FloodCommand($this, "/flood", "Opens the flood fill tool menu", ["/floodfill"]), ]); } else { - $this->getLogger()->notice(TF::RED . "CustomUI NOT found, can NOT use ui-based commands"); + $this->getLogger()->notice(TF::RED . "FormAPI NOT found, can NOT use ui-based commands"); } if (class_exists(ScoreFactory::class)) { $this->getLogger()->notice("Scoreboard API found, can use scoreboards"); @@ -409,9 +410,9 @@ public static function getInfo(): array "| Plugin API Version | " . implode(", ", self::getInstance()->getDescription()->getCompatibleApis()) . " |", "| Authors | " . implode(", ", self::getInstance()->getDescription()->getAuthors()) . " |", "| Enabled | " . (Server::getInstance()->getPluginManager()->isPluginEnabled(self::getInstance()) ? TF::GREEN . "Yes" : TF::RED . "No") . TF::RESET . " |", - "| Uses UI | " . (class_exists(CustomUIAPI::class) ? TF::GREEN . "Yes" : TF::RED . "No") . TF::RESET . " |", + "| Uses UI | " . (class_exists(FormAPI::class) ? TF::GREEN . "Yes" : TF::RED . "No") . TF::RESET . " |", "| Uses ScoreFactory | " . (class_exists(ScoreFactory::class) ? TF::GREEN . "Yes" : TF::RED . "No") . TF::RESET . " |", - "| Phar | " . (strpos(self::getInstance()->getFile(), 'phar:') !== false ? TF::GREEN . "Yes" : TF::RED . "No") . TF::RESET . " |", + "| Phar | " . (str_contains(self::getInstance()->getFile(), 'phar:') ? TF::GREEN . "Yes" : TF::RED . "No") . TF::RESET . " |", "| PMMP Protocol Version | " . Server::getInstance()->getVersion() . " |", "| PMMP Version | " . Server::getInstance()->getPocketMineVersion() . " |", "| PMMP API Version | " . Server::getInstance()->getApiVersion() . " |", diff --git a/src/xenialdan/MagicWE2/clipboard/RevertClipboard.php b/src/xenialdan/MagicWE2/clipboard/RevertClipboard.php index fcc20c35..9fddc849 100644 --- a/src/xenialdan/MagicWE2/clipboard/RevertClipboard.php +++ b/src/xenialdan/MagicWE2/clipboard/RevertClipboard.php @@ -6,6 +6,7 @@ use pocketmine\world\format\Chunk; use pocketmine\world\format\io\FastChunkSerializer; +use pocketmine\world\Position; class RevertClipboard extends Clipboard { @@ -16,7 +17,7 @@ class RevertClipboard extends Clipboard public array $chunks = []; /** * @var array[] - * @phpstan-var array + * @phpstan-var array */ public array $blocksAfter; @@ -25,7 +26,7 @@ class RevertClipboard extends Clipboard * @param int $worldId * @param Chunk[] $chunks * @param array[] $blocksAfter //CHANGED AS HACK - * @phpstan-param array $blocksAfter + * @phpstan-param array $blocksAfter */ public function __construct(int $worldId, array $chunks = [], array $blocksAfter = []) { @@ -40,7 +41,7 @@ public function __construct(int $worldId, array $chunks = [], array $blocksAfter * @return string the string representation of the object or null * @since 5.1.0 */ - public function serialize() + public function serialize(): string { $chunks = []; foreach ($this->chunks as $hash => $chunk) { diff --git a/src/xenialdan/MagicWE2/clipboard/SingleClipboard.php b/src/xenialdan/MagicWE2/clipboard/SingleClipboard.php index c4fc318b..18164845 100644 --- a/src/xenialdan/MagicWE2/clipboard/SingleClipboard.php +++ b/src/xenialdan/MagicWE2/clipboard/SingleClipboard.php @@ -63,7 +63,7 @@ public function getTotalCount(): int * @return string the string representation of the object or null * @since 5.1 */ - public function serialize() + public function serialize(): string { // TODO: Implement serialize() method. return serialize([ diff --git a/src/xenialdan/MagicWE2/commands/DonateCommand.php b/src/xenialdan/MagicWE2/commands/DonateCommand.php index db3e865e..8222a77f 100644 --- a/src/xenialdan/MagicWE2/commands/DonateCommand.php +++ b/src/xenialdan/MagicWE2/commands/DonateCommand.php @@ -26,11 +26,6 @@ protected function prepare(): void $this->setPermission("we.command.donate"); } - /** - * @param CommandSender $sender - * @param string $aliasUsed - * @param mixed[] $args - */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { $lang = Loader::getInstance()->getLanguage(); diff --git a/src/xenialdan/MagicWE2/commands/HelpCommand.php b/src/xenialdan/MagicWE2/commands/HelpCommand.php index 6fa89cf6..c9ecfe70 100644 --- a/src/xenialdan/MagicWE2/commands/HelpCommand.php +++ b/src/xenialdan/MagicWE2/commands/HelpCommand.php @@ -30,11 +30,6 @@ protected function prepare(): void $this->setPermission("we.command.help"); } - /** - * @param CommandSender $sender - * @param string $aliasUsed - * @param mixed[] $args - */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { $lang = Loader::getInstance()->getLanguage(); @@ -48,7 +43,7 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo $cmds = []; if (empty($args["command"])) { foreach (array_filter(Loader::getInstance()->getServer()->getCommandMap()->getCommands(), static function (Command $command) use ($sender) { - return strpos($command->getName(), "/") !== false && $command->testPermissionSilent($sender); + return str_contains($command->getName(), "/") && $command->testPermissionSilent($sender); }) as $cmd) { /** @var Command $cmd */ $cmds[$cmd->getName()] = $cmd; diff --git a/src/xenialdan/MagicWE2/commands/InfoCommand.php b/src/xenialdan/MagicWE2/commands/InfoCommand.php index 074a598d..6f9f5bb3 100644 --- a/src/xenialdan/MagicWE2/commands/InfoCommand.php +++ b/src/xenialdan/MagicWE2/commands/InfoCommand.php @@ -26,11 +26,6 @@ protected function prepare(): void $this->setPermission("we.command.info"); } - /** - * @param CommandSender $sender - * @param string $aliasUsed - * @param mixed[] $args - */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { $lang = Loader::getInstance()->getLanguage(); diff --git a/src/xenialdan/MagicWE2/commands/LanguageCommand.php b/src/xenialdan/MagicWE2/commands/LanguageCommand.php index 8e6701e2..35bcdc3e 100644 --- a/src/xenialdan/MagicWE2/commands/LanguageCommand.php +++ b/src/xenialdan/MagicWE2/commands/LanguageCommand.php @@ -8,16 +8,16 @@ use CortexPE\Commando\exception\ArgumentOrderException; use Exception; use InvalidArgumentException; +use jojoe77777\FormAPI\CustomForm; use pocketmine\command\CommandSender; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; -use xenialdan\customui\elements\Dropdown; -use xenialdan\customui\elements\Label; -use xenialdan\customui\windows\CustomForm; use xenialdan\MagicWE2\commands\args\LanguageArgument; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\SessionHelper; use xenialdan\MagicWE2\Loader; +use function array_search; +use function is_string; class LanguageCommand extends BaseCommand { @@ -33,11 +33,6 @@ protected function prepare(): void $this->setPermission("we.command.language"); } - /** - * @param CommandSender $sender - * @param string $aliasUsed - * @param mixed[] $args - */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { $lang = Loader::getInstance()->getLanguage(); @@ -62,16 +57,15 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo return; } $languages = Loader::getInstance()->getLanguageList(); - $form = new CustomForm(Loader::PREFIX_FORM . TF::BOLD . TF::DARK_PURPLE . $lang->translateString('ui.language.title')); - $form->addElement(new Label($lang->translateString('ui.language.label'))); - $dropdown = new Dropdown($lang->translateString('ui.language.dropdown'), array_values($languages)); - $dropdown->setOptionAsDefault($session->getLanguage()->getName()); - $form->addElement($dropdown); - $form->setCallable(function (Player $player, $data) use ($session, $languages) { + $form = (new CustomForm(function (Player $player, $data) use ($session, $languages) { $langShort = array_search($data[1], $languages, true); if (!is_string($langShort)) throw new InvalidArgumentException("Invalid data received"); $session->setLanguage($langShort); - }); + })) + ->setTitle(Loader::PREFIX_FORM . TF::BOLD . TF::DARK_PURPLE . $lang->translateString('ui.language.title')) + ->addLabel($lang->translateString('ui.language.label')) + ->addDropdown($lang->translateString('ui.language.dropdown'), array_values($languages)); + //$dropdown->setOptionAsDefault($session->getLanguage()->getName()); $sender->sendForm($form); } catch (Exception $error) { $sender->sendMessage(Loader::PREFIX . TF::RED . $lang->translateString('error.command-error')); diff --git a/src/xenialdan/MagicWE2/commands/LimitCommand.php b/src/xenialdan/MagicWE2/commands/LimitCommand.php index 0fd34061..9d9190c4 100644 --- a/src/xenialdan/MagicWE2/commands/LimitCommand.php +++ b/src/xenialdan/MagicWE2/commands/LimitCommand.php @@ -31,11 +31,6 @@ protected function prepare(): void $this->setUsage("//limit [limit: int|-1]"); } - /** - * @param CommandSender $sender - * @param string $aliasUsed - * @param mixed[] $args - */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { $lang = Loader::getInstance()->getLanguage(); diff --git a/src/xenialdan/MagicWE2/commands/ReportCommand.php b/src/xenialdan/MagicWE2/commands/ReportCommand.php index c5323e50..291c11a7 100644 --- a/src/xenialdan/MagicWE2/commands/ReportCommand.php +++ b/src/xenialdan/MagicWE2/commands/ReportCommand.php @@ -31,11 +31,6 @@ protected function prepare(): void $this->setPermission("we.command.report"); } - /** - * @param CommandSender $sender - * @param string $aliasUsed - * @param mixed[] $args - */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { $lang = Loader::getInstance()->getLanguage(); diff --git a/src/xenialdan/MagicWE2/commands/SetRangeCommand.php b/src/xenialdan/MagicWE2/commands/SetRangeCommand.php index 60e1171d..160e5d02 100644 --- a/src/xenialdan/MagicWE2/commands/SetRangeCommand.php +++ b/src/xenialdan/MagicWE2/commands/SetRangeCommand.php @@ -31,11 +31,6 @@ protected function prepare(): void $this->setUsage("//setrange [range: int]"); } - /** - * @param CommandSender $sender - * @param string $aliasUsed - * @param mixed[] $args - */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { $lang = Loader::getInstance()->getLanguage(); diff --git a/src/xenialdan/MagicWE2/commands/VersionCommand.php b/src/xenialdan/MagicWE2/commands/VersionCommand.php index b8166e60..99437802 100644 --- a/src/xenialdan/MagicWE2/commands/VersionCommand.php +++ b/src/xenialdan/MagicWE2/commands/VersionCommand.php @@ -26,11 +26,6 @@ protected function prepare(): void $this->setPermission("we.command.version"); } - /** - * @param CommandSender $sender - * @param string $aliasUsed - * @param mixed[] $args - */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { $lang = Loader::getInstance()->getLanguage(); diff --git a/src/xenialdan/MagicWE2/commands/args/BlocksArgument.php b/src/xenialdan/MagicWE2/commands/args/BlocksArgument.php index 0ae0d7f0..84c529c0 100644 --- a/src/xenialdan/MagicWE2/commands/args/BlocksArgument.php +++ b/src/xenialdan/MagicWE2/commands/args/BlocksArgument.php @@ -39,7 +39,7 @@ public function canParse(string $testString, CommandSender $sender): bool * @throws LegacyStringToItemParserException * @throws UnexpectedTagTypeException */ - public function parse(string $argument, CommandSender $sender) + public function parse(string $argument, CommandSender $sender): BlockPalette { try { return BlockPalette::fromString($argument); diff --git a/src/xenialdan/MagicWE2/commands/args/LanguageArgument.php b/src/xenialdan/MagicWE2/commands/args/LanguageArgument.php index e4d86fc0..1ae054e2 100644 --- a/src/xenialdan/MagicWE2/commands/args/LanguageArgument.php +++ b/src/xenialdan/MagicWE2/commands/args/LanguageArgument.php @@ -22,7 +22,7 @@ public function getTypeName(): string * @return string * @throws LanguageNotFoundException */ - public function parse(string $argument, CommandSender $sender) + public function parse(string $argument, CommandSender $sender): string { return (string)array_search($argument, Loader::getInstance()->getLanguageList(), true); } diff --git a/src/xenialdan/MagicWE2/commands/args/MirrorAxisArgument.php b/src/xenialdan/MagicWE2/commands/args/MirrorAxisArgument.php index fd2fb847..bfdc905f 100644 --- a/src/xenialdan/MagicWE2/commands/args/MirrorAxisArgument.php +++ b/src/xenialdan/MagicWE2/commands/args/MirrorAxisArgument.php @@ -26,7 +26,7 @@ public function getEnumName(): string * @param CommandSender $sender * @return string //TODO consider changing to Axis */ - public function parse(string $argument, CommandSender $sender) + public function parse(string $argument, CommandSender $sender): string { return (string)$this->getValue($argument); } diff --git a/src/xenialdan/MagicWE2/commands/args/RotateAngleArgument.php b/src/xenialdan/MagicWE2/commands/args/RotateAngleArgument.php index 5503e86d..90d7e2f9 100644 --- a/src/xenialdan/MagicWE2/commands/args/RotateAngleArgument.php +++ b/src/xenialdan/MagicWE2/commands/args/RotateAngleArgument.php @@ -27,7 +27,7 @@ public function getEnumName(): string * @param CommandSender $sender * @return int */ - public function parse(string $argument, CommandSender $sender) + public function parse(string $argument, CommandSender $sender): int { return (int)$this->getValue($argument); } diff --git a/src/xenialdan/MagicWE2/commands/asset/AssetCommand.php b/src/xenialdan/MagicWE2/commands/asset/AssetCommand.php index a6e49c64..f6408d99 100644 --- a/src/xenialdan/MagicWE2/commands/asset/AssetCommand.php +++ b/src/xenialdan/MagicWE2/commands/asset/AssetCommand.php @@ -8,16 +8,13 @@ use CortexPE\Commando\BaseCommand; use Exception; use InvalidArgumentException; +use jojoe77777\FormAPI\CustomForm; +use jojoe77777\FormAPI\SimpleForm; use muqsit\invmenu\InvMenu; +use muqsit\invmenu\type\InvMenuTypeIds; use pocketmine\command\CommandSender; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; -use xenialdan\customui\elements\Button; -use xenialdan\customui\elements\Label; -use xenialdan\customui\elements\Toggle; -use xenialdan\customui\elements\UIElement; -use xenialdan\customui\windows\CustomForm; -use xenialdan\customui\windows\SimpleForm; use xenialdan\libstructure\format\MCStructure; use xenialdan\MagicWE2\clipboard\SingleClipboard; use xenialdan\MagicWE2\exception\SessionException; @@ -25,6 +22,16 @@ use xenialdan\MagicWE2\Loader; use xenialdan\MagicWE2\session\data\Asset; use xenialdan\MagicWE2\session\UserSession; +use function array_keys; +use function array_values; +use function count; +use function mkdir; +use function pathinfo; +use function time; +use function var_dump; +use const DIRECTORY_SEPARATOR; +use const PATHINFO_BASENAME; +use const PATHINFO_DIRNAME; class AssetCommand extends BaseCommand { @@ -38,11 +45,6 @@ protected function prepare(): void $this->setPermission("we.command.asset");//TODO perm } - /** - * @param CommandSender $sender - * @param string $aliasUsed - * @param mixed[] $args - */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { $lang = Loader::getInstance()->getLanguage(); @@ -62,13 +64,7 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo if (!$session instanceof UserSession) { throw new SessionException($lang->translateString('error.nosession', [Loader::getInstance()->getName()])); } - $form = new SimpleForm(Loader::PREFIX_FORM . TF::BOLD . TF::DARK_PURPLE . $lang->translateString('ui.asset.title'), $lang->translateString('ui.asset.content'));//TODO - $form->addButton(new Button($lang->translateString('ui.asset.private'))); - $form->addButton(new Button($lang->translateString('ui.asset.global'))); - $form->addButton(new Button($lang->translateString('ui.asset.create.fromclipboard'))); - $form->addButton(new Button($lang->translateString('ui.asset.settings'))); - $form->addButton(new Button($lang->translateString('ui.asset.save'))); - $form->setCallable(function (Player $player, $data) use ($lang, $session) { + $form = (new SimpleForm(function (Player $player, $data) use ($lang, $session) { try { $store = Loader::$assetCollection;//TODO allow private assets again switch ($data) { @@ -93,18 +89,11 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo //save asset //dropdown asset //dropdown type - $form = new CustomForm(Loader::PREFIX_FORM . TF::BOLD . TF::DARK_PURPLE . $lang->translateString('ui.asset.select')); - $options = []; - foreach ($store->getUnlockedAssets() as $asset) { - $options[$asset->filename] = $asset->filename; - } - $form->addDropdown("Asset", array_values($options)); - $form->addDropdown("File type", [Asset::TYPE_SCHEMATIC, Asset::TYPE_MCSTRUCTURE]); - $form->setCallable(function (Player $player, $data) use (/*$lang, $session,*/ $store) { + $form = (new CustomForm(function (Player $player, $data) use (/*$lang, $session,*/ $store) { [$filename, $type] = $data; /** @var Asset $asset */ $asset = $store->assets[$filename]; - $player->sendMessage('Saving ' . (string)$asset); + $player->sendMessage('Saving ' . $asset); //TODO async, convert if ($type === Asset::TYPE_SCHEMATIC) { if ($asset->structure instanceof Schematic) { @@ -129,7 +118,14 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo $player->sendMessage('TODO'); } //$asset->saveAs() //TODO - }); + })) + ->setTitle(Loader::PREFIX_FORM . TF::BOLD . TF::DARK_PURPLE . $lang->translateString('ui.asset.select')); + $options = []; + foreach ($store->getUnlockedAssets() as $asset) { + $options[$asset->filename] = $asset->filename; + } + $form->addDropdown("Asset", array_values($options)) + ->addDropdown("File type", [Asset::TYPE_SCHEMATIC, Asset::TYPE_MCSTRUCTURE]); $player->sendForm($form); break; } @@ -138,24 +134,24 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo //save asset //dropdown asset //dropdown type - $form = new CustomForm(Loader::PREFIX_FORM . TF::BOLD . TF::DARK_PURPLE . $lang->translateString('ui.asset.select')); + $form = (new CustomForm(function (Player $player, $data) use (/*$lang, $session,*/ $store) { + [$filename] = $data; + /** @var Asset $asset */ + $asset = $store->assets[$filename]; + $player->sendForm($asset->getSettingForm()); + })) + ->setTitle(Loader::PREFIX_FORM . TF::BOLD . TF::DARK_PURPLE . $lang->translateString('ui.asset.select')); $options = []; foreach (Loader::$assetCollection->getAll() as $asset) {//TODO allow private assets again $options[$asset->filename] = $asset->filename; } $form->addDropdown("Asset", array_values($options)); - $form->setCallable(function (Player $player, $data) use (/*$lang, $session,*/ $store) { - [$filename] = $data; - /** @var Asset $asset */ - $asset = $store->assets[$filename]; - $player->sendForm($asset->getSettingForm()); - }); $player->sendForm($form); break; } case $lang->translateString('ui.asset.global'): { - $menu = InvMenu::create(InvMenu::TYPE_DOUBLE_CHEST); + $menu = InvMenu::create(InvMenuTypeIds::TYPE_DOUBLE_CHEST); $store = Loader::$assetCollection; foreach ($store->getSharedAssets() as $asset) { $menu->getInventory()->addItem($asset->toItem()); @@ -165,7 +161,7 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo } case $lang->translateString('ui.asset.private'): { - $menu = InvMenu::create(InvMenu::TYPE_DOUBLE_CHEST); + $menu = InvMenu::create(InvMenuTypeIds::TYPE_DOUBLE_CHEST); $store = $session->getAssets(); $playerAssets = $store->getPlayerAssets($player->getXuid()); var_dump(array_keys($playerAssets), array_keys($store->getPlayerAssets())); @@ -183,7 +179,14 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo $session->sendMessage(TF::RED . $error->getMessage()); Loader::getInstance()->getLogger()->logException($error); } - }); + })) + ->setTitle(Loader::PREFIX_FORM . TF::BOLD . TF::DARK_PURPLE . $lang->translateString('ui.asset.title')) + ->setContent($lang->translateString('ui.asset.content'))//TODO + ->addButton($lang->translateString('ui.asset.private')) + ->addButton($lang->translateString('ui.asset.global')) + ->addButton($lang->translateString('ui.asset.create.fromclipboard')) + ->addButton($lang->translateString('ui.asset.settings')) + ->addButton($lang->translateString('ui.asset.save')); $sender->sendForm($form); } catch (Exception $error) { $sender->sendMessage(Loader::PREFIX . TF::RED . $lang->translateString('error.command-error')); @@ -191,23 +194,4 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo $sender->sendMessage($this->getUsage()); } } - - /** - * @param UIElement[] $elements - * @param array $data - * @return array - */ - public static function generateLore(array $elements, array $data): array - { - $return = []; - foreach ($elements as $i => $element) { - if ($element instanceof Label) continue; - if ($element instanceof Toggle) { - $return[] = ($element->getText() . ": " . ($data[$i] ? "Yes" : "No")); - continue; - } - $return[] = ($element->getText() . ": " . $data[$i]); - } - return $return; - } } diff --git a/src/xenialdan/MagicWE2/commands/biome/BiomeInfoCommand.php b/src/xenialdan/MagicWE2/commands/biome/BiomeInfoCommand.php index a23fb808..ccc76511 100644 --- a/src/xenialdan/MagicWE2/commands/biome/BiomeInfoCommand.php +++ b/src/xenialdan/MagicWE2/commands/biome/BiomeInfoCommand.php @@ -38,11 +38,6 @@ protected function prepare(): void $this->setPermission("we.command.biome.info"); } - /** - * @param CommandSender $sender - * @param string $aliasUsed - * @param mixed[] $args - */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { $lang = Loader::getInstance()->getLanguage(); diff --git a/src/xenialdan/MagicWE2/commands/biome/BiomeListCommand.php b/src/xenialdan/MagicWE2/commands/biome/BiomeListCommand.php index 41ad97ce..573109e9 100644 --- a/src/xenialdan/MagicWE2/commands/biome/BiomeListCommand.php +++ b/src/xenialdan/MagicWE2/commands/biome/BiomeListCommand.php @@ -29,11 +29,6 @@ protected function prepare(): void $this->setPermission("we.command.biome.list"); } - /** - * @param CommandSender $sender - * @param string $aliasUsed - * @param mixed[] $args - */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { $lang = Loader::getInstance()->getLanguage(); diff --git a/src/xenialdan/MagicWE2/commands/biome/SetBiomeCommand.php b/src/xenialdan/MagicWE2/commands/biome/SetBiomeCommand.php index d7d0219f..89ab1f9c 100644 --- a/src/xenialdan/MagicWE2/commands/biome/SetBiomeCommand.php +++ b/src/xenialdan/MagicWE2/commands/biome/SetBiomeCommand.php @@ -34,11 +34,6 @@ protected function prepare(): void $this->setPermission("we.command.biome.set"); } - /** - * @param CommandSender $sender - * @param string $aliasUsed - * @param mixed[] $args - */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { $lang = Loader::getInstance()->getLanguage(); diff --git a/src/xenialdan/MagicWE2/commands/brush/BrushCommand.php b/src/xenialdan/MagicWE2/commands/brush/BrushCommand.php index 646b9de6..c392de8c 100644 --- a/src/xenialdan/MagicWE2/commands/brush/BrushCommand.php +++ b/src/xenialdan/MagicWE2/commands/brush/BrushCommand.php @@ -7,15 +7,12 @@ use CortexPE\Commando\BaseCommand; use Exception; use InvalidArgumentException; +use jojoe77777\FormAPI\SimpleForm; use muqsit\invmenu\InvMenu; +use muqsit\invmenu\type\InvMenuTypeIds; use pocketmine\command\CommandSender; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; -use xenialdan\customui\elements\Button; -use xenialdan\customui\elements\Label; -use xenialdan\customui\elements\Toggle; -use xenialdan\customui\elements\UIElement; -use xenialdan\customui\windows\SimpleForm; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\SessionHelper; use xenialdan\MagicWE2\Loader; @@ -35,11 +32,6 @@ protected function prepare(): void $this->setPermission("we.command.brush"); } - /** - * @param CommandSender $sender - * @param string $aliasUsed - * @param mixed[] $args - */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { $lang = Loader::getInstance()->getLanguage(); @@ -59,11 +51,7 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo if (!$session instanceof UserSession) { throw new SessionException($lang->translateString('error.nosession', [Loader::getInstance()->getName()])); } - $form = new SimpleForm(Loader::PREFIX_FORM . TF::BOLD . TF::DARK_PURPLE . $lang->translateString('ui.brush.title'), $lang->translateString('ui.brush.content')); - $form->addButton(new Button($lang->translateString('ui.brush.create'))); - $form->addButton(new Button($lang->translateString('ui.brush.getsession'))); - $form->addButton(new Button($lang->translateString('ui.brush.edithand'))); - $form->setCallable(function (Player $player, $data) use ($lang, $session) { + $form = (new SimpleForm(function (Player $player, $data) use ($lang, $session) { try { switch ($data) { case $lang->translateString('ui.brush.create'): @@ -74,7 +62,7 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo } case $lang->translateString('ui.brush.getsession'): { - $menu = InvMenu::create(InvMenu::TYPE_DOUBLE_CHEST); + $menu = InvMenu::create(InvMenuTypeIds::TYPE_DOUBLE_CHEST); foreach ($session->getBrushes()->getAll() as $brush) { $menu->getInventory()->addItem($brush->toItem()); } @@ -95,7 +83,12 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo $session->sendMessage(TF::RED . $lang->translateString('error')); $session->sendMessage(TF::RED . $error->getMessage()); } - }); + })) + ->setTitle(Loader::PREFIX_FORM . TF::BOLD . TF::DARK_PURPLE . $lang->translateString('ui.brush.title')) + ->setContent($lang->translateString('ui.brush.content')) + ->addButton($lang->translateString('ui.brush.create')) + ->addButton($lang->translateString('ui.brush.getsession')) + ->addButton($lang->translateString('ui.brush.edithand')); $sender->sendForm($form); } catch (Exception $error) { $sender->sendMessage(Loader::PREFIX . TF::RED . $lang->translateString('error.command-error')); @@ -103,23 +96,4 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo $sender->sendMessage($this->getUsage()); } } - - /** - * @param UIElement[] $elements - * @param array $data - * @return array - */ - public static function generateLore(array $elements, array $data): array//TODO remove? - { - $return = []; - foreach ($elements as $i => $element) { - if ($element instanceof Label) continue; - if ($element instanceof Toggle) { - $return[] = ($element->getText() . ": " . ($data[$i] ? "Yes" : "No")); - continue; - } - $return[] = ($element->getText() . ": " . $data[$i]); - } - return $return; - } } diff --git a/src/xenialdan/MagicWE2/commands/brush/BrushNameCommand.php b/src/xenialdan/MagicWE2/commands/brush/BrushNameCommand.php index 518529c6..ab81ffdf 100644 --- a/src/xenialdan/MagicWE2/commands/brush/BrushNameCommand.php +++ b/src/xenialdan/MagicWE2/commands/brush/BrushNameCommand.php @@ -30,11 +30,6 @@ protected function prepare(): void $this->setPermission("we.command.brush.name"); } - /** - * @param CommandSender $sender - * @param string $aliasUsed - * @param mixed[] $args - */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { $lang = Loader::getInstance()->getLanguage(); diff --git a/src/xenialdan/MagicWE2/commands/clipboard/ClearClipboardCommand.php b/src/xenialdan/MagicWE2/commands/clipboard/ClearClipboardCommand.php index cc782867..1c6ca934 100644 --- a/src/xenialdan/MagicWE2/commands/clipboard/ClearClipboardCommand.php +++ b/src/xenialdan/MagicWE2/commands/clipboard/ClearClipboardCommand.php @@ -27,11 +27,6 @@ protected function prepare(): void $this->setPermission("we.command.clipboard.clear"); } - /** - * @param CommandSender $sender - * @param string $aliasUsed - * @param mixed[] $args - */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { $lang = Loader::getInstance()->getLanguage(); diff --git a/src/xenialdan/MagicWE2/commands/clipboard/CopyCommand.php b/src/xenialdan/MagicWE2/commands/clipboard/CopyCommand.php index b006a33a..1c397b29 100644 --- a/src/xenialdan/MagicWE2/commands/clipboard/CopyCommand.php +++ b/src/xenialdan/MagicWE2/commands/clipboard/CopyCommand.php @@ -32,11 +32,6 @@ protected function prepare(): void $this->setPermission("we.command.clipboard.copy"); } - /** - * @param CommandSender $sender - * @param string $aliasUsed - * @param mixed[] $args - */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { $lang = Loader::getInstance()->getLanguage(); diff --git a/src/xenialdan/MagicWE2/commands/clipboard/Cut2Command.php b/src/xenialdan/MagicWE2/commands/clipboard/Cut2Command.php index 7dc16cec..4c92d5a3 100644 --- a/src/xenialdan/MagicWE2/commands/clipboard/Cut2Command.php +++ b/src/xenialdan/MagicWE2/commands/clipboard/Cut2Command.php @@ -36,11 +36,6 @@ protected function prepare(): void $this->setPermission("we.command.clipboard.cut"); } - /** - * @param CommandSender $sender - * @param string $aliasUsed - * @param mixed[] $args - */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { $lang = Loader::getInstance()->getLanguage(); diff --git a/src/xenialdan/MagicWE2/commands/clipboard/CutCommand.php b/src/xenialdan/MagicWE2/commands/clipboard/CutCommand.php index 16a56bc0..75982cba 100644 --- a/src/xenialdan/MagicWE2/commands/clipboard/CutCommand.php +++ b/src/xenialdan/MagicWE2/commands/clipboard/CutCommand.php @@ -33,11 +33,6 @@ protected function prepare(): void $this->setPermission("we.command.clipboard.cut"); } - /** - * @param CommandSender $sender - * @param string $aliasUsed - * @param mixed[] $args - */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { $lang = Loader::getInstance()->getLanguage(); diff --git a/src/xenialdan/MagicWE2/commands/clipboard/FlipCommand.php b/src/xenialdan/MagicWE2/commands/clipboard/FlipCommand.php index 40fdc672..a2cb5d39 100644 --- a/src/xenialdan/MagicWE2/commands/clipboard/FlipCommand.php +++ b/src/xenialdan/MagicWE2/commands/clipboard/FlipCommand.php @@ -35,11 +35,6 @@ protected function prepare(): void //$this->setUsage("//flip "); } - /** - * @param CommandSender $sender - * @param string $aliasUsed - * @param mixed[] $args - */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { $lang = Loader::getInstance()->getLanguage(); diff --git a/src/xenialdan/MagicWE2/commands/clipboard/PasteCommand.php b/src/xenialdan/MagicWE2/commands/clipboard/PasteCommand.php index e3660ddd..6e08307c 100644 --- a/src/xenialdan/MagicWE2/commands/clipboard/PasteCommand.php +++ b/src/xenialdan/MagicWE2/commands/clipboard/PasteCommand.php @@ -11,7 +11,6 @@ use InvalidArgumentException; use pocketmine\command\CommandSender; use pocketmine\player\Player; -use pocketmine\utils\AssumptionFailedError; use pocketmine\utils\TextFormat as TF; use xenialdan\MagicWE2\API; use xenialdan\MagicWE2\clipboard\SingleClipboard; @@ -34,12 +33,6 @@ protected function prepare(): void $this->setPermission("we.command.clipboard.paste"); } - /** - * @param CommandSender $sender - * @param string $aliasUsed - * @param mixed[] $args - * @throws AssumptionFailedError - */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { $lang = Loader::getInstance()->getLanguage(); diff --git a/src/xenialdan/MagicWE2/commands/clipboard/RotateCommand.php b/src/xenialdan/MagicWE2/commands/clipboard/RotateCommand.php index e0c0461d..23612a3d 100644 --- a/src/xenialdan/MagicWE2/commands/clipboard/RotateCommand.php +++ b/src/xenialdan/MagicWE2/commands/clipboard/RotateCommand.php @@ -36,11 +36,6 @@ protected function prepare(): void //$this->setUsage("//rotate "); } - /** - * @param CommandSender $sender - * @param string $aliasUsed - * @param mixed[] $args - */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { $lang = Loader::getInstance()->getLanguage(); diff --git a/src/xenialdan/MagicWE2/commands/debug/GenerateCommandsMDCommand.php b/src/xenialdan/MagicWE2/commands/debug/GenerateCommandsMDCommand.php index 8c558290..60d26f18 100644 --- a/src/xenialdan/MagicWE2/commands/debug/GenerateCommandsMDCommand.php +++ b/src/xenialdan/MagicWE2/commands/debug/GenerateCommandsMDCommand.php @@ -15,7 +15,6 @@ use function count; use function file_put_contents; use function implode; -use function strpos; use function substr; use const LOCK_EX; @@ -31,18 +30,13 @@ protected function prepare(): void $this->setPermission("we.command.debug"); } - /** - * @param CommandSender $sender - * @param string $aliasUsed - * @param mixed[] $args - */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { $lang = Loader::getInstance()->getLanguage(); try { $cmds = []; foreach (array_filter(Loader::getInstance()->getServer()->getCommandMap()->getCommands(), static function (Command $command) use ($sender) { - return strpos($command->getName(), "/") !== false; + return str_contains($command->getName(), "/"); }) as $cmd) { /** @var Command $cmd */ $cmds[$cmd->getName()] = $cmd; diff --git a/src/xenialdan/MagicWE2/commands/debug/PlaceAllBlockstatesCommand.php b/src/xenialdan/MagicWE2/commands/debug/PlaceAllBlockstatesCommand.php index 8ae0ce2e..e449b1b4 100644 --- a/src/xenialdan/MagicWE2/commands/debug/PlaceAllBlockstatesCommand.php +++ b/src/xenialdan/MagicWE2/commands/debug/PlaceAllBlockstatesCommand.php @@ -26,11 +26,6 @@ protected function prepare(): void $this->setPermission("we.command.debug"); } - /** - * @param CommandSender $sender - * @param string $aliasUsed - * @param mixed[] $args - */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { $lang = Loader::getInstance()->getLanguage(); diff --git a/src/xenialdan/MagicWE2/commands/debug/TestAPICommand.php b/src/xenialdan/MagicWE2/commands/debug/TestAPICommand.php index 0ad1ade4..598580a9 100644 --- a/src/xenialdan/MagicWE2/commands/debug/TestAPICommand.php +++ b/src/xenialdan/MagicWE2/commands/debug/TestAPICommand.php @@ -31,11 +31,6 @@ protected function prepare(): void $this->setPermission("we.command.debug"); } - /** - * @param CommandSender $sender - * @param string $aliasUsed - * @param mixed[] $args - */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { $lang = Loader::getInstance()->getLanguage(); diff --git a/src/xenialdan/MagicWE2/commands/generation/CylinderCommand.php b/src/xenialdan/MagicWE2/commands/generation/CylinderCommand.php index 651c46ff..996865b6 100644 --- a/src/xenialdan/MagicWE2/commands/generation/CylinderCommand.php +++ b/src/xenialdan/MagicWE2/commands/generation/CylinderCommand.php @@ -37,11 +37,6 @@ protected function prepare(): void $this->setPermission("we.command.generation.cyl"); } - /** - * @param CommandSender $sender - * @param string $aliasUsed - * @param mixed[] $args - */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { $lang = Loader::getInstance()->getLanguage(); diff --git a/src/xenialdan/MagicWE2/commands/history/ClearhistoryCommand.php b/src/xenialdan/MagicWE2/commands/history/ClearhistoryCommand.php index 6fd92d1e..628d9532 100644 --- a/src/xenialdan/MagicWE2/commands/history/ClearhistoryCommand.php +++ b/src/xenialdan/MagicWE2/commands/history/ClearhistoryCommand.php @@ -27,11 +27,6 @@ protected function prepare(): void $this->setPermission("we.command.history.clear"); } - /** - * @param CommandSender $sender - * @param string $aliasUsed - * @param mixed[] $args - */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { $lang = Loader::getInstance()->getLanguage(); diff --git a/src/xenialdan/MagicWE2/commands/history/RedoCommand.php b/src/xenialdan/MagicWE2/commands/history/RedoCommand.php index 937e5efd..d9760c1d 100644 --- a/src/xenialdan/MagicWE2/commands/history/RedoCommand.php +++ b/src/xenialdan/MagicWE2/commands/history/RedoCommand.php @@ -27,11 +27,6 @@ protected function prepare(): void $this->setPermission("we.command.history.redo"); } - /** - * @param CommandSender $sender - * @param string $aliasUsed - * @param mixed[] $args - */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { $lang = Loader::getInstance()->getLanguage(); diff --git a/src/xenialdan/MagicWE2/commands/history/UndoCommand.php b/src/xenialdan/MagicWE2/commands/history/UndoCommand.php index da8476dc..155b622a 100644 --- a/src/xenialdan/MagicWE2/commands/history/UndoCommand.php +++ b/src/xenialdan/MagicWE2/commands/history/UndoCommand.php @@ -27,11 +27,6 @@ protected function prepare(): void $this->setPermission("we.command.history.undo"); } - /** - * @param CommandSender $sender - * @param string $aliasUsed - * @param mixed[] $args - */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { $lang = Loader::getInstance()->getLanguage(); diff --git a/src/xenialdan/MagicWE2/commands/palette/PaletteCommand.php b/src/xenialdan/MagicWE2/commands/palette/PaletteCommand.php index ccea1a35..6fdb4149 100644 --- a/src/xenialdan/MagicWE2/commands/palette/PaletteCommand.php +++ b/src/xenialdan/MagicWE2/commands/palette/PaletteCommand.php @@ -7,17 +7,17 @@ use CortexPE\Commando\BaseCommand; use Exception; use InvalidArgumentException; +use jojoe77777\FormAPI\SimpleForm; use muqsit\invmenu\InvMenu; use muqsit\invmenu\transaction\InvMenuTransaction; use muqsit\invmenu\transaction\InvMenuTransactionResult; +use muqsit\invmenu\type\InvMenuTypeIds; use pocketmine\block\Block; use pocketmine\block\BlockLegacyIds; use pocketmine\command\CommandSender; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; use Ramsey\Uuid\Uuid; -use xenialdan\customui\elements\Button; -use xenialdan\customui\windows\SimpleForm; use xenialdan\MagicWE2\exception\PaletteException; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\BlockPalette; @@ -39,11 +39,6 @@ protected function prepare(): void $this->setPermission("we.command.palette"); } - /** - * @param CommandSender $sender - * @param string $aliasUsed - * @param mixed[] $args - */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { $lang = Loader::getInstance()->getLanguage(); @@ -63,18 +58,12 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo if (!$session instanceof UserSession) { throw new SessionException($lang->translateString('error.nosession', [Loader::getInstance()->getName()])); } - $form = new SimpleForm(Loader::PREFIX_FORM . TF::BOLD . TF::DARK_PURPLE . $lang->translateString('ui.palette.title'), $lang->translateString('ui.palette.content')); - $form->addButton(new Button($lang->translateString('ui.palette.fromhotbar'))); - $form->addButton(new Button($lang->translateString('ui.palette.frominventory'))); - $form->addButton(new Button($lang->translateString('ui.palette.fromselection'))); - $form->addButton(new Button($lang->translateString('ui.palette.get'))); - $form->addButton(new Button($lang->translateString('ui.palette.modify'))); - $form->setCallable(function (Player $player, $data) use ($lang, $session) { + $form = (new SimpleForm(function (Player $player, $data) use ($lang, $session) { try { switch ($data) { case $lang->translateString('ui.palette.get'): { - $menu = InvMenu::create(InvMenu::TYPE_DOUBLE_CHEST); + $menu = InvMenu::create(InvMenuTypeIds::TYPE_DOUBLE_CHEST); foreach ($session->getPalettes()->getAll() as $id => $palette) { $menu->getInventory()->addItem($palette->toItem($id)); } @@ -123,7 +112,7 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo } case $lang->translateString('ui.palette.modify'): { - $menu = InvMenu::create(InvMenu::TYPE_DOUBLE_CHEST); + $menu = InvMenu::create(InvMenuTypeIds::TYPE_DOUBLE_CHEST); foreach ($session->getPalettes()->getAll() as $id => $palette) { $menu->getInventory()->addItem($palette->toItem($id)); } @@ -136,11 +125,11 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo $inv_transaction = $transaction->getTransaction(); try { $palette = $session->getPalettes()->getPaletteFromItem($itemClicked); + var_dump($player, $itemClicked, $itemClickedWith, $action, $inv_transaction, $itemClicked->getLore(), $palette); } catch (PaletteException $e) { $session->sendMessage($e->getMessage()); Loader::getInstance()->getLogger()->logException($e); } - var_dump($player, $itemClicked, $itemClickedWith, $action, $inv_transaction, $itemClicked->getLore(), $palette); return $transaction->continue(); }); $menu->send($player, "Select a palette to modify"); @@ -152,7 +141,14 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo $session->sendMessage(TF::RED . $lang->translateString('error')); $session->sendMessage(TF::RED . $error->getMessage()); } - }); + })) + ->setTitle(Loader::PREFIX_FORM . TF::BOLD . TF::DARK_PURPLE . $lang->translateString('ui.palette.title')) + ->setContent($lang->translateString('ui.palette.content')) + ->addButton($lang->translateString('ui.palette.fromhotbar')) + ->addButton($lang->translateString('ui.palette.frominventory')) + ->addButton($lang->translateString('ui.palette.fromselection')) + ->addButton($lang->translateString('ui.palette.get')) + ->addButton($lang->translateString('ui.palette.modify')); $sender->sendForm($form); } catch (Exception $error) { $sender->sendMessage(Loader::PREFIX . TF::RED . $lang->translateString('error.command-error')); diff --git a/src/xenialdan/MagicWE2/commands/region/OverlayCommand.php b/src/xenialdan/MagicWE2/commands/region/OverlayCommand.php index a8069582..1d0ec46d 100644 --- a/src/xenialdan/MagicWE2/commands/region/OverlayCommand.php +++ b/src/xenialdan/MagicWE2/commands/region/OverlayCommand.php @@ -31,11 +31,6 @@ protected function prepare(): void $this->setPermission("we.command.region.overlay"); } - /** - * @param CommandSender $sender - * @param string $aliasUsed - * @param mixed[] $args - */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { $lang = Loader::getInstance()->getLanguage(); diff --git a/src/xenialdan/MagicWE2/commands/region/ReplaceCommand.php b/src/xenialdan/MagicWE2/commands/region/ReplaceCommand.php index bac9bf73..9f4a9e7f 100644 --- a/src/xenialdan/MagicWE2/commands/region/ReplaceCommand.php +++ b/src/xenialdan/MagicWE2/commands/region/ReplaceCommand.php @@ -35,11 +35,6 @@ protected function prepare(): void $this->setPermission("we.command.region.replace"); } - /** - * @param CommandSender $sender - * @param string $aliasUsed - * @param mixed[] $args - */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { $lang = Loader::getInstance()->getLanguage(); diff --git a/src/xenialdan/MagicWE2/commands/region/SetCommand.php b/src/xenialdan/MagicWE2/commands/region/SetCommand.php index bca8b276..94e8a43d 100644 --- a/src/xenialdan/MagicWE2/commands/region/SetCommand.php +++ b/src/xenialdan/MagicWE2/commands/region/SetCommand.php @@ -34,11 +34,6 @@ protected function prepare(): void $this->setPermission("we.command.region.set"); } - /** - * @param CommandSender $sender - * @param string $aliasUsed - * @param mixed[] $args - */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { $lang = Loader::getInstance()->getLanguage(); diff --git a/src/xenialdan/MagicWE2/commands/selection/ChunkCommand.php b/src/xenialdan/MagicWE2/commands/selection/ChunkCommand.php index 7aac45f6..2f3d77ee 100644 --- a/src/xenialdan/MagicWE2/commands/selection/ChunkCommand.php +++ b/src/xenialdan/MagicWE2/commands/selection/ChunkCommand.php @@ -32,11 +32,6 @@ protected function prepare(): void $this->setPermission("we.command.selection.chunk"); } - /** - * @param CommandSender $sender - * @param string $aliasUsed - * @param mixed[] $args - */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { $lang = Loader::getInstance()->getLanguage(); diff --git a/src/xenialdan/MagicWE2/commands/selection/HPos1Command.php b/src/xenialdan/MagicWE2/commands/selection/HPos1Command.php index cfe2d435..4140569a 100644 --- a/src/xenialdan/MagicWE2/commands/selection/HPos1Command.php +++ b/src/xenialdan/MagicWE2/commands/selection/HPos1Command.php @@ -29,11 +29,6 @@ protected function prepare(): void $this->setPermission("we.command.selection.hpos"); } - /** - * @param CommandSender $sender - * @param string $aliasUsed - * @param mixed[] $args - */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { $lang = Loader::getInstance()->getLanguage(); diff --git a/src/xenialdan/MagicWE2/commands/selection/HPos2Command.php b/src/xenialdan/MagicWE2/commands/selection/HPos2Command.php index e103ac1b..0c7286d3 100644 --- a/src/xenialdan/MagicWE2/commands/selection/HPos2Command.php +++ b/src/xenialdan/MagicWE2/commands/selection/HPos2Command.php @@ -29,11 +29,6 @@ protected function prepare(): void $this->setPermission("we.command.selection.hpos"); } - /** - * @param CommandSender $sender - * @param string $aliasUsed - * @param mixed[] $args - */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { $lang = Loader::getInstance()->getLanguage(); diff --git a/src/xenialdan/MagicWE2/commands/selection/Pos1Command.php b/src/xenialdan/MagicWE2/commands/selection/Pos1Command.php index b95a1bef..180f1b56 100644 --- a/src/xenialdan/MagicWE2/commands/selection/Pos1Command.php +++ b/src/xenialdan/MagicWE2/commands/selection/Pos1Command.php @@ -29,11 +29,6 @@ protected function prepare(): void $this->setPermission("we.command.selection.pos"); } - /** - * @param CommandSender $sender - * @param string $aliasUsed - * @param mixed[] $args - */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { $lang = Loader::getInstance()->getLanguage(); diff --git a/src/xenialdan/MagicWE2/commands/selection/Pos2Command.php b/src/xenialdan/MagicWE2/commands/selection/Pos2Command.php index d3e2d781..01a4e0dc 100644 --- a/src/xenialdan/MagicWE2/commands/selection/Pos2Command.php +++ b/src/xenialdan/MagicWE2/commands/selection/Pos2Command.php @@ -29,11 +29,6 @@ protected function prepare(): void $this->setPermission("we.command.selection.pos"); } - /** - * @param CommandSender $sender - * @param string $aliasUsed - * @param mixed[] $args - */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { $lang = Loader::getInstance()->getLanguage(); diff --git a/src/xenialdan/MagicWE2/commands/selection/info/CountCommand.php b/src/xenialdan/MagicWE2/commands/selection/info/CountCommand.php index ba220907..4df91ceb 100644 --- a/src/xenialdan/MagicWE2/commands/selection/info/CountCommand.php +++ b/src/xenialdan/MagicWE2/commands/selection/info/CountCommand.php @@ -37,11 +37,6 @@ protected function prepare(): void $this->setPermission("we.command.selection.info.count"); } - /** - * @param CommandSender $sender - * @param string $aliasUsed - * @param mixed[] $args - */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { $lang = Loader::getInstance()->getLanguage(); @@ -57,9 +52,7 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo } /** @var Player $sender */ try { - if (isset($args["blocks"])) { - $filterBlocks = $args["blocks"]; - } else $filterBlocks = BlockPalette::CREATE(); + $filterBlocks = $args["blocks"] ?? BlockPalette::CREATE(); $session = SessionHelper::getUserSession($sender); if (is_null($session)) { throw new SessionException($lang->translateString('error.nosession', [Loader::getInstance()->getName()])); diff --git a/src/xenialdan/MagicWE2/commands/selection/info/ListChunksCommand.php b/src/xenialdan/MagicWE2/commands/selection/info/ListChunksCommand.php index c5de7b0d..97665959 100644 --- a/src/xenialdan/MagicWE2/commands/selection/info/ListChunksCommand.php +++ b/src/xenialdan/MagicWE2/commands/selection/info/ListChunksCommand.php @@ -29,11 +29,6 @@ protected function prepare(): void $this->setPermission("we.command.selection.info.listchunks"); } - /** - * @param CommandSender $sender - * @param string $aliasUsed - * @param mixed[] $args - */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { $lang = Loader::getInstance()->getLanguage(); @@ -75,7 +70,7 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo $biomecount = count($biomes); $biomes = implode(", ", $biomes); World::getXZ($chunkHash, $cx, $cz); - $session->sendMessage(TF::AQUA . "ID: {$chunkHash} | X: {$cx} Z: {$cz} | Subchunks: {$chunk->getHeight()} | Biomes: ($biomecount) $biomes"); + $session->sendMessage(TF::AQUA . "ID: $chunkHash | X: $cx Z: $cz | Subchunks: {$chunk->getHeight()} | Biomes: ($biomecount) $biomes"); } } catch (Exception $error) { $sender->sendMessage(Loader::PREFIX . TF::RED . $lang->translateString('error.command-error')); diff --git a/src/xenialdan/MagicWE2/commands/selection/info/SizeCommand.php b/src/xenialdan/MagicWE2/commands/selection/info/SizeCommand.php index 4c1e0b04..6bdce165 100644 --- a/src/xenialdan/MagicWE2/commands/selection/info/SizeCommand.php +++ b/src/xenialdan/MagicWE2/commands/selection/info/SizeCommand.php @@ -27,11 +27,6 @@ protected function prepare(): void $this->setPermission("we.command.selection.info.size"); } - /** - * @param CommandSender $sender - * @param string $aliasUsed - * @param mixed[] $args - */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { $lang = Loader::getInstance()->getLanguage(); diff --git a/src/xenialdan/MagicWE2/commands/tool/DebugCommand.php b/src/xenialdan/MagicWE2/commands/tool/DebugCommand.php index bd92bcba..70c2c41b 100644 --- a/src/xenialdan/MagicWE2/commands/tool/DebugCommand.php +++ b/src/xenialdan/MagicWE2/commands/tool/DebugCommand.php @@ -31,11 +31,6 @@ protected function prepare(): void $this->setPermission("we.command.tool.debug"); } - /** - * @param CommandSender $sender - * @param string $aliasUsed - * @param mixed[] $args - */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { $lang = Loader::getInstance()->getLanguage(); diff --git a/src/xenialdan/MagicWE2/commands/tool/FloodCommand.php b/src/xenialdan/MagicWE2/commands/tool/FloodCommand.php index c830e6f2..d46c98cd 100644 --- a/src/xenialdan/MagicWE2/commands/tool/FloodCommand.php +++ b/src/xenialdan/MagicWE2/commands/tool/FloodCommand.php @@ -21,11 +21,6 @@ protected function prepare(): void $this->setPermission("we.command.tool.floodfill"); } - /** - * @param CommandSender $sender - * @param string $aliasUsed - * @param mixed[] $args - */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { $sender->sendMessage(TF::RED . "TEMPORARILY DISABLED!"); diff --git a/src/xenialdan/MagicWE2/commands/tool/ToggledebugCommand.php b/src/xenialdan/MagicWE2/commands/tool/ToggledebugCommand.php index ddfa6c8b..da327a27 100644 --- a/src/xenialdan/MagicWE2/commands/tool/ToggledebugCommand.php +++ b/src/xenialdan/MagicWE2/commands/tool/ToggledebugCommand.php @@ -25,11 +25,6 @@ protected function prepare(): void $this->setPermission("we.command.tool.toggledebug"); } - /** - * @param CommandSender $sender - * @param string $aliasUsed - * @param mixed[] $args - */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { $lang = Loader::getInstance()->getLanguage(); diff --git a/src/xenialdan/MagicWE2/commands/tool/TogglewandCommand.php b/src/xenialdan/MagicWE2/commands/tool/TogglewandCommand.php index 053e18d9..55a5c984 100644 --- a/src/xenialdan/MagicWE2/commands/tool/TogglewandCommand.php +++ b/src/xenialdan/MagicWE2/commands/tool/TogglewandCommand.php @@ -25,11 +25,6 @@ protected function prepare(): void $this->setPermission("we.command.tool.togglewand"); } - /** - * @param CommandSender $sender - * @param string $aliasUsed - * @param mixed[] $args - */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { $lang = Loader::getInstance()->getLanguage(); diff --git a/src/xenialdan/MagicWE2/commands/tool/WandCommand.php b/src/xenialdan/MagicWE2/commands/tool/WandCommand.php index d8d92a5e..2bd4d8c3 100644 --- a/src/xenialdan/MagicWE2/commands/tool/WandCommand.php +++ b/src/xenialdan/MagicWE2/commands/tool/WandCommand.php @@ -32,11 +32,6 @@ protected function prepare(): void $this->setPermission("we.command.tool.wand"); } - /** - * @param CommandSender $sender - * @param string $aliasUsed - * @param mixed[] $args - */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { $lang = Loader::getInstance()->getLanguage(); diff --git a/src/xenialdan/MagicWE2/commands/utility/CalculateCommand.php b/src/xenialdan/MagicWE2/commands/utility/CalculateCommand.php index d8687873..a30c8228 100644 --- a/src/xenialdan/MagicWE2/commands/utility/CalculateCommand.php +++ b/src/xenialdan/MagicWE2/commands/utility/CalculateCommand.php @@ -32,11 +32,6 @@ protected function prepare(): void $this->setPermission("we.command.utility.calculate"); } - /** - * @param CommandSender $sender - * @param string $aliasUsed - * @param mixed[] $args - */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { $lang = Loader::getInstance()->getLanguage(); @@ -47,10 +42,10 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo } } try { - $sender->sendMessage((string)$args["expression"] . " = " . API::evalAsMath((string)$args["expression"])); + $sender->sendMessage($args["expression"] . " = " . API::evalAsMath((string)$args["expression"])); } catch (CalculationException $error) { $sender->sendMessage(Loader::PREFIX . TF::RED . $error->getMessage()); - $sender->sendMessage(Loader::PREFIX . TF::RED . (string)$args["expression"]); + $sender->sendMessage(Loader::PREFIX . TF::RED . $args["expression"]); } catch (Exception $error) { $sender->sendMessage(Loader::PREFIX . TF::RED . $lang->translateString('error.command-error')); $sender->sendMessage(Loader::PREFIX . TF::RED . $error->getMessage()); diff --git a/src/xenialdan/MagicWE2/commands/utility/ToggleSidebarCommand.php b/src/xenialdan/MagicWE2/commands/utility/ToggleSidebarCommand.php index 739e094f..740a4497 100644 --- a/src/xenialdan/MagicWE2/commands/utility/ToggleSidebarCommand.php +++ b/src/xenialdan/MagicWE2/commands/utility/ToggleSidebarCommand.php @@ -25,11 +25,6 @@ protected function prepare(): void $this->setPermission("we.command.utility.togglesidebar"); } - /** - * @param CommandSender $sender - * @param string $aliasUsed - * @param mixed[] $args - */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { $lang = Loader::getInstance()->getLanguage(); diff --git a/src/xenialdan/MagicWE2/commands/utility/ToggleWailaCommand.php b/src/xenialdan/MagicWE2/commands/utility/ToggleWailaCommand.php index 691ea30f..4f756034 100644 --- a/src/xenialdan/MagicWE2/commands/utility/ToggleWailaCommand.php +++ b/src/xenialdan/MagicWE2/commands/utility/ToggleWailaCommand.php @@ -25,11 +25,6 @@ protected function prepare(): void $this->setPermission("we.command.utility.togglewaila"); } - /** - * @param CommandSender $sender - * @param string $aliasUsed - * @param mixed[] $args - */ public function onRun(CommandSender $sender, string $aliasUsed, array $args): void { $lang = Loader::getInstance()->getLanguage(); diff --git a/src/xenialdan/MagicWE2/helper/BlockPalette.php b/src/xenialdan/MagicWE2/helper/BlockPalette.php index 8005daf3..1800080f 100644 --- a/src/xenialdan/MagicWE2/helper/BlockPalette.php +++ b/src/xenialdan/MagicWE2/helper/BlockPalette.php @@ -163,7 +163,7 @@ public static function fromStringArray(string $blocks): array $e = []; foreach (json_decode($blocks, true, 512, JSON_THROW_ON_ERROR) as $query) { $q = new BlockQuery($query, null, null, null, null); - $q->parse(true);//TODO the weight might not be parsed + $q->parse();//TODO the weight might not be parsed $e[] = $q; } return $e; diff --git a/src/xenialdan/MagicWE2/helper/BlockStatesEntry.php b/src/xenialdan/MagicWE2/helper/BlockStatesEntry.php index 7abe8de8..56064a3b 100644 --- a/src/xenialdan/MagicWE2/helper/BlockStatesEntry.php +++ b/src/xenialdan/MagicWE2/helper/BlockStatesEntry.php @@ -94,7 +94,7 @@ public function rotate(int $amount): BlockStatesEntry $idMapName = str_replace("minecraft:", "", BlockStatesParser::getBlockIdMapName($block)); $key = $idMapName . ":" . $block->getMeta(); $blockstateParser = BlockStatesParser::getInstance(); - if (strpos($idMapName, "_door") !== false) { + if (str_contains($idMapName, "_door")) { $fromMap = $blockstateParser::getDoorRotationFlipMap()[$block->getMeta()] ?? null; } else { $fromMap = $blockstateParser::getRotationFlipMap()[$key] ?? null; @@ -129,7 +129,7 @@ public function rotate(int $amount): BlockStatesEntry } $clone->blockStates = $bsCompound; $clone->blockFull = TextFormat::clean($blockstateParser::printStates($clone, false)); - if (strpos($idMapName, "_door") !== false) { + if (str_contains($idMapName, "_door")) { $clone->block = $clone->toBlock();//TODO check } else $clone->block = null; diff --git a/src/xenialdan/MagicWE2/helper/BlockStatesParser.php b/src/xenialdan/MagicWE2/helper/BlockStatesParser.php index 36c2eb7e..ee6cb6b6 100644 --- a/src/xenialdan/MagicWE2/helper/BlockStatesParser.php +++ b/src/xenialdan/MagicWE2/helper/BlockStatesParser.php @@ -17,6 +17,7 @@ use pocketmine\data\bedrock\LegacyBlockIdToStringIdMap; use pocketmine\item\LegacyStringToItemParser; use pocketmine\item\LegacyStringToItemParserException; +use pocketmine\item\StringToItemParser; use pocketmine\math\Facing; use pocketmine\nbt\tag\ByteTag; use pocketmine\nbt\tag\CompoundTag; @@ -209,11 +210,11 @@ protected static function getDefaultStates(string $blockIdentifier): CompoundTag */ public static function fromString(BlockQuery $query): Block { - $namespacedSelectedBlockName = strpos($query->blockId, "minecraft:") === false ? "minecraft:" . $query->blockId : $query->blockId; + $namespacedSelectedBlockName = !str_contains($query->blockId, "minecraft:") ? "minecraft:" . $query->blockId : $query->blockId; $selectedBlockName = strtolower(str_replace("minecraft:", "", $namespacedSelectedBlockName));//TODO try to keep namespace "minecraft:" to support custom blocks - $legacyStringToItemParser = LegacyStringToItemParser::getInstance(); - $block = $legacyStringToItemParser->parse($selectedBlockName)->getBlock(); + /** @noinspection PhpDeprecationInspection */ + $block = StringToItemParser::getInstance()->parse($selectedBlockName)?->getBlock() ?? LegacyStringToItemParser::getInstance()->parse($selectedBlockName)?->getBlock(); //no states, just block if (!$query->hasBlockStates()) { $query->blockFullId = $block->getFullId(); @@ -238,9 +239,9 @@ public static function fromString(BlockQuery $query): Block } } foreach ($statesExploded as $stateKeyValuePair) { - if (strpos($stateKeyValuePair, "=") === false) continue; + if (!str_contains($stateKeyValuePair, "=")) continue; [$stateName, $value] = explode("=", $stateKeyValuePair); - $value = strtolower(trim((string)$value)); + $value = strtolower(trim($value)); if ($value === '') { throw new InvalidBlockStateException("Empty value for state $stateName"); } @@ -268,7 +269,7 @@ public static function fromString(BlockQuery $query): Block } //return found block(s) //doors.. special blocks annoying -.- - if (strpos($query->blockId, "_door") !== false) { + if (str_contains($query->blockId, "_door")) { $block = self::buildDoor($query, $finalStatesList); $query->blockFullId = $block->getFullId(); return $block; @@ -324,7 +325,7 @@ public static function getStateByCompound(CompoundTag $compoundTag): ?BlockState throw new InvalidArgumentException("Could not find default block states for $namespacedSelectedBlockName"); } - if (strpos($namespacedSelectedBlockName, "_door") !== false) { + if (str_contains($namespacedSelectedBlockName, "_door")) { $door = self::buildDoor(BlockPalette::fromString($namespacedSelectedBlockName)->randomBlockQueries->generate(1)->current(), $states); //return self::getStateByBlock($door); return new BlockStatesEntry($namespacedSelectedBlockName, $states, $door); @@ -648,7 +649,7 @@ private static function generateBlockStateAliasMapJson(): void "end_portal", ]; foreach ($fullReplace as $stateAlias => $setTo) - if (strpos($alias, $stateAlias) !== false) { + if (str_contains($alias, $stateAlias)) { $alias = $setTo; } foreach ($partReplace as $replace) @@ -690,7 +691,7 @@ public static function generatePossibleStatesJson(): void } if (!in_array($state->getValue(), $all[$stateName], true)) { $all[(string)$stateName][] = $state->getValue(); - if (strpos($stateName, "_bit") !== false) { + if (str_contains($stateName, "_bit")) { var_dump("_bit"); } else { var_dump("no _bit"); @@ -711,7 +712,7 @@ public static function generatePossibleStatesJson(): void * @param string $property * @return mixed */ - public static function &readAnyValue(object $object, string $property) + public static function &readAnyValue(object $object, string $property): mixed { $invoke = Closure::bind(function & () use ($property) { return $this->$property; diff --git a/src/xenialdan/MagicWE2/helper/SessionHelper.php b/src/xenialdan/MagicWE2/helper/SessionHelper.php index 79b3955c..3564ab07 100644 --- a/src/xenialdan/MagicWE2/helper/SessionHelper.php +++ b/src/xenialdan/MagicWE2/helper/SessionHelper.php @@ -187,7 +187,7 @@ public static function loadUserSession(Player $player): ?UserSession if ($contents === false) return null; $data = json_decode($contents, true, 512, JSON_THROW_ON_ERROR); if (is_null($data) || json_last_error() !== JSON_ERROR_NONE) { - Loader::getInstance()->getLogger()->error("Could not load user session from json file {$path}: " . json_last_error_msg()); + Loader::getInstance()->getLogger()->error("Could not load user session from json file $path: " . json_last_error_msg()); #unlink($path);//TODO make safe return null; } diff --git a/src/xenialdan/MagicWE2/helper/WeightedRandom.php b/src/xenialdan/MagicWE2/helper/WeightedRandom.php index 4f3610a9..f95fe1dd 100644 --- a/src/xenialdan/MagicWE2/helper/WeightedRandom.php +++ b/src/xenialdan/MagicWE2/helper/WeightedRandom.php @@ -22,14 +22,14 @@ class WeightedRandom /** @var Random */ private Random $random; - /** @var mixed[] */ + /** @var array */ protected array $indexes = []; /** * @param mixed $value * @param float $weight */ - public function add($value, float $weight): void + public function add(mixed $value, float $weight): void { $this->probabilities[] = $weight; $this->indexes[] = $value; diff --git a/src/xenialdan/MagicWE2/selection/Selection.php b/src/xenialdan/MagicWE2/selection/Selection.php index 79dbb84c..27d7f39c 100644 --- a/src/xenialdan/MagicWE2/selection/Selection.php +++ b/src/xenialdan/MagicWE2/selection/Selection.php @@ -268,7 +268,7 @@ public function getUUID(): UuidInterface * @return string the string representation of the object or null * @since 5.1.0 */ - public function serialize() + public function serialize(): string { return serialize([ $this->worldId, @@ -305,11 +305,11 @@ public function unserialize($data) /** * Specify data which should be serialized to JSON * @link http://php.net/manual/en/jsonserializable.jsonserialize.php - * @return mixed data which can be serialized by json_encode, + * @return array data which can be serialized by json_encode, * which is a value of any type other than a resource. * @since 5.4.0 */ - public function jsonSerialize() + public function jsonSerialize(): array { $arr = (array)$this; if ($this->shape !== null) diff --git a/src/xenialdan/MagicWE2/selection/shape/Shape.php b/src/xenialdan/MagicWE2/selection/shape/Shape.php index ab9d029f..2e83dc39 100644 --- a/src/xenialdan/MagicWE2/selection/shape/Shape.php +++ b/src/xenialdan/MagicWE2/selection/shape/Shape.php @@ -49,7 +49,7 @@ public static function getChunkManager(array $chunks): AsyncChunkManager * @param mixed $manager * @throws InvalidArgumentException */ - public function validateChunkManager($manager): void + public function validateChunkManager(mixed $manager): void { if (!$manager instanceof World && !$manager instanceof AsyncChunkManager) throw new InvalidArgumentException(get_class($manager) . " is not an instance of World or AsyncChunkManager"); } @@ -114,7 +114,7 @@ public function getShapeProperties(): array * @return string the string representation of the object or null * @since 5.1.0 */ - public function serialize() + public function serialize(): string { return serialize((array)$this); } diff --git a/src/xenialdan/MagicWE2/session/Session.php b/src/xenialdan/MagicWE2/session/Session.php index d1c31a3b..4f50881d 100644 --- a/src/xenialdan/MagicWE2/session/Session.php +++ b/src/xenialdan/MagicWE2/session/Session.php @@ -64,8 +64,7 @@ public function &addSelection(Selection $selection): ?Selection { $this->selections[$selection->getUUID()->toString()] = $selection; $this->setLatestSelectionUUID($selection->getUUID()); - $selection = $this->getLatestSelection(); - return $selection; + return $this->getLatestSelection(); } /** @@ -113,7 +112,7 @@ public function getSelections(): array /** * @param mixed $selections */ - public function setSelections($selections): void + public function setSelections(mixed $selections): void { $this->selections = $selections; } diff --git a/src/xenialdan/MagicWE2/session/UserSession.php b/src/xenialdan/MagicWE2/session/UserSession.php index ec64e225..2c8e1dca 100644 --- a/src/xenialdan/MagicWE2/session/UserSession.php +++ b/src/xenialdan/MagicWE2/session/UserSession.php @@ -268,11 +268,11 @@ public function sendMessage(string $message): void /** * Specify data which should be serialized to JSON * @link http://php.net/manual/en/jsonserializable.jsonserialize.php - * @return mixed data which can be serialized by json_encode, + * @return array data which can be serialized by json_encode, * which is a value of any type other than a resource. * @since 5.4.0 */ - public function jsonSerialize() + public function jsonSerialize(): array { return [ "uuid" => $this->getUUID()->toString(), diff --git a/src/xenialdan/MagicWE2/session/data/Asset.php b/src/xenialdan/MagicWE2/session/data/Asset.php index def4dcca..1c099644 100644 --- a/src/xenialdan/MagicWE2/session/data/Asset.php +++ b/src/xenialdan/MagicWE2/session/data/Asset.php @@ -7,6 +7,7 @@ use BlockHorizons\libschematic\Schematic; use Exception; use InvalidArgumentException; +use jojoe77777\FormAPI\CustomForm; use JsonSerializable; use pocketmine\item\enchantment\EnchantmentInstance; use pocketmine\item\Item; @@ -19,7 +20,6 @@ use pocketmine\utils\AssumptionFailedError; use pocketmine\utils\TextFormat as TF; use TypeError; -use xenialdan\customui\windows\CustomForm; use xenialdan\libstructure\format\MCStructure; use xenialdan\MagicWE2\API; use xenialdan\MagicWE2\clipboard\SingleClipboard; @@ -27,6 +27,9 @@ use xenialdan\MagicWE2\helper\SessionHelper; use xenialdan\MagicWE2\Loader; use xenialdan\MagicWE2\session\UserSession; +use function pathinfo; +use function var_dump; +use const PATHINFO_FILENAME; class Asset implements JsonSerializable { @@ -91,7 +94,6 @@ public function getOrigin(): Vector3 public function toItem(bool $renew = false): Item { if ($this->item !== null && !$renew) return $this->item; - /** @noinspection PhpDeprecationInspection */ $item = ItemFactory::getInstance()->get(ItemIds::SCAFFOLDING); $item->addEnchantment(new EnchantmentInstance(Loader::$ench)); try { @@ -216,15 +218,7 @@ public function getSettingForm(bool $new = true, array $errors = []): CustomForm try { // Form //TODO display errors - $form = new CustomForm("Asset settings"); - $form->addInput("Filename", "Filename", $this->filename); - $form->addToggle("Lock asset", $this->locked); - $form->addToggle("Shared asset", $this->shared); - foreach ($this->generateLore() as $value) { - $form->addLabel($value); - } - // Function - $form->setCallable(function (Player $player, $data) /*use ($form, $new)*/ { + $form = (new CustomForm(function (Player $player, $data) /*use ($form, $new)*/ { var_dump(__LINE__, $data); [$filename, $this->locked, $shared] = $data; var_dump($filename, $this->locked ? "true" : "false", $shared ? "true" : "false"); @@ -266,7 +260,14 @@ public function getSettingForm(bool $new = true, array $errors = []): CustomForm $player->sendMessage($ex->getMessage()); Loader::getInstance()->getLogger()->logException($ex); } - }); + })) + ->setTitle("Asset settings") + ->addInput("Filename", "Filename", $this->filename) + ->addToggle("Lock asset", $this->locked) + ->addToggle("Shared asset", $this->shared); + foreach ($this->generateLore() as $value) { + $form->addLabel($value); + } return $form; } catch (Exception $e) { Loader::getInstance()->getLogger()->logException($e); @@ -274,7 +275,7 @@ public function getSettingForm(bool $new = true, array $errors = []): CustomForm } } - public function jsonSerialize() + public function jsonSerialize(): array { return [ 'filename' => $this->filename, diff --git a/src/xenialdan/MagicWE2/task/AsyncActionTask.php b/src/xenialdan/MagicWE2/task/AsyncActionTask.php index ac3c6da1..22e616b0 100644 --- a/src/xenialdan/MagicWE2/task/AsyncActionTask.php +++ b/src/xenialdan/MagicWE2/task/AsyncActionTask.php @@ -111,7 +111,7 @@ public function onRun(): void $resultChunks = $manager->getChunks(); $resultChunks = array_filter($resultChunks, static function (Chunk $chunk) { - return $chunk->isDirty(); + return $chunk->isTerrainDirty(); }); $this->setResult(compact("resultChunks", "oldBlocks", "changed", "messages")); } diff --git a/src/xenialdan/MagicWE2/task/AsyncCopyTask.php b/src/xenialdan/MagicWE2/task/AsyncCopyTask.php index 53196926..f35027b0 100644 --- a/src/xenialdan/MagicWE2/task/AsyncCopyTask.php +++ b/src/xenialdan/MagicWE2/task/AsyncCopyTask.php @@ -123,9 +123,7 @@ public function onCompletion(): void $totalCount = $result["totalCount"]; $session->sendMessage(TF::GREEN . $session->getLanguage()->translateString('task.copy.success', [$this->generateTookString(), $copied, $totalCount])); $session->addClipboard($clipboard); - } catch (SessionException $e) { - Loader::getInstance()->getLogger()->logException($e); - } catch (AssumptionFailedError $e) { + } catch (SessionException | AssumptionFailedError $e) { Loader::getInstance()->getLogger()->logException($e); } } diff --git a/src/xenialdan/MagicWE2/task/AsyncFillTask.php b/src/xenialdan/MagicWE2/task/AsyncFillTask.php index 2feae586..3807172b 100644 --- a/src/xenialdan/MagicWE2/task/AsyncFillTask.php +++ b/src/xenialdan/MagicWE2/task/AsyncFillTask.php @@ -11,6 +11,7 @@ use pocketmine\utils\TextFormat as TF; use pocketmine\world\format\Chunk; use pocketmine\world\format\io\FastChunkSerializer; +use pocketmine\world\Position; use pocketmine\world\World; use Ramsey\Uuid\Uuid; use Ramsey\Uuid\UuidInterface; @@ -90,7 +91,7 @@ public function onRun(): void $resultChunks = $manager->getChunks(); $resultChunks = array_filter($resultChunks, static function (Chunk $chunk) { - return $chunk->isDirty(); + return $chunk->isTerrainDirty(); }); #$this->setResult(compact("resultChunks", "oldBlocks", "changed")); $this->setResult([ @@ -107,7 +108,7 @@ public function onRun(): void * @param null|int $changed * @return Generator * @throws InvalidArgumentException - * @phpstan-return Generator + * @phpstan-return Generator */ private function execute(Selection $selection, AsyncChunkManager $manager, BlockPalette $newBlocks, ?int &$changed): Generator { diff --git a/src/xenialdan/MagicWE2/task/AsyncPasteAssetTask.php b/src/xenialdan/MagicWE2/task/AsyncPasteAssetTask.php index 36e419f2..c74bc9d2 100644 --- a/src/xenialdan/MagicWE2/task/AsyncPasteAssetTask.php +++ b/src/xenialdan/MagicWE2/task/AsyncPasteAssetTask.php @@ -13,6 +13,7 @@ use pocketmine\utils\TextFormat as TF; use pocketmine\world\format\Chunk; use pocketmine\world\format\io\FastChunkSerializer; +use pocketmine\world\Position; use pocketmine\world\World; use Ramsey\Uuid\Uuid; use Ramsey\Uuid\UuidInterface; @@ -91,7 +92,7 @@ public function onRun(): void $resultChunks = $manager->getChunks(); $resultChunks = array_filter($resultChunks, static function (Chunk $chunk) { - return $chunk->isDirty(); + return $chunk->isTerrainDirty(); }); $this->setResult(compact("resultChunks", "oldBlocks", "changed")); } @@ -103,7 +104,7 @@ public function onRun(): void * @return Generator * @throws InvalidArgumentException * @throws OutOfBoundsException - * @phpstan-return Generator + * @phpstan-return Generator */ private function execute(AsyncChunkManager $manager, Asset $asset, ?int &$changed): Generator { diff --git a/src/xenialdan/MagicWE2/task/AsyncPasteTask.php b/src/xenialdan/MagicWE2/task/AsyncPasteTask.php index 9b011b12..77ab93a6 100644 --- a/src/xenialdan/MagicWE2/task/AsyncPasteTask.php +++ b/src/xenialdan/MagicWE2/task/AsyncPasteTask.php @@ -10,6 +10,7 @@ use pocketmine\utils\TextFormat as TF; use pocketmine\world\format\Chunk; use pocketmine\world\format\io\FastChunkSerializer; +use pocketmine\world\Position; use pocketmine\world\World; use Ramsey\Uuid\Uuid; use Ramsey\Uuid\UuidInterface; @@ -81,7 +82,7 @@ public function onRun(): void $resultChunks = $manager->getChunks(); $resultChunks = array_filter($resultChunks, static function (Chunk $chunk) { - return $chunk->isDirty(); + return $chunk->isTerrainDirty(); }); $this->setResult(compact("resultChunks", "oldBlocks", "changed")); } @@ -93,7 +94,7 @@ public function onRun(): void * @param null|int $changed * @return Generator * @throws InvalidArgumentException - * @phpstan-return Generator + * @phpstan-return Generator */ private function execute(Selection $selection, AsyncChunkManager $manager, SingleClipboard $clipboard, ?int &$changed): Generator { diff --git a/src/xenialdan/MagicWE2/task/AsyncReplaceTask.php b/src/xenialdan/MagicWE2/task/AsyncReplaceTask.php index ab927d49..54cf11ef 100644 --- a/src/xenialdan/MagicWE2/task/AsyncReplaceTask.php +++ b/src/xenialdan/MagicWE2/task/AsyncReplaceTask.php @@ -11,6 +11,7 @@ use pocketmine\utils\TextFormat as TF; use pocketmine\world\format\Chunk; use pocketmine\world\format\io\FastChunkSerializer; +use pocketmine\world\Position; use pocketmine\world\World; use Ramsey\Uuid\Uuid; use Ramsey\Uuid\UuidInterface; @@ -83,7 +84,7 @@ public function onRun(): void $resultChunks = $manager->getChunks(); $resultChunks = array_filter($resultChunks, static function (Chunk $chunk) { - return $chunk->isDirty(); + return $chunk->isTerrainDirty(); }); $this->setResult(compact("resultChunks", "oldBlocks", "changed")); } @@ -96,7 +97,7 @@ public function onRun(): void * @param null|int $changed * @return Generator * @throws InvalidArgumentException - * @phpstan-return Generator + * @phpstan-return Generator */ private function execute(Selection $selection, AsyncChunkManager $manager, BlockPalette $replaceBlocks, BlockPalette $newBlocks, ?int &$changed): Generator { diff --git a/src/xenialdan/MagicWE2/task/AsyncRevertTask.php b/src/xenialdan/MagicWE2/task/AsyncRevertTask.php index ad3eff4a..1d80c933 100644 --- a/src/xenialdan/MagicWE2/task/AsyncRevertTask.php +++ b/src/xenialdan/MagicWE2/task/AsyncRevertTask.php @@ -7,6 +7,7 @@ use InvalidArgumentException; use pocketmine\utils\AssumptionFailedError; use pocketmine\utils\TextFormat as TF; +use pocketmine\world\Position; use pocketmine\world\World; use Ramsey\Uuid\Uuid; use Ramsey\Uuid\UuidInterface; @@ -34,7 +35,7 @@ class AsyncRevertTask extends MWEAsyncTask * @param RevertClipboard $clipboard * @param int $type The type of clipboard pasting. */ - public function __construct(UuidInterface $sessionUUID, RevertClipboard $clipboard, $type = self::TYPE_UNDO) + public function __construct(UuidInterface $sessionUUID, RevertClipboard $clipboard, int $type = self::TYPE_UNDO) { $this->sessionUUID = $sessionUUID->toString(); $this->start = microtime(true); @@ -69,7 +70,7 @@ public function onRun(): void * @param RevertClipboard $clipboard * @return Generator * @throws InvalidArgumentException - * @phpstan-return Generator + * @phpstan-return Generator */ private function undoChunks(AsyncChunkManager $manager, RevertClipboard $clipboard): Generator { @@ -91,7 +92,7 @@ private function undoChunks(AsyncChunkManager $manager, RevertClipboard $clipboa * @param RevertClipboard $clipboard * @return Generator * @throws InvalidArgumentException - * @phpstan-return Generator + * @phpstan-return Generator */ private function redoChunks(AsyncChunkManager $manager, RevertClipboard $clipboard): Generator { diff --git a/src/xenialdan/MagicWE2/task/action/CutAction.php b/src/xenialdan/MagicWE2/task/action/CutAction.php index 3e712ccf..f3f8c0bb 100644 --- a/src/xenialdan/MagicWE2/task/action/CutAction.php +++ b/src/xenialdan/MagicWE2/task/action/CutAction.php @@ -54,7 +54,7 @@ public function execute(string $sessionUUID, Selection $selection, AsyncChunkMan $min = $selection->getShape()->getMinVec3(); foreach ($selection->getShape()->getBlocks($manager, $blockFilter) as $block) {//TODO Merged iterator /** @var Block $new */ - $new = $newBlocks->blocks(1)->current();//TODO Merged iterator + $new = $newBlocks->blocks()->current();//TODO Merged iterator if ($new->getId() === $block->getId() && $new->getMeta() === $block->getMeta()) continue;//skip same blocks #$oldBlocks[] = API::setComponents($manager->getBlockAt($block->getPosition()->getFloorX(), $block->getPosition()->getFloorY(), $block->getPosition()->getFloorZ()),$block->x, $block->y, $block->z); $newv3 = $block->getPosition()->subtractVector($min)->floor();//TODO check if only used for clipboard @@ -65,7 +65,7 @@ public function execute(string $sessionUUID, Selection $selection, AsyncChunkMan $changed++; } $i++; - $progress = new Progress($i / $count, "Changed {$changed} blocks out of {$count}"); + $progress = new Progress($i / $count, "Changed $changed blocks out of $count"); if (floor($progress->progress * 100) > floor($lastProgress->progress * 100)) { yield $progress; $lastProgress = $progress; diff --git a/src/xenialdan/MagicWE2/task/action/SetBlockAction.php b/src/xenialdan/MagicWE2/task/action/SetBlockAction.php index 8fe7e6b4..0702382d 100644 --- a/src/xenialdan/MagicWE2/task/action/SetBlockAction.php +++ b/src/xenialdan/MagicWE2/task/action/SetBlockAction.php @@ -47,7 +47,7 @@ public function execute(string $sessionUUID, Selection $selection, AsyncChunkMan $lastProgress = new Progress(0, ""); foreach ($selection->getShape()->getBlocks($manager, $blockFilter) as $block) {//TODO merge iterator /** @var Block $new */ - $new = $newBlocks->blocks(1)->current();//TODO merge iterator + $new = $newBlocks->blocks()->current();//TODO merge iterator if ($new->getId() === $block->getId() && $new->getMeta() === $block->getMeta()) continue;//skip same blocks #$oldBlocks[] = API::setComponents($manager->getBlockAt($block->getPosition()->getFloorX(), $block->getPosition()->getFloorY(), $block->getPosition()->getFloorZ()),$block->x, $block->y, $block->z); $oldBlocksSingleClipboard->addEntry($block->getPosition()->getFloorX(), $block->getPosition()->getFloorY(), $block->getPosition()->getFloorZ(), BlockEntry::fromBlock($block)); @@ -57,7 +57,7 @@ public function execute(string $sessionUUID, Selection $selection, AsyncChunkMan $changed++; } $i++; - $progress = new Progress($i / $count, "Changed {$changed} blocks out of {$count}"); + $progress = new Progress($i / $count, "Changed $changed blocks out of $count"); if (floor($progress->progress * 100) > floor($lastProgress->progress * 100)) { yield $progress; $lastProgress = $progress; diff --git a/src/xenialdan/MagicWE2/task/action/ThawAction.php b/src/xenialdan/MagicWE2/task/action/ThawAction.php index ecb3b0bc..28efa177 100644 --- a/src/xenialdan/MagicWE2/task/action/ThawAction.php +++ b/src/xenialdan/MagicWE2/task/action/ThawAction.php @@ -58,7 +58,7 @@ public function execute(string $sessionUUID, Selection $selection, AsyncChunkMan $changed++; } $i++; - $progress = new Progress($i / $count, "Changed {$changed} blocks out of {$count}"); + $progress = new Progress($i / $count, "Changed $changed blocks out of $count"); if (floor($progress->progress * 100) > floor($lastProgress->progress * 100)) { yield $progress; $lastProgress = $progress; diff --git a/src/xenialdan/MagicWE2/tool/Brush.php b/src/xenialdan/MagicWE2/tool/Brush.php index 50578cf4..a1e7e533 100644 --- a/src/xenialdan/MagicWE2/tool/Brush.php +++ b/src/xenialdan/MagicWE2/tool/Brush.php @@ -6,6 +6,7 @@ use Exception; use InvalidArgumentException; +use jojoe77777\FormAPI\CustomForm; use JsonException; use pocketmine\data\bedrock\BiomeIds; use pocketmine\item\enchantment\EnchantmentInstance; @@ -19,11 +20,6 @@ use Ramsey\Uuid\Uuid; use ReflectionClass; use TypeError; -use xenialdan\customui\elements\Dropdown; -use xenialdan\customui\elements\Input; -use xenialdan\customui\elements\Label; -use xenialdan\customui\elements\Toggle; -use xenialdan\customui\windows\CustomForm; use xenialdan\MagicWE2\API; use xenialdan\MagicWE2\exception\ActionNotFoundException; use xenialdan\MagicWE2\exception\SessionException; @@ -34,6 +30,20 @@ use xenialdan\MagicWE2\selection\shape\ShapeRegistry; use xenialdan\MagicWE2\session\UserSession; use xenialdan\MagicWE2\task\action\ActionRegistry; +use function array_flip; +use function array_intersect_key; +use function array_keys; +use function array_replace; +use function array_search; +use function array_slice; +use function array_walk; +use function gettype; +use function is_bool; +use function is_int; +use function lcfirst; +use function trim; +use function ucfirst; +use function var_dump; class Brush extends WETool { @@ -99,58 +109,20 @@ public function getForm(bool $new = true, array $errors = []): CustomForm return TF::EOL . TF::RED . $value; }, $errors); $brushProperties = $this->properties ?? new BrushProperties(); - $form = new CustomForm("Brush settings"); - // Shape - #$form->addElement(new Label((isset($errors['shape']) ? TF::RED : "") . "Shape" . ($errors['shape'] ?? ""))); - if ($new) { - $dropdownShape = new Dropdown((isset($errors['shape']) ? TF::RED : "") . "Shape" . ($errors['shape'] ?? "")); - foreach (Loader::getShapeRegistry()::getShapes() as $name => $class) { - if ($name === ShapeRegistry::CUSTOM) continue; - $dropdownShape->addOption((string)$name, $class === $brushProperties->shape); - } - $form->addElement($dropdownShape); - } else { - $form->addElement(new Label($brushProperties->getShapeName())); - } - // Action - $dropdownAction = new Dropdown("Action"); - foreach (ActionRegistry::getActions() as $name => $class) { - $dropdownAction->addOption($name, $class === $brushProperties->action); - } - $form->addElement($dropdownAction); - // Name - $form->addElement(new Input("Name", "Name", $new ? "" : $this->getName())); - // Blocks - $form->addElement(new Input((isset($errors['blocks']) ? TF::RED : "") . "Blocks" . ($errors['blocks'] ?? ""), "grass,stone:1", $brushProperties->blocks)); - // Filter - $form->addElement(new Input((isset($errors['filter']) ? TF::RED : "") . "Filter" . ($errors['filter'] ?? ""), "air", $brushProperties->filter)); - // Biome - $dropdownBiome = new Dropdown((isset($errors['biome']) ? TF::RED : "") . "Biome" . ($errors['biome'] ?? "")); - foreach ((new ReflectionClass(BiomeIds::class))->getConstants() as $name => $value) { - if ($value === BiomeIds::HELL) continue; - $dropdownBiome->addOption(BiomeRegistry::getInstance()->getBiome($value)->getName(), $value === $brushProperties->biomeId); - } - $form->addElement($dropdownBiome); - // Hollow - $form->addElement(new Toggle("Hollow", $brushProperties->hollow)); - // Extra properties - if (!$new) { - foreach ($this->getExtradataForm($brushProperties->shape)->getContent() as $element) { - $form->addElement($element); - } - } - // Function - $form->setCallable(function (Player $player, $data) use ($form, $new) { + $form = (new CustomForm(function (Player $player, $data) use ($new) { #var_dump(__LINE__, $data); #$data = array_slice($data, 0, 7); [$shape, $action, $name, $blocks, $filter, $biome, $hollow] = $data; $extraData = []; #var_dump(__LINE__, array_slice($data, 7)); $base = ShapeRegistry::getDefaultShapeProperties(ShapeRegistry::getShape($shape)); + var_dump($base); foreach (array_slice($data, 7, null, true) as $i => $value) { - #var_dump($i, $value, gettype($value), gettype($base[lcfirst($form->getElement($i)->getText())])); - if (is_int($base[lcfirst($form->getElement($i)->getText())])) $value = (int)$value; - $extraData[lcfirst($form->getElement($i)->getText())] = $value;//TODO + var_dump($i, $value, gettype($value), gettype($base[lcfirst($value)]));//TODO IMPLEMENT + //if (is_int($base[lcfirst($form->getElement($i)->getText())])) $value = (int)$value; + //TODO IMPLEMENT + #if (is_int($base[lcfirst($form->getElement($i)->getText())])) $value = (int)$value; + #$extraData[lcfirst($form->getElement($i)->getText())] = $value;//TODO } #var_dump(__LINE__, $extraData); //prepare data @@ -231,26 +203,58 @@ public function getForm(bool $new = true, array $errors = []): CustomForm $player->sendMessage($ex->getMessage()); Loader::getInstance()->getLogger()->logException($ex); } - }); + })) + ->setTitle("Brush settings"); + // Shape + #$form->addElement(new Label((isset($errors['shape']) ? TF::RED : "") . "Shape" . ($errors['shape'] ?? ""))); + if ($new) { + $dropdownShapeOptions = []; + foreach (Loader::getShapeRegistry()::getShapes() as $name => $class) { + if ($name === ShapeRegistry::CUSTOM) continue; + $dropdownShapeOptions[(string)$name]= $class === $brushProperties->shape; + } + $form->addDropdown((isset($errors['shape']) ? TF::RED : "") . "Shape" . ($errors['shape'] ?? ""),$dropdownShapeOptions); + } else { + $form->addLabel($brushProperties->getShapeName()); + } + // Action + $dropdownActionOptions = []; + foreach (ActionRegistry::getActions() as $name => $class) { + $dropdownActionOptions[$name]= $class === $brushProperties->action; + } + $form->addDropdown("Action",$dropdownActionOptions); + // Name + $form->addInput("Name", "Name", $new ? "" : $this->getName()); + // Blocks + $form->addInput((isset($errors['blocks']) ? TF::RED : "") . "Blocks" . ($errors['blocks'] ?? ""), "grass,stone:1", $brushProperties->blocks); + // Filter + $form->addInput((isset($errors['filter']) ? TF::RED : "") . "Filter" . ($errors['filter'] ?? ""), "air", $brushProperties->filter); + // Biome + $dropdownBiomeOptions = []; + foreach ((new ReflectionClass(BiomeIds::class))->getConstants() as $name => $value) { + if ($value === BiomeIds::HELL) continue; + $dropdownBiomeOptions[BiomeRegistry::getInstance()->getBiome($value)->getName()]= $value === $brushProperties->biomeId; + } + $form->addDropdown((isset($errors['biome']) ? TF::RED : "") . "Biome" . ($errors['biome'] ?? ""),$dropdownBiomeOptions); + // Hollow + $form->addToggle("Hollow", $brushProperties->hollow); + // Extra properties + if (!$new) { + $form = $this->getExtradataForm($brushProperties->shape, $form);//TODO check if elements are added + } + // Function return $form; } catch (Exception $e) { throw new AssumptionFailedError("Could not create brush form"); } } - private function getExtradataForm(string $shapeClass): CustomForm + private function getExtradataForm(string $shapeClass,?CustomForm $form = null): CustomForm { - $form = new CustomForm("Shape settings"); #foreach (($defaultReplaced = array_merge(ShapeRegistry::getDefaultShapeProperties($shapeClass), $this->properties->shapeProperties)) as $name => $value) { $base = ShapeRegistry::getDefaultShapeProperties($shapeClass); - foreach (($defaultReplaced = array_replace($base, array_intersect_key($this->properties->shapeProperties, $base))) as $name => $value) { - if (is_bool($value)) $form->addElement(new Toggle(ucfirst($name), $value)); - else $form->addElement(new Input(ucfirst($name), $name . " (" . gettype($value) . ")", (string)$value)); - } - #var_dump($this->properties->shapeProperties); - #var_dump('Base', $base); - #var_dump('Default Replaced', $defaultReplaced); - $form->setCallable(function (Player $player, $data) use ($defaultReplaced, $base) { + $defaultReplaced = array_replace($base, array_intersect_key($this->properties->shapeProperties, $base)); + $form = ($form??new CustomForm(function (Player $player, $data) use ($defaultReplaced, $base) { //TODO validation, resending etc. $extraData = []; $names = array_keys($defaultReplaced); @@ -268,7 +272,15 @@ private function getExtradataForm(string $shapeClass): CustomForm $this->properties->uuid = Uuid::uuid4()->toString(); $session->getBrushes()->addBrush($brush); $player->getInventory()->addItem($brush->toItem()); - }); + })) + ->setTitle("Shape settings"); + foreach ($defaultReplaced as $name => $value) { + if (is_bool($value)) $form->addToggle(ucfirst($name), $value); + else $form->addInput(ucfirst($name), $name . " (" . gettype($value) . ")", (string)$value); + } + #var_dump($this->properties->shapeProperties); + #var_dump('Base', $base); + #var_dump('Default Replaced', $defaultReplaced); return $form; } } \ No newline at end of file diff --git a/src/xenialdan/MagicWE2/tool/BrushProperties.php b/src/xenialdan/MagicWE2/tool/BrushProperties.php index ce309c52..d0ca2b10 100644 --- a/src/xenialdan/MagicWE2/tool/BrushProperties.php +++ b/src/xenialdan/MagicWE2/tool/BrushProperties.php @@ -47,11 +47,11 @@ class BrushProperties implements JsonSerializable /** * Specify data which should be serialized to JSON * @link http://php.net/manual/en/jsonserializable.jsonserialize.php - * @return mixed data which can be serialized by json_encode, + * @return array data which can be serialized by json_encode, * which is a value of any type other than a resource. * @since 5.4.0 */ - public function jsonSerialize() + public function jsonSerialize(): array { return (array)$this; } diff --git a/src/xenialdan/MagicWE2/tool/Flood.php b/src/xenialdan/MagicWE2/tool/Flood.php index 6721e1cf..9689a39e 100644 --- a/src/xenialdan/MagicWE2/tool/Flood.php +++ b/src/xenialdan/MagicWE2/tool/Flood.php @@ -1,4 +1,4 @@ - Date: Fri, 1 Oct 2021 02:58:53 +0200 Subject: [PATCH 44/67] Fix //lang --- src/xenialdan/MagicWE2/commands/LanguageCommand.php | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/xenialdan/MagicWE2/commands/LanguageCommand.php b/src/xenialdan/MagicWE2/commands/LanguageCommand.php index 35bcdc3e..d2b8ad0b 100644 --- a/src/xenialdan/MagicWE2/commands/LanguageCommand.php +++ b/src/xenialdan/MagicWE2/commands/LanguageCommand.php @@ -17,6 +17,7 @@ use xenialdan\MagicWE2\helper\SessionHelper; use xenialdan\MagicWE2\Loader; use function array_search; +use function array_values; use function is_string; class LanguageCommand extends BaseCommand @@ -58,13 +59,13 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo } $languages = Loader::getInstance()->getLanguageList(); $form = (new CustomForm(function (Player $player, $data) use ($session, $languages) { - $langShort = array_search($data[1], $languages, true); + $langShort = array_search(array_values($languages)[$data[1]], $languages, true); if (!is_string($langShort)) throw new InvalidArgumentException("Invalid data received"); $session->setLanguage($langShort); })) ->setTitle(Loader::PREFIX_FORM . TF::BOLD . TF::DARK_PURPLE . $lang->translateString('ui.language.title')) ->addLabel($lang->translateString('ui.language.label')) - ->addDropdown($lang->translateString('ui.language.dropdown'), array_values($languages)); + ->addDropdown($lang->translateString('ui.language.dropdown'), array_values($languages), array_search($session->getLanguage()->getName(), array_values($languages), true)); //$dropdown->setOptionAsDefault($session->getLanguage()->getName()); $sender->sendForm($form); } catch (Exception $error) { From 0ddf475d6a11e5183d4ab243fac73a6f8634ff76 Mon Sep 17 00:00:00 2001 From: XenialDan Date: Fri, 1 Oct 2021 03:07:12 +0200 Subject: [PATCH 45/67] Fix palette, brush, asset command --- src/xenialdan/MagicWE2/Loader.php | 8 +++---- .../MagicWE2/commands/asset/AssetCommand.php | 22 ++++++++--------- .../MagicWE2/commands/brush/BrushCommand.php | 16 ++++++------- .../commands/palette/PaletteCommand.php | 24 +++++++++---------- 4 files changed, 35 insertions(+), 35 deletions(-) diff --git a/src/xenialdan/MagicWE2/Loader.php b/src/xenialdan/MagicWE2/Loader.php index a669be58..bc58bb73 100644 --- a/src/xenialdan/MagicWE2/Loader.php +++ b/src/xenialdan/MagicWE2/Loader.php @@ -223,10 +223,6 @@ public function onEnable(): void new HPos1Command($this, "/hpos1", "Set position 1 to targeted block", ["/h1"]), new HPos2Command($this, "/hpos2", "Set position 2 to targeted block", ["/h2"]), new ChunkCommand($this, "/chunk", "Set the selection to your current chunk"), - /* -- assets -- */ - #new AssetCommand($this, "/asset", "Manage assets (schematics, structures, clipboard)"), - /* -- palette -- */ - new PaletteCommand($this, "/palette", "Manage block palettes"), /* -- tool -- */ new WandCommand($this, "/wand", "Gives you the selection wand"), new TogglewandCommand($this, "/togglewand", "Toggle the wand tool on/off", ["/toggleeditwand"]), @@ -321,8 +317,12 @@ public function onEnable(): void if (class_exists(FormAPI::class)) { $this->getLogger()->notice("FormAPI found, can use ui-based commands"); $this->getServer()->getCommandMap()->registerAll("MagicWE2", [ + /* -- assets -- */ + #new AssetCommand($this, "/asset", "Manage assets (schematics, structures, clipboard)"), /* -- brush -- */ new BrushCommand($this, "/brush", "Opens the brush tool menu"), + /* -- palette -- */ + new PaletteCommand($this, "/palette", "Manage block palettes"), /* -- tool -- */ new FloodCommand($this, "/flood", "Opens the flood fill tool menu", ["/floodfill"]), ]); diff --git a/src/xenialdan/MagicWE2/commands/asset/AssetCommand.php b/src/xenialdan/MagicWE2/commands/asset/AssetCommand.php index f6408d99..6018edf2 100644 --- a/src/xenialdan/MagicWE2/commands/asset/AssetCommand.php +++ b/src/xenialdan/MagicWE2/commands/asset/AssetCommand.php @@ -68,7 +68,7 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo try { $store = Loader::$assetCollection;//TODO allow private assets again switch ($data) { - case $lang->translateString('ui.asset.create.fromclipboard'): + case 'ui.asset.create.fromclipboard': { //create clipboard asset //input Name @@ -84,7 +84,7 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo $player->sendForm($asset->getSettingForm()); break; } - case $lang->translateString('ui.asset.save'): + case 'ui.asset.save': { //save asset //dropdown asset @@ -129,7 +129,7 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo $player->sendForm($form); break; } - case $lang->translateString('ui.asset.settings'): + case 'ui.asset.settings': { //save asset //dropdown asset @@ -140,7 +140,7 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo $asset = $store->assets[$filename]; $player->sendForm($asset->getSettingForm()); })) - ->setTitle(Loader::PREFIX_FORM . TF::BOLD . TF::DARK_PURPLE . $lang->translateString('ui.asset.select')); + ->setTitle(Loader::PREFIX_FORM . TF::BOLD . TF::DARK_PURPLE . $lang->translateString('ui.asset.select')); $options = []; foreach (Loader::$assetCollection->getAll() as $asset) {//TODO allow private assets again $options[$asset->filename] = $asset->filename; @@ -149,7 +149,7 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo $player->sendForm($form); break; } - case $lang->translateString('ui.asset.global'): + case 'ui.asset.global': { $menu = InvMenu::create(InvMenuTypeIds::TYPE_DOUBLE_CHEST); $store = Loader::$assetCollection; @@ -159,7 +159,7 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo $menu->send($player, "Shared assets (" . count($store->getSharedAssets()) . ")"); break; } - case $lang->translateString('ui.asset.private'): + case 'ui.asset.private': { $menu = InvMenu::create(InvMenuTypeIds::TYPE_DOUBLE_CHEST); $store = $session->getAssets(); @@ -182,11 +182,11 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo })) ->setTitle(Loader::PREFIX_FORM . TF::BOLD . TF::DARK_PURPLE . $lang->translateString('ui.asset.title')) ->setContent($lang->translateString('ui.asset.content'))//TODO - ->addButton($lang->translateString('ui.asset.private')) - ->addButton($lang->translateString('ui.asset.global')) - ->addButton($lang->translateString('ui.asset.create.fromclipboard')) - ->addButton($lang->translateString('ui.asset.settings')) - ->addButton($lang->translateString('ui.asset.save')); + ->addButton($lang->translateString('ui.asset.private'), -1, "", 'ui.asset.private') + ->addButton($lang->translateString('ui.asset.global'), -1, "", 'ui.asset.global') + ->addButton($lang->translateString('ui.asset.create.fromclipboard'), -1, "", 'ui.asset.create.fromclipboard') + ->addButton($lang->translateString('ui.asset.settings'), -1, "", 'ui.asset.settings') + ->addButton($lang->translateString('ui.asset.save'), -1, "", 'ui.asset.save'); $sender->sendForm($form); } catch (Exception $error) { $sender->sendMessage(Loader::PREFIX . TF::RED . $lang->translateString('error.command-error')); diff --git a/src/xenialdan/MagicWE2/commands/brush/BrushCommand.php b/src/xenialdan/MagicWE2/commands/brush/BrushCommand.php index c392de8c..a2e0f595 100644 --- a/src/xenialdan/MagicWE2/commands/brush/BrushCommand.php +++ b/src/xenialdan/MagicWE2/commands/brush/BrushCommand.php @@ -54,13 +54,13 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo $form = (new SimpleForm(function (Player $player, $data) use ($lang, $session) { try { switch ($data) { - case $lang->translateString('ui.brush.create'): + case 'ui.brush.create': { $brush = new Brush(new BrushProperties()); $player->sendForm($brush->getForm()); break; } - case $lang->translateString('ui.brush.getsession'): + case 'ui.brush.getsession': { $menu = InvMenu::create(InvMenuTypeIds::TYPE_DOUBLE_CHEST); foreach ($session->getBrushes()->getAll() as $brush) { @@ -69,7 +69,7 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo $menu->send($player, "Session brushes"); break; } - case $lang->translateString('ui.brush.edithand'): + case 'ui.brush.edithand': { $brush = $session->getBrushes()->getBrushFromItem($player->getInventory()->getItemInHand()); if ($brush instanceof Brush) { @@ -84,11 +84,11 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo $session->sendMessage(TF::RED . $error->getMessage()); } })) - ->setTitle(Loader::PREFIX_FORM . TF::BOLD . TF::DARK_PURPLE . $lang->translateString('ui.brush.title')) - ->setContent($lang->translateString('ui.brush.content')) - ->addButton($lang->translateString('ui.brush.create')) - ->addButton($lang->translateString('ui.brush.getsession')) - ->addButton($lang->translateString('ui.brush.edithand')); + ->setTitle(Loader::PREFIX_FORM . TF::BOLD . TF::DARK_PURPLE . $lang->translateString('ui.brush.title')) + ->setContent($lang->translateString('ui.brush.content')) + ->addButton($lang->translateString('ui.brush.create'), -1, "", 'ui.brush.create') + ->addButton($lang->translateString('ui.brush.getsession'), -1, "", 'ui.brush.getsession') + ->addButton($lang->translateString('ui.brush.edithand'), -1, "", 'ui.brush.edithand'); $sender->sendForm($form); } catch (Exception $error) { $sender->sendMessage(Loader::PREFIX . TF::RED . $lang->translateString('error.command-error')); diff --git a/src/xenialdan/MagicWE2/commands/palette/PaletteCommand.php b/src/xenialdan/MagicWE2/commands/palette/PaletteCommand.php index 6fdb4149..808909b4 100644 --- a/src/xenialdan/MagicWE2/commands/palette/PaletteCommand.php +++ b/src/xenialdan/MagicWE2/commands/palette/PaletteCommand.php @@ -61,7 +61,7 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo $form = (new SimpleForm(function (Player $player, $data) use ($lang, $session) { try { switch ($data) { - case $lang->translateString('ui.palette.get'): + case 'ui.palette.get': { $menu = InvMenu::create(InvMenuTypeIds::TYPE_DOUBLE_CHEST); foreach ($session->getPalettes()->getAll() as $id => $palette) { @@ -70,7 +70,7 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo $menu->send($player, "Session palettes"); break; } - case $lang->translateString('ui.palette.fromhotbar'): + case 'ui.palette.fromhotbar': { /** @var Block[] $blocks */ $blocks = []; @@ -82,7 +82,7 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo $session->sendMessage(TF::GREEN . $lang->translateString('Created palette from hotbar')); break; } - case $lang->translateString('ui.palette.frominventory'): + case 'ui.palette.frominventory': { /** @var Block[] $blocks */ $blocks = []; @@ -94,7 +94,7 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo $session->sendMessage(TF::GREEN . $lang->translateString('Created palette from inventory')); break; } - case $lang->translateString('ui.palette.fromselection'): + case 'ui.palette.fromselection': { /** @var Block[] $blocks */ $blocks = []; @@ -110,7 +110,7 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo $session->sendMessage(TF::GREEN . $lang->translateString('Created palette from inventory')); break; } - case $lang->translateString('ui.palette.modify'): + case 'ui.palette.modify': { $menu = InvMenu::create(InvMenuTypeIds::TYPE_DOUBLE_CHEST); foreach ($session->getPalettes()->getAll() as $id => $palette) { @@ -142,13 +142,13 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo $session->sendMessage(TF::RED . $error->getMessage()); } })) - ->setTitle(Loader::PREFIX_FORM . TF::BOLD . TF::DARK_PURPLE . $lang->translateString('ui.palette.title')) - ->setContent($lang->translateString('ui.palette.content')) - ->addButton($lang->translateString('ui.palette.fromhotbar')) - ->addButton($lang->translateString('ui.palette.frominventory')) - ->addButton($lang->translateString('ui.palette.fromselection')) - ->addButton($lang->translateString('ui.palette.get')) - ->addButton($lang->translateString('ui.palette.modify')); + ->setTitle(Loader::PREFIX_FORM . TF::BOLD . TF::DARK_PURPLE . $lang->translateString('ui.palette.title')) + ->setContent($lang->translateString('ui.palette.content')) + ->addButton($lang->translateString('ui.palette.fromhotbar'), -1, "", 'ui.palette.fromhotbar') + ->addButton($lang->translateString('ui.palette.frominventory'), -1, "", 'ui.palette.frominventory') + ->addButton($lang->translateString('ui.palette.fromselection'), -1, "", 'ui.palette.fromselection') + ->addButton($lang->translateString('ui.palette.get'), -1, "", 'ui.palette.get') + ->addButton($lang->translateString('ui.palette.modify'), -1, "", 'ui.palette.modify'); $sender->sendForm($form); } catch (Exception $error) { $sender->sendMessage(Loader::PREFIX . TF::RED . $lang->translateString('error.command-error')); From d7fc6ef48a2deece0f69c4a4e0a973e7d912416d Mon Sep 17 00:00:00 2001 From: XenialDan Date: Fri, 1 Oct 2021 03:32:01 +0200 Subject: [PATCH 46/67] Update ScoreFactory, Fix #233 --- .poggit.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.poggit.yml b/.poggit.yml index 719e0da5..7053f4f0 100644 --- a/.poggit.yml +++ b/.poggit.yml @@ -27,7 +27,7 @@ projects: - src: thebigsmilexd/libstructure/libstructure version: ^0.1.4 branch: mcstructure - - src: buchwasa/ScoreFactory/ScoreFactory + - src: buchwasa/scorefactory/ScoreFactory version: ^3.0.1 branch: pm4 ... From 086d9ea520ff098d5e4b47a465c3f7b06f58e897 Mon Sep 17 00:00:00 2001 From: XenialDan Date: Fri, 1 Oct 2021 04:33:20 +0200 Subject: [PATCH 47/67] Fix brush creation form --- plugin.yml | 2 +- .../MagicWE2/helper/WeightedRandom.php | 1 + src/xenialdan/MagicWE2/tool/Brush.php | 83 ++++++++++--------- 3 files changed, 48 insertions(+), 38 deletions(-) diff --git a/plugin.yml b/plugin.yml index bca9593b..9dae74ed 100644 --- a/plugin.yml +++ b/plugin.yml @@ -1,7 +1,7 @@ --- name: MagicWE2 main: xenialdan\MagicWE2\Loader -version: 10.1.7 +version: 10.1.8 api: ["4.0.0"] php: [ "8.0" ] softdepend: [ "DEVirion" ] diff --git a/src/xenialdan/MagicWE2/helper/WeightedRandom.php b/src/xenialdan/MagicWE2/helper/WeightedRandom.php index f95fe1dd..c67e2031 100644 --- a/src/xenialdan/MagicWE2/helper/WeightedRandom.php +++ b/src/xenialdan/MagicWE2/helper/WeightedRandom.php @@ -43,6 +43,7 @@ final public function count(): int private function normalize(): void { $sum = array_sum($this->probabilities); + if($sum < 1) return; foreach ($this->probabilities as &$weight) { $weight /= $sum; } diff --git a/src/xenialdan/MagicWE2/tool/Brush.php b/src/xenialdan/MagicWE2/tool/Brush.php index a1e7e533..27137f9d 100644 --- a/src/xenialdan/MagicWE2/tool/Brush.php +++ b/src/xenialdan/MagicWE2/tool/Brush.php @@ -109,10 +109,33 @@ public function getForm(bool $new = true, array $errors = []): CustomForm return TF::EOL . TF::RED . $value; }, $errors); $brushProperties = $this->properties ?? new BrushProperties(); - $form = (new CustomForm(function (Player $player, $data) use ($new) { + + + $dropdownShapeOptions = []; + if ($new) { + foreach (Loader::getShapeRegistry()::getShapes() as $name => $class) { + if ($name === ShapeRegistry::CUSTOM) continue; + $dropdownShapeOptions[(string)$name] = $class === $brushProperties->shape; + } + } + $dropdownActionOptions = []; + foreach (ActionRegistry::getActions() as $name => $class) { + $dropdownActionOptions[$name] = $class === $brushProperties->action; + } + $dropdownBiomeOptions = []; + foreach ((new ReflectionClass(BiomeIds::class))->getConstants() as $name => $value) { + if ($value === BiomeIds::HELL) continue; + $dropdownBiomeOptions[BiomeRegistry::getInstance()->getBiome($value)->getName()] = $value === $brushProperties->biomeId; + } + + $form = (new CustomForm(function (Player $player, $data) use ($new,$dropdownShapeOptions,$dropdownActionOptions,$dropdownBiomeOptions) { #var_dump(__LINE__, $data); #$data = array_slice($data, 0, 7); [$shape, $action, $name, $blocks, $filter, $biome, $hollow] = $data; + $shape = array_keys($dropdownShapeOptions)[$shape]; + $action = array_keys($dropdownActionOptions)[$action]; + $biome = array_keys($dropdownBiomeOptions)[$biome];//TODO throw exception if not valid + $extraData = []; #var_dump(__LINE__, array_slice($data, 7)); $base = ShapeRegistry::getDefaultShapeProperties(ShapeRegistry::getShape($shape)); @@ -208,21 +231,12 @@ public function getForm(bool $new = true, array $errors = []): CustomForm // Shape #$form->addElement(new Label((isset($errors['shape']) ? TF::RED : "") . "Shape" . ($errors['shape'] ?? ""))); if ($new) { - $dropdownShapeOptions = []; - foreach (Loader::getShapeRegistry()::getShapes() as $name => $class) { - if ($name === ShapeRegistry::CUSTOM) continue; - $dropdownShapeOptions[(string)$name]= $class === $brushProperties->shape; - } - $form->addDropdown((isset($errors['shape']) ? TF::RED : "") . "Shape" . ($errors['shape'] ?? ""),$dropdownShapeOptions); + $form->addDropdown((isset($errors['shape']) ? TF::RED : "") . "Shape" . ($errors['shape'] ?? ""), array_keys($dropdownShapeOptions)); } else { $form->addLabel($brushProperties->getShapeName()); } // Action - $dropdownActionOptions = []; - foreach (ActionRegistry::getActions() as $name => $class) { - $dropdownActionOptions[$name]= $class === $brushProperties->action; - } - $form->addDropdown("Action",$dropdownActionOptions); + $form->addDropdown("Action", array_keys($dropdownActionOptions)); // Name $form->addInput("Name", "Name", $new ? "" : $this->getName()); // Blocks @@ -230,12 +244,7 @@ public function getForm(bool $new = true, array $errors = []): CustomForm // Filter $form->addInput((isset($errors['filter']) ? TF::RED : "") . "Filter" . ($errors['filter'] ?? ""), "air", $brushProperties->filter); // Biome - $dropdownBiomeOptions = []; - foreach ((new ReflectionClass(BiomeIds::class))->getConstants() as $name => $value) { - if ($value === BiomeIds::HELL) continue; - $dropdownBiomeOptions[BiomeRegistry::getInstance()->getBiome($value)->getName()]= $value === $brushProperties->biomeId; - } - $form->addDropdown((isset($errors['biome']) ? TF::RED : "") . "Biome" . ($errors['biome'] ?? ""),$dropdownBiomeOptions); + $form->addDropdown((isset($errors['biome']) ? TF::RED : "") . "Biome" . ($errors['biome'] ?? ""), array_keys($dropdownBiomeOptions)); // Hollow $form->addToggle("Hollow", $brushProperties->hollow); // Extra properties @@ -249,30 +258,30 @@ public function getForm(bool $new = true, array $errors = []): CustomForm } } - private function getExtradataForm(string $shapeClass,?CustomForm $form = null): CustomForm + private function getExtradataForm(string $shapeClass, ?CustomForm $form = null): CustomForm { #foreach (($defaultReplaced = array_merge(ShapeRegistry::getDefaultShapeProperties($shapeClass), $this->properties->shapeProperties)) as $name => $value) { $base = ShapeRegistry::getDefaultShapeProperties($shapeClass); $defaultReplaced = array_replace($base, array_intersect_key($this->properties->shapeProperties, $base)); - $form = ($form??new CustomForm(function (Player $player, $data) use ($defaultReplaced, $base) { - //TODO validation, resending etc. - $extraData = []; - $names = array_keys($defaultReplaced); - foreach ($data as $index => $value) { - if (is_int($base[$names[$index]])) $value = (int)$value; - $extraData[$names[$index]] = $value; - } - $this->properties->shapeProperties = $extraData; + $form = ($form ?? new CustomForm(function (Player $player, $data) use ($defaultReplaced, $base) { + //TODO validation, resending etc. + $extraData = []; + $names = array_keys($defaultReplaced); + foreach ($data as $index => $value) { + if (is_int($base[$names[$index]])) $value = (int)$value; + $extraData[$names[$index]] = $value; + } + $this->properties->shapeProperties = $extraData; - $brush = $this; - $session = SessionHelper::getUserSession($player); - if (!$session instanceof UserSession) { - throw new SessionException(Loader::getInstance()->getLanguage()->translateString('error.nosession', [Loader::getInstance()->getName()])); - } - $this->properties->uuid = Uuid::uuid4()->toString(); - $session->getBrushes()->addBrush($brush); - $player->getInventory()->addItem($brush->toItem()); - })) + $brush = $this; + $session = SessionHelper::getUserSession($player); + if (!$session instanceof UserSession) { + throw new SessionException(Loader::getInstance()->getLanguage()->translateString('error.nosession', [Loader::getInstance()->getName()])); + } + $this->properties->uuid = Uuid::uuid4()->toString(); + $session->getBrushes()->addBrush($brush); + $player->getInventory()->addItem($brush->toItem()); + })) ->setTitle("Shape settings"); foreach ($defaultReplaced as $name => $value) { if (is_bool($value)) $form->addToggle(ucfirst($name), $value); From 37cbe28c769a7e5025fc7e6b5e041cc6b546f2e4 Mon Sep 17 00:00:00 2001 From: XenialDan Date: Fri, 1 Oct 2021 05:19:24 +0200 Subject: [PATCH 48/67] Fix editing brush extra properties --- src/xenialdan/MagicWE2/tool/Brush.php | 26 ++++++++++++-------------- 1 file changed, 12 insertions(+), 14 deletions(-) diff --git a/src/xenialdan/MagicWE2/tool/Brush.php b/src/xenialdan/MagicWE2/tool/Brush.php index 27137f9d..f386f1df 100644 --- a/src/xenialdan/MagicWE2/tool/Brush.php +++ b/src/xenialdan/MagicWE2/tool/Brush.php @@ -36,14 +36,13 @@ use function array_replace; use function array_search; use function array_slice; +use function array_values; use function array_walk; use function gettype; use function is_bool; use function is_int; -use function lcfirst; use function trim; use function ucfirst; -use function var_dump; class Brush extends WETool { @@ -110,7 +109,6 @@ public function getForm(bool $new = true, array $errors = []): CustomForm }, $errors); $brushProperties = $this->properties ?? new BrushProperties(); - $dropdownShapeOptions = []; if ($new) { foreach (Loader::getShapeRegistry()::getShapes() as $name => $class) { @@ -128,24 +126,24 @@ public function getForm(bool $new = true, array $errors = []): CustomForm $dropdownBiomeOptions[BiomeRegistry::getInstance()->getBiome($value)->getName()] = $value === $brushProperties->biomeId; } - $form = (new CustomForm(function (Player $player, $data) use ($new,$dropdownShapeOptions,$dropdownActionOptions,$dropdownBiomeOptions) { + $form = (new CustomForm(function (Player $player, $data) use ($new, $dropdownShapeOptions, $dropdownActionOptions, $dropdownBiomeOptions) { + if ($data === null) return; #var_dump(__LINE__, $data); #$data = array_slice($data, 0, 7); [$shape, $action, $name, $blocks, $filter, $biome, $hollow] = $data; - $shape = array_keys($dropdownShapeOptions)[$shape]; + if ($new) $shape = array_keys($dropdownShapeOptions)[$shape]; + //else $shape = array_keys($data)[0]??get_class($this->properties->shape); $action = array_keys($dropdownActionOptions)[$action]; $biome = array_keys($dropdownBiomeOptions)[$biome];//TODO throw exception if not valid $extraData = []; #var_dump(__LINE__, array_slice($data, 7)); - $base = ShapeRegistry::getDefaultShapeProperties(ShapeRegistry::getShape($shape)); - var_dump($base); - foreach (array_slice($data, 7, null, true) as $i => $value) { - var_dump($i, $value, gettype($value), gettype($base[lcfirst($value)]));//TODO IMPLEMENT - //if (is_int($base[lcfirst($form->getElement($i)->getText())])) $value = (int)$value; - //TODO IMPLEMENT - #if (is_int($base[lcfirst($form->getElement($i)->getText())])) $value = (int)$value; - #$extraData[lcfirst($form->getElement($i)->getText())] = $value;//TODO + $base = ShapeRegistry::getDefaultShapeProperties(($new ? ShapeRegistry::getShape($shape) : $this->properties->shape)); + $slice = array_values(array_slice($data, 7, null, true));//TODO use label? + $j = 0; + foreach ($base as $i => $value) { + $extraData[$i] = is_int($value) ? (int)$slice[$j] : $slice[$j];//TODO enhance + $j++; } #var_dump(__LINE__, $extraData); //prepare data @@ -174,7 +172,7 @@ public function getForm(bool $new = true, array $errors = []): CustomForm $error['filter'] = $ex->getMessage(); } try { - $shape = Loader::getShapeRegistry()::getShape($shape); + $shape = ($new ? ShapeRegistry::getShape($shape) : $this->properties->shape); } catch (Exception $ex) { $error['shape'] = $ex->getMessage(); } From f2273516c5b18b75905de4bf02871b1733a52500 Mon Sep 17 00:00:00 2001 From: XenialDan Date: Tue, 9 Mar 2021 13:18:27 +0100 Subject: [PATCH 49/67] Add outline test code --- .../MagicWE2/session/data/Outline.php | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 src/xenialdan/MagicWE2/session/data/Outline.php diff --git a/src/xenialdan/MagicWE2/session/data/Outline.php b/src/xenialdan/MagicWE2/session/data/Outline.php new file mode 100644 index 00000000..d211f4b7 --- /dev/null +++ b/src/xenialdan/MagicWE2/session/data/Outline.php @@ -0,0 +1,45 @@ +asset = $asset; + } + + public function __toString(): string + { + return 'Outline'; + } + + /** + * @return Asset|null + */ + public function getAsset(): ?Asset + { + return $this->asset; + } + + /** + * @param Asset|null $asset + * @return Outline + */ + public function setAsset(?Asset $asset): Outline + { + $this->asset = $asset; + return $this; + } +} \ No newline at end of file From f2fb87aab6d5cbc3ca389f293e51e8994ecde065 Mon Sep 17 00:00:00 2001 From: XenialDan Date: Fri, 1 Oct 2021 21:04:39 +0200 Subject: [PATCH 50/67] Add palette item to inventory after creation --- .../commands/palette/PaletteCommand.php | 59 ++++++++++++------- 1 file changed, 37 insertions(+), 22 deletions(-) diff --git a/src/xenialdan/MagicWE2/commands/palette/PaletteCommand.php b/src/xenialdan/MagicWE2/commands/palette/PaletteCommand.php index 808909b4..997ee7e0 100644 --- a/src/xenialdan/MagicWE2/commands/palette/PaletteCommand.php +++ b/src/xenialdan/MagicWE2/commands/palette/PaletteCommand.php @@ -13,7 +13,7 @@ use muqsit\invmenu\transaction\InvMenuTransactionResult; use muqsit\invmenu\type\InvMenuTypeIds; use pocketmine\block\Block; -use pocketmine\block\BlockLegacyIds; +use pocketmine\block\VanillaBlocks; use pocketmine\command\CommandSender; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; @@ -23,7 +23,6 @@ use xenialdan\MagicWE2\helper\BlockPalette; use xenialdan\MagicWE2\helper\SessionHelper; use xenialdan\MagicWE2\Loader; -use xenialdan\MagicWE2\selection\Selection; use xenialdan\MagicWE2\session\UserSession; use function var_dump; @@ -75,42 +74,57 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo /** @var Block[] $blocks */ $blocks = []; for ($i = 0; $i <= $player->getInventory()->getHotbarSize(); $i++) { - if (($block = $player->getInventory()->getHotbarSlotItem($i)->getBlock()) instanceof Block && $block->getId() !== BlockLegacyIds::AIR) $blocks[] = $block; + $item = $player->getInventory()->getHotbarSlotItem($i); + if (!$item->isNull() && ($block = $item->getBlock()) instanceof Block) $blocks[] = $block; } $palette = BlockPalette::fromBlocks($blocks); - $session->getPalettes()->palettes[Uuid::uuid4()->toString()] = $palette; + $id = Uuid::uuid4()->toString(); + $session->getPalettes()->palettes[$id] = $palette; $session->sendMessage(TF::GREEN . $lang->translateString('Created palette from hotbar')); + $player->getInventory()->addItem($palette->toItem($id)); break; } case 'ui.palette.frominventory': { /** @var Block[] $blocks */ $blocks = []; - foreach ($player->getInventory()->getContents() as $block) { - if (($block = $block->getBlock()) instanceof Block) $blocks[] = $block; + foreach ($player->getInventory()->getContents() as $item) { + $block = $item->getBlock(); + if ($block !== VanillaBlocks::AIR()) $blocks[] = $block; } $palette = BlockPalette::fromBlocks($blocks); - $session->getPalettes()->palettes[Uuid::uuid4()->toString()] = $palette; + $id = Uuid::uuid4()->toString(); + $session->getPalettes()->palettes[$id] = $palette; $session->sendMessage(TF::GREEN . $lang->translateString('Created palette from inventory')); + $player->getInventory()->addItem($palette->toItem($id)); break; } - case 'ui.palette.fromselection': + case 'ui.palette.modifyblocks': { - /** @var Block[] $blocks */ - $blocks = []; - $selection = $session->getLatestSelection(); - if (!$selection instanceof Selection) { - $session->sendMessage(TF::RED . $lang->translateString('No selection'));//todo string - } - foreach ($selection as $block) { - if (($block = $block->getBlock()) instanceof Block) $blocks[] = $block; + $menu = InvMenu::create(InvMenuTypeIds::TYPE_DOUBLE_CHEST); + foreach ($session->getPalettes()->getAll() as $id => $palette) { + $menu->getInventory()->addItem($palette->toItem($id)); } - $palette = BlockPalette::fromBlocks($blocks); - $session->getPalettes()->palettes[Uuid::uuid4()->toString()] = $palette; - $session->sendMessage(TF::GREEN . $lang->translateString('Created palette from inventory')); + $menu->setListener(function (InvMenuTransaction $transaction) use ($session): InvMenuTransactionResult { + //todo functionality + $player = $transaction->getPlayer(); + $itemClicked = $transaction->getItemClicked(); + $itemClickedWith = $transaction->getItemClickedWith(); + $action = $transaction->getAction(); + $inv_transaction = $transaction->getTransaction(); + try { + $palette = $session->getPalettes()->getPaletteFromItem($itemClicked); + var_dump($player, $itemClicked, $itemClickedWith, $action, $inv_transaction, $itemClicked->getLore(), $palette); + } catch (PaletteException $e) { + $session->sendMessage($e->getMessage()); + Loader::getInstance()->getLogger()->logException($e); + } + return $transaction->continue(); + }); + $menu->send($player, "Select a palette to modify"); break; } - case 'ui.palette.modify': + case 'ui.palette.modifyweights': { $menu = InvMenu::create(InvMenuTypeIds::TYPE_DOUBLE_CHEST); foreach ($session->getPalettes()->getAll() as $id => $palette) { @@ -146,9 +160,10 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo ->setContent($lang->translateString('ui.palette.content')) ->addButton($lang->translateString('ui.palette.fromhotbar'), -1, "", 'ui.palette.fromhotbar') ->addButton($lang->translateString('ui.palette.frominventory'), -1, "", 'ui.palette.frominventory') - ->addButton($lang->translateString('ui.palette.fromselection'), -1, "", 'ui.palette.fromselection') + #->addButton($lang->translateString('ui.palette.fromselection'), -1, "", 'ui.palette.fromselection') ->addButton($lang->translateString('ui.palette.get'), -1, "", 'ui.palette.get') - ->addButton($lang->translateString('ui.palette.modify'), -1, "", 'ui.palette.modify'); + ->addButton($lang->translateString('ui.palette.modifyblocks'), -1, "", 'ui.palette.modifyblocks') + ->addButton($lang->translateString('ui.palette.modifyweights'), -1, "", 'ui.palette.modifyweights'); $sender->sendForm($form); } catch (Exception $error) { $sender->sendMessage(Loader::PREFIX . TF::RED . $lang->translateString('error.command-error')); From 8e9079299bfe1299fe4537c81253893b8972556b Mon Sep 17 00:00:00 2001 From: XenialDan Date: Sat, 2 Oct 2021 03:24:53 +0200 Subject: [PATCH 51/67] Add BlockQuery::fromString(), implement palette modify option --- .../commands/palette/PaletteCommand.php | 110 ++++++++++-------- .../MagicWE2/helper/BlockPalette.php | 17 +-- src/xenialdan/MagicWE2/helper/BlockQuery.php | 20 +++- .../MagicWE2/helper/WeightedRandom.php | 16 +++ .../session/data/PaletteCollection.php | 15 ++- 5 files changed, 109 insertions(+), 69 deletions(-) diff --git a/src/xenialdan/MagicWE2/commands/palette/PaletteCommand.php b/src/xenialdan/MagicWE2/commands/palette/PaletteCommand.php index 997ee7e0..a4ba1e84 100644 --- a/src/xenialdan/MagicWE2/commands/palette/PaletteCommand.php +++ b/src/xenialdan/MagicWE2/commands/palette/PaletteCommand.php @@ -7,10 +7,10 @@ use CortexPE\Commando\BaseCommand; use Exception; use InvalidArgumentException; +use jojoe77777\FormAPI\CustomForm; use jojoe77777\FormAPI\SimpleForm; use muqsit\invmenu\InvMenu; -use muqsit\invmenu\transaction\InvMenuTransaction; -use muqsit\invmenu\transaction\InvMenuTransactionResult; +use muqsit\invmenu\transaction\DeterministicInvMenuTransaction; use muqsit\invmenu\type\InvMenuTypeIds; use pocketmine\block\Block; use pocketmine\block\VanillaBlocks; @@ -18,12 +18,15 @@ use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; use Ramsey\Uuid\Uuid; +use xenialdan\MagicWE2\API; use xenialdan\MagicWE2\exception\PaletteException; use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\BlockPalette; +use xenialdan\MagicWE2\helper\BlockQuery; use xenialdan\MagicWE2\helper\SessionHelper; use xenialdan\MagicWE2\Loader; use xenialdan\MagicWE2\session\UserSession; +use function implode; use function var_dump; class PaletteCommand extends BaseCommand @@ -79,7 +82,8 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo } $palette = BlockPalette::fromBlocks($blocks); $id = Uuid::uuid4()->toString(); - $session->getPalettes()->palettes[$id] = $palette; + #$session->getPalettes()->palettes[$id] = $palette; + $session->getPalettes()->addPalette($palette, $id); $session->sendMessage(TF::GREEN . $lang->translateString('Created palette from hotbar')); $player->getInventory()->addItem($palette->toItem($id)); break; @@ -94,63 +98,76 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo } $palette = BlockPalette::fromBlocks($blocks); $id = Uuid::uuid4()->toString(); - $session->getPalettes()->palettes[$id] = $palette; + #$session->getPalettes()->palettes[$id] = $palette; + $session->getPalettes()->addPalette($palette, $id); $session->sendMessage(TF::GREEN . $lang->translateString('Created palette from inventory')); $player->getInventory()->addItem($palette->toItem($id)); break; } - case 'ui.palette.modifyblocks': + case 'ui.palette.modify': { $menu = InvMenu::create(InvMenuTypeIds::TYPE_DOUBLE_CHEST); foreach ($session->getPalettes()->getAll() as $id => $palette) { $menu->getInventory()->addItem($palette->toItem($id)); } - $menu->setListener(function (InvMenuTransaction $transaction) use ($session): InvMenuTransactionResult { - //todo functionality - $player = $transaction->getPlayer(); - $itemClicked = $transaction->getItemClicked(); - $itemClickedWith = $transaction->getItemClickedWith(); - $action = $transaction->getAction(); - $inv_transaction = $transaction->getTransaction(); - try { - $palette = $session->getPalettes()->getPaletteFromItem($itemClicked); - var_dump($player, $itemClicked, $itemClickedWith, $action, $inv_transaction, $itemClicked->getLore(), $palette); - } catch (PaletteException $e) { - $session->sendMessage($e->getMessage()); - Loader::getInstance()->getLogger()->logException($e); - } - return $transaction->continue(); + $menu->setListener(InvMenu::readonly(function (DeterministicInvMenuTransaction $transaction) use ($session, $lang): void { + $transaction->getPlayer()->removeCurrentWindow(); + $transaction->then(function (Player $player) use ($transaction, $session, $lang): void { + $itemClicked = $transaction->getItemClicked(); + try { + $tag = $itemClicked->getNamedTag()->getCompoundTag(API::TAG_MAGIC_WE_PALETTE); + if ($tag === null) { + var_dump(__LINE__); + return; + } + $id = $tag->getString("id", ""); + + $palette = $session->getPalettes()->getPalette($id); + var_dump($itemClicked, $palette, $id); + $form1 = (new SimpleForm(static function (Player $player, $data) use ($lang, $palette, $id): void { + switch ($data) { + case 'ui.palette.modify.weights': + { + $form2 = (new CustomForm(static function (Player $player, $data) use ($lang, $palette): void { + var_dump($data); + })) + ->setTitle("Modify weights"); + + foreach ($palette->randomBlockQueries->getIndexes() as $i => $block) { + /** @var BlockQuery $block */ + $form2->addSlider($block->query, 0, 100, 1, (int)$palette->randomBlockQueries->getProbabilities()[$i] ?? 1 * 100, $block->query); + } + $player->sendForm($form2); + break; + } + default: + { + var_dump($data); + } + } + })) + ->setTitle("Modify Palette") + ->setContent(implode(",", $palette->toStringArray())) + ->addButton($lang->translateString('ui.palette.modify.weights'), -1, "", 'ui.palette.modify.weights') + ->addButton($lang->translateString('ui.palette.modify.blocks'), -1, "", 'ui.palette.modify.blocks'); + $player->sendForm($form1); + } catch (PaletteException $e) { + $session->sendMessage($e->getMessage()); + Loader::getInstance()->getLogger()->logException($e); + } + }); + })); + $menu->send($player, "Select a palette to modify", function (bool $sent): void { + var_dump($sent ? "sent" : "not sent"); }); - $menu->send($player, "Select a palette to modify"); break; } - case 'ui.palette.modifyweights': + default: { - $menu = InvMenu::create(InvMenuTypeIds::TYPE_DOUBLE_CHEST); - foreach ($session->getPalettes()->getAll() as $id => $palette) { - $menu->getInventory()->addItem($palette->toItem($id)); - } - $menu->setListener(function (InvMenuTransaction $transaction) use ($session): InvMenuTransactionResult { - //todo functionality - $player = $transaction->getPlayer(); - $itemClicked = $transaction->getItemClicked(); - $itemClickedWith = $transaction->getItemClickedWith(); - $action = $transaction->getAction(); - $inv_transaction = $transaction->getTransaction(); - try { - $palette = $session->getPalettes()->getPaletteFromItem($itemClicked); - var_dump($player, $itemClicked, $itemClickedWith, $action, $inv_transaction, $itemClicked->getLore(), $palette); - } catch (PaletteException $e) { - $session->sendMessage($e->getMessage()); - Loader::getInstance()->getLogger()->logException($e); - } - return $transaction->continue(); - }); - $menu->send($player, "Select a palette to modify"); - break; + var_dump($data); } } - return null; + #return null; } catch (Exception $error) { $session->sendMessage(TF::RED . $lang->translateString('error')); $session->sendMessage(TF::RED . $error->getMessage()); @@ -162,8 +179,7 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo ->addButton($lang->translateString('ui.palette.frominventory'), -1, "", 'ui.palette.frominventory') #->addButton($lang->translateString('ui.palette.fromselection'), -1, "", 'ui.palette.fromselection') ->addButton($lang->translateString('ui.palette.get'), -1, "", 'ui.palette.get') - ->addButton($lang->translateString('ui.palette.modifyblocks'), -1, "", 'ui.palette.modifyblocks') - ->addButton($lang->translateString('ui.palette.modifyweights'), -1, "", 'ui.palette.modifyweights'); + ->addButton($lang->translateString('ui.palette.modify'), -1, "", 'ui.palette.modify'); $sender->sendForm($form); } catch (Exception $error) { $sender->sendMessage(Loader::PREFIX . TF::RED . $lang->translateString('error.command-error')); diff --git a/src/xenialdan/MagicWE2/helper/BlockPalette.php b/src/xenialdan/MagicWE2/helper/BlockPalette.php index 1800080f..a6322715 100644 --- a/src/xenialdan/MagicWE2/helper/BlockPalette.php +++ b/src/xenialdan/MagicWE2/helper/BlockPalette.php @@ -46,9 +46,6 @@ public function __construct(string $name = "") * @return BlockPalette * @throws BlockQueryAlreadyParsedException * @throws InvalidArgumentException - * @throws InvalidBlockStateException - * @throws LegacyStringToItemParserException - * @throws UnexpectedTagTypeException * @throws \xenialdan\MagicWE2\exception\InvalidBlockStateException */ public static function fromString(string $blocksQuery): BlockPalette @@ -58,13 +55,7 @@ public static function fromString(string $blocksQuery): BlockPalette $pregSplit = preg_split('/,(?![^\[]*])/', trim($blocksQuery), -1, PREG_SPLIT_NO_EMPTY); if (!is_array($pregSplit)) throw new InvalidArgumentException("Regex matching failed"); foreach ($pregSplit as $query) { - // How to code ugly 101: https://3v4l.org/2KfNW - preg_match_all('/([\w:]+)(?:\[([\w=,]*)])?/m', $query, $matches, PREG_SET_ORDER); - [$blockMatch, $extraMatch] = [$matches[0] ?? [], $matches[1] ?? []]; - $blockMatch += [null, null, null]; - $extraMatch += [null, null]; - [[$fullBlockQuery, $blockId, $blockStatesQuery], [$fullExtraQuery, $weight]] = [$blockMatch, $extraMatch]; - $palette->addBlockQuery((new BlockQuery($query, $fullBlockQuery, $blockId, $blockStatesQuery, $fullExtraQuery, (float)$weight))->parse()); + $palette->addBlockQuery(BlockQuery::fromString($query)); } $palette->randomBlockQueries->setup(); @@ -82,7 +73,7 @@ public static function fromBlocks(array $blocks): BlockPalette //TODO this really isn't optimal.. $state = BlockStatesParser::getStateByBlock($block); if ($state !== null) { - $palette->addBlockQuery(new BlockQuery($state->blockFull, null, null, null, null, 100)); + $palette->addBlockQuery(BlockQuery::fromString($state->blockFull)); }//TODO exceptions } $palette->randomBlockQueries->setup(); @@ -162,7 +153,7 @@ public static function fromStringArray(string $blocks): array { $e = []; foreach (json_decode($blocks, true, 512, JSON_THROW_ON_ERROR) as $query) { - $q = new BlockQuery($query, null, null, null, null); + $q = new BlockQuery($query, null, null, null, null, 100); $q->parse();//TODO the weight might not be parsed $e[] = $q; } @@ -182,7 +173,7 @@ public function toItem(string $id): Item CompoundTag::create() ->setString("id", $id) ); - $item->setCustomName(Loader::PREFIX . TF::BOLD . TF::LIGHT_PURPLE . "Palette $id"); + $item->setCustomName(Loader::PREFIX . TF::BOLD . TF::LIGHT_PURPLE . "Palette"); $lines = []; $blocks = $this->toStringArray(); $lines[] = TF::RESET . TF::BOLD . TF::GOLD . "Blocks: "; diff --git a/src/xenialdan/MagicWE2/helper/BlockQuery.php b/src/xenialdan/MagicWE2/helper/BlockQuery.php index c9e3c266..a1e7b939 100644 --- a/src/xenialdan/MagicWE2/helper/BlockQuery.php +++ b/src/xenialdan/MagicWE2/helper/BlockQuery.php @@ -9,6 +9,8 @@ use pocketmine\item\LegacyStringToItemParserException; use pocketmine\nbt\UnexpectedTagTypeException; use xenialdan\MagicWE2\exception\BlockQueryAlreadyParsedException; +use function preg_match_all; +use const PREG_SET_ORDER; final class BlockQuery { @@ -29,14 +31,15 @@ final class BlockQuery * @param string|null $fullExtraQuery * @param float|null $weight */ - public function __construct(string $query, ?string $fullBlockQuery, ?string $blockId, ?string $blockStatesQuery, ?string $fullExtraQuery, ?float $weight = 100) + public function __construct(string $query, ?string $fullBlockQuery, ?string $blockId, ?string $blockStatesQuery, ?string $fullExtraQuery, ?float $weight) { $this->query = $query; $this->fullBlockQuery = $fullBlockQuery; $this->blockId = $blockId; $this->blockStatesQuery = $blockStatesQuery; $this->fullExtraQuery = $fullExtraQuery; - $this->weight = (float)$weight / 100; + if ($weight === null) $this->weight = 1; + else $this->weight = $weight / 100; } /** @@ -54,12 +57,23 @@ public function parse(bool $update = true): self //calling methods should check with hasBlock() before parse() if (!$update && $this->hasBlock()) throw new BlockQueryAlreadyParsedException("FullBlockID is already parsed"); $blockstateParser = BlockStatesParser::getInstance(); - $blockstateParser::fromString($this);//this should already set the blockFullId because it is a reference + $this->blockFullId = $blockstateParser::fromString($this)->getFullId();//this should already set the blockFullId because it is a reference //var_dump($this->hasBlock() ? "Has block, " . $this->blockFullId : "Does not have block"); //TODO throw BlockQueryParsingFailedException if blockFullId was not set? `if(!$this->hasBlock())` return $this; } + public static function fromString(string $query): self + { + // How to code ugly 101: https://3v4l.org/2KfNW + preg_match_all('/([\w:]+)(?:\[([\w=,]*)])?/m', $query, $matches, PREG_SET_ORDER); + [$blockMatch, $extraMatch] = [$matches[0] ?? [], $matches[1] ?? []]; + $blockMatch += [null, null, null]; + $extraMatch += [null, null]; + [[$fullBlockQuery, $blockId, $blockStatesQuery], [$fullExtraQuery, $weight]] = [$blockMatch, $extraMatch]; + return (new self($query, $fullBlockQuery, $blockId, $blockStatesQuery, $fullExtraQuery, $weight))->parse(); + } + public function hasBlockStates(): bool { return $this->blockStatesQuery !== null; diff --git a/src/xenialdan/MagicWE2/helper/WeightedRandom.php b/src/xenialdan/MagicWE2/helper/WeightedRandom.php index c67e2031..d9d2f537 100644 --- a/src/xenialdan/MagicWE2/helper/WeightedRandom.php +++ b/src/xenialdan/MagicWE2/helper/WeightedRandom.php @@ -169,4 +169,20 @@ public function indexes(): Generator yield $index; } } + + /** + * @return array + */ + public function getIndexes(): array + { + return $this->indexes; + } + + /** + * @return float[] + */ + public function getProbabilities(): array + { + return $this->probabilities; + } } \ No newline at end of file diff --git a/src/xenialdan/MagicWE2/session/data/PaletteCollection.php b/src/xenialdan/MagicWE2/session/data/PaletteCollection.php index 33430e91..f6bd2eed 100644 --- a/src/xenialdan/MagicWE2/session/data/PaletteCollection.php +++ b/src/xenialdan/MagicWE2/session/data/PaletteCollection.php @@ -5,7 +5,6 @@ namespace xenialdan\MagicWE2\session\data; use pocketmine\item\Item; -use pocketmine\nbt\tag\CompoundTag; use pocketmine\nbt\UnexpectedTagTypeException; use xenialdan\MagicWE2\API; use xenialdan\MagicWE2\exception\PaletteException; @@ -15,7 +14,6 @@ final class PaletteCollection { - /** @var array */ public array $palettes = []; private UserSession $session; @@ -44,6 +42,11 @@ public function getPalette(string $id): ?BlockPalette return $this->palettes[$id];//TODO allow finding by custom name } + public function addPalette(BlockPalette $palette, string $id): void + { + $this->palettes[$id] = $palette; + } + public function toJson(): string { //TODO @@ -64,11 +67,11 @@ public function toJson(): string */ public function getPaletteFromItem(Item $item): BlockPalette { - if ((($entry = $item->getNamedTag()->getCompoundTag(API::TAG_MAGIC_WE_PALETTE))) instanceof CompoundTag) { + if ((($entry = $item->getNamedTag()->getCompoundTag(API::TAG_MAGIC_WE_PALETTE))) !== null) { $id = $entry->getString("id");//todo check if not found - $brush = $this->getPalette($id); - if ($brush instanceof BlockPalette) { - return $brush; + $palette = $this->getPalette($id); + if ($palette instanceof BlockPalette) { + return $palette; } throw new PaletteException("No palette with the id $id could be found!"); } From e651a1a9b21bf40f3a372c5f82eb109b3af9b896 Mon Sep 17 00:00:00 2001 From: XenialDan Date: Sun, 3 Oct 2021 17:00:14 +0200 Subject: [PATCH 52/67] Update libstructure dependency --- .poggit.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.poggit.yml b/.poggit.yml index 7053f4f0..5c49f8c1 100644 --- a/.poggit.yml +++ b/.poggit.yml @@ -25,7 +25,7 @@ projects: version: ^4.1.0 branch: "4.0" - src: thebigsmilexd/libstructure/libstructure - version: ^0.1.4 + version: ^0.1.5 branch: mcstructure - src: buchwasa/scorefactory/ScoreFactory version: ^3.0.1 From c2d74a5ad04fde39046ff8a4050edcec2afda6fc Mon Sep 17 00:00:00 2001 From: XenialDan Date: Sun, 3 Oct 2021 17:02:18 +0200 Subject: [PATCH 53/67] Remove redundant PHPDoc in UserSession --- .../MagicWE2/session/UserSession.php | 55 ------------------- 1 file changed, 55 deletions(-) diff --git a/src/xenialdan/MagicWE2/session/UserSession.php b/src/xenialdan/MagicWE2/session/UserSession.php index 2c8e1dca..b665176c 100644 --- a/src/xenialdan/MagicWE2/session/UserSession.php +++ b/src/xenialdan/MagicWE2/session/UserSession.php @@ -23,24 +23,16 @@ class UserSession extends Session implements JsonSerializable //TODO use JsonMapper { - /** @var Player|null */ private ?Player $player = null; - /** @var BossBar */ private BossBar $bossBar; - /** @var Scoreboard|null */ public ?Scoreboard $sidebar = null; - /** @var bool */ private bool $wandEnabled = true; - /** @var bool */ private bool $debugToolEnabled = true; - /** @var bool */ private bool $wailaEnabled = true; - /** @var bool */ private bool $sidebarEnabled = true;//TODO settings/commands private BrushCollection $brushes; private AssetCollection $assets; private PaletteCollection $palettes; - /** @var Language|null */ private ?Language $lang = null; public bool $displayOutline = false; @@ -76,9 +68,6 @@ public function __destruct() } } - /** - * @return Language - */ public function getLanguage(): Language { return $this->lang; @@ -101,70 +90,43 @@ public function setLanguage(string $langShort): void } } - /** - * @param null|Player $player - */ public function setPlayer(?Player $player): void { $this->player = $player; } - /** - * @return null|Player - */ public function getPlayer(): ?Player { return $this->player; } - /** - * @return bool - */ public function isWandEnabled(): bool { return $this->wandEnabled; } - /** - * @param bool $wandEnabled - * @return string - */ public function setWandEnabled(bool $wandEnabled): string { $this->wandEnabled = $wandEnabled; return Loader::PREFIX . $this->getLanguage()->translateString('tool.wand.setenabled', [($wandEnabled ? TF::GREEN . $this->getLanguage()->translateString('enabled') : TF::RED . $this->getLanguage()->translateString('disabled'))]); } - /** - * @return bool - */ public function isDebugToolEnabled(): bool { return $this->debugToolEnabled; } - /** - * @param bool $debugToolEnabled - * @return string - */ public function setDebugToolEnabled(bool $debugToolEnabled): string { $this->debugToolEnabled = $debugToolEnabled; return Loader::PREFIX . $this->getLanguage()->translateString('tool.debug.setenabled', [($debugToolEnabled ? TF::GREEN . $this->getLanguage()->translateString('enabled') : TF::RED . $this->getLanguage()->translateString('disabled'))]); } - /** - * @return bool - */ public function isSidebarEnabled(): bool { return $this->sidebarEnabled; } - /** - * @param bool $sidebarEnabled - * @return string - */ public function setSidebarEnabled(bool $sidebarEnabled): string { $player = $this->getPlayer(); @@ -178,18 +140,11 @@ public function setSidebarEnabled(bool $sidebarEnabled): string return Loader::PREFIX . $this->getLanguage()->translateString('tool.sidebar.setenabled', [($sidebarEnabled ? TF::GREEN . $this->getLanguage()->translateString('enabled') : TF::RED . $this->getLanguage()->translateString('disabled'))]); } - /** - * @return bool - */ public function isWailaEnabled(): bool { return $this->wailaEnabled; } - /** - * @param bool $wailaEnabled - * @return string - */ public function setWailaEnabled(bool $wailaEnabled): string { $player = $this->getPlayer(); @@ -203,9 +158,6 @@ public function setWailaEnabled(bool $wailaEnabled): string return Loader::PREFIX . $this->getLanguage()->translateString('tool.waila.setenabled', [($wailaEnabled ? TF::GREEN . $this->getLanguage()->translateString('enabled') : TF::RED . $this->getLanguage()->translateString('disabled'))]); } - /** - * @return BossBar - */ public function getBossBar(): BossBar { return $this->bossBar; @@ -265,13 +217,6 @@ public function sendMessage(string $message): void $this->player->sendMessage(Loader::PREFIX . $message); } - /** - * Specify data which should be serialized to JSON - * @link http://php.net/manual/en/jsonserializable.jsonserialize.php - * @return array data which can be serialized by json_encode, - * which is a value of any type other than a resource. - * @since 5.4.0 - */ public function jsonSerialize(): array { return [ From 2d2f2b2c14237d60aef21ffe58fe245360659699 Mon Sep 17 00:00:00 2001 From: XenialDan Date: Sun, 3 Oct 2021 17:03:42 +0200 Subject: [PATCH 54/67] Clear palettes & assets from inventory --- src/xenialdan/MagicWE2/session/UserSession.php | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/src/xenialdan/MagicWE2/session/UserSession.php b/src/xenialdan/MagicWE2/session/UserSession.php index b665176c..4261a7ac 100644 --- a/src/xenialdan/MagicWE2/session/UserSession.php +++ b/src/xenialdan/MagicWE2/session/UserSession.php @@ -8,7 +8,6 @@ use JsonSerializable; use pocketmine\lang\Language; use pocketmine\lang\LanguageNotFoundException; -use pocketmine\nbt\tag\CompoundTag; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; use SplDoublyLinkedList; @@ -181,11 +180,16 @@ public function getPalettes(): PaletteCollection public function cleanupInventory(): void { foreach ($this->getPlayer()->getInventory()->getContents() as $slot => $item) { - /** @var CompoundTag $entry */ - if (!is_null(($entry = $item->getNamedTag()->getCompoundTag(API::TAG_MAGIC_WE_BRUSH)))) { + if (!is_null(($item->getNamedTag()->getCompoundTag(API::TAG_MAGIC_WE_BRUSH)))) { $this->getPlayer()->getInventory()->clear($slot); } - if (!is_null(($entry = $item->getNamedTag()->getCompoundTag(API::TAG_MAGIC_WE)))) { + if (!is_null(($item->getNamedTag()->getCompoundTag(API::TAG_MAGIC_WE)))) { + $this->getPlayer()->getInventory()->clear($slot); + } + if (!is_null(($item->getNamedTag()->getCompoundTag(API::TAG_MAGIC_WE_ASSET)))) { + $this->getPlayer()->getInventory()->clear($slot); + } + if (!is_null(($item->getNamedTag()->getCompoundTag(API::TAG_MAGIC_WE_PALETTE)))) { $this->getPlayer()->getInventory()->clear($slot); } } From f7ca1ba21fe2783258ed63b4d4c650c442c8abb1 Mon Sep 17 00:00:00 2001 From: XenialDan Date: Sun, 3 Oct 2021 17:08:03 +0200 Subject: [PATCH 55/67] Update scoreboard on UserSession bool option change --- src/xenialdan/MagicWE2/session/UserSession.php | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/xenialdan/MagicWE2/session/UserSession.php b/src/xenialdan/MagicWE2/session/UserSession.php index 4261a7ac..c0c0b3c1 100644 --- a/src/xenialdan/MagicWE2/session/UserSession.php +++ b/src/xenialdan/MagicWE2/session/UserSession.php @@ -107,6 +107,7 @@ public function isWandEnabled(): bool public function setWandEnabled(bool $wandEnabled): string { $this->wandEnabled = $wandEnabled; + $this->sidebar?->handleScoreboard($this); return Loader::PREFIX . $this->getLanguage()->translateString('tool.wand.setenabled', [($wandEnabled ? TF::GREEN . $this->getLanguage()->translateString('enabled') : TF::RED . $this->getLanguage()->translateString('disabled'))]); } @@ -118,6 +119,7 @@ public function isDebugToolEnabled(): bool public function setDebugToolEnabled(bool $debugToolEnabled): string { $this->debugToolEnabled = $debugToolEnabled; + $this->sidebar?->handleScoreboard($this); return Loader::PREFIX . $this->getLanguage()->translateString('tool.debug.setenabled', [($debugToolEnabled ? TF::GREEN . $this->getLanguage()->translateString('enabled') : TF::RED . $this->getLanguage()->translateString('disabled'))]); } @@ -154,6 +156,7 @@ public function setWailaEnabled(bool $wailaEnabled): string } else { Loader::getInstance()->wailaBossBar->hideFrom([$player]); } + $this->sidebar?->handleScoreboard($this); return Loader::PREFIX . $this->getLanguage()->translateString('tool.waila.setenabled', [($wailaEnabled ? TF::GREEN . $this->getLanguage()->translateString('enabled') : TF::RED . $this->getLanguage()->translateString('disabled'))]); } From e89cedca5b76868a6d2e395899c94fc84b9e08d2 Mon Sep 17 00:00:00 2001 From: XenialDan Date: Mon, 4 Oct 2021 00:28:40 +0200 Subject: [PATCH 56/67] Outline is now mostly functional --- src/xenialdan/MagicWE2/EventListener.php | 64 ++----------- src/xenialdan/MagicWE2/helper/Scoreboard.php | 1 + .../MagicWE2/helper/SessionHelper.php | 5 +- .../MagicWE2/session/UserSession.php | 42 ++++++++- .../MagicWE2/session/data/Outline.php | 92 +++++++++++++++---- 5 files changed, 128 insertions(+), 76 deletions(-) diff --git a/src/xenialdan/MagicWE2/EventListener.php b/src/xenialdan/MagicWE2/EventListener.php index 22113c33..b9958482 100644 --- a/src/xenialdan/MagicWE2/EventListener.php +++ b/src/xenialdan/MagicWE2/EventListener.php @@ -8,7 +8,6 @@ use InvalidStateException; use jojoe77777\FormAPI\ModalForm; use JsonException; -use pocketmine\block\BlockFactory; use pocketmine\block\BlockLegacyIds; use pocketmine\entity\InvalidSkinException; use pocketmine\event\block\BlockBreakEvent; @@ -20,7 +19,6 @@ use pocketmine\event\player\PlayerJoinEvent; use pocketmine\event\player\PlayerQuitEvent; use pocketmine\item\ItemIds; -use pocketmine\math\Vector3; use pocketmine\nbt\UnexpectedTagTypeException; use pocketmine\player\Player; use pocketmine\plugin\Plugin; @@ -34,9 +32,9 @@ use xenialdan\MagicWE2\exception\SessionException; use xenialdan\MagicWE2\helper\SessionHelper; use xenialdan\MagicWE2\selection\Selection; -use xenialdan\MagicWE2\session\data\Asset; use xenialdan\MagicWE2\session\UserSession; use xenialdan\MagicWE2\tool\Brush; +use function var_dump; class EventListener implements Listener { @@ -383,8 +381,10 @@ public function onDropItem(PlayerDropItemEvent $event): void public function onSelectionChange(MWESelectionChangeEvent $event): void { Loader::getInstance()->getLogger()->debug("Called " . $event->getEventName()); - if (($session = $event->getSession()) instanceof UserSession && $event->getPlayer() !== null) { + $session = $event->getSession(); + if ($session instanceof UserSession && $event->getPlayer() !== null) { /** @var UserSession $session */ + $session->createOrUpdateOutline($event->getSelection()); $session->sidebar->handleScoreboard($session); } } @@ -397,7 +397,7 @@ public function onSelectionChange(MWESelectionChangeEvent $event): void */ public function onChangeSlot(PlayerItemHeldEvent $event): void { - var_dump($event->getSlot()); + /*var_dump($event->getSlot()); $player = $event->getPlayer(); #$item = $player->getInventory()->getItemInHand(); $item = $player->getInventory()->getItem($event->getSlot()); @@ -409,69 +409,25 @@ public function onChangeSlot(PlayerItemHeldEvent $event): void $asset = Loader::$assetCollection->assets[$filename];//TODO allow private assets again var_dump($filename, $asset); #$assets = AssetCollection::getInstance()->getPlayerAssets($player->getXuid()); - $session->displayOutline = true; + $session->setOutlineEnabled(true); #foreach ($assets as $asset) { $backwards = $player->getDirectionVector()->normalize()->multiply(-1); $target = $player->getTargetBlock(10)->getPosition(); $target->addVector($backwards);//this selects the block before raytrace $target->subtract(0, 1, 0);//one block down $target = Position::fromObject($target, $player->getWorld()); - if (/*$session->displayOutline && */ self::sendOutline($player, $target, $asset, $session)) { + if (/*$session->displayOutline && * / self::sendOutline($player, $target, $asset, $session)) { $player->sendMessage("Added asset outline for $asset->filename!"); } else { $player->sendMessage("Did not add asset outline!"); } #} } else { - $session->displayOutline = false; + $session->setOutlineEnabled(false); } } else { - $session->displayOutline = false; - } - } - - public static function sendOutline(Player $player, Position $target, Asset $asset, UserSession $session): bool - { - var_dump(__METHOD__); - #$start = clone $target->asVector3()->floor()->addVector($asset->getOrigin())->floor();//start pos of paste//TODO if using rotate, this fails - #$end = $start->addVector($asset->getSize()->subtractVector($asset->getOrigin()));//add size - //[$target->x,$target->y,$target->z] = [($v=$target->asVector3())->getFloorX(),$v->getFloorY(),$v->getFloorZ()]; - $start = clone $target->asVector3();//start pos of paste//TODO if using rotate, this fails - $end = $start->addVector($asset->getSize()->subtract(1, 1, 1));//add size, remove 1 because structure block outline always covers 1 block - $offset = new Vector3($asset->getSize()->getX() / 2, 0, $asset->getSize()->getZ() / 2); - $start = $start->subtractVector($offset); - $end = $end->subtractVector($offset); - [$ix, $iy, $iz, $ax, $ay, $az] = [Vector3::minComponents($start, $end)->getFloorX(), Vector3::minComponents($start, $end)->getFloorY(), Vector3::minComponents($start, $end)->getFloorZ(), Vector3::maxComponents($start, $end)->getFloorX(), Vector3::maxComponents($start, $end)->getFloorY(), Vector3::maxComponents($start, $end)->getFloorZ()]; - - $minComponents = new Vector3($ix, $iy, $iz); - $maxComponents = new Vector3($ax, $ay, $az); - $block = BlockFactory::getInstance()->get(BlockLegacyIds::STRUCTURE_BLOCK, 0/*StructureEditorData::TYPE_SAVE*/); - var_dump((string)$block); - $target->world->setBlock($target->asVector3(), $block); - var_dump("placing block", __METHOD__, (string)$target->world->getBlock($target->asVector3())); - /** @var null|StructureBlockTile $tile */ - $tile = $target->world->getTile($target->asVector3()); - if ($tile instanceof StructureBlockTile) { - var_dump($tile->getSpawnCompound()->toString()); - $tile - ->setFromV3($minComponents) - ->setToV3($maxComponents) - //TODO add setOffsetV3 - ->setTitle($asset->displayname) - ->setShowBlocks(true) - ->setShowBoundingBox(true) - ->setShowEntities(false) - ->setShowPlayers(false) - ->setHideStructureBlock(false); - $tile->saveNBT(); - #$target->getWorld()->scheduleDelayedBlockUpdate($target, 1); - var_dump($tile->getSpawnCompound()->toString()); - } else { - var_dump("no tile"); - return false; - } - - return true; + $session->setOutlineEnabled(false); + }*/ } public function onStructureBlockClick(PlayerInteractEvent $event): void diff --git a/src/xenialdan/MagicWE2/helper/Scoreboard.php b/src/xenialdan/MagicWE2/helper/Scoreboard.php index 9495f0b5..64f02a37 100644 --- a/src/xenialdan/MagicWE2/helper/Scoreboard.php +++ b/src/xenialdan/MagicWE2/helper/Scoreboard.php @@ -44,6 +44,7 @@ public function handleScoreboard(UserSession $session): void ScoreFactory::setScoreLine($player, ++$line, TF::BOLD . " Wand Tool: " . TF::RESET . API::boolToString($session->isWandEnabled())); ScoreFactory::setScoreLine($player, ++$line, TF::BOLD . " Debug Tool: " . TF::RESET . API::boolToString($session->isDebugToolEnabled())); ScoreFactory::setScoreLine($player, ++$line, TF::BOLD . " WAILA: " . TF::RESET . API::boolToString($session->isWailaEnabled())); + ScoreFactory::setScoreLine($player, ++$line, TF::BOLD . " Outline: " . TF::RESET . API::boolToString($session->isOutlineEnabled())); if (($cb = $session->getCurrentClipboard()) instanceof SingleClipboard) { ScoreFactory::setScoreLine($player, ++$line, TF::GOLD . $session->getLanguage()->translateString("spacer", ["Clipboard"])); diff --git a/src/xenialdan/MagicWE2/helper/SessionHelper.php b/src/xenialdan/MagicWE2/helper/SessionHelper.php index 3564ab07..aec4901b 100644 --- a/src/xenialdan/MagicWE2/helper/SessionHelper.php +++ b/src/xenialdan/MagicWE2/helper/SessionHelper.php @@ -199,12 +199,12 @@ public static function loadUserSession(Player $player): ?UserSession $session->setWailaEnabled($data["wailaEnabled"]); $session->setSidebarEnabled($data["sidebarEnabled"]); $session->setLanguage($data["language"]); - foreach ($data["brushes"] as $brushUUID => $brushJson) { + foreach ($data["brushes"] as $brushJson) { try { $properties = BrushProperties::fromJson($brushJson["properties"]); $brush = new Brush($properties); $session->getBrushes()->addBrush($brush); - } catch (InvalidArgumentException $e) { + } catch (InvalidArgumentException) { continue; } } @@ -239,6 +239,7 @@ public static function loadUserSession(Player $player): ?UserSession } catch (RuntimeException $e) { } } + $session->setOutlineEnabled($data["outlineEnabled"]); //TODO clipboard } catch (Exception $exception) { return null; diff --git a/src/xenialdan/MagicWE2/session/UserSession.php b/src/xenialdan/MagicWE2/session/UserSession.php index c0c0b3c1..af176d1d 100644 --- a/src/xenialdan/MagicWE2/session/UserSession.php +++ b/src/xenialdan/MagicWE2/session/UserSession.php @@ -15,8 +15,10 @@ use xenialdan\MagicWE2\API; use xenialdan\MagicWE2\helper\Scoreboard; use xenialdan\MagicWE2\Loader; +use xenialdan\MagicWE2\selection\Selection; use xenialdan\MagicWE2\session\data\AssetCollection; use xenialdan\MagicWE2\session\data\BrushCollection; +use xenialdan\MagicWE2\session\data\Outline; use xenialdan\MagicWE2\session\data\PaletteCollection; use function mkdir; @@ -29,11 +31,12 @@ class UserSession extends Session implements JsonSerializable //TODO use JsonMap private bool $debugToolEnabled = true; private bool $wailaEnabled = true; private bool $sidebarEnabled = true;//TODO settings/commands + private bool $outlineEnabled = true; + private ?Outline $outline = null; private BrushCollection $brushes; private AssetCollection $assets; private PaletteCollection $palettes; private ?Language $lang = null; - public bool $displayOutline = false; public function __construct(Player $player) { @@ -160,6 +163,39 @@ public function setWailaEnabled(bool $wailaEnabled): string return Loader::PREFIX . $this->getLanguage()->translateString('tool.waila.setenabled', [($wailaEnabled ? TF::GREEN . $this->getLanguage()->translateString('enabled') : TF::RED . $this->getLanguage()->translateString('disabled'))]); } + public function isOutlineEnabled(): bool + { + return $this->outlineEnabled; + } + + public function setOutlineEnabled(bool $outlineEnabled): string + { + $player = $this->getPlayer(); + if (!$player instanceof Player) return TF::RED . "Session has no player"; + $this->outlineEnabled = $outlineEnabled; + if ($outlineEnabled) { + $selection = $this->getLatestSelection(); + $this->outline = $this->createOrUpdateOutline($selection); + } else { + if ($this->outline instanceof Outline) { + $this->outline->remove(); + $this->outline = null; + } + } + $this->sidebar?->handleScoreboard($this); + return Loader::PREFIX . $this->getLanguage()->translateString('tool.outline.setenabled', [($outlineEnabled ? TF::GREEN . $this->getLanguage()->translateString('enabled') : TF::RED . $this->getLanguage()->translateString('disabled'))]); + } + + public function getOutline(): ?Outline + { + return $this->outline; + } + + public function createOrUpdateOutline(Selection $selection): Outline + { + return $this->outline?->setSelection($selection) ?? new Outline($selection, $this->getPlayer()); + } + public function getBossBar(): BossBar { return $this->bossBar; @@ -207,6 +243,7 @@ public function __toString() " Debug tool enabled: " . ($this->isDebugToolEnabled() ? "enabled" : "disabled") . " WAILA enabled: " . ($this->isWailaEnabled() ? "enabled" : "disabled") . " Sidebar enabled: " . ($this->sidebarEnabled ? "enabled" : "disabled") . + " Outline enabled: " . ($this->outlineEnabled ? "enabled" : "disabled") . " BossBar: " . $this->getBossBar()->entityId . " Selections: " . count($this->getSelections()) . " Latest: " . $this->getLatestSelectionUUID() . @@ -232,6 +269,7 @@ public function jsonSerialize(): array "debugToolEnabled" => $this->debugToolEnabled, "wailaEnabled" => $this->wailaEnabled, "sidebarEnabled" => $this->sidebarEnabled, + "outlineEnabled" => $this->outlineEnabled, "brushes" => $this->brushes->brushes, //todo assets, palettes "latestSelection" => $this->getLatestSelection(), @@ -242,7 +280,7 @@ public function jsonSerialize(): array public function save(): void { - @mkdir(Loader::getInstance()->getDataFolder() . "sessions",0777,true); + @mkdir(Loader::getInstance()->getDataFolder() . "sessions", 0777, true); file_put_contents(Loader::getInstance()->getDataFolder() . "sessions" . DIRECTORY_SEPARATOR . $this->getPlayer()->getName() . ".json", json_encode($this, JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT) diff --git a/src/xenialdan/MagicWE2/session/data/Outline.php b/src/xenialdan/MagicWE2/session/data/Outline.php index d211f4b7..0afaa06c 100644 --- a/src/xenialdan/MagicWE2/session/data/Outline.php +++ b/src/xenialdan/MagicWE2/session/data/Outline.php @@ -4,20 +4,77 @@ namespace xenialdan\MagicWE2\session\data; +use pocketmine\block\Block; +use pocketmine\block\BlockFactory; +use pocketmine\block\BlockLegacyIds; +use pocketmine\block\tile\Spawnable; +use pocketmine\network\mcpe\convert\RuntimeBlockMapping; +use pocketmine\network\mcpe\protocol\BlockActorDataPacket; +use pocketmine\network\mcpe\protocol\UpdateBlockPacket; +use pocketmine\player\Player; +use pocketmine\world\Position; +use ReflectionException; +use ReflectionProperty; use xenialdan\libstructure\tile\StructureBlockTile; +use xenialdan\MagicWE2\selection\Selection; +use function get_class; class Outline { - public ?Asset $asset = null; - public ?StructureBlockTile $tile = null; + private Selection $selection; + private Player $player; + private Position $position; + private Block $fakeBlock; + private StructureBlockTile $fakeTile; - /** - * Asset constructor. - * @param Asset|null $asset - */ - public function __construct(?Asset $asset = null) + public function __construct(Selection $selection, Player $player) + { + $this->selection = $selection; + $this->player = $player; + $this->fakeBlock = BlockFactory::getInstance()->get(BlockLegacyIds::STRUCTURE_BLOCK, 0); + $this->position = $this->updateBlockPosition(); + $this->fakeTile = new StructureBlockTile($this->position->getWorld(), $this->position); + $this->fakeTile->setShowBoundingBox(true)->setFromV3($selection->getPos1())->setToV3($selection->getPos2()); + $this->send(); + } + + public function getSelection(): Selection { - $this->asset = $asset; + return $this->selection; + } + + public function setSelection(Selection $selection): self + { + $this->selection = $selection; + $this->remove(); + $this->updatePosition(); + //TODO change position of fakeTile using reflection + #$this->fakeTile->setDirty(); + $this->fakeTile->setShowBoundingBox(true)->setFromV3($selection->getPos1())->setToV3($selection->getPos2()); + $this->send(); + return $this; + } + + public function send(): void + { + $this->player->getNetworkSession()->sendDataPacket(UpdateBlockPacket::create($this->position->x, $this->position->y, $this->position->z, RuntimeBlockMapping::getInstance()->toRuntimeId($this->fakeBlock->getFullId()))); + if ($this->fakeTile instanceof Spawnable) { + $this->player->getNetworkSession()->sendDataPacket(BlockActorDataPacket::create($this->position->x, $this->position->y, $this->position->z, $this->fakeTile->getSerializedSpawnCompound()), true); + } + } + + public function remove(): void + { + $network = $this->player->getNetworkSession(); + $world = $this->player->getWorld(); + $runtime_block_mapping = RuntimeBlockMapping::getInstance(); + $block = $world->getBlockAt($this->position->x, $this->position->y, $this->position->z); + $network->sendDataPacket(UpdateBlockPacket::create($this->position->x, $this->position->y, $this->position->z, $runtime_block_mapping->toRuntimeId($block->getFullId())), true); + + $tile = $world->getTileAt($this->position->x, $this->position->y, $this->position->z); + if ($tile instanceof Spawnable) { + $network->sendDataPacket(BlockActorDataPacket::create($this->position->x, $this->position->y, $this->position->z, $tile->getSerializedSpawnCompound()), true); + } } public function __toString(): string @@ -26,20 +83,19 @@ public function __toString(): string } /** - * @return Asset|null + * @throws ReflectionException */ - public function getAsset(): ?Asset + private function updatePosition(): Position { - return $this->asset; + $this->position = $this->updateBlockPosition(); + $reflection = new ReflectionProperty(get_class($this->fakeTile), 'position'); + $reflection->setAccessible(true); + $reflection->setValue($this->fakeTile, $this->position); + return $this->position; } - /** - * @param Asset|null $asset - * @return Outline - */ - public function setAsset(?Asset $asset): Outline + private function updateBlockPosition(): Position { - $this->asset = $asset; - return $this; + return Position::fromObject($this->player->getPosition()->withComponents(null, $this->player->getPosition()->getWorld()->getMinY(), null)->floor(), $this->player->getWorld()); } } \ No newline at end of file From 16fa1bda2bbf457efe5f4da42301b0d0ac47bc05 Mon Sep 17 00:00:00 2001 From: XenialDan Date: Mon, 4 Oct 2021 00:35:44 +0200 Subject: [PATCH 57/67] Add ToggleOutlineCommand --- plugin.yml | 2 + src/xenialdan/MagicWE2/Loader.php | 2 + .../commands/utility/ToggleOutlineCommand.php | 54 +++++++++++++++++++ 3 files changed, 58 insertions(+) create mode 100644 src/xenialdan/MagicWE2/commands/utility/ToggleOutlineCommand.php diff --git a/plugin.yml b/plugin.yml index 9dae74ed..58eeb54a 100644 --- a/plugin.yml +++ b/plugin.yml @@ -119,6 +119,8 @@ permissions: default: op we.command.utility.togglesidebar: default: op + we.command.utility.toggleoutline: + default: op we.command.debug: default: op ... diff --git a/src/xenialdan/MagicWE2/Loader.php b/src/xenialdan/MagicWE2/Loader.php index bc58bb73..96d6e669 100644 --- a/src/xenialdan/MagicWE2/Loader.php +++ b/src/xenialdan/MagicWE2/Loader.php @@ -66,6 +66,7 @@ use xenialdan\MagicWE2\commands\tool\TogglewandCommand; use xenialdan\MagicWE2\commands\tool\WandCommand; use xenialdan\MagicWE2\commands\utility\CalculateCommand; +use xenialdan\MagicWE2\commands\utility\ToggleOutlineCommand; use xenialdan\MagicWE2\commands\utility\ToggleSidebarCommand; use xenialdan\MagicWE2\commands\utility\ToggleWailaCommand; use xenialdan\MagicWE2\commands\VersionCommand; @@ -307,6 +308,7 @@ public function onEnable(): void new CalculateCommand($this, "/calculate", "Evaluate a mathematical expression", ["/calc", "/eval", "/evaluate", "/solve"]), new ToggleWailaCommand($this, "/togglewaila", "Toggle the What Am I Looking At utility", ["/waila", "/wyla"]), new ToggleSidebarCommand($this, "/togglesidebar", "Toggle the sidebar", ["/sidebar"]), + new ToggleOutlineCommand($this, "/toggleoutline", "Toggle the selection outline", ["/outline", "/showbounds"]), ]); if ($registerDeveloperCommands) $this->getServer()->getCommandMap()->registerAll("MagicWE2", [ /* -- developer commands -- */ diff --git a/src/xenialdan/MagicWE2/commands/utility/ToggleOutlineCommand.php b/src/xenialdan/MagicWE2/commands/utility/ToggleOutlineCommand.php new file mode 100644 index 00000000..5ae223a1 --- /dev/null +++ b/src/xenialdan/MagicWE2/commands/utility/ToggleOutlineCommand.php @@ -0,0 +1,54 @@ +setPermission("we.command.utility.toggleoutline"); + } + + public function onRun(CommandSender $sender, string $aliasUsed, array $args): void + { + $lang = Loader::getInstance()->getLanguage(); + if ($sender instanceof Player && SessionHelper::hasSession($sender)) { + try { + $lang = SessionHelper::getUserSession($sender)->getLanguage(); + } catch (SessionException $e) { + } + } + if (!$sender instanceof Player) { + $sender->sendMessage(TF::RED . $lang->translateString('error.runingame')); + return; + } + /** @var Player $sender */ + try { + $session = SessionHelper::getUserSession($sender); + if (is_null($session)) { + throw new SessionException($lang->translateString('error.nosession', [Loader::getInstance()->getName()])); + } + $sender->sendMessage($session->setOutlineEnabled(!$session->isOutlineEnabled())); + } catch (Exception $error) { + $sender->sendMessage(Loader::PREFIX . TF::RED . $lang->translateString('error.command-error')); + $sender->sendMessage(Loader::PREFIX . TF::RED . $error->getMessage()); + $sender->sendMessage($this->getUsage()); + } + } +} From 62351a3b92e994d74ca3fd4009d03a5151eca4c1 Mon Sep 17 00:00:00 2001 From: XenialDan Date: Mon, 4 Oct 2021 00:56:12 +0200 Subject: [PATCH 58/67] Outline fully functional (#234), Added MWESelectionChangeEvent::TYPE_CREATE --- src/xenialdan/MagicWE2/EventListener.php | 4 ++-- .../MagicWE2/event/MWESelectionChangeEvent.php | 11 ++++++----- src/xenialdan/MagicWE2/selection/Selection.php | 4 ++++ src/xenialdan/MagicWE2/session/UserSession.php | 2 +- src/xenialdan/MagicWE2/session/data/Outline.php | 2 +- 5 files changed, 14 insertions(+), 9 deletions(-) diff --git a/src/xenialdan/MagicWE2/EventListener.php b/src/xenialdan/MagicWE2/EventListener.php index b9958482..e8d4f8c5 100644 --- a/src/xenialdan/MagicWE2/EventListener.php +++ b/src/xenialdan/MagicWE2/EventListener.php @@ -380,11 +380,11 @@ public function onDropItem(PlayerDropItemEvent $event): void public function onSelectionChange(MWESelectionChangeEvent $event): void { - Loader::getInstance()->getLogger()->debug("Called " . $event->getEventName()); + #Loader::getInstance()->getLogger()->debug("Called " . $event->getEventName()); $session = $event->getSession(); if ($session instanceof UserSession && $event->getPlayer() !== null) { /** @var UserSession $session */ - $session->createOrUpdateOutline($event->getSelection()); + if ($session->isOutlineEnabled()) $session->createOrUpdateOutline($event->getSelection()); $session->sidebar->handleScoreboard($session); } } diff --git a/src/xenialdan/MagicWE2/event/MWESelectionChangeEvent.php b/src/xenialdan/MagicWE2/event/MWESelectionChangeEvent.php index fad29fe1..7c5e4eb4 100644 --- a/src/xenialdan/MagicWE2/event/MWESelectionChangeEvent.php +++ b/src/xenialdan/MagicWE2/event/MWESelectionChangeEvent.php @@ -12,11 +12,12 @@ class MWESelectionChangeEvent extends MWEEvent { - public const TYPE_PLUGIN = 0; - public const TYPE_POS1 = 1; - public const TYPE_POS2 = 2; - public const TYPE_WORLD = 3; - public const TYPE_SHAPE = 4; + public const TYPE_CREATE = 0; + public const TYPE_PLUGIN = 1; + public const TYPE_POS1 = 2; + public const TYPE_POS2 = 3; + public const TYPE_WORLD = 4; + public const TYPE_SHAPE = 5; private Selection $selection; private ?Session $session = null; diff --git a/src/xenialdan/MagicWE2/selection/Selection.php b/src/xenialdan/MagicWE2/selection/Selection.php index 27d7f39c..aa2c082f 100644 --- a/src/xenialdan/MagicWE2/selection/Selection.php +++ b/src/xenialdan/MagicWE2/selection/Selection.php @@ -67,6 +67,10 @@ public function __construct(UuidInterface $sessionUUID, World $world, ?int $minX } if ($shape !== null) $this->shape = $shape; $this->setUUID(Uuid::uuid4()); + try { + (new MWESelectionChangeEvent($this, MWESelectionChangeEvent::TYPE_CREATE))->call(); + } catch (RuntimeException $e) { + } } /** diff --git a/src/xenialdan/MagicWE2/session/UserSession.php b/src/xenialdan/MagicWE2/session/UserSession.php index af176d1d..62fb28b4 100644 --- a/src/xenialdan/MagicWE2/session/UserSession.php +++ b/src/xenialdan/MagicWE2/session/UserSession.php @@ -179,7 +179,7 @@ public function setOutlineEnabled(bool $outlineEnabled): string } else { if ($this->outline instanceof Outline) { $this->outline->remove(); - $this->outline = null; + #$this->outline = null; } } $this->sidebar?->handleScoreboard($this); diff --git a/src/xenialdan/MagicWE2/session/data/Outline.php b/src/xenialdan/MagicWE2/session/data/Outline.php index 0afaa06c..842aa13e 100644 --- a/src/xenialdan/MagicWE2/session/data/Outline.php +++ b/src/xenialdan/MagicWE2/session/data/Outline.php @@ -49,8 +49,8 @@ public function setSelection(Selection $selection): self $this->remove(); $this->updatePosition(); //TODO change position of fakeTile using reflection - #$this->fakeTile->setDirty(); $this->fakeTile->setShowBoundingBox(true)->setFromV3($selection->getPos1())->setToV3($selection->getPos2()); + $this->fakeTile->setDirty(); $this->send(); return $this; } From ad4b97ebc17868986a038a7c80b4928bdaa6a7b7 Mon Sep 17 00:00:00 2001 From: XenialDan Date: Mon, 4 Oct 2021 12:30:58 +0200 Subject: [PATCH 59/67] Update COMMANDS.MD --- COMMANDS.MD | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/COMMANDS.MD b/COMMANDS.MD index 539c484b..d27e6fd5 100644 --- a/COMMANDS.MD +++ b/COMMANDS.MD @@ -8,7 +8,6 @@ This list is automatically generated. If you have noticed an error, please creat | `//hpos1` | Set position 1 to targeted block | `//hpos1 ` | `//h1` | | `//hpos2` | Set position 2 to targeted block | `//hpos2 ` | `//h2` | | `//chunk` | Set the selection to your current chunk | `//chunk ` | | -| `//palette` | Manage block palettes | `//palette ` | | | `//wand` | Gives you the selection wand | `//wand ` | | | `//togglewand` | Toggle the wand tool on/off | `//togglewand ` | `//toggleeditwand` | | `//debug` | Gives you the debug stick, which gives information about the clicked block | `//debug ` | | @@ -43,9 +42,11 @@ This list is automatically generated. If you have noticed an error, please creat | `//calculate` | Evaluate a mathematical expression | `//calculate ` | `//calc, //eval, //evaluate, //solve` | | `//togglewaila` | Toggle the What Am I Looking At utility | `//togglewaila ` | `//waila, //wyla` | | `//togglesidebar` | Toggle the sidebar | `//togglesidebar ` | `//sidebar` | +| `//toggleoutline` | Toggle the selection outline | `//toggleoutline ` | `//outline, //showbounds` | | `//placeallblockstates` | Place all blockstates similar to Java debug worlds | `//placeallblockstates ` | | | `//testapi` | Internal command for testing API methods | `//testapi ` | | | `//generatecommandsmd` | Generates the commands.md file | `//generatecommandsmd ` | | | `//brush` | Opens the brush tool menu | `//brush` | | | `//brush name` | Get name or rename a brush | `/brush name [name:string]` | | +| `//palette` | Manage block palettes | `//palette ` | | | `//flood` | Opens the flood fill tool menu | `//flood ` | `//floodfill` | \ No newline at end of file From b95ae3d17c6c675f6b7609f7dd7d24e14a540b30 Mon Sep 17 00:00:00 2001 From: XenialDan Date: Mon, 4 Oct 2021 13:19:34 +0200 Subject: [PATCH 60/67] Update and restructure README.md --- README.md | 65 ++++++++++++++++++++++++++++++++----------------------- 1 file changed, 38 insertions(+), 27 deletions(-) diff --git a/README.md b/README.md index 41c0f3f3..098de0e1 100644 --- a/README.md +++ b/README.md @@ -1,32 +1,38 @@ ![MagicWE2's awesome wide banner!](https://github.com/thebigsmileXD/MagicWE2/blob/master/resources/magicwe_icon_wide.png) --- -# MagicWE2 -Lag free asynchronous world editor for [PMMP](https://github.com/pmmp/PocketMine-MP) -Try the new MagicWE, now way more powerful, with more support, more commands, new tools and more! +# MagicWE2 -[![Poggit-CI](https://poggit.pmmp.io/ci.badge/thebigsmileXD/MagicWE2/MagicWE2/master)](https://poggit.pmmp.io/ci/thebigsmileXD/MagicWE2) + +[![PHPStan](https://github.com/thebigsmileXD/MagicWE2/workflows/PHPStan/badge.svg)](https://github.com/thebigsmileXD/MagicWE2/workflows/PHPStan) +[![Donations Badge](https://raw.githubusercontent.com/k4m4/donations/master/images/badge.svg)](https://paypal.me/xenialdan) -Jokes aside, here is a list of pros: +Lag free asynchronous world editor for [PMMP](https://github.com/pmmp/PocketMine-MP) with focus on mobile usability + +## Features - Simple usage +- Asynchronous world editing +- Strong focus on simplicity - Translations - Good performance and great speeds -- Progress bars like on Windows 98! -- Sessions +- Many commands +- Progress bars +- Cached sessions - Clipboards -- Optimized item / block parsing - you can place any block, by id, name, and item! -- Alot more commands -- Command auto-completion -- Command flags (i.e. -p for relative copying/pasting, -h for hollow objects) -- UI for brush setup and configuration -- Fancy icon and optional startup ASCII art -- Direct bug reporting to GitHub +- Optimized item / block parsing - you can place any block, by id, name, item and even blockstates +- Command auto-completion (broken, [#blameMojang (Jira Issue)](https://bugs.mojang.com/browse/MCPE-138567)) +- Command specific flags (i.e. -p for relative copying/pasting, -h for hollow objects) +- UIs for brushes, palettes, assets etc. +- Selection shapes & outline +- Simplified placement of assets +- Previews of selections / structures +- Scoreboard integration +- Feature rich API +- Prefilled bug report issue url using `//report` + -You can find a list of commands here: [COMMANDS.MD](https://github.com/thebigsmileXD/MagicWE2/blob/palette-preview/COMMANDS.MD) +You can find a list of commands here: [COMMANDS.MD](https://github.com/thebigsmileXD/MagicWE2/blob/outline/COMMANDS.MD) ## Planned features -- Saved sessions (saved brushes and clipboards) -- More commands, a glimpse at the plugin.yml should give you a good look what is coming up -- Command based flags, since they are currently in a global state -- Schematic and structure block data support + +- More saved session data (saved brushes, clipboards, palettes) +- More commands +- Per-command flags, since they are currently in a global state +- Schematic and structure block data support (in progress) - Clipboard naming, exporting and switching -- ScoreboardAPI integration -- Better and more brushes. For now i suggest using [BlockSniper](https://github.com/BlockHorizons/BlockSniper) for brushes! +- Better and more brushes. For now i suggest using [BlockSniper](https://github.com/BlockHorizons/BlockSniper) for + brushes! - [MyPlot](https://github.com/jasonwynn10/MyPlot) integration +- UI with edit history ## Fast updates You have an urgent issue, your server is crashing or players mess with the world and start griefing? @@ -56,9 +64,12 @@ Feel free to open issues, feature requests and criticism are welcome! If you have an urgent issue, tag me on Twitter for faster response time: [@xenialdan](https://twitter.com/xenialdan) ## Quotes -- _"MagicWE2 has a new fresh coating over the plugin, with rainbow colored sprinkle topping!"_ ~ XenialDan, 2017 + +- _"MagicWE2 has a new fresh coating over the plugin, with rainbow colored sprinkle topping!"_ +- _"MWE2 - Not to be confused with MewTwo"_ ### Foot notes + License: GNU GENERAL PUBLIC LICENSE -Readme last updated: 4th August 2019 \ No newline at end of file +Readme last updated: 4th October 2021 \ No newline at end of file From 630db9ec2fa0b6d3a0874e0f5deb5df67a77fd56 Mon Sep 17 00:00:00 2001 From: XenialDan Date: Mon, 11 Oct 2021 19:06:08 +0200 Subject: [PATCH 61/67] Fix #240 (crash on enabling outline without selection) --- src/xenialdan/MagicWE2/session/UserSession.php | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/xenialdan/MagicWE2/session/UserSession.php b/src/xenialdan/MagicWE2/session/UserSession.php index 62fb28b4..b9313d37 100644 --- a/src/xenialdan/MagicWE2/session/UserSession.php +++ b/src/xenialdan/MagicWE2/session/UserSession.php @@ -175,11 +175,10 @@ public function setOutlineEnabled(bool $outlineEnabled): string $this->outlineEnabled = $outlineEnabled; if ($outlineEnabled) { $selection = $this->getLatestSelection(); - $this->outline = $this->createOrUpdateOutline($selection); + if ($selection instanceof Selection) $this->outline = $this->createOrUpdateOutline($selection); } else { if ($this->outline instanceof Outline) { $this->outline->remove(); - #$this->outline = null; } } $this->sidebar?->handleScoreboard($this); From d6a07195ae348e9eddaea48bc749c4b4693d14ee Mon Sep 17 00:00:00 2001 From: XenialDan Date: Mon, 11 Oct 2021 19:06:44 +0200 Subject: [PATCH 62/67] Add Selection isValid check before creating outline --- src/xenialdan/MagicWE2/session/UserSession.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/xenialdan/MagicWE2/session/UserSession.php b/src/xenialdan/MagicWE2/session/UserSession.php index b9313d37..7146fb37 100644 --- a/src/xenialdan/MagicWE2/session/UserSession.php +++ b/src/xenialdan/MagicWE2/session/UserSession.php @@ -175,7 +175,7 @@ public function setOutlineEnabled(bool $outlineEnabled): string $this->outlineEnabled = $outlineEnabled; if ($outlineEnabled) { $selection = $this->getLatestSelection(); - if ($selection instanceof Selection) $this->outline = $this->createOrUpdateOutline($selection); + if ($selection instanceof Selection && $selection->isValid()) $this->outline = $this->createOrUpdateOutline($selection); } else { if ($this->outline instanceof Outline) { $this->outline->remove(); From f387e1caada8410dbe77bf51cdf4f3b10e6dd79c Mon Sep 17 00:00:00 2001 From: XenialDan Date: Mon, 11 Oct 2021 19:33:36 +0200 Subject: [PATCH 63/67] API 4.0.0-BETA5 cc @SalmonDE --- src/xenialdan/MagicWE2/API.php | 8 +------- src/xenialdan/MagicWE2/EventListener.php | 2 -- src/xenialdan/MagicWE2/clipboard/RevertClipboard.php | 4 ++-- src/xenialdan/MagicWE2/commands/args/BlocksArgument.php | 7 +------ .../MagicWE2/commands/biome/BiomeInfoCommand.php | 2 +- .../commands/selection/info/ListChunksCommand.php | 4 ++-- src/xenialdan/MagicWE2/helper/BlockPalette.php | 2 ++ src/xenialdan/MagicWE2/helper/BlockQuery.php | 2 ++ src/xenialdan/MagicWE2/helper/BlockStatesEntry.php | 5 ----- src/xenialdan/MagicWE2/helper/BlockStatesParser.php | 8 ++++---- src/xenialdan/MagicWE2/selection/shape/Cone.php | 2 +- src/xenialdan/MagicWE2/selection/shape/Cube.php | 2 +- src/xenialdan/MagicWE2/selection/shape/Cuboid.php | 2 +- src/xenialdan/MagicWE2/selection/shape/Custom.php | 2 +- src/xenialdan/MagicWE2/selection/shape/Cylinder.php | 2 +- src/xenialdan/MagicWE2/selection/shape/Ellipsoid.php | 2 +- src/xenialdan/MagicWE2/selection/shape/Pyramid.php | 2 +- src/xenialdan/MagicWE2/selection/shape/Sphere.php | 2 +- src/xenialdan/MagicWE2/session/data/Asset.php | 2 ++ src/xenialdan/MagicWE2/task/AsyncActionTask.php | 4 ++-- src/xenialdan/MagicWE2/task/AsyncCopyTask.php | 2 +- src/xenialdan/MagicWE2/task/AsyncCountTask.php | 2 +- src/xenialdan/MagicWE2/task/AsyncFillTask.php | 4 ++-- src/xenialdan/MagicWE2/task/AsyncPasteAssetTask.php | 4 ++-- src/xenialdan/MagicWE2/task/AsyncPasteTask.php | 4 ++-- src/xenialdan/MagicWE2/task/AsyncReplaceTask.php | 4 ++-- src/xenialdan/MagicWE2/tool/Flood.php | 2 +- 27 files changed, 38 insertions(+), 50 deletions(-) diff --git a/src/xenialdan/MagicWE2/API.php b/src/xenialdan/MagicWE2/API.php index 57c335c9..b4fb7911 100644 --- a/src/xenialdan/MagicWE2/API.php +++ b/src/xenialdan/MagicWE2/API.php @@ -8,12 +8,9 @@ use InvalidArgumentException; use pocketmine\block\Block; use pocketmine\block\BlockFactory; -use pocketmine\block\utils\InvalidBlockStateException; -use pocketmine\item\LegacyStringToItemParserException; use pocketmine\math\AxisAlignedBB; use pocketmine\math\Vector3; use pocketmine\nbt\tag\CompoundTag; -use pocketmine\nbt\UnexpectedTagTypeException; use pocketmine\player\Player; use pocketmine\Server; use pocketmine\utils\AssumptionFailedError; @@ -239,7 +236,7 @@ private static function getAABBTouchedChunksTemp(ChunkManager $manager, AxisAlig continue; } print __METHOD__ . " Touched Chunk at: $x:$z" . PHP_EOL; - $touchedChunks[World::chunkHash($x, $z)] = FastChunkSerializer::serialize($chunk); + $touchedChunks[World::chunkHash($x, $z)] = FastChunkSerializer::serializeTerrain($chunk); } } print __METHOD__ . " Touched chunks count: " . count($touchedChunks) . PHP_EOL; @@ -445,9 +442,6 @@ public static function hasFlag(int $flags, int $check): bool * @return BlockPalette * @throws BlockQueryAlreadyParsedException * @throws InvalidArgumentException - * @throws InvalidBlockStateException - * @throws LegacyStringToItemParserException - * @throws UnexpectedTagTypeException * @deprecated Use BlockPalette::fromString() */ public static function blockParser(string $fullstring, array &$messages, bool &$error): BlockPalette diff --git a/src/xenialdan/MagicWE2/EventListener.php b/src/xenialdan/MagicWE2/EventListener.php index e8d4f8c5..4bb9a0dd 100644 --- a/src/xenialdan/MagicWE2/EventListener.php +++ b/src/xenialdan/MagicWE2/EventListener.php @@ -392,8 +392,6 @@ public function onSelectionChange(MWESelectionChangeEvent $event): void /** * TODO use tool classes * @param PlayerItemHeldEvent $event - * @throws SessionException - * @throws UnexpectedTagTypeException */ public function onChangeSlot(PlayerItemHeldEvent $event): void { diff --git a/src/xenialdan/MagicWE2/clipboard/RevertClipboard.php b/src/xenialdan/MagicWE2/clipboard/RevertClipboard.php index 9fddc849..271993a8 100644 --- a/src/xenialdan/MagicWE2/clipboard/RevertClipboard.php +++ b/src/xenialdan/MagicWE2/clipboard/RevertClipboard.php @@ -45,7 +45,7 @@ public function serialize(): string { $chunks = []; foreach ($this->chunks as $hash => $chunk) { - $chunks[$hash] = FastChunkSerializer::serialize($chunk); + $chunks[$hash] = FastChunkSerializer::serializeTerrain($chunk); } return serialize([ $this->worldId, @@ -71,6 +71,6 @@ public function unserialize($data) $this->blocksAfter ] = unserialize($data/*, ['allowed_classes' => [__CLASS__]]*/);//TODO test pm4 foreach ($chunks as $hash => $chunk) - $this->chunks[$hash] = FastChunkSerializer::deserialize($chunk); + $this->chunks[$hash] = FastChunkSerializer::deserializeTerrain($chunk); } } \ No newline at end of file diff --git a/src/xenialdan/MagicWE2/commands/args/BlocksArgument.php b/src/xenialdan/MagicWE2/commands/args/BlocksArgument.php index 84c529c0..ce8b4fd1 100644 --- a/src/xenialdan/MagicWE2/commands/args/BlocksArgument.php +++ b/src/xenialdan/MagicWE2/commands/args/BlocksArgument.php @@ -6,10 +6,7 @@ use CortexPE\Commando\args\RawStringArgument; use InvalidArgumentException as InvalidArgumentExceptionAlias; -use pocketmine\block\utils\InvalidBlockStateException; use pocketmine\command\CommandSender; -use pocketmine\item\LegacyStringToItemParserException; -use pocketmine\nbt\UnexpectedTagTypeException; use pocketmine\player\Player; use pocketmine\utils\TextFormat as TF; use xenialdan\MagicWE2\exception\BlockQueryAlreadyParsedException; @@ -36,14 +33,12 @@ public function canParse(string $testString, CommandSender $sender): bool * * @return BlockPalette * @throws SessionException - * @throws LegacyStringToItemParserException - * @throws UnexpectedTagTypeException */ public function parse(string $argument, CommandSender $sender): BlockPalette { try { return BlockPalette::fromString($argument); - } catch (BlockQueryAlreadyParsedException|InvalidArgumentExceptionAlias|InvalidBlockStateException $error) { + } catch (BlockQueryAlreadyParsedException | InvalidArgumentExceptionAlias $error) { if ($sender instanceof Player) SessionHelper::getUserSession($sender)->sendMessage('error.command-error'); $sender->sendMessage(Loader::PREFIX . TF::RED . $error->getMessage()); diff --git a/src/xenialdan/MagicWE2/commands/biome/BiomeInfoCommand.php b/src/xenialdan/MagicWE2/commands/biome/BiomeInfoCommand.php index ccc76511..d3292bf6 100644 --- a/src/xenialdan/MagicWE2/commands/biome/BiomeInfoCommand.php +++ b/src/xenialdan/MagicWE2/commands/biome/BiomeInfoCommand.php @@ -97,7 +97,7 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo foreach ($touchedChunks as $touchedChunk) { for ($x = 0; $x < 16; $x++) for ($z = 0; $z < 16; $z++) - $biomes[] = (FastChunkSerializer::deserialize($touchedChunk)->getBiomeId($x, $z)); + $biomes[] = (FastChunkSerializer::deserializeTerrain($touchedChunk)->getBiomeId($x, $z));//TODO dylan might have plans to remove biomes from this } $biomes = array_unique($biomes); $session->sendMessage(TF::DARK_AQUA . $lang->translateString('command.biomeinfo.result', [count($biomes)])); diff --git a/src/xenialdan/MagicWE2/commands/selection/info/ListChunksCommand.php b/src/xenialdan/MagicWE2/commands/selection/info/ListChunksCommand.php index 97665959..d1a83561 100644 --- a/src/xenialdan/MagicWE2/commands/selection/info/ListChunksCommand.php +++ b/src/xenialdan/MagicWE2/commands/selection/info/ListChunksCommand.php @@ -61,11 +61,11 @@ public function onRun(CommandSender $sender, string $aliasUsed, array $args): vo $touchedChunks = $selection->getShape()->getTouchedChunks($selection->getWorld()); $session->sendMessage(TF::DARK_AQUA . $lang->translateString('command.listchunks.found', [count($touchedChunks)])); foreach ($touchedChunks as $chunkHash => $touchedChunk) { - $chunk = FastChunkSerializer::deserialize($touchedChunk); + $chunk = FastChunkSerializer::deserializeTerrain($touchedChunk); $biomes = []; for ($x = 0; $x < 16; $x++) for ($z = 0; $z < 16; $z++) - $biomes[] = (FastChunkSerializer::deserialize($touchedChunk)->getBiomeId($x, $z)); + $biomes[] = (FastChunkSerializer::deserializeTerrain($touchedChunk)->getBiomeId($x, $z)); $biomes = array_unique($biomes); $biomecount = count($biomes); $biomes = implode(", ", $biomes); diff --git a/src/xenialdan/MagicWE2/helper/BlockPalette.php b/src/xenialdan/MagicWE2/helper/BlockPalette.php index a6322715..c08eebc9 100644 --- a/src/xenialdan/MagicWE2/helper/BlockPalette.php +++ b/src/xenialdan/MagicWE2/helper/BlockPalette.php @@ -14,6 +14,7 @@ use pocketmine\item\Item; use pocketmine\item\LegacyStringToItemParserException; use pocketmine\item\VanillaItems; +use pocketmine\nbt\NbtException; use pocketmine\nbt\tag\CompoundTag; use pocketmine\nbt\UnexpectedTagTypeException; use pocketmine\utils\TextFormat as TF; @@ -148,6 +149,7 @@ public function toStringArray(): array * @throws JsonException * @throws LegacyStringToItemParserException * @throws UnexpectedTagTypeException + * @throws NbtException */ public static function fromStringArray(string $blocks): array { diff --git a/src/xenialdan/MagicWE2/helper/BlockQuery.php b/src/xenialdan/MagicWE2/helper/BlockQuery.php index a1e7b939..c0fba812 100644 --- a/src/xenialdan/MagicWE2/helper/BlockQuery.php +++ b/src/xenialdan/MagicWE2/helper/BlockQuery.php @@ -7,6 +7,7 @@ use InvalidArgumentException; use pocketmine\block\utils\InvalidBlockStateException; use pocketmine\item\LegacyStringToItemParserException; +use pocketmine\nbt\NbtException; use pocketmine\nbt\UnexpectedTagTypeException; use xenialdan\MagicWE2\exception\BlockQueryAlreadyParsedException; use function preg_match_all; @@ -51,6 +52,7 @@ public function __construct(string $query, ?string $fullBlockQuery, ?string $blo * @throws LegacyStringToItemParserException * @throws UnexpectedTagTypeException * @throws \xenialdan\MagicWE2\exception\InvalidBlockStateException + * @throws NbtException */ public function parse(bool $update = true): self { diff --git a/src/xenialdan/MagicWE2/helper/BlockStatesEntry.php b/src/xenialdan/MagicWE2/helper/BlockStatesEntry.php index 56064a3b..26b84f86 100644 --- a/src/xenialdan/MagicWE2/helper/BlockStatesEntry.php +++ b/src/xenialdan/MagicWE2/helper/BlockStatesEntry.php @@ -8,12 +8,10 @@ use InvalidArgumentException; use pocketmine\block\Block; use pocketmine\block\BlockFactory; -use pocketmine\item\LegacyStringToItemParserException; use pocketmine\nbt\tag\ByteTag; use pocketmine\nbt\tag\CompoundTag; use pocketmine\nbt\tag\IntTag; use pocketmine\nbt\tag\StringTag; -use pocketmine\nbt\UnexpectedTagTypeException; use pocketmine\utils\TextFormat; use RuntimeException; use Throwable; @@ -65,9 +63,6 @@ public function __toString() * @throws BlockQueryAlreadyParsedException * @throws InvalidArgumentException * @throws InvalidBlockStateException - * @throws \pocketmine\block\utils\InvalidBlockStateException - * @throws LegacyStringToItemParserException - * @throws UnexpectedTagTypeException */ public function toBlock(): Block { diff --git a/src/xenialdan/MagicWE2/helper/BlockStatesParser.php b/src/xenialdan/MagicWE2/helper/BlockStatesParser.php index ee6cb6b6..6467be84 100644 --- a/src/xenialdan/MagicWE2/helper/BlockStatesParser.php +++ b/src/xenialdan/MagicWE2/helper/BlockStatesParser.php @@ -15,10 +15,10 @@ use pocketmine\block\Door; use pocketmine\block\utils\BlockDataSerializer; use pocketmine\data\bedrock\LegacyBlockIdToStringIdMap; -use pocketmine\item\LegacyStringToItemParser; use pocketmine\item\LegacyStringToItemParserException; use pocketmine\item\StringToItemParser; use pocketmine\math\Facing; +use pocketmine\nbt\NbtException; use pocketmine\nbt\tag\ByteTag; use pocketmine\nbt\tag\CompoundTag; use pocketmine\nbt\tag\IntTag; @@ -153,6 +153,7 @@ public static function getDoorRotationFlipMap(): array * @throws UnexpectedTagTypeException * @throws \pocketmine\block\utils\InvalidBlockStateException * @throws LegacyStringToItemParserException + * @throws NbtException */ private static function buildDoor(BlockQuery $query, CompoundTag $states): Door { @@ -206,6 +207,7 @@ protected static function getDefaultStates(string $blockIdentifier): CompoundTag * @throws UnexpectedTagTypeException * @throws \pocketmine\block\utils\InvalidBlockStateException * @throws LegacyStringToItemParserException + * @throws NbtException * @noinspection PhpInternalEntityUsedInspection */ public static function fromString(BlockQuery $query): Block @@ -213,8 +215,7 @@ public static function fromString(BlockQuery $query): Block $namespacedSelectedBlockName = !str_contains($query->blockId, "minecraft:") ? "minecraft:" . $query->blockId : $query->blockId; $selectedBlockName = strtolower(str_replace("minecraft:", "", $namespacedSelectedBlockName));//TODO try to keep namespace "minecraft:" to support custom blocks - /** @noinspection PhpDeprecationInspection */ - $block = StringToItemParser::getInstance()->parse($selectedBlockName)?->getBlock() ?? LegacyStringToItemParser::getInstance()->parse($selectedBlockName)?->getBlock(); + $block = StringToItemParser::getInstance()->parse($selectedBlockName)?->getBlock() ?? StringToItemParser::getInstance()->parse($selectedBlockName)?->getBlock(); //no states, just block if (!$query->hasBlockStates()) { $query->blockFullId = $block->getFullId(); @@ -280,7 +281,6 @@ public static function fromString(BlockQuery $query): Block $clonedPrintedCompound = clone $r12ToCurrentBlockMapEntry->getBlockState()->getCompoundTag('states'); if ($clonedPrintedCompound->equals($finalStatesList)) { $blockFactory = BlockFactory::getInstance(); - /** @noinspection PhpDeprecationInspection */ $block = $blockFactory->get($block->getId(), $meta & 0xf); $blocks[] = $block; } diff --git a/src/xenialdan/MagicWE2/selection/shape/Cone.php b/src/xenialdan/MagicWE2/selection/shape/Cone.php index 63508695..00a3a3fd 100644 --- a/src/xenialdan/MagicWE2/selection/shape/Cone.php +++ b/src/xenialdan/MagicWE2/selection/shape/Cone.php @@ -120,7 +120,7 @@ public function getTouchedChunks(AsyncChunkManager|World $manager): array continue; } print "Touched Chunk at: $x:$z" . PHP_EOL; - $touchedChunks[World::chunkHash($x, $z)] = FastChunkSerializer::serialize($chunk); + $touchedChunks[World::chunkHash($x, $z)] = FastChunkSerializer::serializeTerrain($chunk); } } print "Touched chunks count: " . count($touchedChunks) . PHP_EOL; diff --git a/src/xenialdan/MagicWE2/selection/shape/Cube.php b/src/xenialdan/MagicWE2/selection/shape/Cube.php index 66f56609..131aa84c 100644 --- a/src/xenialdan/MagicWE2/selection/shape/Cube.php +++ b/src/xenialdan/MagicWE2/selection/shape/Cube.php @@ -94,7 +94,7 @@ public function getTouchedChunks(AsyncChunkManager|World $manager): array continue; } print "Touched Chunk at: $x:$z" . PHP_EOL; - $touchedChunks[World::chunkHash($x, $z)] = FastChunkSerializer::serialize($chunk); + $touchedChunks[World::chunkHash($x, $z)] = FastChunkSerializer::serializeTerrain($chunk); } } print "Touched chunks count: " . count($touchedChunks) . PHP_EOL; diff --git a/src/xenialdan/MagicWE2/selection/shape/Cuboid.php b/src/xenialdan/MagicWE2/selection/shape/Cuboid.php index 8e1ccc9b..a79f18aa 100644 --- a/src/xenialdan/MagicWE2/selection/shape/Cuboid.php +++ b/src/xenialdan/MagicWE2/selection/shape/Cuboid.php @@ -115,7 +115,7 @@ public function getTouchedChunks(AsyncChunkManager|World $manager): array if ($chunk === null) { continue; } - $touchedChunks[World::chunkHash($x, $z)] = FastChunkSerializer::serialize($chunk); + $touchedChunks[World::chunkHash($x, $z)] = FastChunkSerializer::serializeTerrain($chunk); } } return $touchedChunks; diff --git a/src/xenialdan/MagicWE2/selection/shape/Custom.php b/src/xenialdan/MagicWE2/selection/shape/Custom.php index f4dea198..1f222727 100644 --- a/src/xenialdan/MagicWE2/selection/shape/Custom.php +++ b/src/xenialdan/MagicWE2/selection/shape/Custom.php @@ -82,7 +82,7 @@ public function getTouchedChunks(AsyncChunkManager|World $manager): array continue; } print "Touched Chunk at: $x:$z" . PHP_EOL; - $touchedChunks[World::chunkHash($x, $z)] = FastChunkSerializer::serialize($chunk); + $touchedChunks[World::chunkHash($x, $z)] = FastChunkSerializer::serializeTerrain($chunk); } print "Touched chunks count: " . count($touchedChunks) . PHP_EOL; return $touchedChunks; diff --git a/src/xenialdan/MagicWE2/selection/shape/Cylinder.php b/src/xenialdan/MagicWE2/selection/shape/Cylinder.php index 9dd26b0d..1540bf6f 100644 --- a/src/xenialdan/MagicWE2/selection/shape/Cylinder.php +++ b/src/xenialdan/MagicWE2/selection/shape/Cylinder.php @@ -111,7 +111,7 @@ public function getTouchedChunks(AsyncChunkManager|World $manager): array continue; } print "Touched Chunk at: $x:$z" . PHP_EOL; - $touchedChunks[World::chunkHash($x, $z)] = FastChunkSerializer::serialize($chunk); + $touchedChunks[World::chunkHash($x, $z)] = FastChunkSerializer::serializeTerrain($chunk); } } print "Touched chunks count: " . count($touchedChunks) . PHP_EOL; diff --git a/src/xenialdan/MagicWE2/selection/shape/Ellipsoid.php b/src/xenialdan/MagicWE2/selection/shape/Ellipsoid.php index 51272cbf..5131445a 100644 --- a/src/xenialdan/MagicWE2/selection/shape/Ellipsoid.php +++ b/src/xenialdan/MagicWE2/selection/shape/Ellipsoid.php @@ -139,7 +139,7 @@ public function getTouchedChunks(AsyncChunkManager|World $manager): array continue; } print "Touched Chunk at: $x:$z" . PHP_EOL; - $touchedChunks[World::chunkHash($x, $z)] = FastChunkSerializer::serialize($chunk); + $touchedChunks[World::chunkHash($x, $z)] = FastChunkSerializer::serializeTerrain($chunk); } } print "Touched chunks count: " . count($touchedChunks) . PHP_EOL; diff --git a/src/xenialdan/MagicWE2/selection/shape/Pyramid.php b/src/xenialdan/MagicWE2/selection/shape/Pyramid.php index 4d98b619..0ac07608 100644 --- a/src/xenialdan/MagicWE2/selection/shape/Pyramid.php +++ b/src/xenialdan/MagicWE2/selection/shape/Pyramid.php @@ -127,7 +127,7 @@ public function getTouchedChunks(AsyncChunkManager|World $manager): array continue; } print "Touched Chunk at: $x:$z" . PHP_EOL; - $touchedChunks[World::chunkHash($x, $z)] = FastChunkSerializer::serialize($chunk); + $touchedChunks[World::chunkHash($x, $z)] = FastChunkSerializer::serializeTerrain($chunk); } } print "Touched chunks count: " . count($touchedChunks) . PHP_EOL; diff --git a/src/xenialdan/MagicWE2/selection/shape/Sphere.php b/src/xenialdan/MagicWE2/selection/shape/Sphere.php index fd52a85e..f452900c 100644 --- a/src/xenialdan/MagicWE2/selection/shape/Sphere.php +++ b/src/xenialdan/MagicWE2/selection/shape/Sphere.php @@ -105,7 +105,7 @@ public function getTouchedChunks(AsyncChunkManager|World $manager): array continue; } print "Touched Chunk at: $x:$z" . PHP_EOL; - $touchedChunks[World::chunkHash($x, $z)] = FastChunkSerializer::serialize($chunk); + $touchedChunks[World::chunkHash($x, $z)] = FastChunkSerializer::serializeTerrain($chunk); } } print "Touched chunks count: " . count($touchedChunks) . PHP_EOL; diff --git a/src/xenialdan/MagicWE2/session/data/Asset.php b/src/xenialdan/MagicWE2/session/data/Asset.php index 1c099644..7300676b 100644 --- a/src/xenialdan/MagicWE2/session/data/Asset.php +++ b/src/xenialdan/MagicWE2/session/data/Asset.php @@ -14,6 +14,7 @@ use pocketmine\item\ItemFactory; use pocketmine\item\ItemIds; use pocketmine\math\Vector3; +use pocketmine\nbt\NbtException; use pocketmine\nbt\tag\CompoundTag; use pocketmine\player\Player; use pocketmine\plugin\PluginException; @@ -90,6 +91,7 @@ public function getOrigin(): Vector3 * @param bool $renew * @return Item * @throws InvalidArgumentException + * @throws NbtException */ public function toItem(bool $renew = false): Item { diff --git a/src/xenialdan/MagicWE2/task/AsyncActionTask.php b/src/xenialdan/MagicWE2/task/AsyncActionTask.php index 22e616b0..425e2b27 100644 --- a/src/xenialdan/MagicWE2/task/AsyncActionTask.php +++ b/src/xenialdan/MagicWE2/task/AsyncActionTask.php @@ -90,7 +90,7 @@ public function onRun(): void $touchedChunks = unserialize($this->touchedChunks/*, ['allowed_classes' => false]*/); $touchedChunks = array_map(static function ($chunk) { - return FastChunkSerializer::deserialize($chunk); + return FastChunkSerializer::deserializeTerrain($chunk); }, $touchedChunks); $manager = Shape::getChunkManager($touchedChunks); @@ -132,7 +132,7 @@ public function onCompletion(): void /** @var Chunk[] $resultChunks */ $resultChunks = $result["resultChunks"]; $undoChunks = array_map(static function ($chunk) { - return FastChunkSerializer::deserialize($chunk); + return FastChunkSerializer::deserializeTerrain($chunk); }, unserialize($this->touchedChunks/*, ['allowed_classes' => false]*/));//TODO test pm4 /** @var SingleClipboard $oldBlocks *///TODO make sure changed everywhere $oldBlocks = $result["oldBlocks"]; diff --git a/src/xenialdan/MagicWE2/task/AsyncCopyTask.php b/src/xenialdan/MagicWE2/task/AsyncCopyTask.php index f35027b0..f15762da 100644 --- a/src/xenialdan/MagicWE2/task/AsyncCopyTask.php +++ b/src/xenialdan/MagicWE2/task/AsyncCopyTask.php @@ -62,7 +62,7 @@ public function onRun(): void { $this->publishProgress([0, "Start"]); $chunks = array_map(static function ($chunk) { - return FastChunkSerializer::deserialize($chunk); + return FastChunkSerializer::deserializeTerrain($chunk); }, unserialize($this->chunks/*, ['allowed_classes' => false]*/));//TODO test pm4 /** @var Selection $selection */ $selection = unserialize($this->selection/*, ['allowed_classes' => [Selection::class]]*/);//TODO test pm4 diff --git a/src/xenialdan/MagicWE2/task/AsyncCountTask.php b/src/xenialdan/MagicWE2/task/AsyncCountTask.php index 21ed9a65..7b089278 100644 --- a/src/xenialdan/MagicWE2/task/AsyncCountTask.php +++ b/src/xenialdan/MagicWE2/task/AsyncCountTask.php @@ -60,7 +60,7 @@ public function onRun(): void $this->publishProgress([0, "Start"]); $chunks = unserialize($this->touchedChunks/*, ['allowed_classes' => [false]]*/);//TODO test pm4 foreach ($chunks as $hash => $data) { - $chunks[$hash] = FastChunkSerializer::deserialize($data); + $chunks[$hash] = FastChunkSerializer::deserializeTerrain($data); } /** @var Selection $selection */ $selection = unserialize($this->selection/*, ['allowed_classes' => [Selection::class]]*/);//TODO test pm4 diff --git a/src/xenialdan/MagicWE2/task/AsyncFillTask.php b/src/xenialdan/MagicWE2/task/AsyncFillTask.php index 3807172b..8249edee 100644 --- a/src/xenialdan/MagicWE2/task/AsyncFillTask.php +++ b/src/xenialdan/MagicWE2/task/AsyncFillTask.php @@ -75,7 +75,7 @@ public function onRun(): void $this->publishProgress([0, "Start"]); $touchedChunks = array_map(static function ($chunk) { - return FastChunkSerializer::deserialize($chunk); + return FastChunkSerializer::deserializeTerrain($chunk); }, igbinary_unserialize($this->touchedChunks/*, ['allowed_classes' => false]*/));//TODO test pm4 $manager = Shape::getChunkManager($touchedChunks); @@ -173,7 +173,7 @@ public function onCompletion(): void /** @var Chunk[] $resultChunks */ $resultChunks = $result["resultChunks"]; $undoChunks = array_map(static function ($chunk) { - return FastChunkSerializer::deserialize($chunk); + return FastChunkSerializer::deserializeTerrain($chunk); }, igbinary_unserialize($this->touchedChunks/*, ['allowed_classes' => false]*/));//TODO test pm4) #$oldBlocks = igbinary_unserialize($result["oldBlocks"]); $oldBlocks = $result["oldBlocks"];//this is already a data map diff --git a/src/xenialdan/MagicWE2/task/AsyncPasteAssetTask.php b/src/xenialdan/MagicWE2/task/AsyncPasteAssetTask.php index c74bc9d2..66d31887 100644 --- a/src/xenialdan/MagicWE2/task/AsyncPasteAssetTask.php +++ b/src/xenialdan/MagicWE2/task/AsyncPasteAssetTask.php @@ -77,7 +77,7 @@ public function onRun(): void $this->publishProgress([0, "Start"]); $touchedChunks = array_map(static function ($chunk) {//todo add hash as key - return FastChunkSerializer::deserialize($chunk); + return FastChunkSerializer::deserializeTerrain($chunk); }, unserialize($this->touchedChunks/*, ['allowed_classes' => false]*/));//TODO test pm4 $manager = Shape::getChunkManager($touchedChunks); @@ -212,7 +212,7 @@ public function onCompletion(): void /** @var Chunk[] $resultChunks */ $resultChunks = $result["resultChunks"]; $undoChunks = array_map(static function ($chunk) { - return FastChunkSerializer::deserialize($chunk); + return FastChunkSerializer::deserializeTerrain($chunk); }, unserialize($this->touchedChunks/*, ['allowed_classes' => false]*/));//TODO test pm4 $oldBlocks = $result["oldBlocks"];//already data array $changed = $result["changed"]; diff --git a/src/xenialdan/MagicWE2/task/AsyncPasteTask.php b/src/xenialdan/MagicWE2/task/AsyncPasteTask.php index 77ab93a6..d4af52ef 100644 --- a/src/xenialdan/MagicWE2/task/AsyncPasteTask.php +++ b/src/xenialdan/MagicWE2/task/AsyncPasteTask.php @@ -67,7 +67,7 @@ public function onRun(): void $this->publishProgress([0, "Start"]); $touchedChunks = array_map(static function ($chunk) {//todo add hash as key - return FastChunkSerializer::deserialize($chunk); + return FastChunkSerializer::deserializeTerrain($chunk); }, unserialize($this->touchedChunks/*, ['allowed_classes' => false]*/));//TODO test pm4 $manager = Shape::getChunkManager($touchedChunks); @@ -156,7 +156,7 @@ public function onCompletion(): void /** @var Chunk[] $resultChunks */ $resultChunks = $result["resultChunks"]; $undoChunks = array_map(static function ($chunk) { - return FastChunkSerializer::deserialize($chunk); + return FastChunkSerializer::deserializeTerrain($chunk); }, unserialize($this->touchedChunks/*, ['allowed_classes' => false]*/));//TODO test pm4 $oldBlocks = $result["oldBlocks"];//already data array $changed = $result["changed"]; diff --git a/src/xenialdan/MagicWE2/task/AsyncReplaceTask.php b/src/xenialdan/MagicWE2/task/AsyncReplaceTask.php index 54cf11ef..0d64d755 100644 --- a/src/xenialdan/MagicWE2/task/AsyncReplaceTask.php +++ b/src/xenialdan/MagicWE2/task/AsyncReplaceTask.php @@ -71,7 +71,7 @@ public function onRun(): void $this->publishProgress([0, "Start"]); $touchedChunks = array_map(static function ($chunk) { - return FastChunkSerializer::deserialize($chunk); + return FastChunkSerializer::deserializeTerrain($chunk); }, unserialize($this->touchedChunks/*, ['allowed_classes' => false]*/));//TODO test pm4 $manager = Shape::getChunkManager($touchedChunks); @@ -156,7 +156,7 @@ public function onCompletion(): void /** @var Chunk[] $resultChunks */ $resultChunks = $result["resultChunks"]; $undoChunks = array_map(static function ($chunk) { - return FastChunkSerializer::deserialize($chunk); + return FastChunkSerializer::deserializeTerrain($chunk); }, unserialize($this->touchedChunks/*, ['allowed_classes' => false]*/));//TODO test pm4 $oldBlocks = $result["oldBlocks"];//this is already as data $changed = $result["changed"]; diff --git a/src/xenialdan/MagicWE2/tool/Flood.php b/src/xenialdan/MagicWE2/tool/Flood.php index 9689a39e..18d9fcc7 100644 --- a/src/xenialdan/MagicWE2/tool/Flood.php +++ b/src/xenialdan/MagicWE2/tool/Flood.php @@ -143,7 +143,7 @@ public function getTouchedChunks(AsyncChunkManager|World $chunkManager): array continue; } #print "Touched Chunk at: $x:$z" . PHP_EOL; - $touchedChunks[World::chunkHash($x, $z)] = FastChunkSerializer::serialize($chunk); + $touchedChunks[World::chunkHash($x, $z)] = FastChunkSerializer::serializeTerrain($chunk); } } #print "Touched chunks count: " . count($touchedChunks) . PHP_EOL;; From 576de8792271a155ae96e1c51718c688897cb97a Mon Sep 17 00:00:00 2001 From: XenialDan Date: Mon, 11 Oct 2021 23:59:42 +0200 Subject: [PATCH 64/67] Add API::positiveModulo() --- src/xenialdan/MagicWE2/API.php | 5 +++++ src/xenialdan/MagicWE2/selection/shape/Custom.php | 1 + src/xenialdan/MagicWE2/task/action/SetBiomeAction.php | 2 ++ 3 files changed, 8 insertions(+) diff --git a/src/xenialdan/MagicWE2/API.php b/src/xenialdan/MagicWE2/API.php index b4fb7911..638dc963 100644 --- a/src/xenialdan/MagicWE2/API.php +++ b/src/xenialdan/MagicWE2/API.php @@ -562,4 +562,9 @@ public static function boolToString(bool $b): string { return $b ? TF::RESET . TF::GREEN . "On" . TF::RESET : TF::RESET . TF::RED . "Off" . TF::RESET; } + + public static function positiveModulo(int $i, int $n): int + { + return ($i % $n + $n) % $n; + } } \ No newline at end of file diff --git a/src/xenialdan/MagicWE2/selection/shape/Custom.php b/src/xenialdan/MagicWE2/selection/shape/Custom.php index 1f222727..e4255c88 100644 --- a/src/xenialdan/MagicWE2/selection/shape/Custom.php +++ b/src/xenialdan/MagicWE2/selection/shape/Custom.php @@ -75,6 +75,7 @@ public function getTouchedChunks(AsyncChunkManager|World $manager): array { $this->validateChunkManager($manager); $touchedChunks = []; + /** @var Vector2 $vector2 */ foreach ($this->getLayer($manager) as $vector2) { $x = $vector2->getFloorX() >> 4; $z = $vector2->getFloorY() >> 4; diff --git a/src/xenialdan/MagicWE2/task/action/SetBiomeAction.php b/src/xenialdan/MagicWE2/task/action/SetBiomeAction.php index 97ad8bee..0ce92568 100644 --- a/src/xenialdan/MagicWE2/task/action/SetBiomeAction.php +++ b/src/xenialdan/MagicWE2/task/action/SetBiomeAction.php @@ -6,6 +6,7 @@ use Exception; use Generator; +use pocketmine\math\Vector2; use xenialdan\MagicWE2\clipboard\SingleClipboard; use xenialdan\MagicWE2\helper\AsyncChunkManager; use xenialdan\MagicWE2\helper\BlockPalette; @@ -47,6 +48,7 @@ public function execute(string $sessionUUID, Selection $selection, AsyncChunkMan #$oldBlocks = []; $count = null; $lastProgress = new Progress(0, ""); + /** @var Vector2 $vec2 */ foreach (($all = $selection->getShape()->getLayer($manager)) as $vec2) { if (is_null($count)) $count = count(iterator_to_array($all)); $manager->getChunk($vec2->x >> 4, $vec2->y >> 4)->setBiomeId($vec2->x % 16, $vec2->y % 16, $this->biomeId); From c204d059cd3419af57d91f49d3eca7816255cba5 Mon Sep 17 00:00:00 2001 From: XenialDan Date: Tue, 12 Oct 2021 00:33:22 +0200 Subject: [PATCH 65/67] Resend outline if chunks are out of view --- src/xenialdan/MagicWE2/EventListener.php | 15 +++++++++++++++ src/xenialdan/MagicWE2/session/data/Outline.php | 15 ++++++++------- 2 files changed, 23 insertions(+), 7 deletions(-) diff --git a/src/xenialdan/MagicWE2/EventListener.php b/src/xenialdan/MagicWE2/EventListener.php index 4bb9a0dd..bdc785ea 100644 --- a/src/xenialdan/MagicWE2/EventListener.php +++ b/src/xenialdan/MagicWE2/EventListener.php @@ -17,6 +17,7 @@ use pocketmine\event\player\PlayerItemHeldEvent; use pocketmine\event\player\PlayerItemUseEvent; use pocketmine\event\player\PlayerJoinEvent; +use pocketmine\event\player\PlayerMoveEvent; use pocketmine\event\player\PlayerQuitEvent; use pocketmine\item\ItemIds; use pocketmine\nbt\UnexpectedTagTypeException; @@ -460,4 +461,18 @@ public function onStructureBlockClick(PlayerInteractEvent $event): void } } + + public function onStructureBlockOutOfView(PlayerMoveEvent $event): void + { + if ($event->getFrom()->floor()->equals($event->getTo()->floor())) return; + $player = $event->getPlayer(); + $session = SessionHelper::getUserSession($player); + if (!$session instanceof UserSession) return; + $selection = $session->getLatestSelection(); + if (!$selection instanceof Selection) return; + if (!$session->isOutlineEnabled()) return; + if (!$player->isUsingChunk($session->getOutline()->getPosition()->getFloorX() >> 4, $session->getOutline()->getPosition()->getFloorZ())) { + $session->createOrUpdateOutline($selection); + } + } } \ No newline at end of file diff --git a/src/xenialdan/MagicWE2/session/data/Outline.php b/src/xenialdan/MagicWE2/session/data/Outline.php index 842aa13e..2c9d0037 100644 --- a/src/xenialdan/MagicWE2/session/data/Outline.php +++ b/src/xenialdan/MagicWE2/session/data/Outline.php @@ -13,11 +13,9 @@ use pocketmine\network\mcpe\protocol\UpdateBlockPacket; use pocketmine\player\Player; use pocketmine\world\Position; -use ReflectionException; -use ReflectionProperty; +use ReflectionClass; use xenialdan\libstructure\tile\StructureBlockTile; use xenialdan\MagicWE2\selection\Selection; -use function get_class; class Outline { @@ -82,13 +80,11 @@ public function __toString(): string return 'Outline'; } - /** - * @throws ReflectionException - */ private function updatePosition(): Position { $this->position = $this->updateBlockPosition(); - $reflection = new ReflectionProperty(get_class($this->fakeTile), 'position'); + $reflectionc = new ReflectionClass($this->fakeTile); + $reflection = $reflectionc->getProperty('position'); $reflection->setAccessible(true); $reflection->setValue($this->fakeTile, $this->position); return $this->position; @@ -98,4 +94,9 @@ private function updateBlockPosition(): Position { return Position::fromObject($this->player->getPosition()->withComponents(null, $this->player->getPosition()->getWorld()->getMinY(), null)->floor(), $this->player->getWorld()); } + + public function getPosition(): Position + { + return $this->position; + } } \ No newline at end of file From ddd023516ec5008dc43d16faf0d1b61417187050 Mon Sep 17 00:00:00 2001 From: Yifei Ding Date: Sat, 23 Oct 2021 17:50:21 -0700 Subject: [PATCH 66/67] Updated Simplified Chinese Translation --- resources/lang/zho.ini | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/resources/lang/zho.ini b/resources/lang/zho.ini index ce23b4f2..c731875f 100644 --- a/resources/lang/zho.ini +++ b/resources/lang/zho.ini @@ -18,9 +18,9 @@ error.limitexceeded="您正在尝试修改的方块太多了。减少选择的 error.notarget="找不到目标方块。如果需要,使用//setrange增加工具范围" error.noselection="找不到选中 - 请先选中一个范围" error.selectioninvalid="选中范围无效!检查是否已设置所有位置!" -error.nosession="为创建会话 - 可能没有使用{%0}的权限" +error.nosession="未创建会话 - 可能没有使用{%0}的权限" error.noclipboard = "找不到剪贴板 - 请先创建一个剪贴板" -warning.differentworld = "[警告] 您的编辑不处于您目前所在世界!" +warning.differentworld = "[警告] 您目前所在的世界不是您正在编辑的世界!" ; commands command.info.title="信息" command.limit.current="目前极限:{%0}" @@ -84,6 +84,12 @@ tool.debug.lore.2="例如方块的名称和损耗值" tool.debug.lore.3="使用//toggledebug切换其功能" tool.debug.disabled="故障排除工具已禁用。使用//toggledebug来重新启用它" tool.debug.setenabled = "故障排除工具已{%0}!" +; WAILA tool (What am i looking at) +tool.waila = "Waila" +tool.waila.setenabled = "Waila工具已{%0}!" +; Sidebar +tool.sidebar = "侧边栏" +tool.sidebar.setenabled = "侧边栏已{%0}!" ; flood tool ui.flood.title="覆盖菜单" ui.flood.options.limit="最大方块数" From b48cabb9a02f561e384993570bb7adca1a26fcb1 Mon Sep 17 00:00:00 2001 From: Yifei Ding Date: Sat, 23 Oct 2021 17:52:03 -0700 Subject: [PATCH 67/67] Update zho.ini --- resources/lang/zho.ini | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/resources/lang/zho.ini b/resources/lang/zho.ini index c731875f..3c909313 100644 --- a/resources/lang/zho.ini +++ b/resources/lang/zho.ini @@ -1,4 +1,4 @@ -; Updated time : 3rd 10 2019 +; Updated time : 23rd 10 2021 ; See: https://www.loc.gov/standards/iso639-2/php/English_list.php language.name="Simplified Chinese" ; general