Level.php 102 KB
Newer Older
PeratX's avatar
wow!  
PeratX committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
<?php

/*
 *
 *  ____            _        _   __  __ _                  __  __ ____
 * |  _ \ ___   ___| | _____| |_|  \/  (_)_ __   ___      |  \/  |  _ \
 * | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
 * |  __/ (_) | (__|   <  __/ |_| |  | | | | | |  __/_____| |  | |  __/
 * |_|   \___/ \___|_|\_\___|\__|_|  |_|_|_| |_|\___|     |_|  |_|_|
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * @author PocketMine Team
 * @link http://www.pocketmine.net/
 *
 *
*/

/**
 * All Level related classes are here, like Generators, Populators, Noise, ...
 */
Apple's avatar
Apple committed
25

PeratX's avatar
wow!  
PeratX committed
26 27 28 29 30 31 32 33
namespace pocketmine\level;

use pocketmine\block\Air;
use pocketmine\block\Beetroot;
use pocketmine\block\Block;
use pocketmine\block\BrownMushroom;
use pocketmine\block\Cactus;
use pocketmine\block\Carrot;
Frago9876543210's avatar
Frago9876543210 committed
34
use pocketmine\block\CocoaBlock;
PeratX's avatar
wow!  
PeratX committed
35 36 37 38 39 40 41
use pocketmine\block\Farmland;
use pocketmine\block\Grass;
use pocketmine\block\Ice;
use pocketmine\block\Leaves;
use pocketmine\block\Leaves2;
use pocketmine\block\MelonStem;
use pocketmine\block\Mycelium;
Frago9876543210's avatar
Frago9876543210 committed
42
use pocketmine\block\NetherWart;
PeratX's avatar
wow!  
PeratX committed
43 44 45 46 47 48 49 50
use pocketmine\block\Potato;
use pocketmine\block\PumpkinStem;
use pocketmine\block\RedMushroom;
use pocketmine\block\Sapling;
use pocketmine\block\SnowLayer;
use pocketmine\block\Sugarcane;
use pocketmine\block\Wheat;
use pocketmine\entity\Arrow;
51
use pocketmine\entity\Effect;
PeratX's avatar
wow!  
PeratX committed
52 53
use pocketmine\entity\Entity;
use pocketmine\entity\Item as DroppedItem;
Frago9876543210's avatar
Frago9876543210 committed
54 55
use pocketmine\entity\Lightning;
use pocketmine\entity\XPOrb;
PeratX's avatar
wow!  
PeratX committed
56 57 58 59 60 61 62 63 64 65 66 67 68
use pocketmine\event\block\BlockBreakEvent;
use pocketmine\event\block\BlockPlaceEvent;
use pocketmine\event\block\BlockUpdateEvent;
use pocketmine\event\level\ChunkLoadEvent;
use pocketmine\event\level\ChunkPopulateEvent;
use pocketmine\event\level\ChunkUnloadEvent;
use pocketmine\event\level\LevelSaveEvent;
use pocketmine\event\level\LevelUnloadEvent;
use pocketmine\event\level\SpawnChangeEvent;
use pocketmine\event\LevelTimings;
use pocketmine\event\player\PlayerInteractEvent;
use pocketmine\event\Timings;
use pocketmine\inventory\InventoryHolder;
SuperXingKong's avatar
SuperXingKong committed
69
use pocketmine\item\enchantment\Enchantment;
Frago9876543210's avatar
Frago9876543210 committed
70
use pocketmine\item\Item;
PeratX's avatar
wow!  
PeratX committed
71
use pocketmine\level\format\Chunk;
72 73
use pocketmine\level\format\io\BaseLevelProvider;
use pocketmine\level\format\io\LevelProvider;
PeratX's avatar
wow!  
PeratX committed
74 75 76 77 78 79
use pocketmine\level\generator\GenerationTask;
use pocketmine\level\generator\Generator;
use pocketmine\level\generator\GeneratorRegisterTask;
use pocketmine\level\generator\GeneratorUnregisterTask;
use pocketmine\level\generator\LightPopulationTask;
use pocketmine\level\generator\PopulationTask;
Frago9876543210's avatar
Frago9876543210 committed
80 81 82
use pocketmine\level\particle\DestroyBlockParticle;
use pocketmine\level\particle\Particle;
use pocketmine\level\sound\Sound;
83
use pocketmine\level\sound\BlockPlaceSound;
Frago9876543210's avatar
Frago9876543210 committed
84
use pocketmine\level\weather\Weather;
PeratX's avatar
wow!  
PeratX committed
85 86 87 88 89 90 91
use pocketmine\math\AxisAlignedBB;
use pocketmine\math\Math;
use pocketmine\math\Vector2;
use pocketmine\math\Vector3;
use pocketmine\metadata\BlockMetadataStore;
use pocketmine\metadata\Metadatable;
use pocketmine\metadata\MetadataValue;
PeratX's avatar
php7 !  
PeratX committed
92 93
use pocketmine\nbt\tag\CompoundTag;
use pocketmine\nbt\tag\DoubleTag;
SuperXingKong's avatar
SuperXingKong committed
94
use pocketmine\nbt\tag\FloatTag;
Frago9876543210's avatar
Frago9876543210 committed
95 96
use pocketmine\nbt\tag\ListTag;
use pocketmine\nbt\tag\LongTag;
PeratX's avatar
php7 !  
PeratX committed
97 98
use pocketmine\nbt\tag\ShortTag;
use pocketmine\nbt\tag\StringTag;
99 100 101 102 103 104 105 106 107 108
use pocketmine\network\mcpe\protocol\AddEntityPacket;
use pocketmine\network\mcpe\protocol\BatchPacket;
use pocketmine\network\mcpe\protocol\DataPacket;
use pocketmine\network\mcpe\protocol\FullChunkDataPacket;
use pocketmine\network\mcpe\protocol\LevelEventPacket;
use pocketmine\network\mcpe\protocol\LevelSoundEventPacket;
use pocketmine\network\mcpe\protocol\MoveEntityPacket;
use pocketmine\network\mcpe\protocol\SetEntityMotionPacket;
use pocketmine\network\mcpe\protocol\SetTimePacket;
use pocketmine\network\mcpe\protocol\UpdateBlockPacket;
PeratX's avatar
wow!  
PeratX committed
109 110 111
use pocketmine\Player;
use pocketmine\plugin\Plugin;
use pocketmine\Server;
112 113
use pocketmine\tile\Chest;
use pocketmine\tile\Tile;
114
use pocketmine\utils\Binary;
PeratX's avatar
wow!  
PeratX committed
115 116 117 118 119
use pocketmine\utils\Random;
use pocketmine\utils\ReversePriorityQueue;

#include <rules/Level.h>

