PocketMine-MP 5.33.2 git-1133d49c924b4358c79d44eeb97dcbf56cb4d1eb
Loading...
Searching...
No Matches
BlockStateToObjectDeserializer.php
1<?php
2
3/*
4 *
5 * ____ _ _ __ __ _ __ __ ____
6 * | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
7 * | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
8 * | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
9 * |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
10 *
11 * This program is free software: you can redistribute it and/or modify
12 * it under the terms of the GNU Lesser General Public License as published by
13 * the Free Software Foundation, either version 3 of the License, or
14 * (at your option) any later version.
15 *
16 * @author PocketMine Team
17 * @link http://www.pocketmine.net/
18 *
19 *
20 */
21
22declare(strict_types=1);
23
24namespace pocketmine\data\bedrock\block\convert;
25
32use function array_key_exists;
33use function count;
34
36
41 private array $deserializeFuncs = [];
42
47 private array $simpleCache = [];
48
49 public function deserialize(BlockStateData $stateData) : int{
50 if(count($stateData->getStates()) === 0){
51 //if a block has zero properties, we can keep a map of string ID -> internal blockstate ID
52 return $this->simpleCache[$stateData->getName()] ??= $this->deserializeToStateId($stateData);
53 }
54
55 //we can't cache blocks that have properties - go ahead and deserialize the slow way
56 return $this->deserializeToStateId($stateData);
57 }
58
59 private function deserializeToStateId(BlockStateData $stateData) : int{
60 $stateId = $this->deserializeBlock($stateData)->getStateId();
61 //plugin devs seem to keep missing this and causing core crashes, so we need to verify this at the earliest
62 //available opportunity
63 if(!RuntimeBlockStateRegistry::getInstance()->hasStateId($stateId)){
64 throw new \LogicException("State ID $stateId returned by deserializer for " . $stateData->getName() . " is not registered in RuntimeBlockStateRegistry");
65 }
66 return $stateId;
67 }
68
70 public function map(string $id, \Closure $c) : void{
71 $this->deserializeFuncs[$id] = $c;
72 $this->simpleCache = [];
73 }
74
81 public function getDeserializerForId(string $id) : ?\Closure{
82 return $this->deserializeFuncs[$id] ?? null;
83 }
84
86 public function deserializeBlock(BlockStateData $blockStateData) : Block{
87 $id = $blockStateData->getName();
88 if(!array_key_exists($id, $this->deserializeFuncs)){
89 throw new UnsupportedBlockStateException("Unknown block ID \"$id\"");
90 }
91 $reader = new Reader($blockStateData);
92 $block = $this->deserializeFuncs[$id]($reader);
93 $reader->checkUnreadProperties();
94 return $block;
95 }
96}