PocketMine-MP 5.15.1 git-ed158f8a1b0cfe334ac5f45febc0f633602014f2
RegionWorldProvider.php
1<?php
2
3/*
4 *
5 * ____ _ _ __ __ _ __ __ ____
6 * | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
7 * | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
8 * | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
9 * |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
10 *
11 * This program is free software: you can redistribute it and/or modify
12 * it under the terms of the GNU Lesser General Public License as published by
13 * the Free Software Foundation, either version 3 of the License, or
14 * (at your option) any later version.
15 *
16 * @author PocketMine Team
17 * @link http://www.pocketmine.net/
18 *
19 *
20 */
21
22declare(strict_types=1);
23
24namespace pocketmine\world\format\io\region;
25
35use Symfony\Component\Filesystem\Path;
36use function assert;
37use function file_exists;
38use function is_dir;
39use function is_int;
40use function morton2d_encode;
41use function rename;
42use function scandir;
43use function strlen;
44use function strrpos;
45use function substr;
46use function time;
47use const SCANDIR_SORT_NONE;
48
50
54 abstract protected static function getRegionFileExtension() : string;
55
59 abstract protected static function getPcWorldFormatVersion() : int;
60
61 public static function isValid(string $path) : bool{
62 if(file_exists(Path::join($path, "level.dat")) && is_dir($regionPath = Path::join($path, "region"))){
63 foreach(scandir($regionPath, SCANDIR_SORT_NONE) as $file){
64 $extPos = strrpos($file, ".");
65 if($extPos !== false && substr($file, $extPos + 1) === static::getRegionFileExtension()){
66 //we don't care if other region types exist, we only care if this format is possible
67 return true;
68 }
69 }
70 }
71
72 return false;
73 }
74
76 protected array $regions = [];
77
78 protected function loadLevelData() : WorldData{
79 return new JavaWorldData(Path::join($this->getPath(), "level.dat"));
80 }
81
82 public function doGarbageCollection() : void{
83 $limit = time() - 300;
84 foreach($this->regions as $index => $region){
85 if($region->lastUsed <= $limit){
86 $region->close();
87 unset($this->regions[$index]);
88 }
89 }
90 }
91
98 public static function getRegionIndex(int $chunkX, int $chunkZ, &$regionX, &$regionZ) : void{
99 $regionX = $chunkX >> 5;
100 $regionZ = $chunkZ >> 5;
101 }
102
103 protected function getRegion(int $regionX, int $regionZ) : ?RegionLoader{
104 return $this->regions[morton2d_encode($regionX, $regionZ)] ?? null;
105 }
106
110 protected function pathToRegion(int $regionX, int $regionZ) : string{
111 return Path::join($this->path, "region", "r.$regionX.$regionZ." . static::getRegionFileExtension());
112 }
113
114 protected function loadRegion(int $regionX, int $regionZ) : RegionLoader{
115 if(!isset($this->regions[$index = morton2d_encode($regionX, $regionZ)])){
116 $path = $this->pathToRegion($regionX, $regionZ);
117
118 try{
119 $this->regions[$index] = RegionLoader::loadExisting($path);
120 }catch(CorruptedRegionException $e){
121 $this->logger->error("Corrupted region file detected: " . $e->getMessage());
122
123 $backupPath = $path . ".bak." . time();
124 rename($path, $backupPath);
125 $this->logger->error("Corrupted region file has been backed up to " . $backupPath);
126
127 $this->regions[$index] = RegionLoader::createNew($path);
128 }
129 }
130 return $this->regions[$index];
131 }
132
133 protected function unloadRegion(int $regionX, int $regionZ) : void{
134 if(isset($this->regions[$hash = morton2d_encode($regionX, $regionZ)])){
135 $this->regions[$hash]->close();
136 unset($this->regions[$hash]);
137 }
138 }
139
140 public function close() : void{
141 foreach($this->regions as $index => $region){
142 $region->close();
143 unset($this->regions[$index]);
144 }
145 }
146
150 abstract protected function deserializeChunk(string $data, \Logger $logger) : ?LoadedChunkData;
151
156 protected static function getCompoundList(string $context, ListTag $list) : array{
157 if($list->count() === 0){ //empty lists might have wrong types, we don't care
158 return [];
159 }
160 if($list->getTagType() !== NBT::TAG_Compound){
161 throw new CorruptedChunkException("Expected TAG_List<TAG_Compound> for '$context'");
162 }
163 $result = [];
164 foreach($list as $tag){
165 if(!($tag instanceof CompoundTag)){
166 //this should never happen, but it's still possible due to lack of native type safety
167 throw new CorruptedChunkException("Expected TAG_List<TAG_Compound> for '$context'");
168 }
169 $result[] = $tag;
170 }
171 return $result;
172 }
173
174 protected static function readFixedSizeByteArray(CompoundTag $chunk, string $tagName, int $length) : string{
175 $tag = $chunk->getTag($tagName);
176 if(!($tag instanceof ByteArrayTag)){
177 if($tag === null){
178 throw new CorruptedChunkException("'$tagName' key is missing from chunk NBT");
179 }
180 throw new CorruptedChunkException("Expected TAG_ByteArray for '$tagName'");
181 }
182 $data = $tag->getValue();
183 if(strlen($data) !== $length){
184 throw new CorruptedChunkException("Expected '$tagName' payload to have exactly $length bytes, but have " . strlen($data));
185 }
186 return $data;
187 }
188
192 public function loadChunk(int $chunkX, int $chunkZ) : ?LoadedChunkData{
193 $regionX = $regionZ = null;
194 self::getRegionIndex($chunkX, $chunkZ, $regionX, $regionZ);
195 assert(is_int($regionX) && is_int($regionZ));
196
197 if(!file_exists($this->pathToRegion($regionX, $regionZ))){
198 return null;
199 }
200
201 $chunkData = $this->loadRegion($regionX, $regionZ)->readChunk($chunkX & 0x1f, $chunkZ & 0x1f);
202 if($chunkData !== null){
203 return $this->deserializeChunk($chunkData, new \PrefixedLogger($this->logger, "Loading chunk x=$chunkX z=$chunkZ"));
204 }
205
206 return null;
207 }
208
209 private function createRegionIterator() : \RegexIterator{
210 return new \RegexIterator(
211 new \FilesystemIterator(
212 Path::join($this->path, 'region'),
213 \FilesystemIterator::CURRENT_AS_PATHNAME | \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::UNIX_PATHS
214 ),
215 '/\/r\.(-?\d+)\.(-?\d+)\.' . static::getRegionFileExtension() . '$/',
216 \RegexIterator::GET_MATCH
217 );
218 }
219
220 public function getAllChunks(bool $skipCorrupted = false, ?\Logger $logger = null) : \Generator{
221 $iterator = $this->createRegionIterator();
222
223 foreach($iterator as $region){
224 $regionX = ((int) $region[1]);
225 $regionZ = ((int) $region[2]);
226 $rX = $regionX << 5;
227 $rZ = $regionZ << 5;
228
229 for($chunkX = $rX; $chunkX < $rX + 32; ++$chunkX){
230 for($chunkZ = $rZ; $chunkZ < $rZ + 32; ++$chunkZ){
231 try{
232 $chunk = $this->loadChunk($chunkX, $chunkZ);
233 if($chunk !== null){
234 yield [$chunkX, $chunkZ] => $chunk;
235 }
236 }catch(CorruptedChunkException $e){
237 if(!$skipCorrupted){
238 throw $e;
239 }
240 if($logger !== null){
241 $logger->error("Skipped corrupted chunk $chunkX $chunkZ (" . $e->getMessage() . ")");
242 }
243 }
244 }
245 }
246
247 $this->unloadRegion($regionX, $regionZ);
248 }
249 }
250
251 public function calculateChunkCount() : int{
252 $count = 0;
253 foreach($this->createRegionIterator() as $region){
254 $regionX = ((int) $region[1]);
255 $regionZ = ((int) $region[2]);
256 $count += $this->loadRegion($regionX, $regionZ)->calculateChunkCount();
257 $this->unloadRegion($regionX, $regionZ);
258 }
259 return $count;
260 }
261}
getAllChunks(bool $skipCorrupted=false, ?\Logger $logger=null)
deserializeChunk(string $data, \Logger $logger)
static getCompoundList(string $context, ListTag $list)
static getRegionIndex(int $chunkX, int $chunkZ, &$regionX, &$regionZ)
error($message)