Frago9876543210's avatar
Frago9876543210 committed
120 121
class Level implements ChunkManager, Metadatable
{
122

Frago9876543210's avatar
Frago9876543210 committed
123 124 125
    private static $levelIdCounter = 1;
    private static $chunkLoaderCounter = 1;
    public static $COMPRESSION_LEVEL = 8;
PeratX's avatar
PeratX committed
126

Frago9876543210's avatar
Frago9876543210 committed
127 128
    const Y_MASK = 0xFF;
    const Y_MAX = 0x100; //256
PeratX's avatar
wow!  
PeratX committed
129

Frago9876543210's avatar
Frago9876543210 committed
130 131 132 133 134
    const BLOCK_UPDATE_NORMAL = 1;
    const BLOCK_UPDATE_RANDOM = 2;
    const BLOCK_UPDATE_SCHEDULED = 3;
    const BLOCK_UPDATE_WEAK = 4;
    const BLOCK_UPDATE_TOUCH = 5;
PeratX's avatar
wow!  
PeratX committed
135

Frago9876543210's avatar
Frago9876543210 committed
136 137 138 139
    const TIME_DAY = 0;
    const TIME_SUNSET = 12000;
    const TIME_NIGHT = 14000;
    const TIME_SUNRISE = 23000;
PeratX's avatar
wow!  
PeratX committed
140

Frago9876543210's avatar
Frago9876543210 committed
141
    const TIME_FULL = 24000;
PeratX's avatar
wow!  
PeratX committed
142

Frago9876543210's avatar
Frago9876543210 committed
143 144
    const DIMENSION_NORMAL = 0;
    const DIMENSION_NETHER = 1;
145
    const DIMENSION_END = 2;
PeratX's avatar
wow!  
PeratX committed
146

Frago9876543210's avatar
Frago9876543210 committed
147 148
    /** @var Tile[] */
    private $tiles = [];
PeratX's avatar
wow!  
PeratX committed
149

Frago9876543210's avatar
Frago9876543210 committed
150 151
    private $motionToSend = [];
    private $moveToSend = [];
PeratX's avatar
wow!  
PeratX committed
152

Frago9876543210's avatar
Frago9876543210 committed
153 154
    /** @var Player[] */
    private $players = [];
PeratX's avatar
PeratX committed
155

Frago9876543210's avatar
Frago9876543210 committed
156 157
    /** @var Entity[] */
    private $entities = [];
PeratX's avatar
wow!  
PeratX committed
158

Frago9876543210's avatar
Frago9876543210 committed
159 160 161 162
    /** @var Entity[] */
    public $updateEntities = [];
    /** @var Tile[] */
    public $updateTiles = [];
PeratX's avatar
wow!  
PeratX committed
163

Frago9876543210's avatar
Frago9876543210 committed
164
    private $blockCache = [];
PeratX's avatar
wow!  
PeratX committed
165

Frago9876543210's avatar
Frago9876543210 committed
166 167
    /** @var DataPacket[] */
    private $chunkCache = [];
PeratX's avatar
wow!  
PeratX committed
168

Frago9876543210's avatar
Frago9876543210 committed
169
    private $cacheChunks = false;
PeratX's avatar
wow!  
PeratX committed
170

Frago9876543210's avatar
Frago9876543210 committed
171
    private $sendTimeTicker = 0;
Apple's avatar
Apple committed
172

Frago9876543210's avatar
Frago9876543210 committed
173 174
    /** @var Server */
    private $server;
175

Frago9876543210's avatar
Frago9876543210 committed
176 177
    /** @var int */
    private $levelId;
Apple's avatar
Apple committed
178

Frago9876543210's avatar
Frago9876543210 committed
179 180
    /** @var LevelProvider */
    private $provider;
PeratX's avatar
wow!  
PeratX committed
181

Frago9876543210's avatar
Frago9876543210 committed
182 183 184 185 186 187 188 189
    /** @var ChunkLoader[] */
    private $loaders = [];
    /** @var int[] */
    private $loaderCounter = [];
    /** @var ChunkLoader[][] */
    private $chunkLoaders = [];
    /** @var Player[][] */
    private $playerLoaders = [];
PeratX's avatar
wow!  
PeratX committed
190

Frago9876543210's avatar
Frago9876543210 committed
191 192
    /** @var DataPacket[] */
    private $chunkPackets = [];
PeratX's avatar
wow!  
PeratX committed
193

Frago9876543210's avatar
Frago9876543210 committed
194 195
    /** @var float[] */
    private $unloadQueue;
Apple's avatar
Apple committed
196

Frago9876543210's avatar
Frago9876543210 committed
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
    private $time;
    public $stopTime;

    private $folderName;

    /** @var Chunk[] */
    private $chunks = [];

    /** @var Vector3[][] */
    private $changedBlocks = [];

    /** @var ReversePriorityQueue */
    private $updateQueue;
    private $updateQueueIndex = [];

    /** @var Player[][] */
    private $chunkSendQueue = [];
    private $chunkSendTasks = [];

    private $chunkPopulationQueue = [];
    private $chunkPopulationLock = [];
    private $chunkGenerationQueue = [];
    private $chunkGenerationQueueSize = 8;
    private $chunkPopulationQueueSize = 2;

    private $autoSave = true;

    /** @var BlockMetadataStore */
    private $blockMetadata;

    /** @var Position */
    private $temporalPosition;
    /** @var Vector3 */
    private $temporalVector;

    /** @var \SplFixedArray */
    private $blockStates;

    public $sleepTicks = 0;

    private $chunkTickRadius;
    private $chunkTickList = [];
    private $chunksPerTick;
    private $clearChunksOnTick;
    private $randomTickBlocks = [
        Block::GRASS => Grass::class,
        Block::SAPLING => Sapling::class,
        Block::LEAVES => Leaves::class,
        Block::WHEAT_BLOCK => Wheat::class,
        Block::COCOA_BLOCK => CocoaBlock::class,
        Block::FARMLAND => Farmland::class,
        Block::SNOW_LAYER => SnowLayer::class,
        Block::ICE => Ice::class,
        Block::CACTUS => Cactus::class,
        Block::SUGARCANE_BLOCK => Sugarcane::class,
        Block::RED_MUSHROOM => RedMushroom::class,
        Block::BROWN_MUSHROOM => BrownMushroom::class,
        Block::PUMPKIN_STEM => PumpkinStem::class,
        Block::NETHER_WART_BLOCK => NetherWart::class,
        Block::MELON_STEM => MelonStem::class,
        //Block::VINE => true,
        Block::MYCELIUM => Mycelium::class,
        //Block::COCOA_BLOCK => true,
        Block::CARROT_BLOCK => Carrot::class,
        Block::POTATO_BLOCK => Potato::class,
        Block::LEAVES2 => Leaves2::class,

        Block::BEETROOT_BLOCK => Beetroot::class,
    ];

    /** @var LevelTimings */
    public $timings;

    private $tickRate;
    public $tickRateTime = 0;
    public $tickRateCounter = 0;

    /** @var Generator */
    private $generator;
    /** @var Generator */
    private $generatorInstance;

    private $closed = false;

    /** @var Weather */
    private $weather;

    private $blockTempData = [];

    private $dimension = self::DIMENSION_NORMAL;

    /**
     * This method is internal use only. Do not use this in plugins
     *
     * @param Vector3 $pos
     * @param         $data
     */
294
    public function setBlockTempData(Vector3 $pos, $data = null) {
Frago9876543210's avatar
Frago9876543210 committed
295 296 297 298 299 300 301 302 303 304 305 306 307
        if ($data == null and isset($this->blockTempData[self::blockHash($pos->x, $pos->y, $pos->z)])) {
            unset($this->blockTempData[self::blockHash($pos->x, $pos->y, $pos->z)]);
        } else {
            $this->blockTempData[self::blockHash($pos->x, $pos->y, $pos->z)] = $data;
        }
    }

    /**
     * This method is internal use only. Do not use this in plugins
     *
     * @param Vector3 $pos
     * @return int
     */
308
    public function getBlockTempData(Vector3 $pos) {
Frago9876543210's avatar
Frago9876543210 committed
309 310 311 312 313 314 315 316 317 318 319 320 321 322
        if (isset($this->blockTempData[self::blockHash($pos->x, $pos->y, $pos->z)])) {
            return $this->blockTempData[self::blockHash($pos->x, $pos->y, $pos->z)];
        }
        return 0;
    }

    /**
     * Returns the chunk unique hash/key
     *
     * @param int $x
     * @param int $z
     *
     * @return string
     */
323
    public static function chunkHash(int $x, int $z) {
Frago9876543210's avatar
Frago9876543210 committed
324 325 326
        return PHP_INT_SIZE === 8 ? (($x & 0xFFFFFFFF) << 32) | ($z & 0xFFFFFFFF) : $x . ":" . $z;
    }

327
    public static function blockHash(int $x, int $y, int $z) {
Frago9876543210's avatar
Frago9876543210 committed
328 329 330
        return PHP_INT_SIZE === 8 ? (($x & 0xFFFFFFF) << 36) | (($y & Level::Y_MASK) << 28) | ($z & 0xFFFFFFF) : $x . ":" . $y . ":" . $z;
    }

331
    public static function getBlockXYZ($hash, &$x, &$y, &$z) {
Frago9876543210's avatar
Frago9876543210 committed
332 333 334 335 336 337 338 339 340 341 342 343
        if (PHP_INT_SIZE === 8) {
            $x = $hash >> 36;
            $y = ($hash >> 28) & Level::Y_MASK; //it's always positive
            $z = ($hash & 0xFFFFFFF) << 36 >> 36;
        } else {
            $hash = explode(":", $hash);
            $x = (int)$hash[0];
            $y = (int)$hash[1];
            $z = (int)$hash[2];
        }
    }

344
    public static function getXZ($hash, &$x, &$z) {
Frago9876543210's avatar
Frago9876543210 committed
345 346 347 348 349 350 351 352 353 354
        if (PHP_INT_SIZE === 8) {
            $x = $hash >> 32;
            $z = ($hash & 0xFFFFFFFF) << 32 >> 32;
        } else {
            $hash = explode(":", $hash);
            $x = (int)$hash[0];
            $z = (int)$hash[1];
        }
    }

355
    public static function generateChunkLoaderId(ChunkLoader $loader): int {
Frago9876543210's avatar
Frago9876543210 committed
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
        if ($loader->getLoaderId() === 0 or $loader->getLoaderId() === null or $loader->getLoaderId() === null) {
            return self::$chunkLoaderCounter++;
        } else {
            throw new \InvalidStateException("ChunkLoader has a loader id already assigned: " . $loader->getLoaderId());
        }
    }

    /**
     * Init the default level data
     *
     * @param Server $server
     * @param string $name
     * @param string $path
     * @param string $provider Class that extends LevelProvider
     *
     * @throws \Throwable
     */
373
    public function __construct(Server $server, string $name, string $path, string $provider) {
Frago9876543210's avatar
Frago9876543210 committed
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
        $this->blockStates = Block::$fullList;
        $this->levelId = static::$levelIdCounter++;
        $this->blockMetadata = new BlockMetadataStore($this);
        $this->server = $server;
        $this->autoSave = $server->getAutoSave();

        /** @var LevelProvider $provider */

        if (is_subclass_of($provider, LevelProvider::class, true)) {
            $this->provider = new $provider($this, $path);
        } else {
            throw new LevelException("Provider is not a subclass of LevelProvider");
        }
        $this->server->getLogger()->info($this->server->getLanguage()->translateString("pocketmine.level.preparing", [$this->provider->getName()]));
        $this->generator = Generator::getGenerator($this->provider->getGenerator());

        $this->folderName = $name;
        $this->updateQueue = new ReversePriorityQueue();
        $this->updateQueue->setExtractFlags(\SplPriorityQueue::EXTR_BOTH);
        $this->time = (int)$this->provider->getTime();

        $this->chunkTickRadius = min($this->server->getViewDistance(), max(1, (int)$this->server->getProperty("chunk-ticking.tick-radius", 4)));
        $this->chunksPerTick = (int)$this->server->getProperty("chunk-ticking.per-tick", 40);
        $this->chunkGenerationQueueSize = (int)$this->server->getProperty("chunk-generation.queue-size", 8);
        $this->chunkPopulationQueueSize = (int)$this->server->getProperty("chunk-generation.population-queue-size", 2);
        $this->chunkTickList = [];
        $this->clearChunksOnTick = (bool)$this->server->getProperty("chunk-ticking.clear-tick-list", true);
        $this->cacheChunks = (bool)$this->server->getProperty("chunk-sending.cache-chunks", false);

        $this->timings = new LevelTimings($this);
        $this->temporalPosition = new Position(0, 0, 0, $this);
        $this->temporalVector = new Vector3(0, 0, 0);
        $this->tickRate = 1;
        $this->weather = new Weather($this, 0);
408 409 410 411 412 413 414 415

	    $this->setDimension(self::DIMENSION_NORMAL);

        if ($this->server->netherEnabled and $this->server->netherName == $this->folderName)
            $this->setDimension(self::DIMENSION_NETHER);
        elseif ($this->server->enderEnabled and $this->server->enderName == $this->folderName)
            $this->setDimension(self::DIMENSION_END);

Frago9876543210's avatar
Frago9876543210 committed
416 417 418 419 420
        if ($this->server->weatherEnabled and $this->getDimension() == self::DIMENSION_NORMAL) {
            $this->weather->setCanCalculate(true);
        } else $this->weather->setCanCalculate(false);
    }

421
    public function setDimension(int $dimension) {
Frago9876543210's avatar
Frago9876543210 committed
422 423 424
        $this->dimension = $dimension;
    }

425
    public function getDimension(): int {
Frago9876543210's avatar
Frago9876543210 committed
426 427 428 429 430 431
        return $this->dimension;
    }

    /**
     * @return Weather
     */
432
    public function getWeather() {
Frago9876543210's avatar
Frago9876543210 committed
433 434 435
        return $this->weather;
    }

436
    public function getTickRate(): int {
Frago9876543210's avatar
Frago9876543210 committed
437 438 439
        return $this->tickRate;
    }

440
    public function getTickRateTime() {
Frago9876543210's avatar
Frago9876543210 committed
441 442 443
        return $this->tickRateTime;
    }

444
    public function setTickRate(int $tickRate) {
Frago9876543210's avatar
Frago9876543210 committed
445 446 447
        $this->tickRate = $tickRate;
    }

448
    public function initLevel() {
Frago9876543210's avatar
Frago9876543210 committed
449 450 451 452 453 454 455
        $generator = $this->generator;
        $this->generatorInstance = new $generator($this->provider->getGeneratorOptions());
        $this->generatorInstance->init($this, new Random($this->getSeed()));

        $this->registerGenerator();
    }

456
    public function getWaterHeight(): int {
Frago9876543210's avatar
Frago9876543210 committed
457 458 459 460 461 462
        if ($this->generatorInstance instanceof Generator) {
            return $this->generatorInstance->getWaterHeight();
        }
        return 0;
    }

463
    public function registerGenerator() {
Frago9876543210's avatar
Frago9876543210 committed
464 465 466 467 468 469
        $size = $this->server->getScheduler()->getAsyncTaskPoolSize();
        for ($i = 0; $i < $size; ++$i) {
            $this->server->getScheduler()->scheduleAsyncTaskToWorker(new GeneratorRegisterTask($this, $this->generatorInstance), $i);
        }
    }

470
    public function unregisterGenerator() {
Frago9876543210's avatar
Frago9876543210 committed
471 472
        $size = $this->server->getScheduler()->getAsyncTaskPoolSize();
        for ($i = 0; $i < $size; ++$i) {
473
            $this->server->getScheduler()->scheduleAsyncTaskToWorker(new GeneratorUnregisterTask($this), $i);
Frago9876543210's avatar
Frago9876543210 committed
474 475 476 477 478 479
        }
    }

    /**
     * @return BlockMetadataStore
     */
480
    public function getBlockMetadata(): BlockMetadataStore {
Frago9876543210's avatar
Frago9876543210 committed
481 482 483 484 485 486
        return $this->blockMetadata;
    }

    /**
     * @return Server
     */
487
    public function getServer(): Server {
Frago9876543210's avatar
Frago9876543210 committed
488 489 490 491 492 493
        return $this->server;
    }

    /**
     * @return LevelProvider
     */
494
    final public function getProvider() {
Frago9876543210's avatar
Frago9876543210 committed
495 496 497 498 499 500 501 502
        return $this->provider;
    }

    /**
     * Returns the unique level identifier
     *
     * @return int
     */
503
    final public function getId(): int {
Frago9876543210's avatar
Frago9876543210 committed
504 505 506
        return $this->levelId;
    }

507
    public function isClosed(): bool {
Frago9876543210's avatar
Frago9876543210 committed
508 509 510
        return $this->closed;
    }

511
    public function close() {
Frago9876543210's avatar
Frago9876543210 committed
512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532
        assert(!$this->closed, "Tried to close a level which is already closed");

        if ($this->getAutoSave()) {
            $this->save();
        }

        foreach ($this->chunks as $chunk) {
            $this->unloadChunk($chunk->getX(), $chunk->getZ(), false);
        }

        $this->unregisterGenerator();

        $this->provider->close();
        $this->provider = null;
        $this->blockMetadata = null;
        $this->blockCache = [];
        $this->temporalPosition = null;

        $this->closed = true;
    }

533
    public function addSound(Sound $sound, array $players = null) {
Frago9876543210's avatar
Frago9876543210 committed
534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556
        $pk = $sound->encode();

        if ($players === null) {
            if ($pk !== null) {
                if (!is_array($pk)) {
                    $this->addChunkPacket($sound->x >> 4, $sound->z >> 4, $pk);
                } else {
                    foreach ($pk as $e) {
                        $this->addChunkPacket($sound->x >> 4, $sound->z >> 4, $e);
                    }
                }
            }
        } else {
            if ($pk !== null) {
                if (!is_array($pk)) {
                    $this->server->broadcastPacket($players, $pk);
                } else {
                    $this->server->batchPackets($players, $pk, false);
                }
            }
        }
    }

557
    public function addParticle(Particle $particle, array $players = null) {
Frago9876543210's avatar
Frago9876543210 committed
558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580
        $pk = $particle->encode();

        if ($players === null) {
            if ($pk !== null) {
                if (!is_array($pk)) {
                    $this->addChunkPacket($particle->x >> 4, $particle->z >> 4, $pk);
                } else {
                    foreach ($pk as $e) {
                        $this->addChunkPacket($particle->x >> 4, $particle->z >> 4, $e);
                    }
                }
            }
        } else {
            if ($pk !== null) {
                if (!is_array($pk)) {
                    $this->server->broadcastPacket($players, $pk);
                } else {
                    $this->server->batchPackets($players, $pk, false);
                }
            }
        }
    }

581
    public function broadcastLevelEvent(Vector3 $pos, int $evid, int $data = 0) {
Frago9876543210's avatar
Frago9876543210 committed
582 583 584 585 586 587 588
        $pk = new LevelEventPacket();
        $pk->evid = $evid;
        $pk->data = $data;
        list($pk->x, $pk->y, $pk->z) = [$pos->x, $pos->y, $pos->z];
        $this->addChunkPacket($pos->x >> 4, $pos->z >> 4, $pk);
    }

589
    public function broadcastLevelSoundEvent(Vector3 $pos, int $soundId, int $pitch = 1, int $extraData = -1) {
Frago9876543210's avatar
Frago9876543210 committed
590 591 592 593 594 595 596 597 598 599 600
        $pk = new LevelSoundEventPacket();
        $pk->sound = $soundId;
        $pk->pitch = $pitch;
        $pk->extraData = $extraData;
        list($pk->x, $pk->y, $pk->z) = [$pos->x, $pos->y, $pos->z];
        $this->addChunkPacket($pos->x >> 4, $pos->z >> 4, $pk);
    }

    /**
     * @return bool
     */
601
    public function getAutoSave(): bool {
Frago9876543210's avatar
Frago9876543210 committed
602 603 604 605 606 607
        return $this->autoSave;
    }

    /**
     * @param bool $value
     */
608
    public function setAutoSave(bool $value) {
Frago9876543210's avatar
Frago9876543210 committed
609 610 611 612 613 614 615 616 617 618
        $this->autoSave = $value;
    }

    /**
     * Unloads the current level from memory safely
     *
     * @param bool $force default false, force unload of default level
     *
     * @return bool
     */
619
    public function unload(bool $force = false): bool {
Frago9876543210's avatar
Frago9876543210 committed
620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659

        $ev = new LevelUnloadEvent($this);

        if ($this === $this->server->getDefaultLevel() and $force !== true) {
            $ev->setCancelled(true);
        }

        $this->server->getPluginManager()->callEvent($ev);

        if (!$force and $ev->isCancelled()) {
            return false;
        }

        $this->server->getLogger()->info($this->server->getLanguage()->translateString("pocketmine.level.unloading", [$this->getName()]));
        $defaultLevel = $this->server->getDefaultLevel();
        foreach ($this->getPlayers() as $player) {
            if ($this === $defaultLevel or $defaultLevel === null) {
                $player->close($player->getLeaveMessage(), "Forced default level unload");
            } elseif ($defaultLevel instanceof Level) {
                $player->teleport($this->server->getDefaultLevel()->getSafeSpawn());
            }
        }

        if ($this === $defaultLevel) {
            $this->server->setDefaultLevel(null);
        }

        $this->close();

        return true;
    }

    /**
     * Gets the players being used in a specific chunk
     *
     * @param int $chunkX
     * @param int $chunkZ
     *
     * @return Player[]
     */
660
    public function getChunkPlayers(int $chunkX, int $chunkZ): array {
Frago9876543210's avatar
Frago9876543210 committed
661 662 663 664 665 666 667 668 669 670 671
        return isset($this->playerLoaders[$index = Level::chunkHash($chunkX, $chunkZ)]) ? $this->playerLoaders[$index] : [];
    }

    /**
     * Gets the chunk loaders being used in a specific chunk
     *
     * @param int $chunkX
     * @param int $chunkZ
     *
     * @return ChunkLoader[]
     */
672
    public function getChunkLoaders(int $chunkX, int $chunkZ): array {
Frago9876543210's avatar
Frago9876543210 committed
673 674 675
        return isset($this->chunkLoaders[$index = Level::chunkHash($chunkX, $chunkZ)]) ? $this->chunkLoaders[$index] : [];
    }

676
    public function addChunkPacket(int $chunkX, int $chunkZ, DataPacket $packet) {
Frago9876543210's avatar
Frago9876543210 committed
677 678 679 680 681 682 683
        if (!isset($this->chunkPackets[$index = Level::chunkHash($chunkX, $chunkZ)])) {
            $this->chunkPackets[$index] = [$packet];
        } else {
            $this->chunkPackets[$index][] = $packet;
        }
    }

684
    public function registerChunkLoader(ChunkLoader $loader, int $chunkX, int $chunkZ, bool $autoLoad = true) {
Frago9876543210's avatar
Frago9876543210 committed
685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712
        $hash = $loader->getLoaderId();

        if (!isset($this->chunkLoaders[$index = Level::chunkHash($chunkX, $chunkZ)])) {
            $this->chunkLoaders[$index] = [];
            $this->playerLoaders[$index] = [];
        } elseif (isset($this->chunkLoaders[$index][$hash])) {
            return;
        }

        $this->chunkLoaders[$index][$hash] = $loader;
        if ($loader instanceof Player) {
            $this->playerLoaders[$index][$hash] = $loader;
        }

        if (!isset($this->loaders[$hash])) {
            $this->loaderCounter[$hash] = 1;
            $this->loaders[$hash] = $loader;
        } else {
            ++$this->loaderCounter[$hash];
        }

        $this->cancelUnloadChunkRequest($chunkX, $chunkZ);

        if ($autoLoad) {
            $this->loadChunk($chunkX, $chunkZ);
        }
    }

713
    public function unregisterChunkLoader(ChunkLoader $loader, int $chunkX, int $chunkZ) {
Frago9876543210's avatar
Frago9876543210 committed
714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733
        if (isset($this->chunkLoaders[$index = Level::chunkHash($chunkX, $chunkZ)][$hash = $loader->getLoaderId()])) {
            unset($this->chunkLoaders[$index][$hash]);
            unset($this->playerLoaders[$index][$hash]);
            if (count($this->chunkLoaders[$index]) === 0) {
                unset($this->chunkLoaders[$index]);
                unset($this->playerLoaders[$index]);
                $this->unloadChunkRequest($chunkX, $chunkZ, true);
            }

            if (--$this->loaderCounter[$hash] === 0) {
                unset($this->loaderCounter[$hash]);
                unset($this->loaders[$hash]);
            }
        }
    }

    /**
     * WARNING: Do not use this, it's only for internal use.
     * Changes to this function won't be recorded on the version.
     */
734
    public function checkTime() {
Frago9876543210's avatar
Frago9876543210 committed
735 736 737 738 739 740 741 742 743 744 745
        if ($this->stopTime == true) {
            return;
        } else {
            $this->time += 1;
        }
    }

    /**
     * WARNING: Do not use this, it's only for internal use.
     * Changes to this function won't be recorded on the version.
     */
746
    public function sendTime() {
Frago9876543210's avatar
Frago9876543210 committed
747 748 749 750 751 752 753 754 755 756 757 758 759
        $pk = new SetTimePacket();
        $pk->time = (int)$this->time;
        $pk->started = $this->stopTime == false;

        $this->server->broadcastPacket($this->players, $pk);
    }

    /**
     * WARNING: Do not use this, it's only for internal use.
     * Changes to this function won't be recorded on the version.
     *
     * @param int $currentTick
     */
760
    public function doTick(int $currentTick) {
Frago9876543210's avatar
Frago9876543210 committed
761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883

        $this->timings->doTick->startTiming();

        $this->checkTime();

        if (++$this->sendTimeTicker === 280) {
            $this->sendTime();
            $this->sendTimeTicker = 0;
        }

        $this->weather->calcWeather($currentTick);

        $this->unloadChunks();

        //Do block updates
        $this->timings->doTickPending->startTiming();
        if ($this->updateQueue->count() > 0 and $this->updateQueue->current()["priority"] <= $currentTick) {
            $block = $this->getBlock($this->updateQueue->extract()["data"]);
            unset($this->updateQueueIndex[Level::blockHash($block->x, $block->y, $block->z)]);
            $block->onUpdate(self::BLOCK_UPDATE_SCHEDULED);
        }
        $this->timings->doTickPending->stopTiming();

        $this->timings->entityTick->startTiming();
        //Update entities that need update
        Timings::$tickEntityTimer->startTiming();
        foreach ($this->updateEntities as $id => $entity) {
            if ($entity->closed or !$entity->onUpdate($currentTick)) {
                unset($this->updateEntities[$id]);
            }
        }
        Timings::$tickEntityTimer->stopTiming();
        $this->timings->entityTick->stopTiming();

        $this->timings->tileEntityTick->startTiming();
        Timings::$tickTileEntityTimer->startTiming();
        //Update tiles that need update
        if (count($this->updateTiles) > 0) {
            foreach ($this->updateTiles as $id => $tile) {
                if ($tile->onUpdate() !== true) {
                    unset($this->updateTiles[$id]);
                }
            }
        }
        Timings::$tickTileEntityTimer->stopTiming();
        $this->timings->tileEntityTick->stopTiming();

        $this->timings->doTickTiles->startTiming();
        if (($currentTick % 2) === 0) $this->tickChunks();
        $this->timings->doTickTiles->stopTiming();

        if (count($this->changedBlocks) > 0) {
            if (count($this->players) > 0) {
                foreach ($this->changedBlocks as $index => $blocks) {
                    unset($this->chunkCache[$index]);
                    Level::getXZ($index, $chunkX, $chunkZ);
                    if (count($blocks) > 512) {
                        $chunk = $this->getChunk($chunkX, $chunkZ);
                        foreach ($this->getChunkPlayers($chunkX, $chunkZ) as $p) {
                            $p->onChunkChanged($chunk);
                        }
                    } else {
                        $this->sendBlocks($this->getChunkPlayers($chunkX, $chunkZ), $blocks, UpdateBlockPacket::FLAG_ALL);
                    }
                }
            } else {
                $this->chunkCache = [];
            }

            $this->changedBlocks = [];

        }

        $this->processChunkRequest();

        if ($this->sleepTicks > 0 and --$this->sleepTicks <= 0) {
            $this->checkSleep();
        }

        foreach ($this->moveToSend as $index => $entry) {
            Level::getXZ($index, $chunkX, $chunkZ);
            foreach ($entry as $e) {
                $pk = new MoveEntityPacket();
                $pk->eid = $e[0];
                $pk->x = $e[1];
                $pk->y = $e[2];
                $pk->z = $e[3];
                $pk->yaw = $e[4];
                $pk->headYaw = $e[5];
                $pk->pitch = $e[6];
                $this->addChunkPacket($chunkX, $chunkZ, $pk);
            }
        }
        $this->moveToSend = [];

        foreach ($this->motionToSend as $index => $entry) {
            Level::getXZ($index, $chunkX, $chunkZ);
            foreach ($entry as $entity) {
                $pk = new SetEntityMotionPacket();
                $pk->eid = $entity[0];
                $pk->motionX = $entity[1];
                $pk->motionY = $entity[2];
                $pk->motionZ = $entity[3];
                $this->addChunkPacket($chunkX, $chunkZ, $pk);
            }
        }
        $this->motionToSend = [];

        foreach ($this->chunkPackets as $index => $entries) {
            Level::getXZ($index, $chunkX, $chunkZ);
            $chunkPlayers = $this->getChunkPlayers($chunkX, $chunkZ);
            if (count($chunkPlayers) > 0) {
                foreach ($entries as $pk) {
                    $this->server->broadcastPacket($chunkPlayers, $pk);
                }
            }
        }

        $this->chunkPackets = [];

        $this->timings->doTick->stopTiming();
    }

884
    public function checkSleep() {
Frago9876543210's avatar
Frago9876543210 committed
885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909
        if (count($this->players) === 0) {
            return;
        }

        $resetTime = true;
        foreach ($this->getPlayers() as $p) {
            if (!$p->isSleeping()) {
                $resetTime = false;
                break;
            }
        }

        if ($resetTime) {
            $time = $this->getTime() % Level::TIME_FULL;

            if ($time >= Level::TIME_NIGHT and $time < Level::TIME_SUNRISE) {
                $this->setTime($this->getTime() + Level::TIME_FULL - $time);

                foreach ($this->getPlayers() as $p) {
                    $p->stopSleep();
                }
            }
        }
    }

910
    public function sendBlockExtraData(int $x, int $y, int $z, int $id, int $data, array $targets = null) {
Frago9876543210's avatar
Frago9876543210 committed
911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926
        $pk = new LevelEventPacket;
        $pk->evid = LevelEventPacket::EVENT_SET_DATA;
        $pk->x = $x + 0.5;
        $pk->y = $y + 0.5;
        $pk->z = $z + 0.5;
        $pk->data = ($data << 8) | $id;

        $this->server->broadcastPacket($targets === null ? $this->getChunkPlayers($x >> 4, $z >> 4) : $targets, $pk);
    }

    /**
     * @param Player[] $target
     * @param Block[] $blocks
     * @param int $flags
     * @param bool $optimizeRebuilds
     */
927
    public function sendBlocks(array $target, array $blocks, $flags = UpdateBlockPacket::FLAG_NONE, bool $optimizeRebuilds = false) {
Frago9876543210's avatar
Frago9876543210 committed
928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981
        if ($optimizeRebuilds) {
            $chunks = [];
            foreach ($blocks as $b) {
                if ($b === null) {
                    continue;
                }

                $pk = new UpdateBlockPacket();
                $first = false;
                if (!isset($chunks[$index = Level::chunkHash($b->x >> 4, $b->z >> 4)])) {
                    $chunks[$index] = true;
                    $first = true;
                }

                $pk->x = $b->x;
                $pk->z = $b->z;
                $pk->y = $b->y;

                if ($b instanceof Block) {
                    $pk->blockId = $b->getId();
                    $pk->blockData = $b->getDamage();
                } else {
                    $fullBlock = $this->getFullBlock($b->x, $b->y, $b->z);
                    $pk->blockId = $fullBlock >> 4;
                    $pk->blockData = $fullBlock & 0xf;
                }
                $pk->flags = $first ? $flags : UpdateBlockPacket::FLAG_NONE;
                $this->server->broadcastPacket($target, $pk);
            }
        } else {
            foreach ($blocks as $b) {
                if ($b === null) {
                    continue;
                }
                $pk = new UpdateBlockPacket();

                $pk->x = $b->x;
                $pk->z = $b->z;
                $pk->y = $b->y;

                if ($b instanceof Block) {
                    $pk->blockId = $b->getId();
                    $pk->blockData = $b->getDamage();
                } else {
                    $fullBlock = $this->getFullBlock($b->x, $b->y, $b->z);
                    $pk->blockId = $fullBlock >> 4;
                    $pk->blockData = $fullBlock & 0xf;
                }
                $pk->flags = $flags;
                $this->server->broadcastPacket($target, $pk);
            }
        }
    }

982
    public function clearCache(bool $full = false) {
Frago9876543210's avatar
Frago9876543210 committed
983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998
        if ($full) {
            $this->chunkCache = [];
            $this->blockCache = [];
        } else {
            if (count($this->chunkCache) > 768) {
                $this->chunkCache = [];
            }

            if (count($this->blockCache) > 2048) {
                $this->blockCache = [];
            }

        }

    }

999
    public function clearChunkCache(int $chunkX, int $chunkZ) {
Frago9876543210's avatar
Frago9876543210 committed
1000 1001 1002
        unset($this->chunkCache[Level::chunkHash($chunkX, $chunkZ)]);
    }

1003
    private function tickChunks() {
Frago9876543210's avatar
Frago9876543210 committed
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074
        if ($this->chunksPerTick <= 0 or count($this->loaders) === 0) {
            $this->chunkTickList = [];
            return;
        }

        $chunksPerLoader = min(200, max(1, (int)((($this->chunksPerTick - count($this->loaders)) / count($this->loaders)) + 0.5)));
        $randRange = 3 + $chunksPerLoader / 30;
        $randRange = (int)($randRange > $this->chunkTickRadius ? $this->chunkTickRadius : $randRange);

        foreach ($this->loaders as $loader) {
            $chunkX = $loader->getX() >> 4;
            $chunkZ = $loader->getZ() >> 4;

            $index = Level::chunkHash($chunkX, $chunkZ);
            $existingLoaders = max(0, isset($this->chunkTickList[$index]) ? $this->chunkTickList[$index] : 0);
            $this->chunkTickList[$index] = $existingLoaders + 1;
            for ($chunk = 0; $chunk < $chunksPerLoader; ++$chunk) {
                $dx = mt_rand(-$randRange, $randRange);
                $dz = mt_rand(-$randRange, $randRange);
                $hash = Level::chunkHash($dx + $chunkX, $dz + $chunkZ);
                if (!isset($this->chunkTickList[$hash]) and isset($this->chunks[$hash])) {
                    $this->chunkTickList[$hash] = -1;
                }
            }
        }

        foreach ($this->chunkTickList as $index => $loaders) {
            Level::getXZ($index, $chunkX, $chunkZ);


            if (!isset($this->chunks[$index]) or ($chunk = $this->getChunk($chunkX, $chunkZ, false)) === null) {
                unset($this->chunkTickList[$index]);
                continue;
            } elseif ($loaders <= 0) {
                unset($this->chunkTickList[$index]);
            }

            foreach ($chunk->getEntities() as $entity) {
                $entity->scheduleUpdate();
            }


            foreach ($chunk->getSubChunks() as $Y => $subChunk) {
                if (!$subChunk->isEmpty()) {
                    $k = mt_rand(0, 0x7fffffff);
                    for ($i = 0; $i < 3; ++$i, $k >>= 10) {
                        $x = $k & 0x0f;
                        $y = ($k >> 8) & 0x0f;
                        $z = ($k >> 16) & 0x0f;

                        $blockId = $subChunk->getBlockId($x, $y, $z);
                        if (isset($this->randomTickBlocks[$blockId])) {
                            $class = $this->randomTickBlocks[$blockId];
                            /** @var Block $block */
                            $block = new $class($subChunk->getBlockData($x, $y, $z));
                            $block->x = $chunkX * 16 + $x;
                            $block->y = ($Y << 4) + $y;
                            $block->z = $chunkZ * 16 + $z;
                            $block->level = $this;
                            $block->onUpdate(self::BLOCK_UPDATE_RANDOM);
                        }
                    }
                }
            }
        }

        if ($this->clearChunksOnTick) {
            $this->chunkTickList = [];
        }
    }

1075
    public function __debugInfo(): array {
Frago9876543210's avatar
Frago9876543210 committed
1076 1077 1078 1079 1080 1081 1082 1083
        return [];
    }

    /**
     * @param bool $force
     *
     * @return bool
     */
1084
    public function save(bool $force = false): bool {
Frago9876543210's avatar
Frago9876543210 committed
1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100

        if (!$this->getAutoSave() and !$force) {
            return false;
        }

        $this->server->getPluginManager()->callEvent(new LevelSaveEvent($this));

        $this->provider->setTime((int)$this->time);
        $this->saveChunks();
        if ($this->provider instanceof BaseLevelProvider) {
            $this->provider->saveLevelData();
        }

        return true;
    }

1101
    public function saveChunks() {
Frago9876543210's avatar
Frago9876543210 committed
1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113
        foreach ($this->chunks as $chunk) {
            if ($chunk->hasChanged() and $chunk->isGenerated()) {
                $this->provider->setChunk($chunk->getX(), $chunk->getZ(), $chunk);
                $this->provider->saveChunk($chunk->getX(), $chunk->getZ());
                $chunk->setChanged(false);
            }
        }
    }

    /**
     * @param Vector3 $pos
     */
1114
    public function updateAround(Vector3 $pos) {
Frago9876543210's avatar
Frago9876543210 committed
1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150
        $pos = $pos->floor();
        $this->server->getPluginManager()->callEvent($ev = new BlockUpdateEvent($this->getBlock($this->temporalVector->setComponents($pos->x, $pos->y - 1, $pos->z))));
        if (!$ev->isCancelled()) {
            $ev->getBlock()->onUpdate(self::BLOCK_UPDATE_NORMAL);
        }

        $this->server->getPluginManager()->callEvent($ev = new BlockUpdateEvent($this->getBlock($this->temporalVector->setComponents($pos->x, $pos->y + 1, $pos->z))));
        if (!$ev->isCancelled()) {
            $ev->getBlock()->onUpdate(self::BLOCK_UPDATE_NORMAL);
        }

        $this->server->getPluginManager()->callEvent($ev = new BlockUpdateEvent($this->getBlock($this->temporalVector->setComponents($pos->x - 1, $pos->y, $pos->z))));
        if (!$ev->isCancelled()) {
            $ev->getBlock()->onUpdate(self::BLOCK_UPDATE_NORMAL);
        }

        $this->server->getPluginManager()->callEvent($ev = new BlockUpdateEvent($this->getBlock($this->temporalVector->setComponents($pos->x + 1, $pos->y, $pos->z))));
        if (!$ev->isCancelled()) {
            $ev->getBlock()->onUpdate(self::BLOCK_UPDATE_NORMAL);
        }

        $this->server->getPluginManager()->callEvent($ev = new BlockUpdateEvent($this->getBlock($this->temporalVector->setComponents($pos->x, $pos->y, $pos->z - 1))));
        if (!$ev->isCancelled()) {
            $ev->getBlock()->onUpdate(self::BLOCK_UPDATE_NORMAL);
        }

        $this->server->getPluginManager()->callEvent($ev = new BlockUpdateEvent($this->getBlock($this->temporalVector->setComponents($pos->x, $pos->y, $pos->z + 1))));
        if (!$ev->isCancelled()) {
            $ev->getBlock()->onUpdate(self::BLOCK_UPDATE_NORMAL);
        }
    }

    /**
     * @param Vector3 $pos
     * @param int $delay
     */
1151
    public function scheduleUpdate(Vector3 $pos, int $delay) {
Frago9876543210's avatar
Frago9876543210 committed
1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164
        if (isset($this->updateQueueIndex[$index = Level::blockHash($pos->x, $pos->y, $pos->z)]) and $this->updateQueueIndex[$index] <= $delay) {
            return;
        }
        $this->updateQueueIndex[$index] = $delay;
        $this->updateQueue->insert(new Vector3((int)$pos->x, (int)$pos->y, (int)$pos->z), (int)$delay + $this->server->getTick());
    }

    /**
     * @param AxisAlignedBB $bb
     * @param bool $targetFirst
     *
     * @return Block[]
     */
1165
    public function getCollisionBlocks(AxisAlignedBB $bb, bool $targetFirst = false): array {
Frago9876543210's avatar
Frago9876543210 committed
1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207
        $minX = Math::floorFloat($bb->minX);
        $minY = Math::floorFloat($bb->minY);
        $minZ = Math::floorFloat($bb->minZ);
        $maxX = Math::ceilFloat($bb->maxX);
        $maxY = Math::ceilFloat($bb->maxY);
        $maxZ = Math::ceilFloat($bb->maxZ);

        $collides = [];

        if ($targetFirst) {
            for ($z = $minZ; $z <= $maxZ; ++$z) {
                for ($x = $minX; $x <= $maxX; ++$x) {
                    for ($y = $minY; $y <= $maxY; ++$y) {
                        $block = $this->getBlock($this->temporalVector->setComponents($x, $y, $z));
                        if ($block->getId() !== 0 and $block->collidesWithBB($bb)) {
                            return [$block];
                        }
                    }
                }
            }
        } else {
            for ($z = $minZ; $z <= $maxZ; ++$z) {
                for ($x = $minX; $x <= $maxX; ++$x) {
                    for ($y = $minY; $y <= $maxY; ++$y) {
                        $block = $this->getBlock($this->temporalVector->setComponents($x, $y, $z));
                        if ($block->getId() !== 0 and $block->collidesWithBB($bb)) {
                            $collides[] = $block;
                        }
                    }
                }
            }
        }


        return $collides;
    }

    /**
     * @param Vector3 $pos
     *
     * @return bool
     */
1208
    public function isFullBlock(Vector3 $pos): bool {
Frago9876543210's avatar
Frago9876543210 committed
1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227
        if ($pos instanceof Block) {
            if ($pos->isSolid()) {
                return true;
            }
            $bb = $pos->getBoundingBox();
        } else {
            $bb = $this->getBlock($pos)->getBoundingBox();
        }

        return $bb !== null and $bb->getAverageEdgeLength() >= 1;
    }

    /**
     * @param Entity $entity
     * @param AxisAlignedBB $bb
     * @param boolean $entities
     *
     * @return AxisAlignedBB[]
     */
1228
    public function getCollisionCubes(Entity $entity, AxisAlignedBB $bb, bool $entities = true): array {
Frago9876543210's avatar
Frago9876543210 committed
1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267
        $minX = Math::floorFloat($bb->minX);
        $minY = Math::floorFloat($bb->minY);
        $minZ = Math::floorFloat($bb->minZ);
        $maxX = Math::ceilFloat($bb->maxX);
        $maxY = Math::ceilFloat($bb->maxY);
        $maxZ = Math::ceilFloat($bb->maxZ);

        $collides = [];

        for ($z = $minZ; $z <= $maxZ; ++$z) {
            for ($x = $minX; $x <= $maxX; ++$x) {
                for ($y = $minY; $y <= $maxY; ++$y) {
                    $block = $this->getBlock($this->temporalVector->setComponents($x, $y, $z));
                    if (!$block->canPassThrough() and $block->collidesWithBB($bb)) {
                        $collides[] = $block->getBoundingBox();
                    }
                }
            }
        }

        if ($entities) {
            foreach ($this->getCollidingEntities($bb->grow(0.25, 0.25, 0.25), $entity) as $ent) {
                $collides[] = clone $ent->boundingBox;
            }
        }

        return $collides;
    }

    /*
	public function rayTraceBlocks(Vector3 $pos1, Vector3 $pos2, $flag = false, $flag1 = false, $flag2 = false){
		if(!is_nan($pos1->x) and !is_nan($pos1->y) and !is_nan($pos1->z)){
			if(!is_nan($pos2->x) and !is_nan($pos2->y) and !is_nan($pos2->z)){
				$x1 = (int) $pos1->x;
				$y1 = (int) $pos1->y;
				$z1 = (int) $pos1->z;
				$x2 = (int) $pos2->x;
				$y2 = (int) $pos2->y;
				$z2 = (int) $pos2->z;
PeratX's avatar
wow!  
PeratX committed
1268

Frago9876543210's avatar
Frago9876543210 committed
1269
				$block = $this->getBlock(Vector3::createVector($x1, $y1, $z1));
PeratX's avatar
wow!  
PeratX committed
1270

Frago9876543210's avatar
Frago9876543210 committed
1271 1272 1273 1274
				if(!$flag1 or $block->getBoundingBox() !== null){
					$ob = $block->calculateIntercept($pos1, $pos2);
					if($ob !== null){
						return $ob;
PeratX's avatar
wow!  
PeratX committed
1275 1276 1277
					}
				}

Frago9876543210's avatar
Frago9876543210 committed
1278
				$movingObjectPosition = null;
PeratX's avatar
wow!  
PeratX committed
1279

Frago9876543210's avatar
Frago9876543210 committed
1280
				$k = 200;
PeratX's avatar
wow!  
PeratX committed
1281

Frago9876543210's avatar
Frago9876543210 committed
1282 1283 1284 1285
				while($k-- >= 0){
					if(is_nan($pos1->x) or is_nan($pos1->y) or is_nan($pos1->z)){
						return null;
					}
PeratX's avatar
wow!  
PeratX committed
1286

Frago9876543210's avatar
Frago9876543210 committed
1287 1288 1289
					if($x1 === $x2 and $y1 === $y2 and $z1 === $z2){
						return $flag2 ? $movingObjectPosition : null;
					}
PeratX's avatar
wow!  
PeratX committed
1290

Frago9876543210's avatar
Frago9876543210 committed
1291 1292 1293
					$flag3 = true;
					$flag4 = true;
					$flag5 = true;
PeratX's avatar
PeratX committed
1294

Frago9876543210's avatar
Frago9876543210 committed
1295 1296 1297
					$i = 999;
					$j = 999;
					$k = 999;
PeratX's avatar
wow!  
PeratX committed
1298

Frago9876543210's avatar
Frago9876543210 committed
1299 1300 1301 1302
					if($x1 > $x2){
						$i = $x2 + 1;
					}elseif($x1 < $x2){
						$i = $x2;
PeratX's avatar
wow!  
PeratX committed
1303
					}else{
Frago9876543210's avatar
Frago9876543210 committed
1304
						$flag3 = false;
PeratX's avatar
wow!  
PeratX committed
1305 1306
					}

Frago9876543210's avatar
Frago9876543210 committed
1307 1308 1309 1310 1311 1312 1313
					if($y1 > $y2){
						$j = $y2 + 1;
					}elseif($y1 < $y2){
						$j = $y2;
					}else{
						$flag4 = false;
					}
PeratX's avatar
wow!  
PeratX committed
1314