Merge pull request #60 from Sunch233/master

Unify the code style
This commit is contained in:
enirboreHemaG 2025-04-29 02:07:18 +03:00 • committed by GitHub
commit 682de0f723
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
359 changed files with 3160 additions and 3276 deletions

27
.github/workflows/main.yml vendored Normal file
View file

@ -0,0 +1,27 @@
name: CI
on:
push:
pull_request:
workflow_dispatch:
jobs:
codestyle:
name: Code Style checks
runs-on: ubuntu-latest
strategy:
fail-fast: false
steps:
- uses: actions/checkout@v4
- name: Setup PHP and tools
uses: shivammathur/setup-php@2.31.1
with:
php-version: 8.0
tools: php-cs-fixer:3.60
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Run PHP-CS-Fixer
run: php-cs-fixer fix --dry-run --diff --ansi

3
.gitignore vendored
View file

@ -10,6 +10,9 @@ server.lock
*.txt
*.properties
# php-cs-fixer
/.php_cs.cache
/.php-cs-fixer.cache
############
## Windows

36
.php-cs-fixer.php Normal file
View file

@ -0,0 +1,36 @@
<?php
$finder = PhpCsFixer\Finder::create()
->in(__DIR__ . '/src');
return (new PhpCsFixer\Config)
->setRules([
'array_indentation' => true,
'array_syntax' => [
'syntax' => 'short'
],
'binary_operator_spaces' => [
'default' => 'single_space'
],
'blank_line_after_namespace' => true,
'blank_line_after_opening_tag' => true,
'cast_spaces' => [
'space' => 'single'
],
'elseif' => true,
'indentation_type' => true,
'no_closing_tag' => true,
'no_empty_phpdoc' => true,
'no_extra_blank_lines' => true,
'no_superfluous_phpdoc_tags' => [
'allow_mixed' => true,
],
'no_trailing_whitespace' => true,
'no_trailing_whitespace_in_comment' => true,
'no_whitespace_in_blank_line' => true,
'unary_operator_spaces' => true
])
->setFinder($finder)
->setIndent("\t")
->setLineEnding("\n")
->setParallelConfig(PhpCsFixer\Runner\Parallel\ParallelConfigFactory::detect());

View file

@ -1,7 +1,7 @@
<?php
class AchievementAPI{
public static $achievements = [
/*"openInventory" => array(
"name" => "Taking Inventory",
@ -79,20 +79,19 @@ class AchievementAPI{
"buildSword",
],
],
];
private $server;
function __construct(){
$this->server = ServerAPI::request();
}
/**
* Add an achievement
* @param string $achievementId
* @param string $achievementName
* @param array $requires
* @return boolean
*/
public static function addAchievement($achievementId, $achievementName, array $requires = []){
@ -105,7 +104,7 @@ class AchievementAPI{
}
return false;
}
public static function grantAchievement(Player $player, $achievementId){
if(isset(self::$achievements[$achievementId]) and !self::hasAchievement($player, $achievementId)){
foreach(self::$achievements[$achievementId]["requires"] as $requerimentId){
@ -123,19 +122,19 @@ class AchievementAPI{
}
return false;
}
public static function hasAchievement(Player $player, $achievementId){
if(!isset(self::$achievements[$achievementId]) or !isset($player->achievements)){
$player->achievements = [];
return false;
}
if(!isset($player->achievements[$achievementId]) or !$player->achievements[$achievementId]){
return false;
}
return true;
}
public static function broadcastAchievement(Player $player, $achievementId){
if(isset(self::$achievements[$achievementId])){
$result = ServerAPI::request()->api->dhandle("achievement.broadcast", ["player" => $player, "achievementId" => $achievementId]);
@ -150,13 +149,13 @@ class AchievementAPI{
}
return false;
}
public static function removeAchievement(Player $player, $achievementId){
if(self::hasAchievement($player, $achievementId)){
$player->achievements[$achievementId] = false;
}
}
public function viewAchievements($cmd, $params, $issuer, $alias)
{
if(!isset($params[0])){
@ -171,17 +170,17 @@ class AchievementAPI{
}else{
return false;
}
if(!$data){
return "Player is not found.";
}
if($data instanceof Config){
$achs = $data->get("achievements");
}else{
$achs = $data;
}
if(count($achs) <= 0){
return "Player {$params[0]} unlocked 0 achievements";
}
@ -192,9 +191,9 @@ class AchievementAPI{
$output .= "{$info["name"]}, ";
}
}
return substr($output, 0, - 2);
return substr($output, 0, -2);
}
public function init(){
$this->server->api->console->register("ach", "<player>", [$this, "viewAchievements"]);
$this->server->api->console->alias("getplayerachievements", "ach");

View file

@ -14,7 +14,7 @@ class BanAPI{
private $ops;
/** @var Config */
private $bannedIPs;
public $cmdWhitelist = [];//Command WhiteList
function __construct(){

View file

@ -259,7 +259,7 @@ class BlockAPI{
$output .= "Usage: /setblock <x> <y> <z> <block[:damage]>";
break;
}
$level = $issuer->entity->level;
$block = self::fromString($args[3])->getBlock();
}
@ -294,8 +294,8 @@ class BlockAPI{
break;
case "give":
$player = $this->server->api->player->get($args[0] ?? "");
if($player instanceof Player){
if($player instanceof Player){
$item = self::fromString($args[1] ?? "");
if(($player->gamemode & 0x01) === 0x01){
return "Player is in creative mode.";
@ -303,18 +303,18 @@ class BlockAPI{
if($item->getID() === 0){
return "You cannot give an air block to a player.";
}
if(!isset($args[2])){
$item->count = $item->getMaxStackSize();
}else{
$item->count = (int) $args[2];
}
$player->addItem($item->getID(), $item->getMetadata(), $item->count);
$output .= "Giving ".$item->count." of ".$item->getName()." (".$item->getID().":".$item->getMetadata().") to ".$player->username;
break;
}else{
$item = self::fromString($args[0] ?? "");
$item = self::fromString($args[0] ?? "");
if(!($issuer instanceof Player)){
return "You cant give an item to a non-player.";
}
@ -412,7 +412,6 @@ class BlockAPI{
return $this->cancelAction($target, $player, false);
}
if(is_array($drops) && ($player->gamemode & 0x01) === 0x00 and count($drops) > 0){
foreach($drops as $drop){
$this->server->api->entity->drop(new Position($target->x + 0.5, $target->y, $target->z + 0.5, $target->level), BlockAPI::getItem($drop[0] & 0xFFFF, $drop[1] & 0xFFFF, $drop[2]));
@ -456,7 +455,7 @@ class BlockAPI{
return $this->cancelAction($block, $player);
}
}
StaticBlock::getBlock($target->getID())::interact($target->level, $target->x, $target->y, $target->z, $player);
if($target->isActivable === true){
@ -501,14 +500,14 @@ class BlockAPI{
$hand->position($block);
//$face = -1;
}
if($hand->isSolid === true && ($hand->getID() != BED_BLOCK && $hand->getID() != CARPET)){
$aabb = $hand->getAABB($block->level, $block->x, $block->y, $block->z);
$playerbb = $player->entity->boundingBox;
if(($aabb->maxX > $playerbb->minX && $aabb->minX < $playerbb->maxX) && ($aabb->maxY > ($playerbb->minY+0.21) && $aabb->minY < $playerbb->maxY) && ($aabb->maxZ > $playerbb->minZ && $aabb->minZ < $playerbb->maxZ)){
if(($aabb->maxX > $playerbb->minX && $aabb->minX < $playerbb->maxX) && ($aabb->maxY > ($playerbb->minY + 0.21) && $aabb->minY < $playerbb->maxY) && ($aabb->maxZ > $playerbb->minZ && $aabb->minZ < $playerbb->maxZ)){
return $this->cancelAction($block, $player, false); //Entity in block
}
}
if($this->server->api->dhandle("player.block.place", ["player" => $player, "block" => $block, "target" => $target, "item" => $item]) === false){
@ -537,14 +536,12 @@ class BlockAPI{
return false;
}
$level = $block::onUpdate($pos->level, $pos->x, $pos->y, $pos->z, $type);
return $level;
}
public function blockUpdateAround(Position $pos, $type = BLOCK_UPDATE_NORMAL, $delay = false){
if($type == BLOCK_UPDATE_NORMAL){
try{
throw new Exception("Deprecated: tried updating $pos using BLOCK_UPDATE_NORMAL.");
@ -554,7 +551,7 @@ class BlockAPI{
}
return;
}
if($delay !== false){
$this->scheduleBlockUpdate($pos->getSide(0), $delay, $type);
$this->scheduleBlockUpdate($pos->getSide(1), $delay, $type);
@ -576,7 +573,7 @@ class BlockAPI{
if($delay < 0){
return false;
}
$index = $x . "." . $y . "." . $z . "." . $level->getName() . "." . $type;
$delay = microtime(true) + $delay * 0.05;
if(!isset($this->scheduledUpdates[$index])){
@ -586,7 +583,7 @@ class BlockAPI{
}
return false;
}
public function scheduleBlockUpdate(Position $pos, $delay, $type = BLOCK_UPDATE_SCHEDULED){
$type = (int) $type;
if($delay < 0){

View file

@ -103,8 +103,6 @@ class ChatAPI{
/**
* @param mixed $owner Can be either Player object or string username. Boolean false for broadcast.
* @param string $text
* @param $whitelist
* @param $blacklist
*/
public function send($owner, $text, $whitelist = false, $blacklist = false){
$message = [

View file

@ -24,12 +24,12 @@ class ConsoleAPI{
$this->register("defaultgamemode", "<mode>", [$this, "defaultCommands"]);
$this->server->api->console->alias("tps", "status");
$this->cmdWhitelist("help");
$this->cmdWhitelist("status");
$this->cmdWhitelist("?");
}
/**
* Whitelists a CMD so everyone can issue it - Even non OPs.
* @param string $cmd Command to Whitelist
@ -37,7 +37,7 @@ class ConsoleAPI{
public function cmdWhitelist($cmd){
$this->server->api->ban->cmdWhitelist[strtolower(trim($cmd))] = true;
}
public function register($cmd, $help, $callback){
if(!is_callable($callback)){
return false;

View file

@ -8,26 +8,25 @@ class EntityAPI{
function __construct(){
$this->entities = [];
$this->server = ServerAPI::request();
$this->serverSpawnAnimals = $this->server->api->getProperty("spawn-animals");
$this->serverSpawnMobs = $this->server->api->getProperty("spawn-mobs");
}
public function init(){
$this->server->api->console->register("summon", "<mob>", [$this, "commandHandler"]);
$this->server->api->console->register("spawnmob", "<mob>", [$this, "commandHandler"]);
$this->server->api->console->register("despawn", "", [$this, "CommandHandler"]);
$this->server->api->console->register("entcnt", "", [$this, "CommandHandler"]);
}
public function commandHandler($cmd, $args, $issuer, $alias){
$mob = [
"chicken" => 10,
"cow" => 11,
"pig" => 12,
"sheep" => 13,
"zombie" => 32,
"creeper" => 33,
"skeleton" => 34,
@ -46,24 +45,24 @@ class EntityAPI{
if((count($args) < 1) or (count($args) > 3)){
return "Usage: /$cmd <mob> [amount] [baby]";
}
if(is_int($args[0])) $type = $args[0];
else $type = $mob[strtolower($args[0])] ?? 0;
if($type < 10 || $type > 36){
return "Unknown mob.";
}
$mobName = ucfirst(array_flip($mob)[$type]);
if(((isset($args[1]) && strtolower($args[1]) === "baby") || (isset($args[2]) && strtolower($args[2]) === "baby")) && !Utils::in_range($type, 10, 13)){
return "$mobName cannot be a baby!";
}
$x = round($issuer->entity->x, 2, PHP_ROUND_HALF_UP);
$y = round($issuer->entity->y, 2, PHP_ROUND_HALF_UP);
$z = round($issuer->entity->z, 2, PHP_ROUND_HALF_UP);
$level = $issuer->entity->level;
$pos = new Position($x, $y, $z, $level);
if(count($args) === 1){//summon <mob>
$this->summon($pos, ENTITY_MOB, $type);
return "$mobName spawned in $x, $y, $z.";
@ -77,11 +76,11 @@ class EntityAPI{
if(isset($args[2]) and strtolower($args[2]) === 'baby'){//summon <mob> [amount] [baby]
$isBaby = true;
}
for($cnt = $amount; $cnt > 0; --$cnt){
$this->summon($pos, ENTITY_MOB, $type, ["IsBaby" => $isBaby]);
}
return "$amount ".($isBaby ? "Baby " : "")."$mobName(s) spawned in $x, $y, $z.";
}
elseif(strtolower($args[1]) == "baby"){//summon <mob> [baby]
@ -94,7 +93,7 @@ class EntityAPI{
if(!isset($args[0])){
return "/despawn <all|mobs|objects|items|fallings|minecarts>";
}
$despawnclass = 0;
$despawntype = 0;
switch($args[0]){
@ -138,12 +137,12 @@ class EntityAPI{
}
}
}
return "$cnt entities have been despawned!";
}
return $output;
}
public function summon(Position $pos, $class, $type, array $data = []){
$entity = $this->add($pos->level, $class, $type, [
"x" => $pos->x,
@ -152,16 +151,16 @@ class EntityAPI{
] + $data);
$this->spawnToAll($entity);
}
public function getNextEID(){
return $this->eCnt++;
}
public function addRaw(Entity $e){
$eid = $e->eid;
$this->entities[$eid] = $e;
$cX = (int)$this->entities[$eid]->x >> 4;
$cZ = (int)$this->entities[$eid]->z >> 4;
$cX = (int) $this->entities[$eid]->x >> 4;
$cZ = (int) $this->entities[$eid]->z >> 4;
$e->level->entityListPositioned["$cX $cZ"][$eid] = $eid;
$e->level->entityList[$eid] = &$this->entities[$eid];
$this->server->handle("entity.add", $this->entities[$eid]);
@ -178,7 +177,7 @@ class EntityAPI{
}
return $this->addRaw($e);
}
public function spawnToAll(Entity $e){
foreach($this->server->api->player->getAll($e->level) as $player){
if($player->eid !== false and $player->eid !== $e->eid and $e->class !== ENTITY_PLAYER and $e instanceof Entity){
@ -186,18 +185,18 @@ class EntityAPI{
}
}
}
public function get($eid){
return $this->entities[$eid] ?? false;
}
public function remove($eid){
if(isset($this->entities[$eid])){
$level = $this->entities[$eid]->level;
$this->entities[$eid]->closed = true;
if($level instanceof Level){
$cX = (int)$this->entities[$eid]->x >> 4;
$cZ = (int)$this->entities[$eid]->z >> 4;
$cX = (int) $this->entities[$eid]->x >> 4;
$cZ = (int) $this->entities[$eid]->z >> 4;
$index = "$cX $cZ";
unset($level->entityListPositioned[$index][$eid]);
if(isset($level->mobSpawner->entityAffectedPlayers[$eid])){
@ -221,12 +220,12 @@ class EntityAPI{
unset($this->entities[$eid]);
}
}
public function getRadius(Position $center, $radius = 15, $class = false){
$minChunkX = ((int)($center->x - $radius)) >> 4;
$minChunkZ = ((int)($center->z - $radius)) >> 4;
$maxChunkX = ((int)($center->x + $radius)) >> 4;
$maxChunkZ = ((int)($center->z + $radius)) >> 4;
$minChunkX = ((int) ($center->x - $radius)) >> 4;
$minChunkZ = ((int) ($center->z - $radius)) >> 4;
$maxChunkX = ((int) ($center->x + $radius)) >> 4;
$maxChunkZ = ((int) ($center->z + $radius)) >> 4;
$ents = [];
//TODO also index by chunkY?
for($chunkX = $minChunkX; $chunkX <= $maxChunkX; ++$chunkX){
@ -244,11 +243,11 @@ class EntityAPI{
}
return $ents;
}
public function heal($eid, $heal, $cause){
$this->harm($eid, -$heal, $cause);
}
public function harm($eid, $attack, $cause, $force = false){
$e = $this->get($eid);
if($e === false or $e->dead === true){
@ -256,7 +255,7 @@ class EntityAPI{
}
$e->setHealth($e->getHealth() - $attack, $cause, $force);
}
public function dropRawPos(Level $level, $x, $y, $z, $item, $speedX, $speedY, $speedZ){
if($item->getID() === AIR or $item->count <= 0){
return;
@ -272,7 +271,7 @@ class EntityAPI{
"item" => $item,
"itemID" => $item->getID()
];
if($this->server->api->handle("item.drop", $data) !== false){
for($count = $item->count; $count > 0;){
$item->count = min($item->getMaxStackSize(), $count);
@ -283,7 +282,7 @@ class EntityAPI{
}
}
}
public function drop(Position $pos, Item $item, $pickupDelay = 10){
if($item->getID() === AIR or $item->count <= 0){
return;
@ -310,7 +309,7 @@ class EntityAPI{
}
}
}
public function spawnAll(Player $player){
foreach($player->level->entityList as $e){
if($e->class !== ENTITY_PLAYER){
@ -318,18 +317,18 @@ class EntityAPI{
}
}
}
public function getAll($level = null){
if($level instanceof Level){
return $level->entityList;
}
return $this->entities;
}
/**
* @deprecated this function doesnt do anything
*/
public function updateRadius(Position $center, $radius = 15, $class = false){
}
}

View file

@ -40,7 +40,7 @@ class LevelAPI{
console("[ERROR] Could not load level \"" . $name . "\"");
return false;
}
if(PocketMinecraftServer::$KEEP_CHUNKS_LOADED){
for($X = 0; $X < 16; ++$X){
for($Z = 0; $Z < 16; ++$Z){
@ -48,8 +48,7 @@ class LevelAPI{
}
}
}
$entities = new Config($path . "entities.yml", CONFIG_YAML);
if(file_exists($path . "tileEntities.yml")){
@rename($path . "tileEntities.yml", $path . "tiles.yml");
@ -61,13 +60,13 @@ class LevelAPI{
if(!isset($entity["id"])){
break;
}
$entity["x"] = $entity["Pos"][0];
$entity["y"] = $entity["Pos"][1];
$entity["z"] = $entity["Pos"][2];
$entity["yaw"] = $entity["Rotation"][0];
$entity["pitch"] = $entity["Rotation"][1];
if($entity["id"] === 64){ //Item Drop
$e = $this->server->api->entity->add($this->levels[$name], ENTITY_ITEM, ENTITY_ITEM_TYPE, [
"meta" => $entity["Item"]["Damage"],
@ -105,7 +104,7 @@ class LevelAPI{
foreach($blockUpdates->getAll() as $bupdate){
if($bupdate["type"] !== BLOCK_UPDATE_RANDOM) $this->server->api->block->scheduleBlockUpdate(new Position((int) $bupdate["x"], (int) $bupdate["y"], (int) $bupdate["z"], $this->levels[$name]), (float) $bupdate["delay"], (int) $bupdate["type"]);
}
return true;
}
/**

View file

@ -19,7 +19,7 @@ class PlayerAPI{
$this->registerCmd("ping");
$this->registerCmd("loc");
$this->registerCmd("hotbar", "<slotcount>");
$this->server->api->console->alias("lag", "ping");
$this->server->api->console->alias("gm", "gamemode");
$this->server->api->console->alias("who", "list");
@ -49,9 +49,9 @@ class PlayerAPI{
if($e->shotByEntity && isset($this->server->api->entity->entities[$e->shooterEID]) && $this->server->api->entity->entities[$e->shooterEID] instanceof Entity){
$message = " was shot by {$this->server->api->entity->entities[$e->shooterEID]->name}";
}else{
$message = " was shot";
$message = " was shot";
}
}else{
$message = " was killed by {$e->name}";
}
@ -104,12 +104,12 @@ class PlayerAPI{
case "hotbar":
if(!($issuer instanceof Player)) return "Please run this command in-game.";
if(count($args) < 1) return "Slots in hotbar on server: {$issuer->slotCount}";
$scrw = $args[0];
if(is_numeric($scrw)){
$sc = (int)$scrw;
$sc = (int) $scrw;
if($sc < 5 || $sc > 9) return "Slot count must be between 5 and 9.";
$issuer->setSlotCount($sc);
$issuer->sendInventory();
return "Changed slot count to $sc";
@ -235,10 +235,10 @@ class PlayerAPI{
$level = $issuer->entity->level->getName();
$compass = [0 => "X+", 1 => "Z+", 2 => "X-", 3 => "Z-", null => "null"];
$direction = $compass[$issuer->entity->getDirection()];
$xChunk = $x >> 4;
$zChunk = $z >> 4;
return "Your coordinates: X: $x ($xChunk), Y: $y, Z: $z ($zChunk), world: $level.\nDirection: $direction";
}
return $output;
@ -462,7 +462,7 @@ class PlayerAPI{
unset($player->entity->player);
//unset($player->entity);
}
$player = null;
unset($player);
}

View file

@ -150,20 +150,20 @@ class PluginAPI extends stdClass{
}
}
console("[INFO] Loading PHAR plugin \"".FORMAT_GREEN.$pluginInfo["name"].FORMAT_RESET."\" ".FORMAT_AQUA.$pluginInfo["version"].FORMAT_RESET." by ".FORMAT_AQUA.$pluginInfo["author"].FORMAT_RESET);
$aver = CURRENT_API_VERSION;
if(!in_array((string) CURRENT_API_VERSION, $pluginInfo["api"])){
if(!in_array((string) CURRENT_API_VERSION, $pluginInfo["api"])){
if(is_array($pluginInfo)) $s = implode(",",$pluginInfo["api"]);
else $s = $pluginInfo["api"];
console("[WARNING] API is not the same as Core, might cause bugs({$s} != {$aver})");
}
$phr = "phar://$filePath/";
include($phr."/src/".$pluginInfo["classLoader"]);
$class = $pluginInfo["CLClass"];
$loader = new $class();
$loader->loadAll($phr);
$pluginName = PharUtils::getNameSpaceClass($pluginInfo["mainFile"]);
include($phr."/src/".$pluginInfo["mainFile"]);
$plugin = new $pluginName($this->server->api, false);
@ -268,7 +268,7 @@ class PluginAPI extends stdClass{
$names[] = $p[1]["name"];
$versions[] = $p[1]["version"];
}
foreach($this->plugins as $p){
if($p[0] instanceof OtherPluginRequirement){
foreach($p[0]->getRequiredPlugins() as $required){
@ -312,4 +312,3 @@ class RequiredPluginEntry{ //Use this as object of requirements array
}
}

View file

@ -4,7 +4,7 @@ class ServerAPI{
private static $serverRequest = false;
public $restart = false;
/**
* @var QueryAPI
*/
@ -59,7 +59,7 @@ class ServerAPI{
* @var QueryHandler
*/
public $query;
private $asyncCalls = [];
private $server;
private $config;

View file

@ -17,7 +17,7 @@ class TileAPI{
}
return false;
}
public function invalidateAll(Level $level, $x, $y, $z){
$x = (int) $x;
$y = (int) $y;
@ -31,14 +31,14 @@ class TileAPI{
++$invcnt;
$tl->close();
}
if($invcnt > 1){
ConsoleAPI::warn("{$level->getName()}: ($x $y $z) has more than 1 tile entity! Invalidated ID {$t["ID"]} (Total invaliated: $invcnt)");
}
}
}
}
public function get(Position $pos){
$tile = $this->server->query("SELECT * FROM tiles WHERE level = '" . $pos->level->getName() . "' AND x = {$pos->x} AND y = {$pos->y} AND z = {$pos->z};", true);
if($tile !== false and $tile !== true and ($tile = $this->getByID($tile["ID"])) !== false){

View file

@ -175,5 +175,4 @@ class TimeAPI{
return $this->set("sunset");
}
}

View file

@ -1,6 +1,5 @@
<?php
class Deprecation{
public static $events = [

View file

@ -1,8 +1,7 @@
<?php
class Player{
public static $smallChunks = false, $experimentalHotbar = false;
/** @var Config */
public $data;
@ -69,15 +68,15 @@ class Player{
private $packetStats;
private $chunkCount = [];
private $received = [];
public $slotCount = 7;
public $entityMovementQueue;
public $entityMovementQueueLength = 0;
public $blockUpdateQueue;
public $blockUpdateQueueLength = 0;
/**
* Sent by a client while it is linked to some entity.
* @var boolean $isJumping
@ -86,7 +85,7 @@ class Player{
public $isJumping, $isSneaking;
private $lastPing = -1;
/**
* @param integer $clientID
* @param string $ip
@ -111,18 +110,18 @@ class Player{
$this->slot = 0;
$this->hotbar = [0, 1, 2, 3, 4, 5, 6, 7, 8];
$this->packetStats = [0, 0];
$this->buffer = new RakNetPacket(RakNetInfo::DATA_PACKET_0);
$this->buffer->data = [];
$this->entityMovementQueue = new RakNetPacket(RakNetInfo::DATA_PACKET_0);
$this->entityMovementQueue->data = [];
$this->blockUpdateQueue = new RakNetPacket(RakNetInfo::DATA_PACKET_0);
$this->blockUpdateQueue->data = [];
//$this->server->schedule(20 * 60, [$this, "clearQueue"], [], true);
$this->evid[] = $this->server->event("server.close", [$this, "close"]);
console("[DEBUG] New Session started with " . $ip . ":" . $port . ". MTU " . $this->MTU . ", Client ID " . $this->clientID, true, true, 2);
}
@ -139,7 +138,6 @@ class Player{
}
/**
* @param Vector3 $pos
*
* @return boolean
*/
@ -158,7 +156,7 @@ class Player{
if($this->entity instanceof Entity){
$this->entity->updateMetadata();
}
$spawnPoint = BedBlock::findStandUpPosition($this->level, $pos->x, $pos->y, $pos->z);
if($spawnPoint == null) $spawnPoint = $pos->add(0.5, 1, 0.5);
else{
@ -168,14 +166,13 @@ class Player{
$this->setSpawn($spawnPoint);
return true;
}
public function setSlotCount($cnt){
$this->slotCount = $cnt;
$this->data->set("slot-count", $this->slotCount);
}
/**
* @param Vector3 $pos
* @param float|boolean $yaw
* @param float|boolean $pitch
* @param float|boolean $terrain
@ -215,7 +212,7 @@ class Player{
$pk->pitch = 0;
$pk->bodyYaw = 0;
$e->player->dataPacket($pk);
$pk = new MovePlayerPacket();
$pk->eid = $e->eid;
$pk->x = -256;
@ -225,7 +222,7 @@ class Player{
$pk->pitch = 0;
$pk->bodyYaw = 0;
$this->dataPacket($pk);
}else{
$pk = new MoveEntityPacket_PosRot();
$pk->eid = $e->eid;
@ -264,7 +261,7 @@ class Player{
}
}
}
$pk = new SetTimePacket;
$pk->time = $this->level->getTime();
$this->dataPacket($pk);
@ -297,12 +294,12 @@ class Player{
$player->sendArmor($this);
}
}
$resyncpos = new Position($pos->x, $pos->y, $pos->z, $pos->level);
}else{
$resyncpos = new Vector3($pos->x, $pos->y, $pos->z);
}
$this->lastCorrect = $resyncpos;
$this->entity->fallY = false;
$this->entity->fallStart = false;
@ -320,14 +317,14 @@ class Player{
$this->forceMovement = $resyncpos;
}
}
$pk = new SetEntityMotionPacket();
$pk->eid = 0;
$pk->speedX = 0;
$pk->speedY = 0;
$pk->speedZ = 0;
$this->dataPacket($pk);
$pk = new MovePlayerPacket;
$pk->eid = 0;
$pk->x = $pos->x;
@ -340,8 +337,6 @@ class Player{
}
/**
* @param integer $id
* @param array $data
*
* @return array|bool
*/
@ -353,14 +348,14 @@ class Player{
if(EventHandler::callEvent(new DataPacketSendEvent($this, $packet)) === BaseEvent::DENY){
return;
}
$packet->encode();
$len = strlen($packet->buffer) + 1;
$MTU = $this->MTU - 24;
if($len > $MTU){
return $this->directBigRawPacket($packet);
}
if(($this->bufferLen + $len) >= $MTU){
$this->sendBuffer();
}
@ -436,12 +431,11 @@ class Player{
* @return Item
*/
public function getSlot($slot){
return $this->inventory[(int)$slot] ?? BlockAPI::getItem(AIR, 0, 0);
return $this->inventory[(int) $slot] ?? BlockAPI::getItem(AIR, 0, 0);
}
/**
* @param integer $slot
* @param Item $item
* @param boolean $send
*
* @return boolean
@ -489,18 +483,18 @@ class Player{
}
public $lastOrderX = 0;
public $lastOrderZ = 0;
public function orderChunks(){
if(!($this->entity instanceof Entity) or $this->connected === false){
return false;
}
$X = ((int)$this->entity->x) >> 4;
$Z = ((int)$this->entity->z) >> 4;
$X = ((int) $this->entity->x) >> 4;
$Z = ((int) $this->entity->z) >> 4;
$this->chunksOrder = [];
$this->lastOrderX = $X;
$this->lastOrderZ = $Z;
if(self::$smallChunks){
$Y = ((int)$this->entity->y) >> 4;
$Y = ((int) $this->entity->y) >> 4;
$v = new Vector3($X, $Y, $Z);
for($x = 0; $x < 16; ++$x){
for($z = 0; $z < 16; ++$z){
@ -527,10 +521,10 @@ class Player{
}
}
}
asort($this->chunksOrder);
}
public function loaddAllChunks(){
for($x = 0; $x < 16; $x++){
for($z = 0; $z < 16; $z++){
@ -538,7 +532,7 @@ class Player{
}
}
}
public function useChunk($X, $Z){
$Yndex = 0;
for($iY = 0; $iY < 8; ++$iY){
@ -552,7 +546,7 @@ class Player{
$maxX = (($X << 4) + 15);
$minZ = ($Z << 4);
$maxZ = (($Z << 4) + 15);
$pk = new ChunkDataPacket;
$pk->chunkX = $X;
$pk->chunkZ = $Z;
@ -569,12 +563,12 @@ class Player{
}
}
}
if($cnt === false){
return false;
}
}
public function getNextChunk($world){
if($this->connected === false or $world != $this->level){
return false;
@ -650,9 +644,6 @@ class Player{
$this->server->schedule(MAX_CHUNK_RATE, [$this, "getNextChunk"], $world);
}
/**
* @param Vector3 $pos
*/
public function setSpawn(Vector3 $pos){
if(!($pos instanceof Position)){
$level = $this->entity->level;
@ -687,9 +678,6 @@ class Player{
$this->dataPacket($pk);
}
/**
* @param $type
* @param $damage
* @param $count
*
* @return boolean
*/
@ -704,7 +692,7 @@ class Player{
break;
}elseif($item->getID() === $type and $item->getMetadata() === $damage){
$add = min($item->getMaxStackSize() - $item->count, $count);
if($add <= 0){
continue;
}
@ -726,7 +714,7 @@ class Player{
* @return Item
*/
public function getArmor($slot){
return $this->armor[(int)$slot] ?? BlockAPI::getItem(AIR, 0, 0);
return $this->armor[(int) $slot] ?? BlockAPI::getItem(AIR, 0, 0);
}
public function setArmor($slot, Item $armor, $send = true){
@ -902,25 +890,23 @@ class Player{
}
/**
* @param $type
* @param $damage
* @param integer $count
* @param boolean $send
*
* @return boolean
*/
public function addItem($type, $damage, $count, $send = true){
foreach($this->inventory as $s => $item){ //force check the inventory for non-full stacks of this item first
if($item->getID() === $type and $item->getMetadata() === $damage){
$add = min($item->getMaxStackSize() - $item->count, $count);
if($add <= 0){
continue;
}
$item->count += $add;
if($send) $this->sendInventorySlot($s);
$count -= $add;
if($count <= 0) return true;
}
@ -994,7 +980,7 @@ class Player{
return "view";
}
}
public function checkSpawnPosition(){
if($this->server->api->dhandle("player.checkspawnpos", ["player" => $this]) === false) return;
$level = $this->spawnPosition->level;
@ -1003,20 +989,20 @@ class Player{
$level = $this->server->api->level->getDefault();
$this->spawnPosition = $level->getSpawn();
}else{
$x0 = floor($this->spawnPosition->x - $this->entity->width/2);
$x1 = floor($this->spawnPosition->x + $this->entity->width/2 + 1);
$x0 = floor($this->spawnPosition->x - $this->entity->width / 2);
$x1 = floor($this->spawnPosition->x + $this->entity->width / 2 + 1);
$y0 = floor($this->spawnPosition->y);
$y1 = floor($this->spawnPosition->y + $this->entity->height + 1);
$z0 = floor($this->spawnPosition->z - $this->entity->width/2);
$z1 = floor($this->spawnPosition->z + $this->entity->width/2 + 1);
$z0 = floor($this->spawnPosition->z - $this->entity->width / 2);
$z1 = floor($this->spawnPosition->z + $this->entity->width / 2 + 1);
for($x = $x0; $x < $x1; ++$x) {
for($z = $z0; $z < $z1; ++$z) {
for($y = $y0; $y < $y1; ++$y) {
$bid = $this->entity->level->level->getBlockID($x, $y, $z);
if($bid > 0 && StaticBlock::getIsSolid($bid)){
$blockBounds = StaticBlock::$prealloc[$bid]::getCollisionBoundingBoxes($this->entity->level, $x, $y, $z, $this->entity);
foreach($blockBounds as $blockBound){
if($this->entity->boundingBox->intersectsWith($blockBound)){
$this->sendChat("Your spawn positon is obstructed.");
@ -1032,7 +1018,7 @@ class Player{
$this->spawnPosition = $this->server->api->level->getDefault()->getSpawn();
}
}
public function setGamemode($gm){
if($gm < 0 or $gm > 3 or $this->gamemode === $gm){
return false;
@ -1067,19 +1053,19 @@ class Player{
}
$this->hotbar = [0, 1, 2, 3, 4, 5, 6, 7, 8];
$this->lastCorrect = $this->entity->copy();
$this->blocked = true;
$this->blocked = true;
$this->gamemode = $gm;
$this->sendChat("Your gamemode has been changed to " . $this->getGamemode() . ", you've to do a forced reconnect.\n");
$this->server->schedule(30, [$this, "close"], "gamemode change", false, true); //Forces a kick
}
if($this->gamemode === SPECTATOR){
$this->makeInvisibleForAllPlayers();
}
if($this->gamemode === CREATIVE){
$this->server->api->player->spawnToAllPlayers($this);
}
$this->inventory = $inv;
$this->sendSettings();
$this->sendInventory();
@ -1106,10 +1092,10 @@ class Player{
if($nametags !== false){
$flags |= 0x20; //Show Nametags
}
//$flags |= 0x2; //pvp
//$flags |= 0x4; //pve
$pk = new AdventureSettingsPacket;
$pk->flags = $flags;
$this->dataPacket($pk);
@ -1261,7 +1247,7 @@ class Player{
$this->entityMovementQueue = new RakNetPacket(RakNetInfo::DATA_PACKET_0);
$this->entityMovementQueue->data = [];
}
public function sendBlockUpdateQueue(){
if($this->blockUpdateQueueLength > 0 && $this->blockUpdateQueue instanceof RakNetPacket){
$this->blockUpdateQueue->seqNumber = $this->counter[0]++;
@ -1273,7 +1259,7 @@ class Player{
$this->blockUpdateQueue = new RakNetPacket(RakNetInfo::DATA_PACKET_0);
$this->blockUpdateQueue->data = [];
}
public function addBlockUpdateIntoQueue($x, $y, $z, $id, $meta){
$packet = new UpdateBlockPacket();
$packet->x = $x;
@ -1282,20 +1268,20 @@ class Player{
$packet->block = $id;
$packet->meta = $meta;
$packet->encode();
$len = 1 + strlen($packet->buffer);
$MTU = $this->MTU - 24;
if(($this->blockUpdateQueueLength + $len) >= $MTU){
$this->sendBlockUpdateQueue();
}
$packet->messageIndex = $this->counter[3]++;
$packet->reliability = 2;
@$this->blockUpdateQueue->data[] = $packet;
$this->blockUpdateQueueLength += 6 + $len;
}
public function addEntityMovementUpdateToQueue(Entity $e){
$len = 0;
$packets = 0;
@ -1323,7 +1309,7 @@ class Player{
$e->speedY = $svdYSpeed;
$e->modifySpeedY = false;
}
if($e->x != $e->lastX || $e->y != $e->lastY || $e->z != $e->lastZ || $e->yaw != $e->lastYaw || $e->pitch != $e->lastPitch){
if($e->headYaw != $e->lastHeadYaw){
$move = new MovePlayerPacket();
@ -1345,11 +1331,11 @@ class Player{
$move->pitch = $e->pitch;
$move->encode();
}
$len += strlen($move->buffer) + 1;
++$packets;
$moveSent = true;
}else if($e->headYaw != $e->lastHeadYaw){
}elseif($e->headYaw != $e->lastHeadYaw){
$headyaw = new RotateHeadPacket();
$headyaw->eid = $e->eid;
$headyaw->yaw = $e->headYaw;
@ -1379,10 +1365,10 @@ class Player{
$headyaw->reliability = 0;
$this->entityMovementQueue->data[] = $headyaw;
}
$this->entityMovementQueueLength += 6*$packets + $len;
$this->entityMovementQueueLength += 6 * $packets + $len;
}
/**
* @param string $reason Reason for closing connection
* @param boolean $msg Set to false to silently disconnect player. No broadcast.
@ -1492,13 +1478,13 @@ class Player{
}
public function entityTick(){
if($this->isSleeping) ++$this->sleepingTime;
if($this->server->difficulty == 0 && $this->entity->counter % (20 * 15) == 0){
if($this->entity->health < 20 && $this->entity->health > 0){
$this->entity->setHealth(min(20, $this->entity->health + 1), "regeneration");
}
}
}
public function sendPing() {
@ -1652,7 +1638,6 @@ class Player{
$this->server->api->player->saveOffline($this->data);
$pk = new LoginStatusPacket;
$pk->status = 0;
$this->dataPacket($pk);
@ -1686,7 +1671,7 @@ class Player{
}else{
$this->data->set("slot-count", $this->slotCount);
}
$this->entity = $this->server->api->entity->add($this->level, ENTITY_PLAYER, 0, ["player" => $this]);
$this->eid = $this->entity->eid;
$this->server->query("UPDATE players SET EID = " . $this->eid . " WHERE CID = " . $this->CID . ";");
@ -1718,13 +1703,12 @@ class Player{
$this->evid[] = $this->server->event("tile.update", [$this, "eventHandler"]);
$this->lastMeasure = microtime(true);
$this->server->schedule(50, [$this, "measureLag"], [], true);
$pk = new SetTimePacket;
$pk->time = $this->level->getTime();
$pk->started = !$this->level->isTimeStopped();
$this->dataPacket($pk);
console("[INFO] " . FORMAT_AQUA . $this->username . FORMAT_RESET . "[/" . $this->ip . ":" . $this->port . "] logged in with entity id " . $this->eid . " at (" . $this->entity->level->getName() . ", " . round($this->entity->x, 2) . ", " . round($this->entity->y, 2) . ", " . round($this->entity->z, 2) . ")");
break;
case ProtocolInfo::READY_PACKET:
@ -1736,7 +1720,7 @@ class Player{
if($this->spawned !== false){
break;
}
$pos = new Position($this->entity->x, $this->entity->y, $this->entity->z, $this->level);
$pData = $this->data->get("position");
$this->entity->setHealth($this->data->get("health"), "spawn", true, false);
@ -1750,7 +1734,7 @@ class Player{
//$this->server->schedule(5, [$this->entity, "update"], [], true);
//$this->server->schedule(2, [$this->entity, "updateMovement"], [], true);
$this->sendArmor();
$array = explode("@n", (string)$this->server->motd);
$array = explode("@n", (string) $this->server->motd);
foreach($array as $msg){
$this->sendChat($msg."\n");
}
@ -1825,11 +1809,10 @@ class Player{
$this->slot = -1;
}
break;
}else if($packet->slot > 0){
}elseif($packet->slot > 0){
$packet->slot -= 9;
}
if(($this->gamemode & 0x01) === SURVIVAL){
$data["item"] = $this->getSlot($packet->slot);
if(!($data["item"] instanceof Item)){
@ -1867,7 +1850,7 @@ class Player{
break;
}
}
if(Player::$experimentalHotbar && $has) {
$this->slot = $packet->slot;
$this->curHotbarIndex = $packetSlotPos;
@ -1907,7 +1890,7 @@ class Player{
}
$blockVector = new Vector3($packet->x, $packet->y, $packet->z);
if(($this->spawned === false or $this->blocked === true) and $packet->face >= 0 and $packet->face <= 5){
$target = $this->level->getBlock($blockVector);
$block = $target->getSide($packet->face);
@ -1983,20 +1966,20 @@ class Player{
$this->dataPacket($pk);
break;
}elseif($packet->face === 0xff){
$slotItem = $this->getHeldItem();
if($slotItem->getID() == SNOWBALL || $slotItem->getID() == EGG){ //TODO better way
$x = $packet->x * 0.000030518;
$y = $packet->y * 0.000030518;
$z = $packet->z * 0.000030518;
$d = sqrt($x*$x + $y*$y + $z*$z);
$d = sqrt($x * $x + $y * $y + $z * $z);
if($d >= 0.0001){
$shootX = $x / $d;
$shootY = $y / $d;
$shootZ = $z / $d;
$data = [
"x" => $this->entity->x,
"y" => $this->entity->y + $this->entity->getEyeHeight(),
@ -2008,13 +1991,13 @@ class Player{
"shootY" => $shootY,
"shootZ" => $shootZ
];
if($slotItem->getID() == EGG){
$e = $this->server->api->entity->add($this->entity->level, ENTITY_OBJECT, OBJECT_EGG, $data);
}else{
$e = $this->server->api->entity->add($this->level, ENTITY_OBJECT, OBJECT_SNOWBALL, $data);
}
if(($this->gamemode & 0x01) == 0x0) {
if($slotItem !== false){
if($slotItem->count == 1) $this->inventory[$this->slot] = BlockAPI::getItem(AIR, 0, 0);
@ -2022,10 +2005,10 @@ class Player{
//$this->sendInventory();
}
}
$this->server->api->entity->spawnToAll($e);
}
}else{
if($this->server->handle("player.action", $data) !== false){
$this->entity->inAction = true;
@ -2059,7 +2042,7 @@ class Player{
"player" => $this,
"power" => &$power,
]);
$d = [
"x" => $this->entity->x,
"y" => $this->entity->y + 1.6,
@ -2083,7 +2066,7 @@ class Player{
* args: xvel, yvel, zvel, (power+power)*1.5, 1.0
*/
$e->critical = ($power == 1);
$e->shoot($e->speedX, $e->speedY, $e->speedZ, ($power+$power) * 1.5, 1.0);
$e->shoot($e->speedX, $e->speedY, $e->speedZ, ($power + $power) * 1.5, 1.0);
$this->server->api->entity->spawnToAll($e);
if(($this->gamemode & 0x01) == 0x0) {
$bow = $this->getSlot($this->slot);
@ -2203,10 +2186,10 @@ class Player{
}
$this->craftingItems = [];
$this->toCraft = [];
$this->checkSpawnPosition();
$this->teleport($this->spawnPosition, false, false, true, false);
$pk = new MovePlayerPacket();
$pk->eid = $this->entity->eid;
$pk->x = $this->entity->x;
@ -2220,7 +2203,7 @@ class Player{
$player->dataPacket(clone $pk);
}
}
if($this->entity instanceof Entity){
$this->entity->fire = 0;
$this->entity->air = $this->entity->maxAir;
@ -2273,23 +2256,23 @@ class Player{
if($this->spawned === false or $this->blocked === true){
break;
}
if($this->gamemode & 0x01 == 1){
ConsoleAPI::warn("{$this->iusername} tried dropping item while in creative!");
return;
}
$packet->eid = $this->eid;
$prevItem = $packet->item;
$packet->item = $this->getSlot($this->slot);
$sendOnDrop = false;
if($prevItem->getID() != $packet->item->getID() || $prevItem->getMetadata() != $packet->item->getMetadata()){
if(count($this->inventory) >= 36){
foreach($this->inventory as $slot => $item){
if($item->getID() == 0) goto inv_desync_on_drop;
}
$this->toCraft[] = $prevItem; //vanilla drops only result?
$this->lastCraft = microtime(true);
break;
@ -2299,7 +2282,7 @@ class Player{
$sendOnDrop = true;
}
}
$this->craftingItems = [];
$this->toCraft = [];
$data["eid"] = $packet->eid;
@ -2349,11 +2332,11 @@ class Player{
$this->sendChat("Your message contains illegal characters");
break;
}
//if($message == "pf"){
// Living::$pathfind = !Living::$pathfind;
//}
if($this->server->api->handle("player.chat", $data) !== false){
$this->server->send2Discord("<" . $this->username . "> " . $message);
if(isset($data["message"])){
@ -2476,13 +2459,13 @@ class Player{
$slot = $tile->getSlot($slotn);
if($this->server->api->dhandle("player.container.slot", [
"tile" => $tile,
"slot" => $packet->slot,
"offset" => $offset,
"slotdata" => $slot,
"itemdata" => $item,
"player" => $this
]) === false){
"tile" => $tile,
"slot" => $packet->slot,
"offset" => $offset,
"slotdata" => $slot,
"itemdata" => $item,
"player" => $this
]) === false){
$pk = new ContainerSetSlotPacket;
$pk->windowid = $packet->windowid;
$pk->slot = $packet->slot;
@ -2490,7 +2473,7 @@ class Player{
$this->dataPacket($pk);
break;
}
if($item->getID() !== AIR and $slot->getID() == $item->getID()){
if($slot->count < $item->count){
if($this->removeItem($item->getID(), $item->getMetadata(), $item->count - $slot->count, false) === false){
@ -2515,12 +2498,12 @@ class Player{
$slot = $tile->getSlot($packet->slot);
if($this->server->api->dhandle("player.container.slot", [
"tile" => $tile,
"slot" => $packet->slot,
"slotdata" => $slot,
"itemdata" => $item,
"player" => $this,
]) === false){
"tile" => $tile,
"slot" => $packet->slot,
"slotdata" => $slot,
"itemdata" => $item,
"player" => $this,
]) === false){
$pk = new ContainerSetSlotPacket;
$pk->windowid = $packet->windowid;
$pk->slot = $packet->slot;
@ -2587,7 +2570,7 @@ class Player{
$this->isSneaking = $packet->isSneaking;
$this->entity->moveForward = $packet->moveForward;
$this->entity->moveStrafing = $packet->moveStrafe;
if(strlen(bin2hex($packet->buffer)) === 24 && $this->entity->linkedEntity != 0){
$this->entity->stopRiding();
break;
@ -2612,23 +2595,23 @@ class Player{
console("{$e} {$this->entity}");
//$this->entity->linkedEntity->moveFlying($packet->moveStrafe, $packet->moveForward, 1);*/
}
break;
default:
console("[DEBUG] Unhandled 0x" . dechex($packet->pid()) . " data packet for " . $this->username . " (" . $this->clientID . "): " . print_r($packet, true), true, true, 2);
break;
}
}
/**
* Get an Item which is currently held by player
* @return Item
*/
public function getHeldItem(){
return $this->getSlot($this->slot);
}
public function stopSleep(){
$this->isSleeping = false;
$this->sleepingTime = 0;
@ -2672,16 +2655,13 @@ class Player{
}
/**
* @param array $craft
* @param array $recipe
* @param $type
*
* @return array|bool
*/
public function craftItems(array $craft, array $recipe, $type){
$craftItem = [0, true, 0];
unset($craft[-1]);
foreach($craft as $slot => $item){
if($item instanceof Item){
$craftItem[0] = $item->getID();
@ -2731,7 +2711,7 @@ class Player{
$s = $this->getSlot($slot);
if($s->count <= 0 or $s->getID() === AIR){
$this->setSlot($slot, BlockAPI::getItem($item->getID(), $item->getMetadata(), $item->count), false);
}else if($s->getID() == $item->getID() && $s->getMetadata() == $item->getMetadata() && ($s->count + $item->count) <= $s->getMaxStackSize()){
}elseif($s->getID() == $item->getID() && $s->getMetadata() == $item->getMetadata() && ($s->count + $item->count) <= $s->getMaxStackSize()){
$this->setSlot($slot, BlockAPI::getItem($item->getID(), $item->getMetadata(), $s->count + $item->count), false);
}else{
$f1 = 0.3;
@ -2746,9 +2726,9 @@ class Player{
$sZ += sin($f3) * $f1;
$this->server->api->entity->dropRawPos($this->level, $this->entity->x, $this->entity->y - 0.3 + $this->entity->height - 0.12, $this->entity->z, $item, $sX, $sY, $sZ);
}
$this->sendInventory(); //force send on crafting
switch($item->getID()){
case WORKBENCH:
AchievementAPI::grantAchievement($this, "buildWorkBench");
@ -2796,7 +2776,7 @@ class Player{
case RakNetInfo::NACK:
foreach($packet->packets as $count){
if(isset($this->recoveryQueue[$count])){
$this->resendQueue[$count] =& $this->recoveryQueue[$count];
$this->resendQueue[$count] = &$this->recoveryQueue[$count];
$this->lag[] = $time - $this->recoveryQueue[$count]->sendtime;
unset($this->recoveryQueue[$count]);
}else{

View file

@ -9,7 +9,7 @@ class PocketMinecraftServer{
*/
public $api;
private $serverip, $evCnt, $handCnt, $events, $eventsID, $handlers, $serverType, $lastTick, $memoryStats, $async = [], $asyncID = 0;
public $doTick, $levelData, $tiles, $entities, $schedule, $scheduleCnt, $whitelist, $spawn, $difficulty, $stop, $asyncThread;
public static $FORCE_20_TPS = false, $KEEP_CHUNKS_LOADED = true, $PACKET_READING_LIMIT = 100;
function __construct($name, $gamemode = SURVIVAL, $seed = false, $port = 19132, $serverip = "0.0.0.0"){
@ -23,10 +23,9 @@ class PocketMinecraftServer{
$this->serverip = $serverip;
$this->load();
}
public static $SAVE_PLAYER_DATA = true;
private function load(){
global $dolog;
/*if(defined("DEBUG") and DEBUG >= 0){
@ -85,10 +84,10 @@ class PocketMinecraftServer{
"discord-ru-smiles" => false,
"discord-webhook-url" => "none",
"discord-bot-name" => "NostalgiaCore Logger",
"despawn-mobs" => true,
"despawn-mobs" => true,
"mob-despawn-ticks" => 18000,
"16x16x16_chunk_sending" => false,
"experimental-mob-ai" => false,
"experimental-mob-ai" => false,
"force-20-tps" => false,
"enable-mob-pushing" => Living::$entityPushing,
"keep-chunks-loaded" => self::$KEEP_CHUNKS_LOADED,
@ -229,7 +228,7 @@ class PocketMinecraftServer{
}
release_lock();
}
public function send2Discord($msg){
if($this->extraprops->get("discord-msg") and $this->extraprops->get("discord-webhook-url") !== "none"){
$url = $this->extraprops->get("discord-webhook-url");
@ -243,7 +242,7 @@ class PocketMinecraftServer{
], null);
}
}
public function asyncOperation($type, array $data, callable $callable = null){
if(defined("NO_THREADS")){
return false;
@ -347,7 +346,6 @@ class PocketMinecraftServer{
/**
* @param string $event
* @param callable $callable
* @param integer $priority
*
* @return boolean
@ -432,7 +430,7 @@ class PocketMinecraftServer{
pcntl_signal(SIGINT, [$this, "close"]);
pcntl_signal(SIGHUP, [$this, "close"]);
}
console("[INFO] Default game type: " . strtoupper($this->getGamemode()));
$this->trigger("server.start", microtime(true));
console('[INFO] Done (' . round(microtime(true) - START_TIME, 3) . 's)! For help, type "help" or "?"');
@ -452,7 +450,7 @@ class PocketMinecraftServer{
if(!is_callable($callback)){
return false;
}
$chcnt = $this->scheduleCnt++;
$this->schedule[$chcnt] = [$callback, $data, $eventName];
$this->query("INSERT INTO actions (ID, interval, last, repeat) VALUES(" . $chcnt . ", " . ($ticks / 20) . ", " . microtime(true) . ", " . (((bool) $repeat) === true ? 1 : 0) . ");");
@ -490,7 +488,7 @@ class PocketMinecraftServer{
}
}
}
$this->tick();
}
}else{
@ -523,12 +521,11 @@ class PocketMinecraftServer{
$this->tick();
}
}
}
public function packetHandler(Packet $packet){
$data =& $packet;
$data = &$packet;
$CID = PocketMinecraftServer::clientID($packet->ip, $packet->port);
if(isset($this->clients[$CID])){
$this->clients[$CID]->handlePacket($packet);
@ -616,14 +613,14 @@ class PocketMinecraftServer{
$this->tickMeasure[] = $this->lastTick = $time;
unset($this->tickMeasure[key($this->tickMeasure)]);
++$this->ticks;
foreach($this->clients as $client){
$client->handlePacketQueues();
if($this->ticks % 40 == 0){ //2s
$client->sendPing();
}
}
foreach($this->api->level->levels as $l){
$l->onTick($this, $time);
}

View file

@ -1,14 +1,15 @@
<?php
class TileNavigator
{
const OFFSETS = [
[0, 0, 1],
[0, 0, -1],
[1, 0, 0],
[-1, 0, 0],
];
public static $pathfinderAccessed = 0;
public $entity;
public $avoidFallDamage = true;
@ -17,13 +18,13 @@ class TileNavigator
$this->entity = $entity;
$this->tall = $entity->height > 1;
}
public function reconstructPath($path, $current){
console("path built");
$totalPath = [$current];
while (isset($path[(string)$current]))
while (isset($path[(string) $current]))
{
$current = $path[(string)$current];
$current = $path[(string) $current];
$totalPath[] = $current;
}
//foreach(array_unique($path) as $k => $p) console($k.":".$p);
@ -33,17 +34,17 @@ class TileNavigator
}
public function isLocBlocked(PMFLevel $level, $loc){
$chunkX = $loc >> 20 & 0xf;
$chunkZ = $loc >> 12 & 0xf;
$chunkY = $loc >> 4 & 0xf;
$index = $chunkZ << 4 | $chunkX;
$blockX = $loc >> 16 & 0xf;
$blockZ = $loc >> 8 & 0xf;
$blockY = $loc & 0xf;
$id = $level->fastGetBlockID($chunkX, $chunkY, $chunkZ, $blockX, $blockY, $blockZ, $index);
$b = StaticBlock::getIsSolid($id);
if($this->tall){
@ -53,33 +54,32 @@ class TileNavigator
$id = $level->fastGetBlockID($chunkX, $chunkY, $chunkZ, $blockX, $blockY, $blockZ, $index);
return $b || StaticBlock::getIsSolid($id);
}
return $b;
}
public function navigate(Level $level, $fromX, $fromY, $fromZ, $toX, $toY, $toZ, $maxDist)
{
$from = $fromX << 16 | $fromZ << 8 | $fromY;
$to = $toX << 16 | $toZ << 8 | $toY;
$pmfLevel = $level->level;
$open = new SplPriorityQueue();
//$open->insert(, 0);
$open->insert($from, 0);
$path = [];
$gScore = [];
$gScore[(string) $from] = 0;
$has = [(string)$from, true];
$has = [(string) $from, true];
if($this->isLocBlocked($pmfLevel, $to)){
return null;
}
$visited = [];
$maxDist*=$maxDist; //no square root
$maxDist *= $maxDist; //no square root
$closestToTarget = null;
$closestToTargetDist = INF;
while(!$open->isEmpty())
{
$current = $open->top();
@ -90,7 +90,7 @@ class TileNavigator
if ($current == $to){
return $this->reconstructPath($path, $current);
}
$points = [];
foreach(self::OFFSETS as $offset){
$newX = $offset[0] + $currentX;
@ -98,7 +98,7 @@ class TileNavigator
$newZ = $offset[2] + $currentZ;
if($newX < 0 || $newX > 255 || $newY < 0 || $newY > 255 || $newZ < 0 || $newZ > 255) continue;
$new = $newX << 16 | $newZ << 8 | $newY;
if(!$this->isLocBlocked($pmfLevel, $new)){
if($newY > 0 && !$this->isLocBlocked($pmfLevel, $new - 1)){
if(!$this->avoidFallDamage){
@ -108,60 +108,59 @@ class TileNavigator
if($this->isLocBlocked($pmfLevel, $new - 2)){
$new -= 1;
$newY -= 1;
}else if($this->isLocBlocked($pmfLevel, $new - 3)){
}elseif($this->isLocBlocked($pmfLevel, $new - 3)){
$new -= 2;
$newY -= 2;
}else if($this->isLocBlocked($pmfLevel, $new - 4)){
}elseif($this->isLocBlocked($pmfLevel, $new - 4)){
$new -= 3;
$newY -= 3;
}else{
continue;
continue;
}
}
}
$dist = ($fromX - $newX)*($fromX - $newX) + ($fromY - $newY)*($fromY - $newY) + ($fromZ - $newZ)*($fromZ - $newZ);
$dist = ($fromX - $newX) * ($fromX - $newX) + ($fromY - $newY) * ($fromY - $newY) + ($fromZ - $newZ) * ($fromZ - $newZ);
if($dist < -$maxDist || $dist > $maxDist){
continue;
}
$points[] = $new;
}else if(!$this->isLocBlocked($pmfLevel, $current+1) && !$this->isLocBlocked($pmfLevel, $new+1)){
}elseif(!$this->isLocBlocked($pmfLevel, $current + 1) && !$this->isLocBlocked($pmfLevel, $new + 1)){
$new += 1;
$newY += 1;
$dist = ($fromX - $newX)*($fromX - $newX) + ($fromY - $newY)*($fromY - $newY) + ($fromZ - $newZ)*($fromZ - $newZ);
$dist = ($fromX - $newX) * ($fromX - $newX) + ($fromY - $newY) * ($fromY - $newY) + ($fromZ - $newZ) * ($fromZ - $newZ);
if($dist < -$maxDist || $dist > $maxDist){
continue;
}
$points[] = $new;
}
}
foreach($points as $neighbor)
{
if(isset($visited[$neighbor])){
continue;
}
$visited[$neighbor] = true;
$diffX = ($toX - ($neighbor >> 16 & 0xff));
$diffY = ($toY - ($neighbor & 0xff));
$diffZ = ($toZ - ($neighbor >> 8 & 0xff));
$targetDist = $diffX*$diffX + $diffY*$diffY + $diffZ*$diffZ;
$targetDist = $diffX * $diffX + $diffY * $diffY + $diffZ * $diffZ;
$diffX = ($currentX - ($neighbor >> 16 & 0xff));
$diffY = ($currentY - ($neighbor & 0xff));
$diffZ = ($currentZ - ($neighbor >> 8 & 0xff));
$distbetweenCost = $diffX*$diffX + $diffY*$diffY + $diffZ*$diffZ;
$distbetweenCost = $diffX * $diffX + $diffY * $diffY + $diffZ * $diffZ;
$tentativeG = $gScore[$current] + $distbetweenCost;
if (!isset($has[$neighbor]))
{
{
//if(isset($open[-$tentativeG])) console("overwriting $tentativeG");
//$open[-$tentativeG] = $neighbor;
$open->insert($neighbor, -$tentativeG);
$has[$neighbor] = true;
}
@ -171,26 +170,25 @@ class TileNavigator
}
if(!isset($gScore[$neighbor]) || $distbetweenCost < $gScore[$neighbor]){
$path[$neighbor] = $current;
if($targetDist < $closestToTargetDist){
//console("found new best to target: $neighbor($closestToTargetDist -> $targetDist)");
$closestToTarget = $neighbor;
$closestToTargetDist = $targetDist;
$closestToTargetDist = $targetDist;
}
}
$gScore[$neighbor] = $tentativeG;
}
}
if($closestToTarget != null){
return $this->reconstructPath($path, $closestToTarget);
}
return null;
}
}
}

View file

@ -1,4 +1,5 @@
<?php
set_time_limit(0);
function parseOffset(string $offset) : string|false{

View file

@ -109,7 +109,6 @@ define("SOUL_SAND", 88);
define("GLOWSTONE", 89);
define("GLOWSTONE_BLOCK", 89);
define("LIT_PUMPKIN", 91);
define("JACK_O_LANTERN", 91);
define("CAKE_BLOCK", 92);

View file

@ -26,10 +26,10 @@ define("ENTITY_OBJECT", 3);
define("ENTITY_ITEM", 4);
define("ENTITY_ITEM_TYPE", 64);
define("ENTITY_FALLING", 5);
define("FALLING_SAND", 66);
//TileEntities
define("TILE_SIGN", "Sign");
define("TILE_CHEST", "Chest");
@ -44,7 +44,7 @@ const CORRECT_ENTITY_CLASSES = [
MOB_COW => true,
MOB_PIG => true,
MOB_SHEEP => true,
MOB_ZOMBIE => true,
MOB_SKELETON => true,
MOB_SPIDER => true,
@ -64,5 +64,5 @@ const CORRECT_ENTITY_CLASSES = [
ENTITY_FALLING => [
FALLING_SAND => true
]
];

View file

@ -103,7 +103,6 @@ require_once(FILE_PATH . "/src/pmf/PMF.php");
require_once(FILE_PATH . "/src/astarnavigator/TileNavigator.php");
require_once(FILE_PATH . "/src/entity/ai/tasks/TaskBase.php");
require_once(FILE_PATH . "/src/entity/Rideable.php");
@ -138,8 +137,6 @@ require_once(FILE_PATH . "/src/world/generator/vanilla/feature/Feature.php");
require_all(FILE_PATH . "src/");
$inc = get_included_files();
$inc[] = array_shift($inc);
$srcdir = realpath(FILE_PATH . "src/");

View file

@ -1,17 +1,15 @@
<?php
abstract class Animal extends Creature implements Ageable, Breedable{
public $parent;
public $inLove; //do NOT add it into metadata, it doesnt send it to player
public $age;
public $loveTimeout;
public $closestPlayerThatCanFeedEID = false;
public $closestPlayerThatCanFeedDist = INF;
public function __construct(Level $level, $eid, $class, $type = 0, $data = []){
parent::__construct($level, $eid, $class, $type, $data);
$this->setAge($data["Age"] ?? 0);
@ -20,11 +18,11 @@ abstract class Animal extends Creature implements Ageable, Breedable{
}
$this->searchForClosestPlayers = true;
}
public function isPlayerValid(Player $player){
return $player->spawned && $this->isFood($player->getHeldItem()->id) && !$player->entity->dead;
}
public function handlePrePlayerSearcher(){
parent::handlePrePlayerSearcher();
if($this->closestPlayerThatCanFeedEID !== false){
@ -33,15 +31,15 @@ abstract class Animal extends Creature implements Ageable, Breedable{
$this->closestPlayerThatCanFeedEID = false;
$this->closestPlayerThatCanFeedDist = INF;
}else{
$dist = ($this->x - $player->x)*($this->x - $player->x) + ($this->y - $player->y)*($this->y - $player->y) + ($this->z - $player->z)*($this->z - $player->z);
$dist = ($this->x - $player->x) * ($this->x - $player->x) + ($this->y - $player->y) * ($this->y - $player->y) + ($this->z - $player->z) * ($this->z - $player->z);
$this->closestPlayerThatCanFeedDist = $dist;
}
}
}
public function handlePlayerSearcher(Player $player, $dist){
parent::handlePlayerSearcher($player, $dist);
if($this->closestPlayerThatCanFeedDist >= $dist){
if($this->isPlayerValid($player)){
$this->closestPlayerThatCanFeedDist = $dist;
@ -49,18 +47,18 @@ abstract class Animal extends Creature implements Ageable, Breedable{
}
}
}
public function harm($dmg, $cause = "generic", $force = false){
$ret = parent::harm($dmg, $cause, $force);
$this->inPanic |= ($ret && is_numeric($cause));
$this->inLove = false;
return $ret;
}
public function isBaby(){
return $this->getAge() < 0;
}
public function breed(){
if($this->server->dhandle("entity.animal.breed", ["parent" => $this]) !== false){
$c = $this->spawnChild();
@ -70,22 +68,22 @@ abstract class Animal extends Creature implements Ageable, Breedable{
}
return false;
}
public function resetInLove(){
$this->inLove = 0;
}
public function canMate($ent){
return $ent->eid != $this->eid && $this->type === $ent->type && $this->isInLove() && $ent->isInLove();
}
public function update($now){
parent::update($now);
if($this->loveTimeout > 0){
--$this->loveTimeout;
}
$age = $this->getAge() + 1; //100 - fast. debug, 1 - normal
if($age >= 0 && $this->isBaby()){
$this->setAge($age);
@ -99,15 +97,15 @@ abstract class Animal extends Creature implements Ageable, Breedable{
unset($this->level->entitiesInLove[$this->eid]);
}
}
public function getAge(){
return $this->age;
}
public function setAge($i){
$this->age = $i;
}
public function spawnChild()
{
return $this->server->api->entity->add($this->level, $this->class, $this->type, [
@ -118,24 +116,24 @@ abstract class Animal extends Creature implements Ageable, Breedable{
"Age" => -24000,
]);
}
public function getMetadata(){
$d = parent::getMetadata();
$d[14]["value"] = $this->isBaby();
return $d;
}
public function createSaveData(){
$data = parent::createSaveData();
$data["IsBaby"] = $this->isBaby();
$data["Age"] = $this->getAge();
return $data;
}
public function isInLove(){
return $this->inLove > 0;
}
public function interactWith(Entity $e, $action){
if($e->isPlayer() && $action === InteractPacket::ACTION_HOLD){
$slot = $e->player->getHeldItem();
@ -149,14 +147,14 @@ abstract class Animal extends Creature implements Ageable, Breedable{
}
parent::interactWith($e, $action);
}
public function counterUpdate(){
parent::counterUpdate();
if($this->isInLove()){
--$this->inLove;
}
}
public function getDrops(){
if($this->isBaby()){
return [];

View file

@ -2,8 +2,8 @@
interface Breedable{
public function isFood($id); //original name
public function spawnChild();
public function isInLove();
}

View file

@ -2,12 +2,11 @@
abstract class Creature extends Living{
const CLASS_TYPE = ENTITY_MOB;
public $inPanic;
public $closestPlayerEID = false;
public $closestPlayerDist = INF;
public function __construct(Level $level, $eid, $class, $type = 0, $data = []){
$this->inPanic = false; //force for now
parent::__construct($level, $eid, $class, $type, $data);
@ -15,13 +14,12 @@ abstract class Creature extends Living{
$this->enableAutojump = true;
$this->searchForClosestPlayers = true;
}
public function update($now){
$this->handlePrePlayerSearcher();
return parent::update($now);
}
public function handlePrePlayerSearcher(){
parent::handlePrePlayerSearcher();
if($this->closestPlayerEID !== false){
@ -30,12 +28,12 @@ abstract class Creature extends Living{
$this->closestPlayerEID = false;
$this->closestPlayerDist = INF;
}else{
$dist = ($this->x - $player->x)*($this->x - $player->x) + ($this->y - $player->y)*($this->y - $player->y) + ($this->z - $player->z)*($this->z - $player->z);
$dist = ($this->x - $player->x) * ($this->x - $player->x) + ($this->y - $player->y) * ($this->y - $player->y) + ($this->z - $player->z) * ($this->z - $player->z);
$this->closestPlayerDist = $dist;
}
}
}
public function handlePlayerSearcher(Player $player, $dist){
parent::handlePlayerSearcher($player, $dist);
if($this->closestPlayerDist >= $dist){
@ -43,13 +41,13 @@ abstract class Creature extends Living{
$this->closestPlayerDist = $dist;
}
}
public function createSaveData(){
$data = parent::createSaveData();
$data["State"] = @$this->getState();
return $data;
}
public function getSpeedModifer(){
return 0.7;
}
@ -71,19 +69,19 @@ abstract class Creature extends Living{
$pk->z = $this->z;
$pk->yaw = $this->yaw;
$pk->pitch = $this->pitch;
$pk->metadata = $this->getMetadata();
$pk->metadata = $this->getMetadata();
$player->dataPacket($pk);
$pk = new SetEntityMotionPacket;
$pk->eid = $this->eid;
$pk->speedX = $this->speedX;
$pk->speedY = $this->speedY;
$pk->speedZ = $this->speedZ;
$player->dataPacket($pk);
if($this->linkedEntity != 0 && $this->isRider){
$player->eventHandler(["rider" => $this->eid, "riding" => $this->linkedEntity, "type" => 0], "entity.link");
}
}
}

File diff suppressed because it is too large Load diff

View file

@ -1,12 +1,11 @@
<?php
abstract class Living extends Entity implements Pathfindable{
public static $despawnMobs, $despawnTimer, $entityPushing = false;
public static $pathfinderTest = false;
/**
* @var Entity $target
* @var EntityAI $ai
@ -14,14 +13,14 @@ abstract class Living extends Entity implements Pathfindable{
public $target, $ai;
public $pathFinder, $path = null, $currentIndex = 0, $currentNode, $pathFollower;
public $ticksExisted = 0;
public $landMovementFactor = 0.1;
public $jumpMovementFactor = 0.02;
public $aiMoveSpeed;
public $renderYawOffset = 0.0; //used by head rotation, TODO better name
public $jumping, $jumpTicks;
public function __construct(Level $level, $eid, $class, $type = 0, $data = array()){
public function __construct(Level $level, $eid, $class, $type = 0, $data = []){
$this->target = false;
$this->ai = new EntityAI($this);
$this->pathFinder = new TileNavigator($this);
@ -30,43 +29,43 @@ abstract class Living extends Entity implements Pathfindable{
$this->canBeAttacked = true;
$this->hasGravity = true;
$this->hasKnockback = true;
//if(self::$despawnMobs) $this->server->schedule(self::$despawnTimer, [$this, "close"]); //900*20
}
public function isPickable(){
return !$this->dead;
}
public function fall(){
$dmg = ceil($this->fallDistance - 3);
if($dmg > 0){
$this->harm($dmg, "fall");
}
}
public function handlePlayerSearcher(Player $player, $dist){
}
public function getAIMoveSpeed(){
return $this->aiMoveSpeed;
}
public function getVerticalFaceSpeed(){
return 40; //unused in 0.8 but may be useful in 0.9/0.10
}
public function setAIMoveSpeed($speed){
$this->aiMoveSpeed = $speed;
$this->moveForward = $speed;
}
public function hasPath(){
return $this->path != null;
}
public function eatGrass(){}
public function close(){
parent::close();
unset($this->pathFollower->entity);
@ -76,22 +75,22 @@ abstract class Living extends Entity implements Pathfindable{
unset($this->parent);
unset($this->pathFinder->entity);
}
public function canBeShot(){
return true;
}
public function isPushable(){
return !$this->dead;
}
public function collideHandler(){
$bb = $this->boundingBox->expand(0.2, 0, 0.2);
$minChunkX = ((int)($bb->minX)) >> 4;
$minChunkZ = ((int)($bb->minZ)) >> 4;
$maxChunkX = ((int)($bb->minX)) >> 4;
$maxChunkZ = ((int)($bb->minZ)) >> 4;
$minChunkX = ((int) ($bb->minX)) >> 4;
$minChunkZ = ((int) ($bb->minZ)) >> 4;
$maxChunkX = ((int) ($bb->minX)) >> 4;
$maxChunkZ = ((int) ($bb->minZ)) >> 4;
//TODO also index by chunkY?
for($chunkX = $minChunkX; $chunkX <= $maxChunkX; ++$chunkX){
for($chunkZ = $minChunkZ; $chunkZ <= $maxChunkZ; ++$chunkZ){
@ -106,14 +105,14 @@ abstract class Living extends Entity implements Pathfindable{
}
}
}
public function update($now){
if(self::$despawnMobs && ++$this->ticksExisted > self::$despawnTimer){
$this->close();
return;
}
if($this->closed) return;
$check = $this->level->mobSpawner->checkDespawn($this);
if($check){
$this->close();
@ -121,7 +120,7 @@ abstract class Living extends Entity implements Pathfindable{
}
parent::update($now);
}
public $pathEIDS = [];
private static $lastPathEID = 10000000;
public static $pathfind = true;
@ -139,22 +138,21 @@ abstract class Living extends Entity implements Pathfindable{
}
if(self::$pathfind){
$this->path = $this->pathFinder->navigate(
$this->level,
(int)$this->x, (int)$this->y, (int)$this->z,
//(int)$pl->entity->x, (int)$pl->entity->y, (int)$pl->entity->z,
(int)$this->x + mt_rand(-16, 16), (int)$this->y, (int)$this->z + mt_rand(-16, 16),
$this->level,
(int) $this->x, (int) $this->y, (int) $this->z,
//(int)$pl->entity->x, (int)$pl->entity->y, (int)$pl->entity->z,
(int) $this->x + mt_rand(-16, 16), (int) $this->y, (int) $this->z + mt_rand(-16, 16),
16
);
}
/*if($this->path){
console("Found path of length ".count($this->path));
foreach($this->path as $node){
$eid = self::$lastPathEID++;
$this->pathEIDS[] = $eid;
$pk = new AddItemEntityPacket();
$pk->eid = $eid;
$pk->item = BlockAPI::getItem(GOLD_BLOCK, 0, 1);
@ -171,8 +169,7 @@ abstract class Living extends Entity implements Pathfindable{
}
$this->pathFollower->followPath();
}
//not exactly here
if($this->jumping){
if(!$this->inWater && !$this->inLava){
@ -186,12 +183,11 @@ abstract class Living extends Entity implements Pathfindable{
}else{
$this->jumpTicks = 0;
}
$this->ai->mobController->movementTick();
$this->ai->mobController->rotateTick();
$this->ai->mobController->jumpTick();
if(abs($this->speedX) < self::MIN_POSSIBLE_SPEED) $this->speedX = 0;
if(abs($this->speedZ) < self::MIN_POSSIBLE_SPEED) $this->speedZ = 0;
if(abs($this->speedY) < self::MIN_POSSIBLE_SPEED) $this->speedY = 0;
@ -203,24 +199,23 @@ abstract class Living extends Entity implements Pathfindable{
$this->landMovementFactor = $savedLandFactor;
//Yaw rotation in 1.5 is handled in a bit different place but hopefully this will work too
$this->ai->mobController->updateHeadYaw();
if(self::$entityPushing){
$this->collideHandler();
}
}
public function jump(){
$this->speedY = 0.42;
//TODO also set AirBorne?
}
public function counterUpdate(){
parent::counterUpdate();
if($this->jumpTicks > 0) --$this->jumpTicks;
}
public function moveEntityWithHeading($strafe, $forward){
if($this->inWater){ //also check is player, and can it fly or not
$prevPosY = $this->y;
@ -230,8 +225,7 @@ abstract class Living extends Entity implements Pathfindable{
$this->speedY *= 0.8;
$this->speedZ *= 0.8;
$this->speedY -= 0.02;
if($this->isCollidedHorizontally && $this->isFree($this->speedX, $this->speedY + 0.6 - $this->y + $prevPosY, $this->speedZ)){
$this->speedY = 0.3;
}
@ -243,69 +237,69 @@ abstract class Living extends Entity implements Pathfindable{
$this->speedY *= 0.5;
$this->speedZ *= 0.5;
$this->speedY -= 0.02;
if($this->isCollidedHorizontally && $this->isFree($this->speedX, $this->speedY + 0.6 - $this->y + $prevPosY, $this->speedZ)){
$this->speedY = 0.3;
}
}else{
$friction = 0.91;
if($this->onGround){
$friction = 0.546;
$blockAt = $this->level->level->getBlockID(floor($this->x), floor($this->boundingBox->minY) - 1, floor($this->z));
if($blockAt > 0) $friction = StaticBlock::getSlipperiness($blockAt) * 0.91;
}
$var8 = 0.16277 / ($friction*$friction*$friction);
$var8 = 0.16277 / ($friction * $friction * $friction);
if($this->onGround){
$var5 = $this->getAIMoveSpeed(); //in vanilla it returns either this.seed or calls getBaseSpeed(depending on useNewAi)
$var5 *= $var8; //in vanilla it also multiplies by speedModifer
}else{
$var5 = $this->jumpMovementFactor;
}
$this->moveFlying($strafe, $forward, $var5);
//recalculating friction, might be not neccessary
$friction = 0.91;
if($this->onGround){
$friction = 0.546;
$blockAt = $this->level->level->getBlockID(floor($this->x), floor($this->boundingBox->minY) - 1, floor($this->z));
if($blockAt > 0) $friction = StaticBlock::getSlipperiness($blockAt) * 0.91;
}
if($this->isOnLadder()){
$speedY = $this->speedY;
$this->fallDistance = 0;
if($speedY < -0.15) $this->speedY = -0.15;
}
$this->move($this->speedX, $this->speedY, $this->speedZ);
if($this->isOnLadder() && $this->isCollidedHorizontally){
$this->speedY = 0.2;
}
$this->speedY -= 0.08; //gravity
$this->speedY *= 0.98;
$this->speedX *= $friction;
$this->speedZ *= $friction;
if($this->isCollidedHorizontally && $this->enableAutojump){
$this->ai->mobController->setJumping(true); //non vanilla
}
}
}
public function sendMoveUpdate(){
if($this->counter % 3 != 0){
return;
}
parent::sendMoveUpdate();
}
}

View file

@ -1,17 +1,18 @@
<?php
class Monster extends Creature{
public $closestPlayerToAttackEID = false;
public $closestPlayerToAttackDist = INF;
public function __construct(Level $level, $eid, $class, $type = 0, $data = []){
parent::__construct($level, $eid, $class, $type, $data);
}
public function getAttackDamage(){
return 2;
}
/**
*
*
* @see Entity::attackEntity()
*/
public function attackEntity($entity, $distance){
@ -22,11 +23,11 @@ class Monster extends Creature{
return false;
}
}
public function isPlayerValid(Player $player){
return $player->spawned && !$player->entity->dead;
}
public function handlePrePlayerSearcher(){
parent::handlePrePlayerSearcher();
if($this->closestPlayerToAttackEID !== false){
@ -35,15 +36,15 @@ class Monster extends Creature{
$this->closestPlayerToAttackEID = false;
$this->closestPlayerToAttackDist = INF;
}else{
$dist = ($this->x - $player->x)*($this->x - $player->x) + ($this->y - $player->y)*($this->y - $player->y) + ($this->z - $player->z)*($this->z - $player->z);
$dist = ($this->x - $player->x) * ($this->x - $player->x) + ($this->y - $player->y) * ($this->y - $player->y) + ($this->z - $player->z) * ($this->z - $player->z);
$this->closestPlayerToAttackDist = $dist;
}
}
}
public function handlePlayerSearcher(Player $player, $dist){
parent::handlePlayerSearcher($player, $dist);
if($this->closestPlayerToAttackDist >= $dist){
if($this->isPlayerValid($player)){
$this->closestPlayerToAttackDist = $dist;
@ -51,5 +52,5 @@ class Monster extends Creature{
}
}
}
}

View file

@ -1,4 +1,5 @@
<?php
abstract class Projectile extends Entity{
const CLASS_TYPE = ENTITY_OBJECT;
public $shooterEID;
@ -7,13 +8,13 @@ abstract class Projectile extends Entity{
public $ticksInAir = 0, $ticksInGround = 0;
public $xTile = 0, $yTile = 0, $zTile = 0;
public $inTile = false;
public function __construct(Level $level, $eid, $class, $type = 0, $data = [])
{
parent::__construct($level, $eid, $class, $type, $data);
$this->gravity = 0.03;
$this->setSize(0.25, 0.25);
$this->x -= cos($this->yaw / 180 * M_PI) * 0.16;
$this->y -= 0.1;
$this->z -= cos($this->yaw / 180 * M_PI) * 0.16;
@ -25,7 +26,7 @@ abstract class Projectile extends Entity{
$this->xTile = $data["xTile"] ?? $this->xTile;
$this->yTile = $data["yTile"] ?? $this->yTile;
$this->zTile = $data["zTile"] ?? $this->zTile;
if($shooter instanceof Entity){
$this->shooterEID = $shooter->eid;
if($shooter->isPlayer()){
@ -44,9 +45,9 @@ abstract class Projectile extends Entity{
$this->shoot(, , , $throwPower, 1.0);*/
}
}
}
public function shoot($d, $d1, $d2, $f, $f1){ //unchecked, may be not same as arrow
$f2 = sqrt($d * $d + $d1 * $d1 + $d2 * $d2);
$d /= $f2;
@ -66,7 +67,7 @@ abstract class Projectile extends Entity{
$this->pitch = (atan2($d1, $f3) * 180) / M_PI;
$this->updatePosition();
}
public function update($now){
$this->lastX = $this->x;
$this->lastY = $this->y;
@ -88,32 +89,32 @@ abstract class Projectile extends Entity{
$this->fire -= 4;
if($this->fire <= 0) $this->fire = 0;
}
if($this->fire <= 0){
$this->updateMetadata();
}
}
if($this->handleLavaMovement()){
if(!$this->isImmuneToFire){
$this->harm(4, "fire");
$oldOnFire = $this->fire;
if($oldOnFire < 20*30) $this->fire = 20*30; //30 seconds
if($oldOnFire < 20 * 30) $this->fire = 20 * 30; //30 seconds
}
}
if($this->isInVoid()){
$this->outOfWorld();
}
//Entity::update end
if($this->shake > 0) --$this->shake;
if(!$this->inGround){
++$this->ticksInAir;
goto CHECK_COLLISIONS; //TODO dont use gotos
}
$blockID = $this->level->level->getBlockID($this->xTile, $this->yTile, $this->zTile);
if($this->inTile != $blockID){
$this->speedX += (lcg_value() * 0.2);
@ -122,7 +123,7 @@ abstract class Projectile extends Entity{
$this->inGround = false;
$this->ticksInAir = $this->ticksInGround = 0;
CHECK_COLLISIONS:
$start = new Vector3($this->x, $this->y, $this->z);
$end = new Vector3($this->x + $this->speedX, $this->y + $this->speedY, $this->z + $this->speedZ);
/**
@ -135,44 +136,44 @@ abstract class Projectile extends Entity{
}else{
$end = new Vector3($this->x + $this->speedX, $this->y + $this->speedY, $this->z + $this->speedZ);
}
$entities = $this->level->getEntitiesInAABB($this->boundingBox->addCoord($this->speedX, $this->speedY, $this->speedZ)->expand(1, 1, 1));
$bestDist = 0;
$bestEnt = null;
foreach($entities as $eid => $ent){
if($eid != $this->eid && $ent->isPickable() && ($eid != $this->shooterEID || $this->ticksInAir >= 5)){
$v12 = $ent->boundingBox->expand(0.3, 0.3, 0.3);
$v13 = $v12->calculateIntercept($start, $end);
if($v13 != null){
$dist = $start->distance($v13->hitVector);
if($dist < $bestDist || $bestDist == 0){
$bestEnt = $ent;
}
}
}
}
if($bestEnt != null){
$v4 = MovingObjectPosition::fromEntity($bestEnt);
}
if($v4 != null){
$this->onHit($v4);
}
$this->x += $this->speedX;
$this->y += $this->speedY;
$this->z += $this->speedZ;
$v21 = sqrt($this->speedX*$this->speedX + $this->speedZ*$this->speedZ);
$v21 = sqrt($this->speedX * $this->speedX + $this->speedZ * $this->speedZ);
$this->yaw = atan2($this->speedX, $this->speedZ) * 180 / M_PI;
$this->pitch = atan2($this->speedY, $v21) * 180 / M_PI;
$this->pitch = $this->lastPitch + ($this->pitch - $this->lastPitch) * 0.2;
$this->yaw = $this->lastYaw + ($this->yaw - $this->lastYaw) * 0.2;
$v24 = $this->inWater ? 0.8 : 0.99;
$this->speedX *= $v24;
$this->speedY *= $v24;
@ -183,19 +184,19 @@ abstract class Projectile extends Entity{
$this->boundingBox->setBounds($this->x - $v7, $this->y - $this->yOffset /*+ $this->ySize*/, $this->z - $v7, $this->x + $v7, $this->y - $this->yOffset + $v8 /*+ $this->ySize*/, $this->z + $v7);
}
}
public function onHit(MovingObjectPosition $hitResult){
}
public function createSaveData(){
$data = parent::createSaveData();
$data["inTile"] = $this->inTile;
$data["inGround"] = $this->inGround;
$data["xTile"] = $this->xTile;
$data["yTile"] = $this->yTile;
$data["zTile"] = $this->zTile;
return $data;
}
public function spawn($player)
@ -212,5 +213,5 @@ abstract class Projectile extends Entity{
$pk->did = 0;
$player->dataPacket($pk);
}
}

View file

@ -10,29 +10,27 @@ class EntityAI
* @var Living
*/
public $entity;
/**
* @var TaskBase[]
*/
protected $tasks;
public $lastTask;
public function __construct($entity){
$this->entity = $entity;
$this->tasks = [];
$this->mobController = new MobController($entity);
}
public function canSee(Entity $entity){
//TODO caches
return $this->entity->canSee($entity);
}
/**
* Add a task for entity
* @param TaskBase $task
*/
public function addTask(TaskBase $task){
$this->tasks[$task->__toString()] = $task;
@ -44,16 +42,16 @@ class EntityAI
}
return false;
}
/**
*
*
* @param mixed $id classname
* @return TaskBase | false
*/
public function getTask($id){
return $this->tasks[$id] ?? false;
}
public function isStarted($id){
$task = $this->getTask($id);
return $task instanceof TaskBase && $task->isStarted;
@ -75,10 +73,10 @@ class EntityAI
}
}
}
public function __destruct(){
unset($this->entity);
}
}

View file

@ -14,24 +14,24 @@ class MobController
* @var Living
*/
public $entity;
public $finalYaw, $finalPitch, $finalHeadYaw;
public $headYaw;
public $someTicker = 0;
protected $jumping;
public $moveToX, $moveToY, $moveToZ;
public $speedMultiplier;
public $updateMove = false;
public $lookX, $lookY, $lookZ;
public $deltaLookYaw, $deltaLookPitch;
public $isLooking = false;
public $headYawIsYaw = false;
public function __construct($e){
$this->entity = $e;
}
@ -41,11 +41,11 @@ class MobController
public function isJumping(){
return $this->jumping;
}
public function setJumping($b){
$this->jumping = $b;
}
public function isRotationCompleted(){
return $this->finalHeadYaw === $this->entity->headYaw;
}
@ -56,7 +56,7 @@ class MobController
$this->speedMultiplier = $speed;
$this->updateMove = true;
}
public function setMovingOffset($x, $y, $z, $speed){
$this->moveToX = $this->entity->x + ($x);
$this->moveToY = $this->entity->y + ($y);
@ -64,50 +64,50 @@ class MobController
$this->speedMultiplier = $speed;
$this->updateMove = true;
}
public function canJump(){
return $this->isJumping() && $this->jumpTimeout <= 0 && $this->entity->onGround;
}
public static function limitAngle2($old, $newA, $limit){
$v4 = Utils::wrapAngleTo180($old - $newA);
if($v4 < -$limit) $v4 = -$limit;
if($v4 >= $limit) $v4 = $limit;
return $old - $v4;
}
public static function limitAngle($old, $newA, $limit){
$v4 = Utils::wrapAngleTo180($newA - $old);
if($v4 > $limit) $v4 = $limit;
if($v4 < -$limit) $v4 = -$limit;
return $old + $v4;
}
public function jumpTick(){
$this->entity->jumping = $this->jumping;
$this->jumping = false;
}
public function movementTick(){
$this->entity->moveForward = 0;
if($this->updateMove){
$this->updateMove = false;
$v1 = floor($this->entity->boundingBox->minY + 0.5);
$diffX = $this->moveToX - $this->entity->x;
$diffZ = $this->moveToZ - $this->entity->z;
$diffY = $this->moveToY - $v1;
$v8 = $diffX*$diffX + $diffY*$diffY + $diffZ*$diffZ;
$v8 = $diffX * $diffX + $diffY * $diffY + $diffZ * $diffZ;
if($v8 >= 0.00000025){
$v10 = (atan2($diffZ, $diffX) * 180 / M_PI) - 90;
$this->entity->yaw = self::limitAngle($this->entity->yaw, $v10, 30);
$this->entity->setAIMoveSpeed($this->speedMultiplier * $this->entity->getSpeed() * $this->entity->getSpeedModifer());
if($diffY > 0 && $diffX*$diffX + $diffZ*$diffZ < 1) $this->setJumping(true);
if($diffY > 0 && $diffX * $diffX + $diffZ * $diffZ < 1) $this->setJumping(true);
}
}
//TODO handle jumps somewhere
@ -117,11 +117,11 @@ class MobController
//}
//if($this->jumpTimeout > 0) --$this->jumpTimeout;
}
public function updateHeadYaw(){
$diffX = $this->entity->x - $this->entity->lastX;
$diffZ = $this->entity->z - $this->entity->lastZ;
if(($diffX*$diffX + $diffZ*$diffZ) > 0.00000025){
if(($diffX * $diffX + $diffZ * $diffZ) > 0.00000025){
$this->entity->renderYawOffset = $this->entity->yaw;
$this->entity->headYaw = self::limitAngle2($this->entity->renderYawOffset, $this->entity->headYaw, 75);
$this->headYaw = $this->entity->headYaw;
@ -133,7 +133,7 @@ class MobController
$this->headYaw = $this->entity->headYaw;
}else{
++$this->someTicker;
if($this->someTicker > 10){
$v5 = max(1 - ($this->someTicker - 10) / 10, 0) * 75;
}
@ -141,53 +141,53 @@ class MobController
$this->entity->renderYawOffset = self::limitAngle2($this->entity->headYaw, $this->entity->renderYawOffset, $v5);
}
}
public function rotateTick(){ //TODO handle more rotation
$this->entity->pitch = 0;
if($this->isLooking){
$this->isLooking = false;
$diffX = $this->lookX - $this->entity->x;
$diffY = $this->lookY - ($this->entity->y + $this->entity->getEyeHeight());
$diffZ = $this->lookZ - $this->entity->z;
$distance = sqrt($diffX*$diffX + $diffZ*$diffZ);
$v9 = (atan2($diffZ, $diffX)*180 / M_PI) - 90;
$v10 = -(atan2($diffY, $distance)*180 / M_PI);
$distance = sqrt($diffX * $diffX + $diffZ * $diffZ);
$v9 = (atan2($diffZ, $diffX) * 180 / M_PI) - 90;
$v10 = -(atan2($diffY, $distance) * 180 / M_PI);
$this->entity->pitch = self::limitAngle($this->entity->pitch, $v10, $this->deltaLookPitch);
$this->entity->headYaw = self::limitAngle($this->entity->headYaw, $v9, $this->deltaLookYaw);
}else{
$this->entity->headYaw = self::limitAngle($this->entity->headYaw, $this->entity->renderYawOffset, 10);
}
if($this->headYawIsYaw) $this->entity->yaw = $this->entity->headYaw;
$this->headYawIsYaw = false;
/* Some stuff for pathfinder - nc doesnt have it now
* float var11 = MathHelper.wrapAngleTo180_float(this.entity.rotationYawHead - this.entity.renderYawOffset);
if (!this.entity.getNavigator().noPath())
{
if (var11 < -75.0F)
{
this.entity.rotationYawHead = this.entity.renderYawOffset - 75.0F;
}
if (!this.entity.getNavigator().noPath())
{
if (var11 < -75.0F)
{
this.entity.rotationYawHead = this.entity.renderYawOffset - 75.0F;
}
if (var11 > 75.0F)
{
this.entity.rotationYawHead = this.entity.renderYawOffset + 75.0F;
}
}
if (var11 > 75.0F)
{
this.entity.rotationYawHead = this.entity.renderYawOffset + 75.0F;
}
}
*/
//$this->entity->lastHeadYaw = $this->entity->headYaw;
//$w180 = Utils::wrapAngleTo180($this->finalHeadYaw - $this->entity->headYaw);
//$w180 = Utils::wrapAngleTo180($this->finalHeadYaw - $this->entity->headYaw);
//$w180min = min(abs($w180), 20)*Utils::getSign($w180);
//$this->entity->headYaw = Utils::wrapAngleTo360($this->entity->headYaw + $w180min);
}
public function setLookPosition($posX, $posY, $posZ, $lookYaw, $lookPitch){
$this->lookX = $posX;
$this->lookY = $posY;
@ -196,9 +196,9 @@ class MobController
$this->deltaLookPitch = $lookPitch;
$this->isLooking = true;
}
public function faceEntity($x, $y, $z){
$len = sqrt($x*$x + $z*$z + $y*$y);
$len = sqrt($x * $x + $z * $z + $y * $y);
//$d = $len == 0 ?//$v->subtract($this->entity)->normalize();
if($len == 0){
$dx = 0;
@ -207,38 +207,37 @@ class MobController
$dx = $x / $len;
$dz = $z / $len;
}
$tan = $dz == 0 ? ($dx < 0 ? 180 : 0) : (90 - rad2deg(atan($dx / $dz)));
$tan = $dz == 0 ? ($dx < 0 ? 180 : 0) : (90 - rad2deg(atan($dx / $dz)));
$thetaOffset = $dz < 0 ? 90 : 270;
$calcYaw = ($thetaOffset + $tan);
$this->finalHeadYaw = $this->entity->yaw = Utils::wrapAngleTo360($calcYaw);
}
public function lookOffset($x, $y, $z, $pitch = true){
$tan = $z == 0 ? ($x < 0 ? 180 : 0) : (90 - rad2deg(atan($x / $z))); /*arctan(infinity) = pi/2 = (90deg) - 90 = 0*/
$thetaOffset = $z < 0 ? 90 : 270;
$calcYaw = $tan + $thetaOffset;
$this->entity->yaw = $this->finalHeadYaw = Utils::wrapAngleTo360($calcYaw);
if($pitch){
$diff = sqrt($x * $x + $z * $z);
$calcPitch = $diff == 0 ? ($y < 0 ? -90 : 90) : rad2deg(atan($y / $diff));
$this->entity->pitch = $calcPitch;
}
//$this->entity->server->query("UPDATE entities SET pitch = ".$this->entity->pitch.", yaw = ".$this->entity->yaw." WHERE EID = ".$this->entity->eid.";");
return true;
}
public function lookOn($x, $y = 0, $z = 0, $pitch = true){
if($x instanceof Vector3){
return $this->lookOn($x->x, $x->y + $x->getEyeHeight(), $x->z, $pitch);
}
return $this->lookOffset($x - $this->entity->x, ($this->entity->y + $this->entity->height) - $y, $z - $this->entity->z, $pitch);
}
public function __destruct(){
unset($this->entity);
}

View file

@ -5,16 +5,16 @@ class PathFollower{
* @var Living
*/
public $entity;
public function __construct(Living $entity){
$this->entity = $entity;
}
public function followPath(){
if(!isset($this->entity) || !($this->entity instanceof Living)) return;
if(!$this->entity->hasPath()) return;
if($this->entity->currentNode == null){
$this->entity->currentNode = $this->entity->path[$this->entity->currentIndex];
}
@ -27,14 +27,13 @@ class PathFollower{
//console("next");
$this->entity->currentNode = null;
}
if($this->entity->currentIndex >= count($this->entity->path)){
console("path finished.");
$this->entity->currentNode = null;
$this->entity->path = null;
$this->entity->currentIndex = 0;
/*foreach($this->entity->pathEIDS as $eid){
$pk = new RemoveEntityPacket();
$pk->eid = $eid;
@ -42,9 +41,9 @@ class PathFollower{
$player->dataPacket($pk);
}
}*/
}
}
}

View file

@ -4,20 +4,19 @@ class TaskAttackPlayer extends TaskBase
{
public $speedMultiplier;
public $rangeSquared;
public $attackCounter;
public function __construct($speed, $range){
$this->speedMultiplier = $speed;
$this->rangeSquared = $range*$range;
$this->rangeSquared = $range * $range;
}
public function onStart(EntityAI $ai)
{
$this->selfCounter = 1;
}
public function onUpdate(EntityAI $ai)
{
if(!$this->isTargetValid($ai)){
@ -27,7 +26,7 @@ class TaskAttackPlayer extends TaskBase
}
$ai->mobController->setMovingTarget($ai->entity->target->x, $ai->entity->target->y, $ai->entity->target->z, $this->speedMultiplier);
$ai->mobController->setLookPosition($ai->entity->target->x, $ai->entity->target->y + 0.12, $ai->entity->target->z, 10, $ai->entity->getVerticalFaceSpeed());
--$this->attackCounter;
$v1 = $ai->entity->width * $ai->entity->width * 4;
if($ai->entity instanceof Creeper){
@ -38,16 +37,15 @@ class TaskAttackPlayer extends TaskBase
$xDiff = ($t->x - $e->x);
$yDiff = ($t->y - $e->y);
$zDiff = ($t->z - $e->z);
$dist = ($xDiff*$xDiff + $yDiff*$yDiff + $zDiff*$zDiff);
$dist = ($xDiff * $xDiff + $yDiff * $yDiff + $zDiff * $zDiff);
if($dist <= $v1){
if($this->attackCounter <= 0){
$this->attackCounter = $e->attackEntity($t, sqrt($dist)) ? 20 : 0;
}
}
}
public function isTargetValid(EntityAI $ai){
$e = $ai->entity;
if($e->target instanceof Entity && !$e->target->closed && !$e->target->dead){
@ -55,11 +53,11 @@ class TaskAttackPlayer extends TaskBase
$xDiff = ($t->x - $e->x);
$yDiff = ($t->y - $e->y);
$zDiff = ($t->z - $e->z);
return ($xDiff*$xDiff + $yDiff*$yDiff + $zDiff*$zDiff) <= $this->rangeSquared;
return ($xDiff * $xDiff + $yDiff * $yDiff + $zDiff * $zDiff) <= $this->rangeSquared;
}
return false;
}
public function tryTargeting(EntityAI $ai){
$e = $ai->entity;
if($e->target instanceof Entity){
@ -67,25 +65,25 @@ class TaskAttackPlayer extends TaskBase
$xDiff = ($t->x - $e->x);
$yDiff = ($t->y - $e->y);
$zDiff = ($t->z - $e->z);
if(($xDiff*$xDiff + $yDiff*$yDiff + $zDiff*$zDiff) <= $this->rangeSquared){
if(($xDiff * $xDiff + $yDiff * $yDiff + $zDiff * $zDiff) <= $this->rangeSquared){
return true;
}
}
$closestTarget = $e->closestPlayerToAttackDist <= $this->rangeSquared ? $e->level->entityList[$e->closestPlayerToAttackEID] : null;
if($closestTarget != null){
$e->target = $closestTarget; //TODO dont save entity object ?
return true;
}
return false;
}
public function canBeExecuted(EntityAI $ai)
{
return $this->tryTargeting($ai);
}
public function onEnd(EntityAI $ai)
{
$ai->entity->target = false;

View file

@ -3,45 +3,41 @@
abstract class TaskBase
{
public $isStarted = false, $selfCounter = 0;
public function __construct(){}
/**
* Executed when entity starts task. It is recommended to set counter here.
* @param EntityAI $ai
*/
abstract function onStart(EntityAI $ai);
/**
* Every tick until counter will be not equal to 0. It is recommended to update value of counter here.
* @param EntityAI $ai
*/
abstract function onUpdate(EntityAI $ai);
/**
* On task end.
* @param EntityAI $ai
*/
abstract function onEnd(EntityAI $ai);
/**
* Can start the task
* @param EntityAI $ai
*/
abstract function canBeExecuted(EntityAI $ai);
/**
* @return number ticks
*/
function getIdleTimeAfterEnd(){
return 0;
}
function reset(){
$this->isStarted = false;
$this->selfCounter = 0;
}
final function __toString(){
return get_class($this);
}

View file

@ -10,7 +10,7 @@ class TaskEatTileGoal extends TaskBase
public function onEnd(EntityAI $ai)
{
}
public function onUpdate(EntityAI $ai)
@ -18,7 +18,7 @@ class TaskEatTileGoal extends TaskBase
if($ai->isStarted("TaskPanic")){
$this->reset();
return false;
}
}
if (--$this->selfCounter == 4)
{
@ -27,7 +27,7 @@ class TaskEatTileGoal extends TaskBase
if($id === TALL_GRASS){
$ai->entity->level->fastSetBlockUpdate($ai->entity->x, $ai->entity->y, $ai->entity->z, AIR, 0);
$ai->entity->eatGrass();
}elseif($idb === GRASS){
$ai->entity->level->fastSetBlockUpdate($ai->entity->x, $ai->entity->y - 1, $ai->entity->z, DIRT, 0);
$ai->entity->eatGrass();

View file

@ -5,7 +5,7 @@ class TaskFollowParent extends TaskBase
public function __construct($speed){
$this->speedMultiplier = $speed;
}
public function onStart(EntityAI $ai)
{
$this->selfCounter = 1;
@ -23,19 +23,19 @@ class TaskFollowParent extends TaskBase
$ai->entity->parent = null;
return false;
}
$dist = $ai->entity->distanceSquared($ai->entity->parent);
if($dist > 256 || $dist < 9){ //3-16 blocks
$this->reset();
return false;
}
$parent = $ai->entity->parent;
$ai->mobController->setLookPosition($parent->x, $parent->y + $parent->getEyeHeight(), $parent->z, 10, $ai->entity->getVerticalFaceSpeed());
$ai->mobController->setMovingTarget($parent->x, $parent->y, $parent->z, $this->speedMultiplier);
}
public function canBeExecuted(EntityAI $ai)
{
return $ai->entity->isBaby() && ($ai->entity->parent instanceof Entity) && !$ai->entity->parent->dead; //TODO find a new parent if the current one is dead

View file

@ -3,7 +3,7 @@
class TaskLookAround extends TaskBase
{
public $lookOffsetX, $lookOffsetZ;
public function onStart(EntityAI $ai)
{
$this->selfCounter = 20 + lcg_value();
@ -19,9 +19,9 @@ class TaskLookAround extends TaskBase
public function canBeExecuted(EntityAI $ai)
{
return !$ai->entity->inPanic && !$ai->entity->isMoving() && lcg_value() < 0.02 && !$ai->isStarted("TaskLookAtPlayer") && !$ai->isStarted("TaskAttackPlayer") && !$ai->isStarted("TaskMate") && !$ai->isStarted("TaskTempt") && !$ai->entity->hasPath(); /*Vanilla value*/
return !$ai->entity->inPanic && !$ai->entity->isMoving() && lcg_value() < 0.02 && !$ai->isStarted("TaskLookAtPlayer") && !$ai->isStarted("TaskAttackPlayer") && !$ai->isStarted("TaskMate") && !$ai->isStarted("TaskTempt") && !$ai->entity->hasPath(); /*Vanilla value*/
}
public function onUpdate(EntityAI $ai)
{
--$this->selfCounter;

View file

@ -6,13 +6,13 @@ class TaskLookAtPlayer extends TaskBase{
public function __construct($distance){
$this->distance = $distance;
}
public function canBeExecuted(EntityAI $ai){
return !$ai->entity->inPanic && lcg_value() < 0.02 && !$ai->entity->isMovingHorizontally() && !$ai->isStarted("TaskMate") && !$ai->isStarted("TaskLookAround") && !$ai->isStarted("TaskTempt") && !$ai->isStarted("TaskPanic") && !$ai->entity->hasPath();
return !$ai->entity->inPanic && lcg_value() < 0.02 && !$ai->entity->isMovingHorizontally() && !$ai->isStarted("TaskMate") && !$ai->isStarted("TaskLookAround") && !$ai->isStarted("TaskTempt") && !$ai->isStarted("TaskPanic") && !$ai->entity->hasPath();
}
protected function findTarget(Creature $e, $r){
return $e->closestPlayerDist > $r*$r ? null : $e->level->entityList[$e->closestPlayerEID];
return $e->closestPlayerDist > $r * $r ? null : $e->level->entityList[$e->closestPlayerEID];
}
public function onStart(EntityAI $ai){
@ -22,7 +22,7 @@ class TaskLookAtPlayer extends TaskBase{
$this->onEnd($ai);
return;
}
$this->selfCounter = mt_rand(20, 60);
}
@ -35,7 +35,7 @@ class TaskLookAtPlayer extends TaskBase{
$ai->mobController->setLookPosition($this->target->x, $this->target->y + $this->target->getEyeHeight(), $this->target->z, 10, $ai->entity->getVerticalFaceSpeed());
$this->selfCounter--;
}
public function onEnd(EntityAI $ai){
unset($this->target);
$ai->entity->pitch = 0;

View file

@ -5,9 +5,9 @@ class TaskMate extends TaskBase
public function __construct($speed){
$this->speedMultiplier = $speed;
}
public $targetMateID;
public function onStart(EntityAI $ai)
{
$this->selfCounter = 60;
@ -27,17 +27,16 @@ class TaskMate extends TaskBase
$this->onEnd($ai);
return;
}
$ai->mobController->setLookPosition($movTo->x, $movTo->y + $movTo->getEyeHeight(), $movTo->z, 10, $ai->entity->getVerticalFaceSpeed());
$ai->mobController->setMovingTarget($movTo->x, $movTo->y, $movTo->z, $this->speedMultiplier);
--$this->selfCounter;
if($this->selfCounter <= 0 && $ai->entity->distanceSquared($movTo) < 9){
$this->createBaby($ai, $movTo);
}
}
public function createBaby(EntityAI $ai, Entity $entpar2){
/**
* @var Animal $baby
@ -45,20 +44,20 @@ class TaskMate extends TaskBase
$baby = $ai->entity->breed();
//this.theAnimal.setGrowingAge(6000); TODO growing age?
//this.targetMate.setGrowingAge(6000);
$ai->entity->loveTimeout = 6000;
$entpar2->loveTimeout = 6000;
$ai->entity->resetInLove();
$entpar2->resetInLove();
$baby->setAge(-24000);
}
public function findMate(EntityAI $ai){
$distance = 8.0*8.0;
$distance = 8.0 * 8.0;
$minDist = $distance; //TODO check bb intersection?
$matedEID = null;
foreach($ai->entity->level->entitiesInLove as $eid => $_){
$e = $ai->entity->level->entityList[$eid] ?? false;
if($e instanceof Entity){
@ -71,7 +70,7 @@ class TaskMate extends TaskBase
}
return $matedEID;
}
public function canBeExecuted(EntityAI $ai)
{
return $ai->entity->isInLove() && ($this->targetMateID = $this->findMate($ai)) != null;

View file

@ -3,12 +3,12 @@
class TaskPanic extends TaskBase
{
protected $randX = 2, $randZ = 2;
public $speedMultiplier;
public function __construct($speedMultiplier){
$this->speedMultiplier = $speedMultiplier;
}
public function onStart(EntityAI $ai)
{
$this->selfCounter = 60;
@ -20,16 +20,16 @@ class TaskPanic extends TaskBase
$ai->entity->inPanic = false;
$this->reset();
}
public function regenerateRandXZ(){
$this->randX = (mt_rand(0, 1) ? -1 : 1);
$this->randZ = (mt_rand(0, 1) ? -1 : 1);
}
public function reset(){
$this->randX = $this->randZ = 2;
}
public function onUpdate(EntityAI $ai)
{
--$this->selfCounter;
@ -42,6 +42,5 @@ class TaskPanic extends TaskBase
return $ai->entity instanceof Animal && $ai->entity->inPanic && $ai->entity->knockbackTime <= 0;
}
}
}

View file

@ -7,7 +7,7 @@ class TaskRandomWalk extends TaskBase
public function __construct($speedMultiplier){
$this->speedMultiplier = $speedMultiplier;
}
public function onStart(EntityAI $ai)
{
$this->x = mt_rand(-1, 1);
@ -30,7 +30,7 @@ class TaskRandomWalk extends TaskBase
$this->reset();
return false; //TODO Better way: block movement
}
--$this->selfCounter;
$ai->mobController->setMovingOffset($this->x, 0, $this->z, $this->speedMultiplier);
}
@ -40,8 +40,7 @@ class TaskRandomWalk extends TaskBase
if(($ai->entity instanceof Creeper && $ai->entity->isIgnited()) || $ai->entity->hasPath() || $ai->isStarted("TaskTempt") || $ai->isStarted("TaskAttackPlayer") || $ai->isStarted("TaskRangedAttack")) {
return false;
} // i really need mutexBits
return !$ai->entity->inPanic && !$ai->isStarted("TaskMate") && !$ai->isStarted("TaskEatTileGoal") && !$ai->isStarted("TaskLookAround") && !$ai->isStarted("TaskFollowParent") && !$ai->isStarted("TaskLookAtPlayer") && mt_rand(0, 120) == 0;
return !$ai->entity->inPanic && !$ai->isStarted("TaskMate") && !$ai->isStarted("TaskEatTileGoal") && !$ai->isStarted("TaskLookAround") && !$ai->isStarted("TaskFollowParent") && !$ai->isStarted("TaskLookAtPlayer") && mt_rand(0, 120) == 0;
}
}
}

View file

@ -7,10 +7,10 @@ class TaskRangedAttack extends \TaskBase
public $seenTicks = 0;
public function __construct($speed, $range){
$this->speedMultiplier = $speed;
$this->rangeSquared = $range*$range;
$this->rangeSquared = $range * $range;
$this->server = ServerAPI::request();
}
public function onStart(EntityAI $ai)
{
$this->selfCounter = 1;
@ -20,7 +20,7 @@ class TaskRangedAttack extends \TaskBase
public function onEnd(EntityAI $ai)
{
$ai->entity->target = false;
}
public function onUpdate(EntityAI $ai)
@ -36,24 +36,23 @@ class TaskRangedAttack extends \TaskBase
}else{
$this->seenTicks = 0;
}
$dist = $ai->entity->distanceSquared($ai->entity->target);
if($dist > 100 || $this->seenTicks < 20){
$ai->mobController->setMovingTarget($ai->entity->target->x, $ai->entity->target->y, $ai->entity->target->z, $this->speedMultiplier);
}else{
$ai->mobController->headYawIsYaw = true;
}
$ai->mobController->setLookPosition($ai->entity->target->x, $ai->entity->target->y + 0.12, $ai->entity->target->z, 10, $ai->entity->getVerticalFaceSpeed());
if($this->attackCounter <= 0 && $this->seenTicks > 0){
$this->rangedAttack($ai->entity, $ai->entity->target);
$this->attackCounter = 60;
}
}
public function rangedAttack($selfEntity, $target){
$d = [
"x" => $selfEntity->x,
@ -88,8 +87,7 @@ class TaskRangedAttack extends \TaskBase
$this->server->api->entity->spawnToAll($arrow);
}
}
public function isTargetValid(EntityAI $ai){
$e = $ai->entity;
if($e->target instanceof Entity && !$e->target->closed && !$e->target->dead){
@ -97,11 +95,11 @@ class TaskRangedAttack extends \TaskBase
$xDiff = ($t->x - $e->x);
$yDiff = ($t->y - $e->y);
$zDiff = ($t->z - $e->z);
return ($xDiff*$xDiff + $yDiff*$yDiff + $zDiff*$zDiff) <= $this->rangeSquared;
return ($xDiff * $xDiff + $yDiff * $yDiff + $zDiff * $zDiff) <= $this->rangeSquared;
}
return false;
}
public function tryTargeting(EntityAI $ai){
$e = $ai->entity;
if($e->target instanceof Entity){
@ -109,21 +107,20 @@ class TaskRangedAttack extends \TaskBase
$xDiff = ($t->x - $e->x);
$yDiff = ($t->y - $e->y);
$zDiff = ($t->z - $e->z);
if(($xDiff*$xDiff + $yDiff*$yDiff + $zDiff*$zDiff) <= $this->rangeSquared){
if(($xDiff * $xDiff + $yDiff * $yDiff + $zDiff * $zDiff) <= $this->rangeSquared){
return true;
}
}
$closestTarget = $e->closestPlayerToAttackDist <= $this->rangeSquared ? $e->level->entityList[$e->closestPlayerToAttackEID] : null;
if($closestTarget != null){
$e->target = $closestTarget; //TODO dont save entity object ?
return true;
}
return false;
}
public function canBeExecuted(EntityAI $ai)
{
return $this->tryTargeting($ai);

View file

@ -9,7 +9,7 @@ class TaskSwimming extends TaskBase
public function onEnd(EntityAI $ai)
{
}
public function onUpdate(EntityAI $ai)
@ -18,12 +18,12 @@ class TaskSwimming extends TaskBase
$this->reset();
return;
}
if(lcg_value() < 0.8){ #1.5.2 method
$ai->mobController->setJumping(true);
}
}
public function canBeExecuted(EntityAI $ai)
{
return $ai->entity->inWater || $ai->entity->inLava;

View file

@ -4,19 +4,19 @@ class TaskTempt extends TaskBase
{
public function __construct($speed){
$this->speedMultiplier = $speed;
$this->targetDistance = 10*10;
$this->targetDistance = 10 * 10;
}
public function onStart(EntityAI $ai)
{
$this->selfCounter = 1;
}
public function onEnd(EntityAI $ai)
{
$ai->entity->target = false;
}
public function onUpdate(EntityAI $ai)
{
if(!$this->isTargetValid($ai) || $ai->entity->inPanic || $ai->isStarted("TaskMate")){
@ -24,22 +24,21 @@ class TaskTempt extends TaskBase
$this->onEnd($ai);
return false;
}
$target = $ai->entity->target;
$xdiff = ($target->x - $ai->entity->x);
$ydiff = ($target->y - $ai->entity->y);
$zdiff = ($target->z - $ai->entity->z);
$dist = $xdiff*$xdiff + $ydiff*$ydiff + $zdiff*$zdiff;
$dist = $xdiff * $xdiff + $ydiff * $ydiff + $zdiff * $zdiff;
$ai->mobController->setLookPosition($target->x, $target->y + $target->getEyeHeight(), $target->z, 30, $ai->entity->getVerticalFaceSpeed());
if($dist >= 6.25){
$ai->mobController->setMovingTarget($target->x, $target->y, $target->z, $this->speedMultiplier);
}else{
$ai->mobController->headYawIsYaw = true;
}
}
public function isTargetValid(EntityAI $ai){
$e = $ai->entity;
if($e->target instanceof Entity && !$e->target->closed && $e->isFood($e->target->player->getHeldItem()->id)){
@ -47,16 +46,16 @@ class TaskTempt extends TaskBase
$xDiff = ($t->x - $e->x);
$yDiff = ($t->y - $e->y);
$zDiff = ($t->z - $e->z);
return ($xDiff*$xDiff + $yDiff*$yDiff + $zDiff*$zDiff) <= $this->targetDistance;
return ($xDiff * $xDiff + $yDiff * $yDiff + $zDiff * $zDiff) <= $this->targetDistance;
}
return false;
}
public function canBeExecuted(EntityAI $ai)
{
return !$ai->entity->inPanic && !$ai->isStarted("TaskMate") && $this->tryTargeting($ai);
}
public function tryTargeting(EntityAI $ai){
$e = $ai->entity;
if($e->target instanceof Entity){
@ -64,13 +63,13 @@ class TaskTempt extends TaskBase
$xDiff = ($t->x - $e->x);
$yDiff = ($t->y - $e->y);
$zDiff = ($t->z - $e->z);
if(($xDiff*$xDiff + $yDiff*$yDiff + $zDiff*$zDiff) <= $this->targetDistance){
if(($xDiff * $xDiff + $yDiff * $yDiff + $zDiff * $zDiff) <= $this->targetDistance){
return true;
}
}
$closestTarget = $e->closestPlayerThatCanFeedDist <= $this->targetDistance ? $e->level->entityList[$e->closestPlayerThatCanFeedEID] : null;
if($closestTarget != null){
$e->target = $closestTarget; //TODO dont save entity object ?
return true;

View file

@ -10,7 +10,7 @@ class Chicken extends Animal{
$this->setHealth($this->data["Health"] ?? 4, "generic");
$this->setName('Chicken');
$this->setSpeed(0.25);
$this->ai->addTask(new TaskRandomWalk(1.0));
$this->ai->addTask(new TaskLookAtPlayer(6));
$this->ai->addTask(new TaskPanic(1.5));
@ -23,27 +23,27 @@ class Chicken extends Animal{
public function isFood($id){
return $id === PUMPKIN_SEEDS || $id === MELON_SEEDS || $id === BEETROOT_SEEDS || $id === WHEAT_SEEDS;
}
public function updateEntityMovement(){
parent::updateEntityMovement();
if(!$this->onGround && $this->speedY < 0) $this->speedY *= 0.6;
if($this->timeUntilEgg-- <= 0 && !$this->isBaby()){
$this->dropAnEgg();
$this->timeUntilEgg = mt_rand(0,6000) + 6000;
}
}
public function fall(){} //chickens have no fall dmg?
public function dropAnEgg(){
if($this->closed){
return;
}
ServerAPI::request()->api->entity->drop(new Position($this->x + 0.5, $this->y, $this->z + 0.5, $this->level), BlockAPI::getItem(EGG, 0, 1));
}
public function getDrops(){
return $this->isBaby() ? parent::getDrops() : [
[FEATHER, 0, mt_rand(0,2)],

View file

@ -17,11 +17,11 @@ class Cow extends Animal{
$this->ai->addTask(new TaskMate(1.0));
$this->ai->addTask(new TaskFollowParent(1.1));
}
public function isFood($id){
return $id === WHEAT;
}
public function interactWith(Entity $e, $action){
if($e->isPlayer() && $action === InteractPacket::ACTION_HOLD){
$slot = $e->player->getHeldItem();
@ -33,9 +33,9 @@ class Cow extends Animal{
}
parent::interactWith($e, $action);
}
public function getDrops(){
return $this->isBaby() ? parent::getDrops() : [
return $this->isBaby() ? parent::getDrops() : [
[LEATHER, 0, mt_rand(0,2)],
[($this->fire > 0 ? STEAK : BEEF), 0, mt_rand(0, 3)]
];

View file

@ -1,7 +1,8 @@
<?php
class Pig extends Animal implements Rideable{
const TYPE = MOB_PIG;
public function __construct(Level $level, $eid, $class, $type = 0, $data = []){
$this->setSize(0.9, 0.9);
parent::__construct($level, $eid, $class, $type, $data);
@ -9,7 +10,7 @@ class Pig extends Animal implements Rideable{
$this->server = ServerAPI::request();
$this->setName("Pig");
$this->setSpeed(0.25);
$this->ai->addTask(new TaskRandomWalk(1.0));
$this->ai->addTask(new TaskLookAtPlayer(6));
$this->ai->addTask(new TaskPanic(1.5));
@ -25,18 +26,18 @@ class Pig extends Animal implements Rideable{
public function isSaddled(){
return (boolean) $this->getState();
}
/**
* @param boolean $value
*/
public function setSaddled($value = null){
$this->setState($value === null ? !$this->getState() : $value);
}
public function canRide($e){
return $this->isSaddled() && $this->linkedEntity == 0 && $e->linkedEntity == 0;
}
public function updateEntityMovement(){
/*if($this->linkedEntity != 0){
$e = $this->level->entityList[$this->linkedEntity] ?? false;
@ -47,10 +48,10 @@ class Pig extends Animal implements Rideable{
$this->yaw = $e->headYaw;
}
}*/
parent::updateEntityMovement();
}
public function interactWith(Entity $e, $action)
{
if($e->isPlayer() && $action === InteractPacket::ACTION_HOLD){
@ -59,7 +60,7 @@ class Pig extends Animal implements Rideable{
$e->setRiding($this);
return true;
}
if($slot->getID() === SADDLE){
if(!$this->isSaddled()){
$e->player->removeItem($slot->getID(), 0, 1);
@ -67,15 +68,15 @@ class Pig extends Animal implements Rideable{
}
return true; //avoid further interactions
}
}
return parent::interactWith($e, $action);
}
public function isFood($id){
return $id === POTATO || $id === CARROT || $id === BEETROOT;
}
public function getDrops(){
return $this->isBaby() ? parent::getDrops() : ($this->isSaddled() ? [
[($this->fire > 0 ? COOKED_PORKCHOP : RAW_PORKCHOP), 0, mt_rand(0,2)],

View file

@ -3,7 +3,7 @@
class Sheep extends Animal{
public $color;
const TYPE = MOB_SHEEP;
function __construct(Level $level, $eid, $class, $type = 0, $data = []){
$this->setSize(0.9, 1.3);
parent::__construct($level, $eid, $class, $type, $data);
@ -12,7 +12,7 @@ class Sheep extends Animal{
$this->data["Sheared"] = $this->data["Sheared"] ?? 0;
$this->data["Color"] = $this->data["Color"] ?? $this->sheepColor();
$this->setSpeed(0.25);
$this->ai->addTask(new TaskRandomWalk(1.0));
$this->ai->addTask(new TaskLookAtPlayer(6));
$this->ai->addTask(new TaskPanic(1.5));
@ -23,14 +23,14 @@ class Sheep extends Animal{
$this->ai->addTask(new TaskMate(1.0));
$this->ai->addTask(new TaskFollowParent(1.0));
}
public function createSaveData(){
$data = parent::createSaveData();
$data["Color"] = @$this->data["Color"];
$data["Sheared"] = @$this->data["Sheared"];
return $data;
}
public function eatGrass(){
$this->setSheared(0);
if($this->isBaby()){
@ -39,24 +39,24 @@ class Sheep extends Animal{
$this->setAge($age);
}
}
public function setSheared($v = null){
$this->data["Sheared"] = $v === null ? !$this->isSheared() : $v;
$this->updateMetadata();
}
public function isSheared(){
return $this->data["Sheared"];
}
public function getColor(){
return $this->data["Color"]; //color === 16 -> color = 0, color === 17 -> color = 1 ...
}
public function switchColorMeta($meta){
return abs($meta - 15);
}
public function setColor($meta){
$this->data["Color"] = $meta;
}
@ -65,11 +65,11 @@ class Sheep extends Animal{
[WOOL, $this->getColor(), 1]
];
}
public function isFood($id){
return $id === WHEAT;
}
public function interactWith(Entity $e, $action){
if($e->isPlayer() && $action === InteractPacket::ACTION_HOLD){
$slot = $e->player->getHeldItem();
@ -79,7 +79,7 @@ class Sheep extends Animal{
$this->setSheared(1);
$speedX = (lcg_value() * 0.2 - 0.1) + (lcg_value() - lcg_value()) * 0.1;
$speedZ = (lcg_value() * 0.2 - 0.1) + (lcg_value() - lcg_value()) * 0.1;
$speedY = 0.2 + (lcg_value()) * 0.05;
$speedY = 0.2 + (lcg_value()) * 0.05;
$this->server->api->entity->dropRawPos($this->level, $this->x, $this->y + 1, $this->z, BlockAPI::getItem(WOOL, $this->getColor(), mt_rand(1, 3)), $speedX, $speedY, $speedZ);
if($slot->getMetadata() >= $slot->getMaxDurability()){
$e->player->removeItem($slot->getID(), $slot->getMetadata(), $slot->count, true);
@ -90,7 +90,7 @@ class Sheep extends Animal{
return true;
}elseif($slot->getID() === DYE){
$this->setColor($this->switchColorMeta($slot->getMetadata()));
if(($e->player->gamemode & 0x01) === SURVIVAL){
$e->player->removeItem($slot->getID(), $slot->getMetadata(), 1, true);
}
@ -98,7 +98,7 @@ class Sheep extends Animal{
}
return parent::interactWith($e, $action);
}
public function getMetadata(){
$d = parent::getMetadata();
if(!isset($this->data["Sheared"])){
@ -107,7 +107,7 @@ class Sheep extends Animal{
$d[16]["value"] = ($this->data["Sheared"] << 4) | ($this->getColor() & 0x0F);
return $d;
}
public function sheepColor(){ //a method from 0.8.1
$c = mt_rand(0,100);
if($c <= 4){

View file

@ -1,4 +1,5 @@
<?php
class Creeper extends Monster{
const TYPE = MOB_CREEPER;
const EXPL_TIME = 30;
@ -12,30 +13,28 @@ class Creeper extends Monster{
$this->ignited = 0;
$this->setSpeed(0.25);
$this->timeUntilExplode = $this->isIgnited() ? self::EXPL_TIME : 0;
$this->ai->addTask(new TaskRandomWalk(1.0));
$this->ai->addTask(new TaskAttackPlayer(1.25, 16));
$this->ai->addTask(new TaskLookAround());
$this->ai->addTask(new TaskSwimming());
}
public function getAttackDamage(){
return 0;
}
public function setIgnited($v = null){
$this->setState($v === null ? !$this->getState() : $v);
$this->setState($v === null ? !$this->getState() : $v);
}
/**
* @return boolean
*/
public function isIgnited(){
return $this->getState() > 0;
}
public function interactWith(Entity $e, $action){
if($e->isPlayer() && $action === InteractPacket::ACTION_HOLD){
$slot = $e->player->getHeldItem();
@ -51,12 +50,12 @@ class Creeper extends Monster{
}
return parent::interactWith($e, $action);
}
public function ignite(){
$this->setIgnited(1);
$this->timeUntilExplode = self::EXPL_TIME;
}
public function attackEntity($entity, $distance){
if(Utils::distance_noroot($entity, $this) <= 49 && !$this->isIgnited() && $this->ai->canSee($entity)){
$this->ignite();
@ -88,7 +87,7 @@ class Creeper extends Monster{
$this->close();
$explosion->explode();
}
public function getDrops(){
return [
[GUNPOWDER, 0, mt_rand(0,2)]

View file

@ -1,4 +1,5 @@
<?php
class PigZombie extends Monster{ //TODO extends zombie
const TYPE = MOB_PIGMAN;
function __construct(Level $level, $eid, $class, $type = 0, $data = []){

View file

@ -1,4 +1,5 @@
<?php
class Skeleton extends Monster{
const TYPE = MOB_SKELETON;
function __construct(Level $level, $eid, $class, $type = 0, $data = []){
@ -8,31 +9,31 @@ class Skeleton extends Monster{
$this->setName("Skeleton");
$this->ai->removeTask("TaskAttackPlayer");
$this->setSpeed(0.25);
$this->ai->addTask(new TaskRandomWalk(1.0));
$this->ai->addTask(new TaskLookAround());
$this->ai->addTask(new TaskSwimming());
$this->ai->addTask(new TaskRangedAttack(1.0, 16));
}
public function getAttackDamage(){
return 0;
}
public function updateBurning(){
if($this->fire > 0 || !$this->level->isDay() || $this->inWater){
return false;
}
//bad fix for burning in water
[$block, $meta] = $this->level->level->getBlock((int)$this->x, (int)$this->y, (int)$this->z);
[$block, $meta] = $this->level->level->getBlock((int) $this->x, (int) $this->y, (int) $this->z);
if($block == WATER || $block == STILL_WATER){
$v16 = ((int)$this->y + 1) - LiquidBlock::getPercentAir($meta);
if($this->boundingBox->intersectsWith(new AxisAlignedBB((int)$this->x, (int)$this->y, (int)$this->z, (int)$this->x + 1, $v16, (int)$this->z + 1))){
$v16 = ((int) $this->y + 1) - LiquidBlock::getPercentAir($meta);
if($this->boundingBox->intersectsWith(new AxisAlignedBB((int) $this->x, (int) $this->y, (int) $this->z, (int) $this->x + 1, $v16, (int) $this->z + 1))){
return false;
}
}
for($y = (int)$this->y; $y < 129; $y++){
for($y = (int) $this->y; $y < 129; $y++){
$block = $this->level->level->getBlockID($this->x, $y, $this->z);
if(StaticBlock::getIsSolid($block)){
return false;
@ -49,12 +50,12 @@ class Skeleton extends Monster{
return false;
}
}
public function updateEntityMovement(){
$this->updateBurning();
return parent::updateEntityMovement();
}
public function getDrops(){
return [
[ARROW, 0, mt_rand(0,2)],

View file

@ -1,8 +1,9 @@
<?php
class Spider extends Monster{
const TYPE = MOB_SPIDER;
function __construct(Level $level, $eid, $class, $type = 0, $data = array()){
function __construct(Level $level, $eid, $class, $type = 0, $data = []){
$this->setSize(1.4, 0.9);
parent::__construct($level, $eid, $class, $type, $data);
$this->setHealth($this->data["Health"] ?? 8, "generic");
@ -11,35 +12,35 @@ class Spider extends Monster{
$this->ai->addTask(new TaskRandomWalk(1.2));
$this->ai->addTask(new TaskLookAround());
$this->ai->addTask(new TaskSwimming());
$this->ai->addTask(new TaskAttackPlayer(1.2, 16));
$this->ai->addTask(new TaskAttackPlayer(1.2, 16));
}
public function getAttackDamage(){
return 2;
}
public function attackEntity($entity, $distance){
if($distance > 2.0 && $distance < 6.0){
if($this->onGround){
$diffX = $entity->x - $this->x;
$diffZ = $entity->z - $this->z;
$dist = sqrt($diffX*$diffX + $diffZ*$diffZ);
$this->speedX = $diffX / $dist*0.5*0.8 + $this->speedX*0.2;
$this->speedZ = $diffZ / $dist*0.5*0.8 + $this->speedZ*0.2;
$dist = sqrt($diffX * $diffX + $diffZ * $diffZ);
$this->speedX = $diffX / $dist * 0.5 * 0.8 + $this->speedX * 0.2;
$this->speedZ = $diffZ / $dist * 0.5 * 0.8 + $this->speedZ * 0.2;
$this->speedY = 0.4;
}
return false;
}else{
return parent::attackEntity($entity, $distance);
}
}
public function isOnLadder(){
return $this->isCollidedHorizontally;
}
public function getDrops(){
return [
[STRING, 0, mt_rand(0,2)]

View file

@ -1,37 +1,38 @@
<?php
class Zombie extends Monster{
const TYPE = MOB_ZOMBIE;
function __construct(Level $level, $eid, $class, $type = 0, $data = array()){
function __construct(Level $level, $eid, $class, $type = 0, $data = []){
$this->setSize(0.6, 1.85);
parent::__construct($level, $eid, $class, $type, $data);
$this->setHealth($this->data["Health"] ?? 12, "generic");
$this->setName("Zombie");
$this->setSpeed(0.23);
$this->ai->addTask(new TaskRandomWalk(1.0));
$this->ai->addTask(new TaskLookAround());
$this->ai->addTask(new TaskSwimming());
$this->ai->addTask(new TaskAttackPlayer(1.0, 16));
}
public function getArmorValue(){
return 2;
}
public function updateBurning(){
if($this->fire > 0 || !$this->level->isDay() || $this->inWater){
return false;
}
//bad fix for burning in water
[$block, $meta] = $this->level->level->getBlock((int)$this->x, (int)$this->y, (int)$this->z);
[$block, $meta] = $this->level->level->getBlock((int) $this->x, (int) $this->y, (int) $this->z);
if($block == WATER || $block == STILL_WATER){
$v16 = ((int)$this->y + 1) - LiquidBlock::getPercentAir($meta);
if($this->boundingBox->intersectsWith(new AxisAlignedBB((int)$this->x, (int)$this->y, (int)$this->z, (int)$this->x + 1, $v16, (int)$this->z + 1))){
$v16 = ((int) $this->y + 1) - LiquidBlock::getPercentAir($meta);
if($this->boundingBox->intersectsWith(new AxisAlignedBB((int) $this->x, (int) $this->y, (int) $this->z, (int) $this->x + 1, $v16, (int) $this->z + 1))){
return false;
}
}
for($y = (int)$this->y; $y < 129; $y++){
for($y = (int) $this->y; $y < 129; $y++){
$block = $this->level->level->getBlockID($this->x, $y, $this->z);
if(StaticBlock::getIsSolid($block)){
return false;
@ -48,7 +49,7 @@ class Zombie extends Monster{
return false;
}
}
public function getAttackDamage(){
return 4;
}
@ -57,7 +58,7 @@ class Zombie extends Monster{
$this->updateBurning();
return parent::updateEntityMovement();
}
public function getDrops(){
return [
[CARROT, 0, Utils::chance(0.83) ? 1 : 0],

View file

@ -3,7 +3,7 @@
class Arrow extends Entity{
const TYPE = OBJECT_ARROW;
const CLASS_TYPE = ENTITY_OBJECT;
public $shooterEID = 0;
public $xTile, $yTile, $zTile;
public $inTile, $inData;
@ -13,7 +13,7 @@ class Arrow extends Entity{
public $criticial = false;
public $groundTicks = 0;
public $shotByPlayer = false;
function __construct(Level $level, $eid, $class, $type = 0, $data = []){
parent::__construct($level, $eid, $class, $type, $data);
$this->gravity = 0.05;
@ -32,12 +32,12 @@ class Arrow extends Entity{
$this->yTile = $data["yTile"] ?? $this->yTile;
$this->zTile = $data["zTile"] ?? $this->zTile;
$this->shotByPlayer = $data["shotByPlayer"] ?? $this->shotByPlayer;
//$this->server->schedule(1210, array($this, "update")); //Despawn
}
public function createSaveData(){
$data = parent::createSaveData();
$data["inTile"] = $this->inTile;
$data["inData"] = $this->inData;
$data["inGround"] = $this->inGround;
@ -57,7 +57,7 @@ class Arrow extends Entity{
$pk->pitch = $this->pitch;
$this->server->api->player->broadcastPacket($this->level->players, $pk);
}
public function shoot($d, $d1, $d2, $f, $f1){ //original name from 0.8.1 IDA decompilation, var names are taken from b1.7.3
$f2 = sqrt($d * $d + $d1 * $d1 + $d2 * $d2);
$d /= $f2;
@ -79,7 +79,7 @@ class Arrow extends Entity{
//$this->update();
$this->groundTicks = 0;
}
public function update($now){
$this->lastX = $this->x;
$this->lastY = $this->y;
@ -101,40 +101,39 @@ class Arrow extends Entity{
$this->fire -= 4;
if($this->fire <= 0) $this->fire = 0;
}
if($this->fire <= 0){
$this->updateMetadata();
}
}
if($this->handleLavaMovement()){
if(!$this->isImmuneToFire){
$this->harm(4, "fire");
$oldOnFire = $this->fire;
if($oldOnFire < 20*30) $this->fire = 20*30; //30 seconds
if($oldOnFire < 20 * 30) $this->fire = 20 * 30; //30 seconds
}
}
if($this->isInVoid()){
$this->outOfWorld();
}
//Entity::update end
if($this->lastPitch == $this->lastYaw && $this->lastYaw == 0){
$v1 = sqrt($this->speedX*$this->speedX + $this->speedZ*$this->speedZ);
$v1 = sqrt($this->speedX * $this->speedX + $this->speedZ * $this->speedZ);
$this->lastYaw = $this->yaw = atan2($this->speedX, $this->speedZ) * 180 / M_PI;
$this->lastPitch = $this->pitch = atan2($this->speedY, $v1) * 180 / M_PI;
}
if($this->shake > 0){
--$this->shake;
}
if($this->inGround){
[$blockID, $blockMeta] = $this->level->level->getBlock($this->xTile, $this->yTile, $this->zTile);
$this->speedZ = $this->speedX = $this->speedY = 0;
if($blockID == $this->inTile && $blockMeta == $this->inData){
++$this->groundTicks;
if($this->groundTicks >= 1200){ //TODO customizeable?
@ -147,7 +146,7 @@ class Arrow extends Entity{
$this->speedZ *= lcg_value() * 0.2;
$this->groundTicks = $this->airTicks = 0;
}
}else{
++$this->airTicks;
$start = new Vector3($this->x, $this->y, $this->z);
@ -162,42 +161,40 @@ class Arrow extends Entity{
}else{
$end = new Vector3($this->x + $this->speedX, $this->y + $this->speedY, $this->z + $this->speedZ);
}
$entities = $this->level->getEntitiesInAABB($this->boundingBox->addCoord($this->speedX, $this->speedY, $this->speedZ)->expand(1, 1, 1));
$bestDist = 0;
$bestEnt = null;
foreach($entities as $eid => $ent){
if($eid != $this->eid && $ent->isPickable() && ($eid != $this->shooterEID || $this->airTicks >= 5)){
$v12 = $ent->boundingBox->expand(0.3, 0.3, 0.3);
$v13 = $v12->calculateIntercept($start, $end);
if($v13 != null){
$dist = $start->distance($v13->hitVector);
if($dist < $bestDist || $bestDist == 0){
$bestEnt = $ent;
}
}
}
}
if($bestEnt != null){
$v4 = MovingObjectPosition::fromEntity($bestEnt);
}
if($v4 != null){
if($v4->entityHit != null){
$v49 = sqrt($this->speedY*$this->speedY + $this->speedX*$this->speedX + $this->speedZ*$this->speedZ);
$damage = ceil($v49+$v49);
$v49 = sqrt($this->speedY * $this->speedY + $this->speedX * $this->speedX + $this->speedZ * $this->speedZ);
$damage = ceil($v49 + $v49);
if($this->criticial){
$damage += mt_rand(0, $damage / 2 + 1);
}
if($v4->entityHit->harm($damage, $this->eid)){
//vanilla seems to increase arrow count if $v4->entity is mob
$this->close();
@ -213,36 +210,36 @@ class Arrow extends Entity{
$this->xTile = $v4->blockX;
$this->yTile = $v4->blockY;
$this->zTile = $v4->blockZ;
[$this->inTile, $this->inData] = $this->level->level->getBlock($this->xTile, $this->yTile, $this->zTile);
$this->speedX = $v4->hitVector->x - $this->x;
$this->speedY = $v4->hitVector->y - $this->y;
$this->speedZ = $v4->hitVector->z - $this->z;
$v21 = sqrt($this->speedX*$this->speedX + $this->speedY*$this->speedY + $this->speedZ*$this->speedZ);
$v21 = sqrt($this->speedX * $this->speedX + $this->speedY * $this->speedY + $this->speedZ * $this->speedZ);
if($v21 != 0){
$this->x -= $this->speedX / $v21 * 0.05;
$this->y -= $this->speedY / $v21 * 0.05;
$this->z -= $this->speedZ / $v21 * 0.05;
}
$this->inGround = true;
$this->shake = 7;
$this->criticial = false;
}
}
$this->x += $this->speedX;
$this->y += $this->speedY;
$this->z += $this->speedZ;
$v21 = sqrt($this->speedX*$this->speedX + $this->speedZ*$this->speedZ);
$v21 = sqrt($this->speedX * $this->speedX + $this->speedZ * $this->speedZ);
$this->yaw = atan2($this->speedX, $this->speedZ) * 180 / M_PI;
$this->pitch = atan2($this->speedY, $v21) * 180 / M_PI;
$this->pitch = $this->lastPitch + ($this->pitch - $this->lastPitch) * 0.2;
$this->yaw = $this->lastYaw + ($this->yaw - $this->lastYaw) * 0.2;
$v24 = $this->inWater ? 0.8 : 0.99;
$this->speedX *= $v24;
$this->speedY *= $v24;
@ -252,14 +249,12 @@ class Arrow extends Entity{
$v7 = $this->width / 2;
$v8 = $this->height;
$this->boundingBox->setBounds($this->x - $v7, $this->y - $this->yOffset /*+ $this->ySize*/, $this->z - $v7, $this->x + $v7, $this->y - $this->yOffset + $v8 /*+ $this->ySize*/, $this->z + $v7);
$this->doBlocksCollision();
}
}
public function spawn($player){
if($this->type === OBJECT_ARROW){
$pk = new AddEntityPacket;
@ -268,7 +263,7 @@ class Arrow extends Entity{
$pk->x = $this->x;
$pk->y = $this->y;
$pk->z = $this->z;
$pk->did = 1;
$pk->did = 1;
$pk->speedX = $this->speedX;
$pk->speedY = $this->speedY;
$pk->speedZ = $this->speedZ;

View file

@ -3,9 +3,9 @@
class FallingSand extends Entity{
const TYPE = FALLING_SAND;
const CLASS_TYPE = ENTITY_FALLING;
public $fallTime = 0;
public function __construct($level, $eid, $class, $type = 0, $data = []){
parent::__construct($level, $eid, $class, $type, $data);
$this->setHealth(PHP_INT_MAX, "generic");
@ -15,14 +15,14 @@ class FallingSand extends Entity{
$this->hasGravity = true;
$this->gravity = 0.04;
}
public function isPickable(){
return !$this->dead;
}
public function update($now){
if($this->closed) return;
if( $this->data["Tile"] == AIR) {
$this->close();
return;
@ -33,15 +33,15 @@ class FallingSand extends Entity{
++$this->fallTime;
$this->speedY -= 0.04;
$this->move($this->speedX, $this->speedY, $this->speedZ);
$this->speedX *= 0.98;
$this->speedY *= 0.98;
$this->speedZ *= 0.98;
$x = floor($this->x);
$y = floor($this->y);
$z = floor($this->z);
if($this->onGround){
$this->speedX *= 0.7;
$this->speedZ *= 0.7;

View file

@ -4,10 +4,10 @@ class ItemEntity extends Entity{
const TYPE = ENTITY_ITEM_TYPE;
const CLASS_TYPE = ENTITY_ITEM;
public static $searchRadiusX = 0.5, $searchRadiusY = 0.0, $searchRadiusZ = 0.5;
public $meta, $stack, $itemID;
public function __construct(Level $level, $eid, $class, $type = 0, $data = array())
public function __construct(Level $level, $eid, $class, $type = 0, $data = [])
{
parent::__construct($level, $eid, $class, $type, $data);
$this->setSize(0.25, 0.25);
@ -27,21 +27,21 @@ class ItemEntity extends Entity{
$this->delayBeforePickup = 40; //in vanilla it is 0 by default
$this->stepHeight = 0;
}
public function counterUpdate(){
parent::counterUpdate();
if($this->delayBeforePickup > 0) --$this->delayBeforePickup;
}
public function searchForOtherItemsNearby(){
$ents = $this->level->getEntitiesInAABBOfType($this->boundingBox->expand(self::$searchRadiusX, self::$searchRadiusY, self::$searchRadiusZ), ENTITY_ITEM);
foreach($ents as $e){
$this->tryCombining($e);
}
}
public function spawn($player)
{
$pk = new AddItemEntityPacket();
@ -55,7 +55,7 @@ class ItemEntity extends Entity{
$pk->item = BlockAPI::getItem($this->itemID, $this->meta, $this->stack);
$pk->metadata = $this->getMetadata();
$player->dataPacket($pk);
$pk = new SetEntityMotionPacket();
$pk->eid = $this->eid;
$pk->speedX = $this->speedX;
@ -63,16 +63,15 @@ class ItemEntity extends Entity{
$pk->speedZ = $this->speedZ;
$player->dataPacket($pk);
}
public function tryCombining(Entity $another){
if($another->eid == $this->eid) return false;
if(!$another->closed && !$this->closed){
if($another->itemID == $this->itemID && $another->meta == $this->meta){
if(($another->stack + $this->stack) > 64) return false; //TODO dynamic stack size
$another->stack += $this->stack;
$another->age = min($this->age, $another->age);
$this->close();
@ -84,29 +83,29 @@ class ItemEntity extends Entity{
$xFloor = floor($x);
$yFloor = floor($y);
$zFloor = floor($z);
$id = $this->level->level->getBlockID($xFloor, $yFloor, $zFloor);
if(StaticBlock::getIsSolid($id)){
$xDiff = $x - $xFloor;
$id = $this->level->level->getBlockID($xFloor - 1, $yFloor, $zFloor);
$xNeg = StaticBlock::getIsSolid($id);
$id = $this->level->level->getBlockID($xFloor + 1, $yFloor, $zFloor);
$xPos = StaticBlock::getIsSolid($id);
$id = $this->level->level->getBlockID($xFloor, $yFloor - 1, $zFloor);
$yNeg = StaticBlock::getIsSolid($id);
$id = $this->level->level->getBlockID($xFloor, $yFloor + 1, $zFloor);
$yPos = StaticBlock::getIsSolid($id);
$id = $this->level->level->getBlockID($xFloor - 1, $yFloor, $zFloor - 1);
$zNeg = StaticBlock::getIsSolid($id);
$zPos = $this->level->level->getBlockID($xFloor + 1, $yFloor, $zFloor + 1);
if($xNeg || $xDiff >= 9999.0){ //TODO not needed check?
$v15 = 9999.0;
$v16 = -1;
@ -114,22 +113,22 @@ class ItemEntity extends Entity{
$v15 = $xDiff;
$v16 = 0;
}
if(!$xPos){
$v17 = 1 - $xDiff;
if($v17 < $v15){
$v15 = $v17;
$v16 = 1;
}
}
$yDiff = $y - $yFloor;
if(!$yNeg && $yDiff < $v15){
$v15 = $yDiff;
$v16 = 2;
}
if(!$yPos){
$v19 = 1.0 - $yDiff;
if($v19 < $v15){
@ -137,17 +136,17 @@ class ItemEntity extends Entity{
$v16 = 3;
}
}
$zDiff = $z - $zFloor;
if(!$zNeg && $zDiff < $v15){
$v15 = $zDiff;
$v16 = 4;
}
if(!StaticBlock::getIsSolid($zPos) && ((1.0 - $zDiff) < $v15)){
$v16 = 5;
}
$v21 = lcg_value() * 0.2 + 0.1;
switch($v16){
case 0:
@ -166,24 +165,24 @@ class ItemEntity extends Entity{
$this->speedZ = $v21;
return 0;
}
return 0;
}
}
public function handleWaterMovement(){
return $this->level->handleMaterialAcceleration($this->boundingBox, 0, $this);
}
public function updateEntityMovement(){
//TODO custom update( method
$this->speedY -= 0.04;
//$this->noClip = false;
$this->checkInTile($this->x, $this->y, $this->z);
$this->move($this->speedX, $this->speedY, $this->speedZ);
$var1 = (int)$this->x != (int)$this->lastX || (int)$this->y != (int)$this->lastY || (int)$this->z != (int)$this->lastZ;
$var1 = (int) $this->x != (int) $this->lastX || (int) $this->y != (int) $this->lastY || (int) $this->z != (int) $this->lastZ;
if($var1 || $this->counter % 25 == 0){
$blockIDAt = $this->level->level->getBlockID(floor($this->x), floor($this->y), floor($this->z));
if($blockIDAt == LAVA || $blockIDAt == STILL_LAVA){
@ -191,30 +190,30 @@ class ItemEntity extends Entity{
$this->speedX = (lcg_value() - lcg_value()) * 0.2;
$this->speedZ = (lcg_value() - lcg_value()) * 0.2;
}
//$this->searchForOtherItemsNearby(); //not in vanilla 0.8.1
}
if($this->closed) return;
$friction = 0.98;
if($this->onGround){
$friction = 0.588;
$v3 = $this->level->level->getBlockID($this->x, floor($this->boundingBox->minY) - 1, $this->z);
if($v3 > 0) $friction = StaticBlock::getSlipperiness($v3);
}
$this->speedX *= $friction;
$this->speedY *= 0.98;
$this->speedZ *= $friction;
if($this->onGround) $this->speedY *= -0.5;
if(abs($this->speedX) < self::MIN_POSSIBLE_SPEED) $this->speedX = 0;
if(abs($this->speedZ) < self::MIN_POSSIBLE_SPEED) $this->speedZ = 0;
if(abs($this->speedY) < self::MIN_POSSIBLE_SPEED) $this->speedY = 0;
++$this->age;
//TODO despawn after age >= 6000 ?;
//TODO despawn after age >= 6000 ?;
}
}

View file

@ -4,7 +4,7 @@ class Minecart extends Vehicle{
const TYPE = OBJECT_MINECART;
/**
* A minecart rotation matrix
* @var int[][][]
* @var int[][][]
*/
private static $matrix = [
[
@ -48,14 +48,14 @@ class Minecart extends Vehicle{
[1, 0, 0]
]
];
private $hurtTime = 0; //syncentdata 17 int
private $damage = 0; //syncentdata 19 float
private $minecartX = 0, $minecartY = 0, $minecartZ = 0;
private $turnProgress = 0;
public $isInReverse = false;
function __construct(Level $level, $eid, $class, $type = 0, $data = []){
parent::__construct($level, $eid, $class, $type, $data);
$this->canBeAttacked = true;
@ -67,76 +67,76 @@ class Minecart extends Vehicle{
$this->yOffset = $this->height / 2;
$this->stepHeight = 0;
}
public function isPickable(){
return !$this->dead;
}
public function getDrops(){
return [
[MINECART, 0, 1]
];
}
public function getPos($x, $y, $z){
$blockX = floor($x);
$blockY = floor($y);
$blockZ = floor($z);
if(RailBaseBlock::isRailBlock($this->level, $blockX, $blockY - 1, $blockZ)) --$blockY;
[$id, $meta] = $this->level->level->getBlock($blockX, $blockY, $blockZ);
if(RailBaseBlock::isRailID($id)){
if($id == POWERED_RAIL) $meta &= 7;
$mat = self::$matrix[$meta];
$v13 = 0;
$v15 = $blockX + 0.5 + $mat[0][0] * 0.5;
$v17 = $blockY + 0.5 + $mat[0][1] * 0.5;
$v19 = $blockZ + 0.5 + $mat[0][2] * 0.5;
$v21 = $blockX + 0.5 + $mat[1][0] * 0.5;
$v23 = $blockY + 0.5 + $mat[1][1] * 0.5;
$v25 = $blockZ + 0.5 + $mat[1][2] * 0.5;
$v27 = $v21 - $v15;
$v29 = ($v23 - $v17) * 2;
$v31 = $v25 - $v19;
if($v27 == 0){
$x = $blockX + 0.5;
$v13 = $z - $blockZ;
}else if($v31 == 0){
}elseif($v31 == 0){
$z = $blockZ + 0.5;
$v13 = $x - $blockX;
}else{
$v33 = $x - $v15;
$v35 = $z - $v19;
$v13 = ($v33*$v27 + $v35*$v31) * 2;
$v13 = ($v33 * $v27 + $v35 * $v31) * 2;
}
$x = $v15 + $v27 * $v13;
$y = $v17 + $v29 * $v13;
$z = $v19 + $v31 * $v13;
if($v29 < 0) ++$y;
if($v29 > 0) $y += 0.5;
return [$x, $y, $z];
}
return false;
}
public function moveAlongTrack($x, $y, $z, $maxSpeed, $boost, $id, $meta){
$this->fallDistance = 0;
$vec = $this->getPos($this->x, $this->y, $this->z);
$this->y = $y;
if($id == POWERED_RAIL) $meta &= 7;
if($meta >= 2 && $meta <= 5) $this->y = $y + 1;
switch($meta){
case 2:
$this->speedX -= $boost;
@ -151,53 +151,53 @@ class Minecart extends Vehicle{
$this->speedZ -= $boost;
break;
}
$mat = self::$matrix[$meta];
$matXDiff = $mat[1][0] - $mat[0][0];
$matZDiff = $mat[1][2] - $mat[0][2];
$matDiffTotal = sqrt($matXDiff*$matXDiff + $matZDiff*$matZDiff);
$matDiffTotal = sqrt($matXDiff * $matXDiff + $matZDiff * $matZDiff);
if(($this->speedZ * $matZDiff + $this->speedX * $matXDiff) < 0){
$matXDiff = -$matXDiff;
$matZDiff = -$matZDiff;
}
$speedTotal = sqrt($this->speedZ*$this->speedZ + $this->speedX*$this->speedX);
$speedTotal = sqrt($this->speedZ * $this->speedZ + $this->speedX * $this->speedX);
if($speedTotal > 2) $speedTotal = 2;
$this->speedX = ($speedTotal * $matXDiff) / $matDiffTotal;
$this->speedZ = ($speedTotal * $matZDiff) / $matDiffTotal;
if($this->linkedEntity != 0 && !$this->isRider){
$rider = $this->level->entityList[$this->linkedEntity] ?? false;
if($rider instanceof Entity && ($rider->isPlayer() || $rider->class == ENTITY_MOB)){
if($rider->moveForward > 0){
$v32 = sin($this->yaw * M_PI / 180);
$v33 = cos($this->yaw * M_PI / 180);
if($this->speedZ*$this->speedZ + $this->speedX*$this->speedX < 0.01){
$this->speedX -= $v32*0.1;
$this->speedZ += $v33*0.1;
if($this->speedZ * $this->speedZ + $this->speedX * $this->speedX < 0.01){
$this->speedX -= $v32 * 0.1;
$this->speedZ += $v33 * 0.1;
}
}
}
}
$v38 = ($x + 0.5) + ($mat[0][0] * 0.5);
$v39 = ($z + 0.5) + ($mat[0][2] * 0.5);
$v40 = (($x + 0.5) + ($mat[1][0] * 0.5)) - $v38;
$v41 = (($z + 0.5) + ($mat[1][2] * 0.5)) - $v39;
if($v40 == 0){
$v42 = $this->z - $z;
}else if($v41 == 0){
}elseif($v41 == 0){
$v42 = $this->x - $x;
}else{
$v44 = (($this->z - $v39) * $v41) + (($this->x - $v38) * $v40);
$v42 = $v44 + $v44;
}
$this->x = $v38 + ($v40 * $v42);
$this->z = $v39 + ($v41 * $v42);
$this->setPos($this->x, $this->y + $this->yOffset + 0.00001, $this->z);
$dx = $this->speedX;
$dz = $this->speedZ;
@ -205,55 +205,55 @@ class Minecart extends Vehicle{
$dx *= 0.75;
$dz *= 0.75;
}
if($dx < -$maxSpeed) $dx = -$maxSpeed;
else if($dx > $maxSpeed) $dx = $maxSpeed;
elseif($dx > $maxSpeed) $dx = $maxSpeed;
if($dz < -$maxSpeed) $dz = -$maxSpeed;
else if($dz > $maxSpeed) $dz = $maxSpeed;
elseif($dz > $maxSpeed) $dz = $maxSpeed;
$this->move($dx, 0, $dz);
if($mat[0][1]){
if((floor($this->x) - $x) == $mat[0][0] && (floor($this->z) - $z) == $mat[0][2]){
$this->setPos($this->x, $mat[0][1] + $this->y, $this->z);
}else if($mat[1][1]){
}elseif($mat[1][1]){
goto mat_1_1;
}
}else if($mat[1][1]){
}elseif($mat[1][1]){
mat_1_1:
if((floor($this->x) - $x) == $mat[1][0] && (floor($this->z) - $z) == $mat[1][2]){
$this->setPos($this->x, $mat[1][1] + $this->y, $this->z);
}
}
$this->applyNaturalSlowdown();
$vec2 = $this->getPos($this->x, $this->y, $this->z);
if($vec2 !== false && $vec !== false){
$yDiff = ($vec[1] - $vec2[1]) * 0.05;
$totalSpeed = sqrt($this->speedZ*$this->speedZ + $this->speedX*$this->speedX);
$totalSpeed = sqrt($this->speedZ * $this->speedZ + $this->speedX * $this->speedX);
if($totalSpeed > 0){
$this->speedX = ($this->speedX / $totalSpeed) * ($totalSpeed + $yDiff);
$this->speedZ = ($this->speedZ / $totalSpeed) * ($totalSpeed + $yDiff);
$this->speedZ = ($this->speedZ / $totalSpeed) * ($totalSpeed + $yDiff);
}
$this->setPos($this->x, $vec2[1], $this->z);
}
if(floor($this->x) != $x || floor($this->z) != $z){ //this breaks everything
$totalSpeed = sqrt($this->speedZ*$this->speedZ + $this->speedX*$this->speedX);
$totalSpeed = sqrt($this->speedZ * $this->speedZ + $this->speedX * $this->speedX);
$this->speedX = (floor($this->x) - $x) * $totalSpeed;
$this->speedZ = (floor($this->z) - $z) * $totalSpeed;
}
if($id == POWERED_RAIL){
$totalSpeed = sqrt($this->speedZ*$this->speedZ + $this->speedX*$this->speedX);
$totalSpeed = sqrt($this->speedZ * $this->speedZ + $this->speedX * $this->speedX);
if($totalSpeed > 0.01){
$this->speedX += (($this->speedX / $totalSpeed) * 0.06);
$this->speedZ += (($this->speedZ / $totalSpeed) * 0.06);
return;
}
if($meta == 1){
//TODO Level::isSolidBlockingTile
if(StaticBlock::getIsSolid($this->level->level->getBlockID($x - 1, $y, $z))){
@ -265,7 +265,7 @@ class Minecart extends Vehicle{
$v63 = -0.02;
}
$this->speedX = $v63;
}else if($meta == 0){
}elseif($meta == 0){
//TODO Level::isSolidBlockingTile
if(StaticBlock::getIsSolid($this->level->level->getBlockID($x, $y, $z - 1))){
return;
@ -278,58 +278,57 @@ class Minecart extends Vehicle{
$this->speedZ = $v64;
}
}
}
public function applyNaturalSlowdown(){
$mult = $this->linkedEntity != 0 && !$this->isRider ? 0.997 : 0.96;
$this->speedX *= $mult;
$this->speedY = 0;
$this->speedZ *= $mult;
}
public function comeOffTrack($topSpeed){
if($this->speedX < -$topSpeed) $this->speedX = -$topSpeed;
else if($this->speedX > $topSpeed) $this->speedX = $topSpeed;
elseif($this->speedX > $topSpeed) $this->speedX = $topSpeed;
if($this->speedZ < -$topSpeed) $this->speedZ = -$topSpeed;
else if($this->speedZ > $topSpeed) $this->speedZ = $topSpeed;
elseif($this->speedZ > $topSpeed) $this->speedZ = $topSpeed;
if($this->onGround){
$this->speedX *= 0.5;
$this->speedY *= 0.5;
$this->speedZ *= 0.5;
}
$this->move($this->speedX, $this->speedY, $this->speedZ);
if(!$this->onGround){
$this->speedX *= 0.95;
$this->speedY *= 0.95;
$this->speedZ *= 0.95;
}
}
public function applyCollision(Entity $collided){
$diffX = $collided->x - $this->x;
$diffZ = $collided->z - $this->z;
$dist = $diffX*$diffX + $diffZ*$diffZ;
$dist = $diffX * $diffX + $diffZ * $diffZ;
if($dist >= 0.0001){
$sqrtMax = sqrt($dist);
$diffX /= $sqrtMax;
$diffZ /= $sqrtMax;
$col = (($v = 1 / $sqrtMax) > 1 ? 1 : $v);
$diffX *= $col;
$diffZ *= $col;
$diffX *= 0.1;
$diffZ *= 0.1;
$diffX *= 0.5;
$diffZ *= 0.5;
$this->addVelocity(-$diffX, 0, -$diffZ);
$collided->addVelocity($diffX / 4, 0, $diffZ / 4);
}
@ -341,18 +340,18 @@ class Minecart extends Vehicle{
}
$this->updateLast();
//$this->updatePosition();
$this->speedY -= 0.04;
//TODO port stuff
$blockX = floor($this->x);
$blockY = floor($this->y);
$blockZ = floor($this->z);
if(RailBaseBlock::isRailBlock($this->level, $blockX, $blockY - 1, $blockZ)){
--$blockY;
}
[$id, $meta] = $this->level->level->getBlock($blockX, $blockY, $blockZ);
if(RailBaseBlock::isRailID($id)){
$this->moveAlongTrack($blockX, $blockY, $blockZ, 0.4, 0.0078125, $id, $meta);
@ -362,32 +361,32 @@ class Minecart extends Vehicle{
}
$this->doBlocksCollision();
$this->pitch = 0;
$diffX = $this->lastX - $this->x;
$diffZ = $this->lastZ - $this->z;
if($diffX*$diffX + $diffZ*$diffZ > 0.001){
if($diffX * $diffX + $diffZ * $diffZ > 0.001){
$this->yaw = atan2($diffZ, $diffX) * 180 / M_PI;
if($this->isInReverse) $this->yaw += 180;
}
$yw = fmod($this->yaw - $this->lastYaw, 360);
if($yw >= 180) $yw -= 360;
if($yw < 180) $yw += 360;
if($yw < -170 || $yw >= 170){
$this->isInReverse = !$this->isInReverse;
$this->yaw = $this->yaw + 180;
}
$bb = $this->boundingBox->expand(0.2, 0, 0.2);
$minChunkX = ((int)($bb->minX - 2)) >> 4;
$minChunkZ = ((int)($bb->minZ - 2)) >> 4;
$maxChunkX = ((int)($bb->minX + 2)) >> 4;
$maxChunkZ = ((int)($bb->minZ + 2)) >> 4;
$minChunkX = ((int) ($bb->minX - 2)) >> 4;
$minChunkZ = ((int) ($bb->minZ - 2)) >> 4;
$maxChunkX = ((int) ($bb->minX + 2)) >> 4;
$maxChunkZ = ((int) ($bb->minZ + 2)) >> 4;
//TODO also index by chunkY?
for($chunkX = $minChunkX; $chunkX <= $maxChunkX; ++$chunkX){
for($chunkZ = $minChunkZ; $chunkZ <= $maxChunkZ; ++$chunkZ){
@ -401,14 +400,14 @@ class Minecart extends Vehicle{
}else{
$e->applyCollision($this);
}
}
}
}
}
}
}
public function close()
{
parent::close();
@ -421,11 +420,11 @@ class Minecart extends Vehicle{
}
}
}
public function isPushable(){
return false; //TODO replace with true
}
public function spawn($player){
$pk = new AddEntityPacket;
$pk->eid = $this->eid;
@ -436,7 +435,7 @@ class Minecart extends Vehicle{
$pk->yaw = $this->yaw;
$pk->pitch = $this->pitch;
$player->dataPacket($pk);
$pk = new SetEntityMotionPacket;
$pk->eid = $this->eid;
$pk->speedX = $this->speedX;
@ -444,7 +443,7 @@ class Minecart extends Vehicle{
$pk->speedZ = $this->speedZ;
$player->dataPacket($pk);
}
public function interactWith(Entity $e, $action){
if($action === InteractPacket::ACTION_HOLD && $e->isPlayer() && $this->canRide($e)){
$e->setRiding($this);

View file

@ -3,23 +3,23 @@
class Painting extends Entity{
const CLASS_TYPE = ENTITY_OBJECT;
const TYPE = OBJECT_PAINTING;
public $motive;
public $direction;
public $xPos, $yPos, $zPos;
public $isValid = true;
public function __construct(Level $level, $eid, $class, $type = 0, $data = []){
parent::__construct($level, $eid, $class, $type, $data);
$this->x = $this->data["TileX"] ?? $this->x;
$this->y = $this->data["TileY"] ?? $this->y;
$this->z = $this->data["TileZ"] ?? $this->z;
$this->xPos = $this->data["xPos"] ?? (int)$this->x;
$this->zPos = $this->data["zPos"] ?? (int)$this->z;
$this->yPos = $this->data["yPos"] ?? (int)$this->y;
$this->xPos = $this->data["xPos"] ?? (int) $this->x;
$this->zPos = $this->data["zPos"] ?? (int) $this->z;
$this->yPos = $this->data["yPos"] ?? (int) $this->y;
$this->health = 1;
$this->canBeAttacked = true;
$this->width = 1;
@ -30,30 +30,30 @@ class Painting extends Entity{
if($dir === false){
$dir = floor($this->yaw / 90);
}
if($mot === false){
$this->setRandomMotive($dir);
}else{
$this->motive = $mot;
$this->direction = $dir;
$this->setDirection($dir);
}
}
public $counter = 0;
public function update($now){
if($this->closed === true){
return false;
}
if($this->closed === true){
return false;
}
if(++$this->counter >= 100){
$this->counter = 0;
if(!$this->survives() && !$this->dead){ //maybe dont check entity collision?
$this->makeDead("nosurvive");
}
}
return true;
}
@ -62,34 +62,34 @@ class Painting extends Entity{
foreach(PaintingItem::$motives as $name => $motive){
$this->motive = $name;
$this->setDirection($dir);
if($this->survives()){
$tochoose[] = $name;
}
}
if(count($tochoose) > 0){
$ind = mt_rand(0, count($tochoose)-1);
$ind = mt_rand(0, count($tochoose) - 1);
}else{
$this->isValid = false;
return;
}
$this->motive = $tochoose[$ind];
$this->setDirection($dir);
}
public static function offs($n){
if($n == 32 || $n == 64) return 0.5;
return 0;
}
const DIRECTION_OPPOSITE = [2, 3, 0, 1];
public function setDirection($dir){
$this->direction = $dir;
$this->lastYaw = $this->yaw = $dir * 90;
$size = PaintingItem::$motives[$this->motive] ?? array(1, 1);
$width = $size[0]*16;
$height = $size[1]*16;
$size = PaintingItem::$motives[$this->motive] ?? [1, 1];
$width = $size[0] * 16;
$height = $size[1] * 16;
if($dir == 2 || $dir == 0){
$v10 = 2;
$v9 = $width;
@ -98,28 +98,28 @@ class Painting extends Entity{
$v9 = 2;
$v10 = $width;
}
$v12 = $v9 * 0.03125;
$v13 = $height * 0.03125;
$v14 = $v10 * 0.03125;
$v15 = $this->xPos + 0.5;
$v16 = $this->yPos + 0.5;
$v17 = $this->zPos + 0.5; //XXX check
if($dir == 2){
$v17 = $v17 - 0.5625;
$v15 = $v15 - self::offs($width);
}else if($dir == 1){
}elseif($dir == 1){
$v15 = $v15 - 0.5625;
$v17 = $v17 + self::offs($width);
}else if($dir == 3){
}elseif($dir == 3){
$v15 = $v15 + 0.5625;
$v17 = $v17 - self::offs($width);
}else{
$v17 = $v17 + 0.5625;
$v15 = $v15 + self::offs($width);
}
$v23 = $v16 + self::offs($height);
$this->setPos($v15, $v23, $v17);
$this->boundingBox->minX = ($v15 - $v12) + 0.03125;
@ -129,35 +129,35 @@ class Painting extends Entity{
$this->boundingBox->maxY = ($v23 + $v13) - 0.03125;
$this->boundingBox->maxZ = ($v17 + $v14) - 0.03125;
}
public function getDrops(){
return [
[PAINTING, 0, 1]
];
}
public function isPickable(){
return true;
}
public function survives(){
$cubes = $this->level->getCubes($this, $this->boundingBox);
if(count($cubes) == 0){
$size = PaintingItem::$motives[$this->motive] ?? array(1, 1);
$size = PaintingItem::$motives[$this->motive] ?? [1, 1];
$width = $size[0];
$width2 = $width*16/32;
$width2 = $width * 16 / 32;
$height = $size[1];
$height2 = $height*16/32;
$height2 = $height * 16 / 32;
if($width < 1) $width = 1;
if($height < 1) $height = 1;
$positionX = $this->xPos;
$positionZ = $this->zPos;
if($this->direction == 2 || $this->direction == 0) $positionX = floor($this->x - $width2);
if($this->direction == 1 || $this->direction == 3) $positionZ = floor($this->z - $width2);
$minY = floor($this->y - $height2);
for($off = 0; $off < $width; ++$off){
for($yoff = 0; $yoff < $height; ++$yoff){
$y = $minY + $yoff;
@ -166,13 +166,13 @@ class Painting extends Entity{
}else{
$id = $this->level->level->getBlockId($positionX + $off, $y, $this->zPos);
}
if(!StaticBlock::getIsSolid($id)){
return false;
}
}
}
$ents = $this->level->getEntitiesInAABBOfType($this->boundingBox, ENTITY_OBJECT);
foreach($ents as $e){
if($e->eid == $this->eid) continue;
@ -182,13 +182,13 @@ class Painting extends Entity{
}
return true;
}
return false;
}
public function createSaveData(){
$data = parent::createSaveData();
$data["Motive"] = $this->motive;
$data["Direction"] = $this->direction;
$data["xPos"] = $this->xPos;

View file

@ -14,11 +14,11 @@ class PrimedTNT extends Entity{
$this->yOffset = $this->height / 2;
$this->setHealth(10000000, "generic");
}
public function isPickable(){
return !$this->dead;
}
public function getMetadata(){
$d = parent::getMetadata();
$d[16]["value"] = (int) $this->data["fuse"];
@ -26,34 +26,34 @@ class PrimedTNT extends Entity{
}
public function createSaveData(){
$data = parent::createSaveData();
$data["fuse"] = $this->data["fuse"];
$data["power"] = $this->data["power"];
return $data;
}
public function update($now){
if($this->closed) return;
$this->lastX = $this->x;
$this->lastY = $this->y;
$this->lastZ = $this->z;
$this->speedY -= 0.04;
$this->move($this->speedX, $this->speedY, $this->speedZ);
$this->speedX *- 0.98;
$this->speedX * -0.98;
$this->speedY *= 0.98;
$this->speedZ *= 0.98;
if($this->onGround){
$this->speedX *= 0.7;
$this->speedZ *= 0.7;
$this->speedY *= -0.5;
}
$tickDiff = ($now - $this->lastUpdate) / 0.05;
$this->data["fuse"] -= $tickDiff;
$this->updateMetadata();
if($this->data["fuse"] <= 0){
@ -61,10 +61,10 @@ class PrimedTNT extends Entity{
$explosion = new Explosion($this, $this->data["power"]);
$explosion->explode();
}
$this->lastUpdate = $now;
}
public function spawn($player){
$pk = new AddEntityPacket;
$pk->eid = $this->eid;

View file

@ -1,32 +1,32 @@
<?php
class ThrownEgg extends Projectile{
const TYPE = OBJECT_EGG;
public function onHit(MovingObjectPosition $hitResult){
if($hitResult->typeOfHit == 1){
$hitResult->entityHit->harm(0, $this->eid);
}
$rand = mt_rand(0, 7);
if($rand == 0){
$count = mt_rand(0, 31) == 0 ? 4 : 1;
$data = [
"x" => $this->x,
"y" => $this->y,
"z" => $this->z,
"z" => $this->z,
"yaw" => $this->yaw,
"pitch" => 0,
"IsBaby" => true
];
for($i = 0; $i < $count; ++$i){
$chicken = $this->server->api->entity->add($this->level, ENTITY_MOB, MOB_CHICKEN, $data);
$this->server->api->entity->spawnToAll($chicken);
}
}
$this->close();
}
}
}

View file

@ -1,11 +1,12 @@
<?php
class ThrownSnowball extends Projectile{
const TYPE = OBJECT_SNOWBALL;
public function onHit(MovingObjectPosition $hitResult){
if($hitResult->typeOfHit == 1){
$hitResult->entityHit->harm(0, $this->eid);
}
$this->close();
}
}

View file

@ -2,16 +2,16 @@
class TripodCamera extends Entity{
const TYPE = OBJECT_TRIPOD_CAMERA;
function __construct(Level $level, $eid, $class, $type = 0, $data = []){
parent::__construct($level, $eid, $class, $type, $data);
$this->setHealth(PHP_INT_MAX, "generic");
}
public function isPickable(){
return !$this->dead;
}
public function interactWith(Entity $e, $action){
if($e->isPlayer() and $action === InteractPacket::ACTION_HOLD){
//todo

View file

@ -1,8 +1,8 @@
<?php
class EntityRegistry{
class EntityRegistry{
public static $entityList;
/*Register all entities*/
public static function registerEntities(){
ConsoleAPI::info("Registering entities...");
@ -25,13 +25,13 @@ class EntityRegistry{
self::registerEntity(ThrownEgg::class);
self::registerEntity(ThrownSnowball::class);
}
/*Register an Entity*/
public static function registerEntity($className){
$class = new \ReflectionClass($className);
if(is_a($className, Entity::class, true) and !$class->isAbstract()){
//self::$entityList[$className::TYPE] = $className;
self::$entityList->addEntity(new PropertyEntity($className::CLASS_TYPE, $className::TYPE, $className));
//self::$shortNames[$className] = $class->getShortName(); what is this even supposed to do?
//console("[INFO] Registered a ".$className);

View file

@ -2,13 +2,13 @@
class PropertyEntity{
private $class,$type,$name;
function __construct($class, $type, $name){
$this->class = $class;
$this->type = $type;
$this->name = $name;
}
public function getEntityClass(){
return $this->class;
}

View file

@ -16,7 +16,7 @@ abstract class EventHandler{
}else{
return BaseEvent::ALLOW;
}
}
}
}
}

View file

@ -2,11 +2,11 @@
/**
*
* ____ _ _ __ __ _ __ __ ____
* | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
* ____ _ _ __ __ _ __ __ ____
* | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
* | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
* | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
* |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
* | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
* |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
*
* 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
@ -15,7 +15,7 @@
*
* @author PocketMine Team
* @link http://www.pocketmine.net/
*
*
*
*/
@ -44,9 +44,9 @@ abstract class EventPriority{
const HIGHEST = 1;
/**
* Event is listened to purely for monitoring the outcome of an event.
*
*
* No modifications to the event should be made under this priority
*/
const MONITOR = 0;
}

View file

@ -1,6 +1,5 @@
<?php
/**
* Plugins that create events must use this class as the base
*/

View file

@ -2,11 +2,11 @@
/**
*
* ____ _ _ __ __ _ __ __ ____
* | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
* ____ _ _ __ __ _ __ __ ____
* | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
* | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
* | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
* |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
* | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
* |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
*
* 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
@ -15,7 +15,7 @@
*
* @author PocketMine Team
* @link http://www.pocketmine.net/
*
*
*
*/

View file

@ -2,11 +2,11 @@
/**
*
* ____ _ _ __ __ _ __ __ ____
* | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
* ____ _ _ __ __ _ __ __ ____
* | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
* | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
* | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
* |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
* | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
* |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
*
* 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
@ -15,26 +15,26 @@
*
* @author PocketMine Team
* @link http://www.pocketmine.net/
*
*
*
*/
class DataPacketReceiveEvent extends ServerEvent implements CancellableEvent{
public static $handlers;
public static $handlerPriority;
private $packet;
private $player;
private $player;
public function __construct(Player $player, RakNetDataPacket $packet){
$this->packet = $packet;
$this->player = $player;
}
public function getPacket(){
return $this->packet;
}
public function getPlayer(){
return $this->player;
}

View file

@ -2,11 +2,11 @@
/**
*
* ____ _ _ __ __ _ __ __ ____
* | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
* ____ _ _ __ __ _ __ __ ____
* | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
* | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
* | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
* |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
* | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
* |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
*
* 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
@ -15,26 +15,26 @@
*
* @author PocketMine Team
* @link http://www.pocketmine.net/
*
*
*
*/
class DataPacketSendEvent extends ServerEvent implements CancellableEvent{
public static $handlers;
public static $handlerPriority;
private $packet;
private $player;
private $player;
public function __construct(Player $player, RakNetDataPacket $packet){
$this->packet = $packet;
$this->player = $player;
}
public function getPacket(){
return $this->packet;
}
public function getPlayer(){
return $this->player;
}

View file

@ -2,11 +2,11 @@
/**
*
* ____ _ _ __ __ _ __ __ ____
* | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
* ____ _ _ __ __ _ __ __ ____
* | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
* | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
* | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
* |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
* | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
* |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
*
* 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
@ -15,21 +15,20 @@
*
* @author PocketMine Team
* @link http://www.pocketmine.net/
*
*
*
*/
class PacketReceiveEvent extends ServerEvent implements CancellableEvent{
public static $handlers;
public static $handlerPriority;
private $packet;
public function __construct(Packet $packet){
$this->packet = $packet;
}
public function getPacket(){
return $this->packet;
}

View file

@ -2,11 +2,11 @@
/**
*
* ____ _ _ __ __ _ __ __ ____
* | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
* ____ _ _ __ __ _ __ __ ____
* | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
* | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
* | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
* |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
* | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
* |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
*
* 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
@ -15,21 +15,20 @@
*
* @author PocketMine Team
* @link http://www.pocketmine.net/
*
*
*
*/
class PacketSendEvent extends ServerEvent implements CancellableEvent{
public static $handlers;
public static $handlerPriority;
private $packet;
public function __construct(Packet $packet){
$this->packet = $packet;
}
public function getPacket(){
return $this->packet;
}

View file

@ -11,7 +11,6 @@ if(!function_exists("cli_set_process_title")){
}
}
function dummy(){
}
@ -69,8 +68,6 @@ function nullsafe(&$a, $null){
return $a ?? $null;
}
function require_all($path, &$count = 0){
$dir = dir($path . "/");
$dirs = [];

View file

@ -8,7 +8,7 @@
const DEFAULT_MEMORY = 128;
const DEFAULT_PLAYERS = 20;
const DEFAULT_GAMEMODE = SURVIVAL;
private $lang, $config;
public function __construct(){
echo "[*] NostalgiaCore set-up wizard\n";
@ -34,12 +34,12 @@
$this->welcome();
$this->generateBaseConfig();
$this->generateUserFiles();
$this->networkFunctions();
$this->endWizard();
}
private function welcome(){
echo $this->lang->welcome_to_pocketmine."\n";
echo <<<LICENSE
@ -59,9 +59,9 @@ LICENSE;
echo "[*] ".$this->lang->setting_up_server_now."\n";
echo "[*] ".$this->lang->default_values_info."\n";
echo "[*] ".$this->lang->server_properties."\n";
}
private function generateBaseConfig(){
$config = new Config(DATA_PATH . "server.properties", CONFIG_PROPERTIES);
echo "[?] ".$this->lang->name_your_server." (".self::DEFAULT_NAME."): ";
@ -95,7 +95,7 @@ LICENSE;
}
$config->save();
}
private function generateUserFiles(){
echo "[*] ".$this->lang->op_info."\n";
echo "[?] ".$this->lang->op_who.": ";
@ -118,7 +118,7 @@ LICENSE;
}
$config->save();
}
private function networkFunctions(){
$config = new Config(DATA_PATH . "server.properties", CONFIG_PROPERTIES);
echo "[!] ".$this->lang->query_warning1."\n";
@ -129,7 +129,7 @@ LICENSE;
}else{
$config->set("enable-query", true);
}
echo "[*] ".$this->lang->rcon_info."\n";
echo "[?] ".$this->lang->rcon_enable." (y/N): ";
if(strtolower($this->getInput("n")) === "y"){
@ -142,35 +142,33 @@ LICENSE;
}
$config->save();
echo "[*] ".$this->lang->ip_get."\n";
$externalIP = Utils::getIP();
$internalIP = gethostbyname(trim(`hostname`));
echo "[!] ".$this->lang->get("ip_warning", array("{{EXTERNAL_IP}}", "{{INTERNAL_IP}}"), array($externalIP, $internalIP))."\n";
echo "[!] ".$this->lang->get("ip_warning", ["{{EXTERNAL_IP}}", "{{INTERNAL_IP}}"], [$externalIP, $internalIP])."\n";
echo "[!] ".$this->lang->ip_confirm;
$this->getInput();
}
private function endWizard(){
echo "[*] ".$this->lang->you_have_finished."\n";
echo "[*] ".$this->lang->pocketmine_plugins."\n";
echo "[*] ".$this->lang->pocketmine_will_start."\n\n\n";
sleep(4);
}
private function getInput($default = ""){
$input = trim(fgets(STDIN));
return $input === "" ? $default:$input;
}
}
class InstallerLang{
public static $languages = array(
public static $languages = [
"ru" => "Pyccĸий",
"en" => "English",
"es" => "Español",
@ -180,7 +178,7 @@ LICENSE;
//"vi" => "Tiếng Việt",
"ko" => "한국어",
"fr" => "Français",
"it" => "Italiano",
"it" => "Italiano",
//"lv" => "Latviešu",
"nl" => "Nederlands",
//"pt" => "Português",
@ -189,8 +187,8 @@ LICENSE;
"tr" => "Türkçe",
"uk" => "Український"
//"et" => "Eesti",
);
private $texts = array();
];
private $texts = [];
private $lang;
private $langfile;
public function __construct($lang = ""){
@ -200,7 +198,7 @@ LICENSE;
}else{
$l = glob(FILE_PATH."src/lang/Installer/".$lang."_*.ini");
if(count($l) > 0){
$files = array();
$files = [];
foreach($l as $file){
$files[$file] = filesize($file);
}
@ -215,32 +213,32 @@ LICENSE;
$this->langfile = FILE_PATH."src/lang/Installer/en.ini";
}
}
$this->loadLang(FILE_PATH."src/lang/Installer/en.ini", "en");
if($this->lang !== "en"){
$this->loadLang($this->langfile, $this->lang);
}
}
public function getLang(){
return ($this->lang);
}
public function loadLang($langfile, $lang = "en"){
$this->texts[$lang] = array();
$texts = explode("\n", str_replace(array("\r", "\/\/"), array("", "//"), file_get_contents($langfile)));
$this->texts[$lang] = [];
$texts = explode("\n", str_replace(["\r", "\/\/"], ["", "//"], file_get_contents($langfile)));
foreach($texts as $line){
$line = trim($line);
if($line === ""){
continue;
}
$line = explode("=", $line);
$this->texts[$lang][array_shift($line)] = str_replace(array("\\n", "\\N",), "\n", implode("=", $line));
$this->texts[$lang][array_shift($line)] = str_replace(["\\n", "\\N",], "\n", implode("=", $line));
}
}
public function get($name, $search = array(), $replace = array()){
public function get($name, $search = [], $replace = []){
if(!isset($this->texts[$this->lang][$name])){
if($this->lang !== "en" and isset($this->texts["en"][$name])){
return $this->texts["en"][$name];
@ -253,10 +251,10 @@ LICENSE;
return $this->texts[$this->lang][$name];
}
}
public function __get($name){
return $this->get($name);
}
}
}
/***REM_END***/

View file

@ -1,138 +1,138 @@
<?php
abstract class Block extends Position{
public static $class = array(
AIR => "AirBlock",
STONE => "StoneBlock",
GRASS => "GrassBlock",
DIRT => "DirtBlock",
COBBLESTONE => "CobblestoneBlock",
PLANKS => "PlanksBlock",
SAPLING => "SaplingBlock",
BEDROCK => "BedrockBlock",
WATER => "WaterBlock",
STILL_WATER => "StillWaterBlock",
LAVA => "LavaBlock",
STILL_LAVA => "StillLavaBlock",
SAND => "SandBlock",
GRAVEL => "GravelBlock",
GOLD_ORE => "GoldOreBlock",
IRON_ORE => "IronOreBlock",
COAL_ORE => "CoalOreBlock",
WOOD => "WoodBlock",
LEAVES => "LeavesBlock",
SPONGE => "SpongeBlock",
GLASS => "GlassBlock",
LAPIS_ORE => "LapisOreBlock",
LAPIS_BLOCK => "LapisBlock",
SANDSTONE => "SandstoneBlock",
BED_BLOCK => "BedBlock",
POWERED_RAIL => "PoweredRailBlock",
COBWEB => "CobwebBlock",
TALL_GRASS => "TallGrassBlock",
DEAD_BUSH => "DeadBushBlock",
WOOL => "WoolBlock",
DANDELION => "DandelionBlock",
CYAN_FLOWER => "CyanFlowerBlock",
BROWN_MUSHROOM => "BrownMushroomBlock",
RED_MUSHROOM => "RedMushRoomBlock",
GOLD_BLOCK => "GoldBlock",
IRON_BLOCK => "IronBlock",
DOUBLE_SLAB => "DoubleSlabBlock",
SLAB => "SlabBlock",
BRICKS_BLOCK => "BricksBlock",
TNT => "TNTBlock",
BOOKSHELF => "BookshelfBlock",
MOSS_STONE => "MossStoneBlock",
OBSIDIAN => "ObsidianBlock",
TORCH => "TorchBlock",
FIRE => "FireBlock",
public static $class = [
AIR => "AirBlock",
STONE => "StoneBlock",
GRASS => "GrassBlock",
DIRT => "DirtBlock",
COBBLESTONE => "CobblestoneBlock",
PLANKS => "PlanksBlock",
SAPLING => "SaplingBlock",
BEDROCK => "BedrockBlock",
WATER => "WaterBlock",
STILL_WATER => "StillWaterBlock",
LAVA => "LavaBlock",
STILL_LAVA => "StillLavaBlock",
SAND => "SandBlock",
GRAVEL => "GravelBlock",
GOLD_ORE => "GoldOreBlock",
IRON_ORE => "IronOreBlock",
COAL_ORE => "CoalOreBlock",
WOOD => "WoodBlock",
LEAVES => "LeavesBlock",
SPONGE => "SpongeBlock",
GLASS => "GlassBlock",
LAPIS_ORE => "LapisOreBlock",
LAPIS_BLOCK => "LapisBlock",
SANDSTONE => "SandstoneBlock",
BED_BLOCK => "BedBlock",
POWERED_RAIL => "PoweredRailBlock",
COBWEB => "CobwebBlock",
TALL_GRASS => "TallGrassBlock",
DEAD_BUSH => "DeadBushBlock",
WOOL => "WoolBlock",
DANDELION => "DandelionBlock",
CYAN_FLOWER => "CyanFlowerBlock",
BROWN_MUSHROOM => "BrownMushroomBlock",
RED_MUSHROOM => "RedMushRoomBlock",
GOLD_BLOCK => "GoldBlock",
IRON_BLOCK => "IronBlock",
DOUBLE_SLAB => "DoubleSlabBlock",
SLAB => "SlabBlock",
BRICKS_BLOCK => "BricksBlock",
TNT => "TNTBlock",
BOOKSHELF => "BookshelfBlock",
MOSS_STONE => "MossStoneBlock",
OBSIDIAN => "ObsidianBlock",
TORCH => "TorchBlock",
FIRE => "FireBlock",
WOOD_STAIRS => "WoodStairsBlock",
CHEST => "ChestBlock",
WOOD_STAIRS => "WoodStairsBlock",
CHEST => "ChestBlock",
DIAMOND_ORE => "DiamondOreBlock",
DIAMOND_BLOCK => "DiamondBlock",
WORKBENCH => "WorkbenchBlock",
WHEAT_BLOCK => "WheatBlock",
FARMLAND => "FarmlandBlock",
FURNACE => "FurnaceBlock",
BURNING_FURNACE => "BurningFurnaceBlock",
SIGN_POST => "SignPostBlock",
WOOD_DOOR_BLOCK => "WoodDoorBlock",
LADDER => "LadderBlock",
RAIL => "RailBlock",
COBBLESTONE_STAIRS => "CobblestoneStairsBlock",
WALL_SIGN => "WallSignBlock",
DIAMOND_ORE => "DiamondOreBlock",
DIAMOND_BLOCK => "DiamondBlock",
WORKBENCH => "WorkbenchBlock",
WHEAT_BLOCK => "WheatBlock",
FARMLAND => "FarmlandBlock",
FURNACE => "FurnaceBlock",
BURNING_FURNACE => "BurningFurnaceBlock",
SIGN_POST => "SignPostBlock",
WOOD_DOOR_BLOCK => "WoodDoorBlock",
LADDER => "LadderBlock",
RAIL => "RailBlock",
COBBLESTONE_STAIRS => "CobblestoneStairsBlock",
WALL_SIGN => "WallSignBlock",
IRON_DOOR_BLOCK => "IronDoorBlock",
REDSTONE_ORE => "RedstoneOreBlock",
GLOWING_REDSTONE_ORE => "GlowingRedstoneOreBlock",
IRON_DOOR_BLOCK => "IronDoorBlock",
REDSTONE_ORE => "RedstoneOreBlock",
GLOWING_REDSTONE_ORE => "GlowingRedstoneOreBlock",
SNOW_LAYER => "SnowLayerBlock",
ICE => "IceBlock",
SNOW_BLOCK => "SnowBlock",
CACTUS => "CactusBlock",
CLAY_BLOCK => "ClayBlock",
SUGARCANE_BLOCK => "SugarcaneBlock",
SNOW_LAYER => "SnowLayerBlock",
ICE => "IceBlock",
SNOW_BLOCK => "SnowBlock",
CACTUS => "CactusBlock",
CLAY_BLOCK => "ClayBlock",
SUGARCANE_BLOCK => "SugarcaneBlock",
FENCE => "FenceBlock",
PUMPKIN => "PumpkinBlock",
NETHERRACK => "NetherrackBlock",
SOUL_SAND => "SoulSandBlock",
GLOWSTONE_BLOCK => "GlowstoneBlock",
FENCE => "FenceBlock",
PUMPKIN => "PumpkinBlock",
NETHERRACK => "NetherrackBlock",
SOUL_SAND => "SoulSandBlock",
GLOWSTONE_BLOCK => "GlowstoneBlock",
LIT_PUMPKIN => "LitPumpkinBlock",
INVISIBLE_BEDROCK => "InvisibleBedrockBlock",
CAKE_BLOCK => "CakeBlock",
TRAPDOOR => "TrapdoorBlock",
LIT_PUMPKIN => "LitPumpkinBlock",
INVISIBLE_BEDROCK => "InvisibleBedrockBlock",
STONE_BRICKS => "StoneBricksBlock",
CAKE_BLOCK => "CakeBlock",
IRON_BARS => "IronBarsBlock",
GLASS_PANE => "GlassPaneBlock",
MELON_BLOCK => "MelonBlock",
PUMPKIN_STEM => "PumpkinStemBlock",
MELON_STEM => "MelonStemBlock",
TRAPDOOR => "TrapdoorBlock",
FENCE_GATE => "FenceGateBlock",
BRICK_STAIRS => "BrickStairsBlock",
STONE_BRICK_STAIRS => "StoneBrickStairsBlock",
STONE_BRICKS => "StoneBricksBlock",
NETHER_BRICKS => "NetherBricksBlock",
IRON_BARS => "IronBarsBlock",
GLASS_PANE => "GlassPaneBlock",
MELON_BLOCK => "MelonBlock",
PUMPKIN_STEM => "PumpkinStemBlock",
MELON_STEM => "MelonStemBlock",
NETHER_BRICKS_STAIRS => "NetherBricksStairsBlock",
FENCE_GATE => "FenceGateBlock",
BRICK_STAIRS => "BrickStairsBlock",
STONE_BRICK_STAIRS => "StoneBrickStairsBlock",
SANDSTONE_STAIRS => "SandstoneStairsBlock",
SPRUCE_WOOD_STAIRS => "SpruceWoodStairsBlock",
BIRCH_WOOD_STAIRS => "BirchWoodStairsBlock",
JUNGLE_WOOD_STAIRS => "JungleWoodStairsBlock",
STONE_WALL => "StoneWallBlock",
CARROT_BLOCK => "CarrotBlock",
POTATO_BLOCK => "PotatoBlock",
NETHER_BRICKS => "NetherBricksBlock",
QUARTZ_BLOCK => "QuartzBlock",
QUARTZ_STAIRS => "QuartzStairsBlock",
DOUBLE_WOOD_SLAB => "DoubleWoodSlabBlock",
WOOD_SLAB => "WoodSlabBlock",
HAY_BALE => "HayBaleBlock",
CARPET => "CarpetBlock",
COAL_BLOCK => "CoalBlock",
BEETROOT_BLOCK => "BeetrootBlock",
STONECUTTER => "StonecutterBlock",
GLOWING_OBSIDIAN => "GlowingObsidianBlock",
NETHER_REACTOR => "NetherReactorBlock",
INFO_UPDATE => "InfoUpdateBlock",
INFO_UPDATE2 => "InfoUpdate2Block",
RESERVED6 => "Reserved6Block",
);
NETHER_BRICKS_STAIRS => "NetherBricksStairsBlock",
SANDSTONE_STAIRS => "SandstoneStairsBlock",
SPRUCE_WOOD_STAIRS => "SpruceWoodStairsBlock",
BIRCH_WOOD_STAIRS => "BirchWoodStairsBlock",
JUNGLE_WOOD_STAIRS => "JungleWoodStairsBlock",
STONE_WALL => "StoneWallBlock",
CARROT_BLOCK => "CarrotBlock",
POTATO_BLOCK => "PotatoBlock",
QUARTZ_BLOCK => "QuartzBlock",
QUARTZ_STAIRS => "QuartzStairsBlock",
DOUBLE_WOOD_SLAB => "DoubleWoodSlabBlock",
WOOD_SLAB => "WoodSlabBlock",
HAY_BALE => "HayBaleBlock",
CARPET => "CarpetBlock",
COAL_BLOCK => "CoalBlock",
BEETROOT_BLOCK => "BeetrootBlock",
STONECUTTER => "StonecutterBlock",
GLOWING_OBSIDIAN => "GlowingObsidianBlock",
NETHER_REACTOR => "NetherReactorBlock",
INFO_UPDATE => "InfoUpdateBlock",
INFO_UPDATE2 => "InfoUpdate2Block",
RESERVED6 => "Reserved6Block",
];
public $id;
public $meta;
public $name;
@ -155,50 +155,50 @@ abstract class Block extends Position{
public $z = 0;
public $slipperiness;
public static function interact(Level $level, $x, $y, $z, Player $player){}
public static function neighborChanged(Level $level, $x, $y, $z, $nX, $nY, $nZ, $oldID){}
public static function getAABB(Level $level, $x, $y, $z){
return StaticBlock::getAABB(static::$blockID, $x, $y, $z);
}
public static function containsX($id, $v){
return !($v == null) && $v->y >= StaticBlock::$minYs[$id] && $v->y <= StaticBlock::$maxYs[$id] && $v->z >= StaticBlock::$minZs[$id] && $v->z <= StaticBlock::$maxZs[$id];
}
public static function containsY($id, $v){
return !($v == null) && $v->x >= StaticBlock::$minXs[$id] && $v->x <= StaticBlock::$maxXs[$id] && $v->z >= StaticBlock::$minZs[$id] && $v->z <= StaticBlock::$maxZs[$id];
}
public static function containsZ($id, $v){
return !($v == null) && $v->x >= StaticBlock::$minXs[$id] && $v->x <= StaticBlock::$maxXs[$id] && $v->y >= StaticBlock::$minYs[$id] && $v->y <= StaticBlock::$maxYs[$id];
}
public static function updateShape(Level $level, $x, $y, $z){
}
public static function clip(Level $level, $x, $y, $z, Vector3 $start, Vector3 $end){
static::updateShape($level, $x, $y, $z);
$id = $level->level->getBlockID($x, $y, $z);
$start = $start->subtract($x, $y, $z);
$end = $end->subtract($x, $y, $z);
$v7 = $start->clipX($end, StaticBlock::$minXs[$id]);
$v8 = $start->clipX($end, StaticBlock::$maxXs[$id]);
$v9 = $start->clipY($end, StaticBlock::$minYs[$id]);
$v10 = $start->clipY($end, StaticBlock::$maxYs[$id]);
$v11 = $start->clipZ($end, StaticBlock::$minZs[$id]);
$v12 = $start->clipZ($end, StaticBlock::$maxZs[$id]);
if(!self::containsX($id, $v7)) $v7 = null;
if(!self::containsX($id, $v8)) $v8 = null;
if(!self::containsY($id, $v9)) $v9 = null;
if(!self::containsY($id, $v10)) $v10 = null;
if(!self::containsZ($id, $v11)) $v11 = null;
if(!self::containsZ($id, $v12)) $v12 = null;
$v13 = null;
if($v7 != null && ($v13 == null || $start->distanceSquared($v7) < $start->distanceSquared($v13))) $v13 = $v7;
if($v8 != null && ($v13 == null || $start->distanceSquared($v8) < $start->distanceSquared($v13))) $v13 = $v8;
@ -206,9 +206,9 @@ abstract class Block extends Position{
if($v10 != null && ($v13 == null || $start->distanceSquared($v10) < $start->distanceSquared($v13))) $v13 = $v10;
if($v11 != null && ($v13 == null || $start->distanceSquared($v11) < $start->distanceSquared($v13))) $v13 = $v11;
if($v12 != null && ($v13 == null || $start->distanceSquared($v12) < $start->distanceSquared($v13))) $v13 = $v12;
if($v13 == null) return null;
$v14 = -1;
if($v13 == $v7) $v14 = 4;
if($v13 == $v8) $v14 = 5;
@ -216,10 +216,10 @@ abstract class Block extends Position{
if($v13 == $v10) $v14 = 1;
if($v13 == $v11) $v14 = 2;
if($v13 == $v12) $v14 = 3;
return MovingObjectPosition::fromBlock($x, $y, $z, $v14, $v13->add($x, $y, $z));
}
public static function onPlace(Level $level, $x, $y, $z){}
public static function addVelocityToEntity(Level $level, $x, $y, $z, Entity $entity, Vector3 $velocityVector){}
public static function onRandomTick(Level $level, $x, $y, $z){}
@ -229,8 +229,7 @@ abstract class Block extends Position{
return [static::getAABB($level, $x, $y, $z)];
}
public static function onEntityCollidedWithBlock(Level $level, $x, $y, $z, Entity $entity){}
public function __construct($id, $meta = 0, $name = "Unknown"){
$this->id = (int) $id;
$this->meta = (int) $meta;
@ -240,15 +239,15 @@ abstract class Block extends Position{
$this->slipperiness = 0.6;
$this->boundingBox = new AxisAlignedBB($this->x, $this->y, $this->z, $this->x + 1, $this->y + 1, $this->z + 1);
}
final public function getHardness(){
return ($this->hardness);
}
final public function getName(){
return $this->name;
}
final public function getID(){
return $this->id;
}
@ -258,7 +257,7 @@ abstract class Block extends Position{
final public function getMetadata(){
return $this->meta & 0x0F;
}
final public function position(Position $v){
$this->level = $v->level;
$this->x = (int) $v->x;
@ -266,24 +265,24 @@ abstract class Block extends Position{
$this->z = (int) $v->z;
$this->boundingBox->setBounds($this->x, $this->y, $this->z, $this->x + 1, $this->y + 1, $this->z + 1);
}
public function getDrops(Item $item, Player $player){
if(!isset(Block::$class[$this->id])){ //Unknown blocks
return array();
return [];
}else{
return array(
array($this->id, $this->meta, 1),
);
return [
[$this->id, $this->meta, 1],
];
}
}
public function getBreakTime(Item $item, Player $player){
if(($player->gamemode & 0x01) === 0x01){
return 0.15;
}
return $this->breakTime;
}
public function getSide($side, $step = 1){
$v = parent::getSide($side, $step);
if($this->level instanceof Level){
@ -291,17 +290,17 @@ abstract class Block extends Position{
}
return $v;
}
final public function __toString(){
return "Block ". $this->name ." (".$this->id.":".$this->meta.")";
}
abstract function isBreakable(Item $item, Player $player);
abstract function onBreak(Item $item, Player $player);
abstract function place(Item $item, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz);
abstract function onActivate(Item $item, Player $player);
}

View file

@ -5,12 +5,12 @@ class Item{
const TOOL_PICKAXE = 1;
const TOOL_AXE = 2;
const TOOL_SHOVEL = 3;
const TOOL_HOE = 4;
const TOOL_HOE = 4;
const DEF_DAMAGE = 1;
public static $class = array(
public static $class = [
//armor
LEATHER_CAP => "LeatherCapItem",
LEATHER_TUNIC => "LeatherTunicItem",
@ -32,7 +32,7 @@ class Item{
GOLDEN_CHESTPLATE => "GoldenChestplateItem",
GOLDEN_LEGGINGS => "GoldenLeggingsItem",
GOLDEN_BOOTS => "GoldenBootsItem",
//food
APPLE => "AppleItem",
MUSHROOM_STEW => "MushroomStewItem",
@ -51,7 +51,7 @@ class Item{
PUMPKIN_PIE => "PumpkinPieItem",
BEETROOT => "BeetrootItem",
BEETROOT_SOUP => "BeetrootSoupItem",
//generic
ARROW => "ArrowItem",
COAL => "CoalItem",
@ -95,7 +95,7 @@ class Item{
QUARTZ => "QuartzItem",
CAMERA => "CameraItem",
BEETROOT_SEEDS => "BeetrootSeedsItem",
//tool
IRON_SHOVEL => "IronShovelItem",
IRON_PICKAXE => "IronPickaxeItem",
@ -127,21 +127,21 @@ class Item{
COMPASS => "CompassItem",
CLOCK => "ClockItem",
SHEARS => "ShearsItem",
);
];
public $block;
public $id;
public $meta;
public $count;
/**
* @var int
* @var int
* Max stack size of the item. Use Item::getMaxStackSize to get stack size for specific item.
*/
public $maxStackSize = 64;
public $durability = 0;
public $name;
public $isActivable = false;
public function __construct($id, $meta = 0, $count = 1, $name = "Unknown"){
$this->id = (int) $id;
$this->meta = (int) $meta;
@ -155,19 +155,19 @@ class Item{
$this->maxStackSize = 1;
}
}
public function isPickaxe(){
return false;
}
public function getName(){
return $this->name;
}
public function isPlaceable(){
return (($this->block instanceof Block) and $this->block->isPlaceable === true);
}
public function getBlock(){
if($this->block instanceof Block){
return $this->block;
@ -175,23 +175,23 @@ class Item{
return BlockAPI::get(AIR);
}
}
public function getID(){
return $this->id;
}
public function getMetadata(){
return $this->meta;
}
}
public function isArmor(){
return false;
}
public function getMaxStackSize(){
return $this->maxStackSize;
}
public function getFuelTime(){
if(!isset(FuelData::$duration[$this->id])){
return false;
@ -201,24 +201,24 @@ class Item{
}
return false;
}
public function getSmeltItem(){
if(!isset(SmeltingData::$product[$this->id])){
return false;
}
if(isset(SmeltingData::$product[$this->id][0]) and !is_array(SmeltingData::$product[$this->id][0])){
return BlockAPI::getItem(SmeltingData::$product[$this->id][0], SmeltingData::$product[$this->id][1]);
}
if(!isset(SmeltingData::$product[$this->id][$this->meta])){
return false;
}
return BlockAPI::getItem(SmeltingData::$product[$this->id][$this->meta][0], SmeltingData::$product[$this->id][$this->meta][1]);
}
public function useOn($object, $force = false){
if($force){
if(($object instanceof Entity) and !$this->isSword()){
@ -230,16 +230,16 @@ class Item{
}
return false;
}
public function isTool(){
return false;
}
public function getMaxDurability(){
if(!$this->isTool() and $this->id !== BOW){
return false;
}
$levels = [ //TODO rewrite(item usage too)
2 => 33, //GOLD
1 => 60, //WOODEN
@ -256,14 +256,14 @@ class Item{
}
return $levels[$type];
}
public function getLevel(){
return false;
}
//TODO remove?
public function getPickaxeLevel(){ //Returns false or level of the pickaxe
return match ($this->id) {
return match ($this->id) {
WOODEN_PICKAXE => 1,
GOLDEN_PICKAXE => 2,
STONE_PICKAXE => 3,
@ -272,7 +272,7 @@ class Item{
default => false,
};
}
public function isAxe(){
return false;
}
@ -280,11 +280,11 @@ class Item{
public function isSword(){
return false;
}
public function isShovel(){
return false;
}
public function isHoe(){
return false;
}
@ -292,23 +292,23 @@ class Item{
public function isShears(){
return ($this->id === SHEARS);
}
public function __toString(){
return "Item ". $this->name ." (".$this->id.":".$this->meta.")";
}
public function getDamageAgainstOf($e){
return Item::DEF_DAMAGE;
}
public function getDestroySpeed(Block $block, Player $player){
return 1;
}
public function onActivate(Level $level, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){
return false;
}
public static function getFoodHeal($id){
return match($id){
APPLE => 4,
@ -328,9 +328,9 @@ class Item{
POTATO => 1,
BAKED_POTATO => 6,
BEETROOT => 1,
default => 0
};
}
}

View file

@ -1,4 +1,5 @@
<?php
/*value - durability*/
class Material{
const LEATHER = 5; //when enums

View file

@ -6,7 +6,7 @@ class StaticBlock
{
const DEFAULT_SLIPPERINESS = 0.6;
const DEFAULT_HARDNESS = 0;
private static $NULL_BOUNDS;
public static $prealloc = [];
public static $isSolid = [];
@ -17,18 +17,18 @@ class StaticBlock
public static $hasPhysics = [];
public static $isLiquid = [];
public static $isFullBlock = [];
public static $hardness = [];
public static $slipperiness = [];
public static $boundingBoxes = [];
public static $minXs = [], $minYs = [], $minZs = [], $maxXs = [], $maxYs = [], $maxZs = [];
public static function init(){
self::$NULL_BOUNDS = new AxisAlignedBB(0, 0, 0, 0, 0, 0);
foreach(Block::$class as $nonstaticname){
/**@var Block $b*/
$b = new $nonstaticname();
self::$isSolid[$b->getID()] = $b->isSolid;
self::$isTransparent[$b->getID()] = $b->isTransparent;
self::$isFlowable[$b->getID()] = $b->isFlowable;
@ -45,7 +45,7 @@ class StaticBlock
FireBlock::setFlammabilityAndCatchingChance($b->getID(), 0, 0);
self::setBlockBounds($b->getID(), 0, 0, 0, 1, 1, 1);
}
self::setBlockBounds(BED_BLOCK, 0, 0, 0, 1, 0.5625, 1);
//Cake: has bounds based on world state
//Chest: has bounds based on world state
@ -68,16 +68,16 @@ class StaticBlock
self::setBlockBounds(SLAB, 0, 0, 0, 1, 0.5, 1);
self::setBlockBounds(RAIL, 0, 0, 0, 1, 0.125, 1);
self::setBlockBounds(POWERED_RAIL, 0, 0, 0, 1, 0.125, 1);
self::setBlockBounds(DANDELION, 0.3, 0.0, 0.3, 0.7, 0.6, 0.7); //extends Bush
self::setBlockBounds(ROSE, 0.3, 0.0, 0.3, 0.7, 0.6, 0.7); //extends Bush
self::setBlockBounds(SUGARCANE_BLOCK, 0.5 - 0.375, 0, 0.5 - 0.375, 0.5 + 0.375, 1, 0.5 + 0.375);
self::setBlockBounds(SNOW_LAYER, 0, 0, 0, 1, 0.125, 1);
self::setBlockBounds(CARPET, 0, 0, 0, 1, 0, 1);
//Stairs: based on different factors
//Stone wall: based on state
//Fire related stuff
FireBlock::setFlammabilityAndCatchingChance(PLANKS, 5, 20);
FireBlock::setFlammabilityAndCatchingChance(DOUBLE_WOOD_SLAB, 5, 20);
@ -101,29 +101,29 @@ class StaticBlock
FireBlock::setFlammabilityAndCatchingChance(HAY_BALE, 60, 20);
FireBlock::setFlammabilityAndCatchingChance(SPONGE, 30, 60);
}
public static function setBlockBounds($blockID, $minX, $minY, $minZ, $maxX, $maxY, $maxZ){
self::$maxXs[$blockID] = $maxX;
self::$maxYs[$blockID] = $maxY;
self::$maxZs[$blockID] = $maxZ;
self::$minXs[$blockID] = $minX;
self::$minYs[$blockID] = $minY;
self::$minZs[$blockID] = $minZ;
}
public static function getAABB($id, $x, $y, $z){
return new AxisAlignedBB(self::$minXs[$id] + $x, self::$minYs[$id] + $y, self::$minZs[$id] + $z, self::$maxXs[$id] + $x, self::$maxYs[$id] + $y, self::$maxZs[$id] + $z); //TODO get bb from self::$boundingBoxes ?
}
public static function getBlock($id){
return self::$prealloc[$id] ?? self::$prealloc[0]; //accessing preallocated instances is faster Block::$class[$id] ?? Block::$class[0];
}
public static function getHardness($id){
return self::$hardness[$id] ?? StaticBlock::DEFAULT_HARDNESS;
return self::$hardness[$id] ?? StaticBlock::DEFAULT_HARDNESS;
}
//TODO: use static block min/max
public static function getBoundingBoxForBlockCoords($id, $x, $y, $z){
/**@var AxisAlignedBB $bb*/
@ -134,40 +134,39 @@ class StaticBlock
$bb = clone $bb;
return $bb->setBounds($x + $bb->minX, $y + $bb->minY, $z + $bb->minZ, $x + $bb->maxX, $y + $bb->maxY, $z + $bb->maxZ);
}
public static function getSlipperiness($id){
return self::$slipperiness[$id] ?? StaticBlock::DEFAULT_SLIPPERINESS;
}
public static function getIsSolid($id){
return self::$isSolid[$id] ?? false;
}
public static function getIsTransparent($id){
return self::$isTransparent[$id] ?? false;
}
public static function getIsFlowable($id){
return self::$isFlowable[$id] ?? false;
}
public static function getIsReplaceable($id){
return self::$isReplaceable[$id] ?? false;
}
public static function getIsPlaceable($id){
return self::$isPlaceable[$id] ?? false;
}
public static function getHasPhysics($id){
return self::$hasPhysics[$id] ?? false;
return self::$hasPhysics[$id] ?? false;
}
public static function getIsLiquid($id){
return self::$isLiquid[$id] ?? false;
}
public static function getIsFullBlock($id){
return self::$isFullBlock[$id] ?? false;
}

View file

@ -86,14 +86,13 @@ class DoorBlock extends TransparentBlock{
}
break;
}
return [$aabb->offset($x, $y, $z)];
}
public static function getCompositeData(Level $level, $x, $y, $z){
$myMeta = $level->level->getBlockDamage($x, $y, $z);
if(($myMeta & 8) != 0){
$metaLower = $level->level->getBlockDamage($x, $y - 1, $z);
$metaUpper = $myMeta;
@ -101,19 +100,18 @@ class DoorBlock extends TransparentBlock{
$metaLower = $myMeta;
$metaUpper = $level->level->getBlockDamage($x, $y + 1, $z);
}
return $metaLower & 7 | (($myMeta & 8) != 0 ? 8 : 0) | (($metaUpper & 1 != 0) ? 16 : 0);
}
public static function neighborChanged(Level $level, $x, $y, $z, $nX, $nY, $nZ, $oldID){
if($level->level->getBlockID($x, $y - 1, $z) == AIR){ //Replace with common break method
$level->fastSetBlockUpdate($x, $y, $z, 0, 0);
$id = $level->level->getBlockID($x, $y, $z);
if($id == 64) ServerAPI::request()->api->entity->drop(new Position($x+0.5, $y, $z+0.5, $level), BlockAPI::getItem(324, 0, 1));
elseif($id == 71) ServerAPI::request()->api->entity->drop(new Position($x+0.5, $y, $z+0.5, $level), BlockAPI::getItem(330, 0, 1));
if($id == 64) ServerAPI::request()->api->entity->drop(new Position($x + 0.5, $y, $z + 0.5, $level), BlockAPI::getItem(324, 0, 1));
elseif($id == 71) ServerAPI::request()->api->entity->drop(new Position($x + 0.5, $y, $z + 0.5, $level), BlockAPI::getItem(330, 0, 1));
$top = $level->level->getBlockID($x, $y + 1, $z);
if($top == IRON_DOOR_BLOCK || $top == DOOR_BLOCK){
$level->fastSetBlockUpdate($x, $y + 1, $z, 0, 0);
@ -121,12 +119,7 @@ class DoorBlock extends TransparentBlock{
}
}
/**
* @param Item $item
* @param Player $player
* @param Block $block
* @param Block $target
* @param integer $face
* @param integer $fx
* @param integer $fy
@ -142,12 +135,12 @@ class DoorBlock extends TransparentBlock{
return false;
}
$direction = $player->entity->getDirection();
$face = array(
$face = [
0 => 3,
1 => 4,
2 => 2,
3 => 5,
);
];
$next = $this->getSide($face[(($direction + 2) % 4)]);
$next2 = $this->getSide($face[$direction]);
$metaUp = 0x08;
@ -155,17 +148,15 @@ class DoorBlock extends TransparentBlock{
$metaUp |= 0x01;
}
$this->level->setBlock($blockUp, BlockAPI::get($this->id, $metaUp), true, false, true); //Top
$this->meta = $direction & 0x03;
$this->level->setBlock($block, $this, true, false, true); //Bottom
return true;
return true;
}
return false;
}
/**
* @param Item $item
* @param Player $player
*
* @return boolean
*/
@ -186,8 +177,6 @@ class DoorBlock extends TransparentBlock{
}
/**
* @param Item $item
* @param Player $player
*
* @return boolean
*/

View file

@ -12,10 +12,6 @@ class FallableBlock extends SolidBlock{
}
/**
* @param Item $item
* @param Player $player
* @param Block $block
* @param Block $target
* @param int $face
* @param int $fx
* @param int $fy

View file

@ -1,6 +1,5 @@
<?php
class GenericBlock extends Block{
/**
* @param int $id
@ -12,10 +11,6 @@ class GenericBlock extends Block{
}
/**
* @param Item $item
* @param Player $player
* @param Block $block
* @param Block $target
* @param integer $face
* @param integer $fx
* @param integer $fy
@ -28,8 +23,6 @@ class GenericBlock extends Block{
}
/**
* @param Item $item
* @param Player $player
*
* @return boolean
*/
@ -38,8 +31,6 @@ class GenericBlock extends Block{
}
/**
* @param Item $item
* @param Player $player
*
* @return mixed
*/
@ -55,26 +46,25 @@ class GenericBlock extends Block{
parent::onPlace($level, $x, $y, $z);
}
}
public static function onUpdate(Level $level, $x, $y, $z, $type){
[$id, $meta] = $level->level->getBlock($x, $y, $z);
$down = $level->level->getBlockID($x, $y - 1, $z);
if($down == AIR || StaticBlock::getIsLiquid($down)){
$data = array(
$data = [
"x" => $x + 0.5,
"y" => $y - 0.5,
"z" => $z + 0.5,
"Tile" => $id,
);
];
$server = ServerAPI::request();
$level->fastSetBlockUpdate($x, $y, $z, 0, 0, true);
$e = $server->api->entity->add($level, ENTITY_FALLING, FALLING_SAND, $data);
$server->api->entity->spawnToAll($e);
}
}
/**
* @param integer $type
*
* @return boolean
*/
@ -86,8 +76,6 @@ class GenericBlock extends Block{
}
/**
* @param Item $item
* @param Player $player
*
* @return boolean
*/

View file

@ -21,14 +21,14 @@ class LiquidBlock extends TransparentBlock{
return match(static::$blockID){
WATER, STILL_WATER => $id == WATER || $id == STILL_WATER ? $meta : -1,
LAVA, STILL_LAVA => $id == LAVA || $id == STILL_LAVA ? $meta : -1,
default=> -1
default => -1
};
}
public static function onPlace(Level $level, $x, $y, $z){
static::updateLiquid($level, $x, $y, $z);
}
public static function neighborChanged(Level $level, $x, $y, $z, $nX, $nY, $nZ, $oldID){
static::updateLiquid($level, $x, $y, $z);
}
@ -40,10 +40,10 @@ class LiquidBlock extends TransparentBlock{
$f = ($meta + 1) / 9;
return $f;
}
public static function getRenderedDepth(Level $level, $x, $y, $z){
[$id, $meta] = $level->level->getBlock($x, $y, $z);
$cond = match($id){
WATER, STILL_WATER => static::$blockID == WATER || static::$blockID == STILL_WATER,
LAVA, STILL_LAVA => static::$blockID == LAVA || static::$blockID == STILL_LAVA,
@ -52,23 +52,23 @@ class LiquidBlock extends TransparentBlock{
if(!$cond) return -1;
return $meta >= 8 ? 0 : $meta;
}
public static function shouldRenderFace(Level $level, $x, $y, $z, $face){
$id = $level->level->getBlockID($x, $y, $z);
if($id == ICE) return false;
if((($id == WATER || $id == STILL_WATER) && (static::$blockID == WATER || static::$blockID == STILL_WATER))) return false;
if((($id == LAVA || $id == STILL_LAVA) && (static::$blockID == LAVA || static::$blockID == STILL_LAVA))) return false;
if($face == 1) return true;
return StaticBlock::getIsSolid($id);
//return parent::shouldRenderFace($level, $x, $y, $z, $face);
}
public static function getFlow(Level $level, $x, $y, $z){
$flowVector = new Vector3(0, 0, 0);
$v6 = static::getRenderedDepth($level, $x, $y, $z);
for($v7 = 0; $v7 < 4; ++$v7){
$v8 = $x;
$v10 = $z;
@ -86,12 +86,12 @@ class LiquidBlock extends TransparentBlock{
++$v10;
break;
}
$v11 = static::getRenderedDepth($level, $v8, $y, $v10);
if($v11 < 0){
if(!StaticBlock::getIsSolid($level->level->getBlockID($v8, $y, $v10))){ //TODO material.blocksMovement
$v11 = static::getRenderedDepth($level, $v8, $y - 1, $v10);
if($v11 >= 0){
$v12 = $v11 - ($v6 - 8);
$flowVector->x += ($v8 - $x) * $v12;
@ -99,29 +99,29 @@ class LiquidBlock extends TransparentBlock{
$flowVector->z += ($v10 - $z) * $v12;
}
}
}else if($v11 >= 0){
}elseif($v11 >= 0){
$v12 = $v11 - $v6;
$flowVector->x += ($v8 - $x) * $v12;
$flowVector->y += ($y - $y) * $v12;
$flowVector->z += ($v10 - $z) * $v12;
}
}
$meta = $level->level->getBlockDamage($x, $y, $z);
if($meta >= 8){
$v13 = //TODO more vanilla way to do it
static::shouldRenderFace($level, $x, $y, $z - 1, 2) ||
static::shouldRenderFace($level, $x, $y, $z + 1, 3) ||
static::shouldRenderFace($level, $x - 1, $y, $z, 4) ||
static::shouldRenderFace($level, $x + 1, $y, $z, 5) ||
static::shouldRenderFace($level, $x, $y + 1, $z - 1, 2) ||
static::shouldRenderFace($level, $x, $y + 1, $z + 1, 3) ||
static::shouldRenderFace($level, $x - 1, $y + 1, $z, 4) ||
static::shouldRenderFace($level, $x + 1, $y + 1, $z, 5)
;
if($v13){
$ln = $flowVector->length();
if($ln){
@ -141,37 +141,37 @@ class LiquidBlock extends TransparentBlock{
}else{
$flowVector->x = $flowVector->y = $flowVector->z = 0;
}
return $flowVector;
}
public static function addVelocityToEntity(Level $level, $x, $y, $z, Entity $entity, Vector3 $velocityVector){
$flow = static::getFlow($level, $x, $y, $z);
$velocityVector->x += $flow->x * 0.5;
$velocityVector->y += $flow->y * 0.5;
$velocityVector->z += $flow->z * 0.5;
}
public static function getTickDelay(){
throw new RuntimeException("If you see this, something bad happened");
}
public static function updateLiquid(Level $level, $x, $y, $z){
[$id, $meta] = $level->level->getBlock($x, $y, $z);
if($id != LAVA && $id != STILL_LAVA) return;
$zNeg = $level->level->getBlockID($x, $y, $z - 1);
$zPos = $level->level->getBlockID($x, $y, $z + 1);
$xNeg = $level->level->getBlockID($x - 1, $y, $z);
$xPos = $level->level->getBlockID($x + 1, $y, $z);
$yPos = $level->level->getBlockID($x, $y + 1, $z);
if(
$zNeg == WATER || $zNeg == STILL_WATER
|| $zPos == WATER || $zPos == STILL_WATER
|| $xNeg == WATER || $xNeg == STILL_WATER
|| $xPos == WATER || $xPos == STILL_WATER
|| $yPos == WATER || $yPos == STILL_WATER
|| $zPos == WATER || $zPos == STILL_WATER
|| $xNeg == WATER || $xNeg == STILL_WATER
|| $xPos == WATER || $xPos == STILL_WATER
|| $yPos == WATER || $yPos == STILL_WATER
) {
if($meta){
//if($meta > 4) -> fizz & ret
@ -179,17 +179,16 @@ class LiquidBlock extends TransparentBlock{
}else{
$replacement = OBSIDIAN;
}
$level->fastSetBlockUpdate($x, $y, $z, $replacement, true);
}
}
public function getDrops(Item $item, Player $player){
return array();
return [];
}
public function getLiquidHeight(){
return (($this->meta >= 8 ? 0 : $this->meta)+1) / 9;
return (($this->meta >= 8 ? 0 : $this->meta) + 1) / 9;
}
}

View file

@ -11,7 +11,7 @@ class SolidBlock extends GenericBlock{
$this->isSolid = true;
$this->isFullBlock = true;
}
public static function getCollisionBoundingBoxes(Level $level, $x, $y, $z, Entity $entity){
return [new AxisAlignedBB($x, $y, $z, $x + 1, $y + 1, $z + 1)];
}

View file

@ -15,26 +15,26 @@ class StairBlock extends TransparentBlock{
}
$this->hardness = 30;
}
public static function isBlocksStairsID($id){
return $id > 0 && StaticBlock::getBlock($id) instanceof StairBlock;
}
public static function isStairsAtXYZAndAreTheirMetadataSame(Level $level, $x, $y, $z, $meta){
$block = $level->level->getBlock($x, $y, $z);
return self::isBlocksStairsID($block[0]) && $block[1] == $meta;
}
public static function setBaseShape(Level $level, $x, $y, $z){
$meta = $level->level->getBlockDamage($x, $y, $z);
if(($meta & 4) != 0){
return new AxisAlignedBB(0, 0.5, 0, 1, 1, 1);
}else{
return new AxisAlignedBB(0, 0, 0, 1, 0.5, 1);
}
}
const DEAD_SAPCES = [
[2, 6],
[3, 7],
@ -45,72 +45,72 @@ class StairBlock extends TransparentBlock{
[0, 1],
[4, 5]
];
public static function updateShape(Level $level, $x, $y, $z){
if(self::$complexState){
$id = $level->level->getBlockID($x, $y, $z);
$cid = self::$complexStateID;
StaticBlock::setBlockBounds($id,
StaticBlock::setBlockBounds($id,
0.5 * ($cid % 2),
0.5 * ((int)($cid / 2) % 2),
0.5 * ((int)($cid / 4) % 2),
0.5 * ((int) ($cid / 2) % 2),
0.5 * ((int) ($cid / 4) % 2),
0.5 + 0.5 * ($cid % 2),
0.5 + 0.5 * ((int)($cid / 2) % 2),
0.5 + 0.5 * ((int)($cid / 4) % 2)
0.5 + 0.5 * ((int) ($cid / 2) % 2),
0.5 + 0.5 * ((int) ($cid / 4) % 2)
);
}else{
StaticBlock::setBlockBounds($level->level->getBlockID($x, $y, $z), 0, 0, 0, 1, 1, 1);
}
}
static $complexState = false;
static $complexStateID = 0;
public static function clip(Level $level, $x, $y, $z, Vector3 $start, Vector3 $end){
$v7 = [];
$v8 = $level->level->getBlockDamage($x, $y, $z);
$v9 = $v8 & 3;
$v10 = ($v8 & 4) == 4;
$v11 = self::DEAD_SAPCES[$v9 + ($v10 ? 4 : 0)];
self::$complexState = true;
for($v12 = 0; $v12 < 8; ++$v12){
self::$complexStateID = $v12;
for($v15 = 0; $v15 < /*count($v11}*/ 2; ++$v15){
$v16 = $v11[$v15];
if($v16 == $v12){
//wat
}
}
$v7[$v12] = parent::clip($level, $x, $y, $z, $start, $end);
}
for($v14 = 0; $v14 < /*count($v11}*/ 2; ++$v14){
$v15 = $v11[$v14];
$v7[$v15] = null;
}
$v24 = 0;
$v22 = null;
for($v17 = 0; $v17 < count($v7); ++$v17){
$v18 = $v7[$v17];
if($v18 != null){
$v19 = $v18->hitVector->distanceSquared($end);
if($v19 > $v24){
$v22 = $v18;
$v24 = $v19;
}
}
}
return $v22;
}
public static function setStepShape(Level $level, $x, $y, $z){
$blockMeta = $level->level->getBlockDamage($x, $y, $z);
$metaAnd3 = $blockMeta & 3;
@ -120,13 +120,13 @@ class StairBlock extends TransparentBlock{
$minY = 0.0;
$maxY = 0.5;
}
$minX = 0;
$maxX = 1;
$minZ = 0;
$maxZ = 0.5;
$v13 = true;
switch($metaAnd3){
case 0:
$minX = 0.5;
@ -134,10 +134,10 @@ class StairBlock extends TransparentBlock{
$blockNearby = $level->level->getBlock($x + 1, $y, $z);
$blockIDNearby = $blockNearby[0];
$blockMetaNearby = $blockNearby[1];
if(self::isBlocksStairsID($blockIDNearby) && (($blockMeta & 4) == ($blockMetaNearby & 4))){
$blockMetaNearbyAnd3 = $blockMetaNearby & 3;
if($blockMetaNearbyAnd3 == 3 && !self::isStairsAtXYZAndAreTheirMetadataSame($level, $x, $y, $z + 1, $blockMeta)){
$maxZ = 0.5;
$v13 = false;
@ -153,10 +153,10 @@ class StairBlock extends TransparentBlock{
$blockNearby = $level->level->getBlock($x - 1, $y, $z);
$blockIDNearby = $blockNearby[0];
$blockMetaNearby = $blockNearby[1];
if(self::isBlocksStairsID($blockIDNearby) && (($blockMeta & 4) == ($blockMetaNearby & 4))){
$blockMetaNearbyAnd3 = $blockMetaNearby & 3;
if($blockMetaNearbyAnd3 == 3 && !self::isStairsAtXYZAndAreTheirMetadataSame($level, $x, $y, $z + 1, $blockMeta)){
$maxZ = 0.5;
$v13 = false;
@ -172,10 +172,10 @@ class StairBlock extends TransparentBlock{
$blockNearby = $level->level->getBlock($x, $y, $z + 1);
$blockIDNearby = $blockNearby[0];
$blockMetaNearby = $blockNearby[1];
if(self::isBlocksStairsID($blockIDNearby) && (($blockMeta & 4) == ($blockMetaNearby & 4))){
$blockMetaNearbyAnd3 = $blockMetaNearby & 3;
if($blockMetaNearbyAnd3 == 1 && !self::isStairsAtXYZAndAreTheirMetadataSame($level, $x + 1, $y, $z, $blockMeta)){
$maxX = 0.5;
$v13 = false;
@ -191,7 +191,7 @@ class StairBlock extends TransparentBlock{
$blockMetaNearby = $blockNearby[1];
if(self::isBlocksStairsID($blockIDNearby) && (($blockMeta & 4) == ($blockMetaNearby & 4))){
$blockMetaNearbyAnd3 = $blockMetaNearby & 3;
if($blockMetaNearbyAnd3 == 1 && !self::isStairsAtXYZAndAreTheirMetadataSame($level, $x + 1, $y, $z, $blockMeta)){
$maxX = 0.5;
$v13 = false;
@ -203,34 +203,34 @@ class StairBlock extends TransparentBlock{
break;
}
return [new AxisAlignedBB($minX, $minY, $minZ, $maxX, $maxY, $maxZ), $v13];
}
public static function setInnerPieceShape(Level $level, $x, $y, $z){
$meta = $level->level->getBlockDamage($x, $y, $z);
$metaAnd3 = $meta & 3;
$minY = 0.5;
$maxY = 1.0;
if(($meta & 4) != 0){
$minY = 0.0;
$maxY = 0.5;
}
$minX = 0.0;
$maxX = 0.5;
$minZ = 0.5;
$maxZ = 1.0;
$v13 = false;
switch($metaAnd3){
case 0:
$idNearby = $level->level->getBlockID($x - 1, $y, $z);
$metaNearby = $level->level->getBlockDamage($x - 1, $y, $z);
if(self::isBlocksStairsID($idNearby) && ($meta & 4) == ($metaNearby & 4)){
$metaNearbyAnd3 = $metaNearby & 3;
if($metaNearbyAnd3 == 3 && !self::isStairsAtXYZAndAreTheirMetadataSame($level, $x, $y, $z - 1, $meta)){
$minZ = 0;
$maxZ = 0.5;
@ -245,7 +245,7 @@ class StairBlock extends TransparentBlock{
case 1:
$idNearby = $level->level->getBlockID($x + 1, $y, $z);
$metaNearby = $level->level->getBlockDamage($x + 1, $y, $z);
if(self::isBlocksStairsID($idNearby) && ($meta & 4) == ($metaNearby & 4)){
$minX = 0.5;
$maxX = 1.0;
@ -261,17 +261,17 @@ class StairBlock extends TransparentBlock{
$v13 = true;
}
}
break;
case 2:
$idNearby = $level->level->getBlockID($x, $y, $z - 1);
$metaNearby = $level->level->getBlockDamage($x, $y, $z - 1);
if(self::isBlocksStairsID($idNearby) && ($meta & 4) == ($metaNearby & 4)){
$minZ = 0;
$maxZ = 0.5;
$metaNearbyAnd3 = $metaNearby & 3;
if($metaNearbyAnd3 == 1 && !self::isStairsAtXYZAndAreTheirMetadataSame($level, $x - 1, $y, $z, $meta)){
$v13 = true;
}elseif($metaNearbyAnd3 == 0 && !self::isStairsAtXYZAndAreTheirMetadataSame($level, $x + 1, $y, $z, $meta)){
@ -280,16 +280,16 @@ class StairBlock extends TransparentBlock{
$v13 = true;
}
}
break;
case 3:
$idNearby = $level->level->getBlockID($x, $y, $z + 1);
$metaNearby = $level->level->getBlockDamage($x, $y, $z + 1);
if(self::isBlocksStairsID($idNearby) && ($meta & 4) == ($metaNearby & 4)){
$metaNearbyAnd3 = $metaNearby & 3;
if($metaNearbyAnd3 == 1 && !self::isStairsAtXYZAndAreTheirMetadataSame($level, $x - 1, $y, $z, $meta)){
$v13 = true;
}elseif($metaNearbyAnd3 == 0 && !self::isStairsAtXYZAndAreTheirMetadataSame($level, $x + 1, $y, $z, $meta)){
@ -300,10 +300,10 @@ class StairBlock extends TransparentBlock{
}
break;
}
return [new AxisAlignedBB($minX, $minY, $minZ, $maxX, $maxY, $maxZ), $v13];
}
public static function getCollisionBoundingBoxes(Level $level, $x, $y, $z, Entity $entity){
$bbs = [self::setBaseShape($level, $x, $y, $z)->offset($x, $y, $z)];
$ret = self::setStepShape($level, $x, $y, $z);
@ -314,15 +314,11 @@ class StairBlock extends TransparentBlock{
$bbs[] = $ret2[0]->offset($x, $y, $z);
}
}
return $bbs;
}
/**
* @param Item $item
* @param Player $player
* @param Block $block
* @param Block $target
* @param int $face
* @param int $fx
* @param int $fy
@ -331,12 +327,12 @@ class StairBlock extends TransparentBlock{
* @return bool|mixed
*/
public function place(Item $item, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){
$faces = array(
$faces = [
0 => 0,
1 => 2,
2 => 1,
3 => 3,
);
];
$this->meta = $faces[$player->entity->getDirection()] & 0x03;
if(($fy > 0.5 and $face !== 1) or $face === 0){
$this->meta |= 0x04; //Upside-down stairs
@ -346,18 +342,16 @@ class StairBlock extends TransparentBlock{
}
/**
* @param Item $item
* @param Player $player
*
* @return array
*/
public function getDrops(Item $item, Player $player){
if($item->getPickaxeLevel() >= 1){
return array(
array($this->id, 0, 1),
);
return [
[$this->id, 0, 1],
];
}else{
return array();
return [];
}
}
}

View file

@ -13,11 +13,11 @@ class TransparentBlock extends GenericBlock{
$this->isFlowable = false;
$this->isTransparent = true;
$this->isReplaceable = false;
$this->isPlaceable = true;
$this->isPlaceable = true;
$this->isSolid = true;
$this->boundingBox->setBounds($this->x, $this->y, $this->z, $this->x + 1, $this->y + 1, $this->z + 1);
}
public static function getCollisionBoundingBoxes(Level $level, $x, $y, $z, Entity $entity){
return [];
}

View file

@ -4,7 +4,7 @@ class LadderBlock extends TransparentBlock{
public static $blockID;
public static function getAABB(Level $level, $x, $y, $z){
[$id, $meta] = $level->level->getBlock($x, $y, $z);
switch($meta){
case 2:
StaticBlock::setBlockBounds($id, 0.0, 0.0, 0.875, 1.0, 1.0, 1.0);
@ -18,9 +18,9 @@ class LadderBlock extends TransparentBlock{
case 5:
StaticBlock::setBlockBounds($id, 0, 0.0, 0.0, 0.125, 1.0, 1.0);
break;
}
return parent::getAABB($level, $x, $y, $z);
}
public function __construct($meta = 0){
@ -43,7 +43,7 @@ class LadderBlock extends TransparentBlock{
public static function neighborChanged(Level $level, $x, $y, $z, $nX, $nY, $nZ, $oldID){
$side = $level->level->getBlockDamage($x, $y, $z);
$attached = match($side){
3 => $level->level->getBlockID($x, $y, $z - 1),
2 => $level->level->getBlockID($x, $y, $z + 1),
@ -51,7 +51,7 @@ class LadderBlock extends TransparentBlock{
4 => $level->level->getBlockID($x + 1, $y, $z),
default => 0 //TODO
};
if($attached == AIR){ //Replace with common break method
ServerAPI::request()->api->entity->drop(new Position($x, $y, $z, $level), BlockAPI::getItem(LADDER, 0, 1));
$level->fastSetBlockUpdate($x, $y, $z, 0, 0, true);
@ -59,8 +59,8 @@ class LadderBlock extends TransparentBlock{
}
public function getDrops(Item $item, Player $player){
return array(
array($this->id, 0, 1),
);
}
return [
[$this->id, 0, 1],
];
}
}

View file

@ -17,7 +17,7 @@ class SignPostBlock extends TransparentBlock{
$this->isFullBlock = false;
$this->hardness = 5;
}
public function place(Item $item, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){
if(($target->isSolid || $target->getID() === SIGN_POST || $target->getID() === WALL_SIGN) && $face !== 0){
if(!isset(self::$faces[$face])){
@ -32,7 +32,7 @@ class SignPostBlock extends TransparentBlock{
}
return false;
}
public static function neighborChanged(Level $level, $x, $y, $z, $nX, $nY, $nZ, $oldID){
if($level->level->getBlockID($x, $y - 1, $z) === AIR){ //Replace with common break method
ServerAPI::request()->api->entity->drop(new Position($x, $y, $z, $level), BlockAPI::getItem(SIGN, 0, 1));
@ -40,15 +40,15 @@ class SignPostBlock extends TransparentBlock{
$level->fastSetBlockUpdate($x, $y, $z, 0, 0, true, true);
}
}
public function onBreak(Item $item, Player $player){
$this->level->setBlock($this, new AirBlock(), true, true, true);
return true;
}
public function getDrops(Item $item, Player $player){
return array(
array(SIGN, 0, 1),
);
}
return [
[SIGN, 0, 1],
];
}
}

View file

@ -6,15 +6,15 @@ class TorchBlock extends FlowableBlock implements LightingBlock{
parent::__construct(TORCH, $meta, "Torch");
$this->hardness = 0;
}
public function getMaxLightValue(){
return 15;
}
public static function getAABB(Level $level, $x, $y, $z){
return null;
}
public static function neighborChanged(Level $level, $x, $y, $z, $nX, $nY, $nZ, $oldID){
$side = $level->level->getBlockDamage($x, $y, $z);
$attach = match($side){
@ -22,9 +22,9 @@ class TorchBlock extends FlowableBlock implements LightingBlock{
2 => $level->level->getBlockID($x + 1, $y, $z),
3 => $level->level->getBlockID($x, $y, $z - 1),
4 => $level->level->getBlockID($x, $y, $z + 1),
default => $level->level->getBlockID($x, $y - 1, $z)
default => $level->level->getBlockID($x, $y - 1, $z)
};
if(StaticBlock::getIsTransparent($attach) && !($side === 0 && $attach === FENCE)){ //Replace with common break method
ServerAPI::request()->api->entity->drop(new Position($x, $y, $z, $level), BlockAPI::getItem(TORCH, 0, 1));
$level->fastSetBlockUpdate($x, $y, $z, 0, 0);
@ -33,13 +33,13 @@ class TorchBlock extends FlowableBlock implements LightingBlock{
public function place(Item $item, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){
if($target->isTransparent === false and $face !== 0){
$faces = array(
$faces = [
1 => 5,
2 => 4,
3 => 3,
4 => 2,
5 => 1,
);
];
$this->meta = $faces[$face];
$this->level->setBlock($block, $this, true, false, true);
return true;
@ -51,8 +51,8 @@ class TorchBlock extends FlowableBlock implements LightingBlock{
return false;
}
public function getDrops(Item $item, Player $player){
return array(
array($this->id, 0, 1),
);
return [
[$this->id, 0, 1],
];
}
}

View file

@ -17,25 +17,25 @@ class TrapdoorBlock extends TransparentBlock{
$id = $target->getID();
return $id === SLAB || $id === GLOWSTONE || $id === SLAB || $id === WOOD_SLAB || (!$target->isTransparent || $target instanceof StairBlock);
}
public static function isOpen($meta){
return ($meta >> 2) & 1;
}
public static function getAABB(Level $level, $x, $y, $z){
static::updateShape($level, $x, $y, $z);
return StaticBlock::getAABB(static::$blockID, $x, $y, $z);
}
public static function getCollisionBoundingBoxes(Level $level, $x, $y, $z, Entity $entity){
return [static::getAABB($level, $x, $y, $z)];
}
public static function updateShape(Level $level, $x, $y, $z){
[$id, $meta] = $level->level->getBlock($x, $y, $z);
StaticBlock::setBlockBounds($id, 0.0, 0.0, 0.0, 1.0, 0.1875, 1.0);
if(static::isOpen($meta)){
$facing = $meta & 3;
switch($facing){
@ -56,24 +56,24 @@ class TrapdoorBlock extends TransparentBlock{
}
}
}
public function place(Item $item, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){
if(($this->canAttachTo($target)) and $face !== 0 and $face !== 1){
$faces = array(
$faces = [
2 => 0,
3 => 1,
4 => 2,
5 => 3,
);
];
$this->meta = $faces[$face] & 0x03;
$this->level->setBlock($block, $this, true, false, true);
return true;
}
}
public function getDrops(Item $item, Player $player){
return array(
array($this->id, 0, 1),
);
return [
[$this->id, 0, 1],
];
}
public static function neighborChanged(Level $level, $x, $y, $z, $nX, $nY, $nZ, $oldID){
$attach = match($level->level->getBlockDamage($x, $y, $z)){
@ -83,13 +83,13 @@ class TrapdoorBlock extends TransparentBlock{
3, 7 => $level->level->getBlockID($x - 1, $y, $z),
default => 0
};
if($attach == AIR){ //Replace with common break method
ServerAPI::request()->api->entity->drop(new Position($x, $y, $z, $level), BlockAPI::getItem(TRAPDOOR, 0, 1));
$level->fastSetBlockUpdate($x, $y, $z, 0, 0, true);
}
}
public function onActivate(Item $item, Player $player){
$this->meta ^= 0x04;
$this->level->setBlock($this, $this, true, false, true);

View file

@ -10,7 +10,7 @@ class WallSignBlock extends SignPostBlock{
TransparentBlock::__construct(WALL_SIGN, $meta, "Wall Sign");
$this->isSolid = false;
}
public static function neighborChanged(Level $level, $x, $y, $z, $nX, $nY, $nZ, $oldID){
$attached = match($level->level->getBlockDamage($x, $y, $z)){
2 => $level->level->getBlockID($x, $y, $z + 1),
@ -19,7 +19,7 @@ class WallSignBlock extends SignPostBlock{
5 => $level->level->getBlockID($x - 1, $y, $z),
default => WALL_SIGN
};
if(!StaticBlock::getIsSolid($attached) && $attached != SIGN_POST && $attached != WALL_SIGN){
$level->fastSetBlockUpdate($x, $y, $z, 0, 0, true, true);
(ServerAPI::request())->api->entity->drop(new Position($x + 0.5, $y + 0.5, $z + 0.5, $level), BlockAPI::getItem(SIGN, 0, 1));

View file

@ -1,4 +1,5 @@
<?php
require_once("LiquidBlockDynamic.php"); //TODO class loader?
class LavaBlock extends LiquidBlockDynamic implements LightingBlock{
@ -7,16 +8,16 @@ class LavaBlock extends LiquidBlockDynamic implements LightingBlock{
parent::__construct(LAVA, $meta, "Lava");
$this->hardness = 500;
}
public function place(Item $item, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){
$ret = $this->level->setBlock($this, $this, true, false, true);
return $ret;
}
public static function getTickDelay(){
return 30;
}
public function getMaxLightValue(){
return 15;
}

View file

@ -4,55 +4,55 @@ class LiquidBlockDynamic extends LiquidBlock{
public function __construct($id, $meta = 0, $name = "Unknown"){
parent::__construct($id, $meta, $name);
}
public static $blockID = 0;
public static $sourcesAround = 0;
public static $spread = [0, 0, 0, 0];
public static function getHighest(Level $level, $x, $y, $z, $highest){
$depth = static::getDepth($level, $x, $y, $z);
if($depth < 0) return $highest;
if($depth == 0) ++static::$sourcesAround;
if($depth >= 8) $depth = 0;
return $highest >= 0 && $depth >= $highest ? $highest : $depth;
}
public static function setStatic(Level $level, $x, $y, $z){
$meta = $level->level->getBlockDamage($x, $y, $z);
$level->fastSetBlockUpdate($x, $y, $z, static::$blockID + 1, $meta);
}
public static function isWaterBlocking(Level $level, $x, $y, $z){
$id = $level->level->getBlockID($x, $y, $z);
if($id == AIR) return false;
if($id == DOOR_BLOCK || $id == SIGN_POST || $id == WALL_SIGN || $id == LADDER || $id == SUGARCANE_BLOCK) return true;
if($id == CARPET || $id == SNOW_LAYER || $id == RAIL || $id == POWERED_RAIL) return false; //TODO Tile::getThickness() > 0
//TODO materials
//if(!StaticBlock::getIsFlowable($id)) return true;
return StaticBlock::getIsSolid($id);
}
public static function canSpreadTo(Level $level, $x, $y, $z){
$id = $level->level->getBlockID($x, $y, $z);
if($id == LAVA || $id == STILL_LAVA) return false;
if((static::$blockID == WATER) && ($id == WATER || $id == STILL_WATER)) return false;
return static::isWaterBlocking($level, $x, $y, $z) ^ 1;
}
public static function getSpread(Level $level, $x, $y, $z){
for($i = 0; $i < 4; ++$i){
static::$spread[$i] = 1000;
$xs = $x;
$ys = $y;
$zs = $z;
switch($i){
case 0:
--$xs;
@ -67,13 +67,13 @@ class LiquidBlockDynamic extends LiquidBlock{
++$zs;
break;
}
if(static::isWaterBlocking($level, $xs, $ys, $zs)) continue;
[$id, $meta] = $level->level->getBlock($xs, $ys, $zs);
if(((static::$blockID == WATER && ($id == WATER || $id == STILL_WATER)) || (static::$blockID == LAVA && ($id == LAVA || $id == STILL_LAVA))) && $meta == 0){
continue;
}
if(!static::isWaterBlocking($level, $xs, $ys - 1, $zs)) static::$spread[$i] = 0;
else static::$spread[$i] = static::getSlopeDistance($level, $xs, $ys, $zs, 1, $i);
}
@ -85,18 +85,18 @@ class LiquidBlockDynamic extends LiquidBlock{
for($i = 0; $i < 4; ++$i) $ba[$i] = ($i1 == static::$spread[$i]);
return $ba;
}
public static function getSlopeDistance(Level $level, $x, $y, $z, $l, $i1){
$j1 = 1000;
for($k1 = 0; $k1 < 4; ++$k1){
if($k1 == 0 && $i1 == 1 || $k1 == 1 && $i1 == 0 || $k1 == 2 && $i1 == 3 || $k1 == 3 && $i1 == 2){
if($k1 == 0 && $i1 == 1 || $k1 == 1 && $i1 == 0 || $k1 == 2 && $i1 == 3 || $k1 == 3 && $i1 == 2){
continue;
}
$xs = $x;
$ys = $y;
$zs = $z;
switch($k1){
case 0:
--$xs;
@ -111,10 +111,10 @@ class LiquidBlockDynamic extends LiquidBlock{
++$zs;
break;
}
if(static::isWaterBlocking($level, $xs, $ys, $zs)) continue;
[$id, $meta] = $level->level->getBlock($xs, $ys, $zs);
if(
((static::$blockID == WATER && ($id == WATER || $id == STILL_WATER)) ||
(static::$blockID == LAVA && ($id == LAVA || $id == STILL_LAVA))) &&
@ -122,20 +122,20 @@ class LiquidBlockDynamic extends LiquidBlock{
){
continue;
}
if(!static::isWaterBlocking($level, $xs, $ys - 1, $zs)) return $l;
if($l >= 4) continue;
$k2 = static::getSlopeDistance($level, $xs, $ys, $zs, $l + 1, $k1);
if($k2 < $j1) $j1 = $k2;
}
return $j1;
}
public static function trySpreadTo(Level $level, $x, $y, $z, $meta){
if(static::canSpreadTo($level, $x, $y, $z)){
[$id, $meta2] = $level->level->getBlock($x, $y, $z);
if($id > 0){
if(($id == LAVA || $id == STILL_LAVA) && (static::$blockID == LAVA || static::$blockID == STILL_LAVA)); //fizz
else{
@ -147,23 +147,23 @@ class LiquidBlockDynamic extends LiquidBlock{
}
}
}
$level->fastSetBlockUpdate($x, $y, $z, static::$blockID, $meta, true);
}
}
public static function onPlace(Level $level, $x, $y, $z){
static::updateLiquid($level, $x, $y, $z);
$id = $level->level->getBlockID($x, $y, $z);
if($id == static::$blockID) ServerAPI::request()->api->block->scheduleBlockUpdateXYZ($level, $x, $y, $z, BLOCK_UPDATE_SCHEDULED, static::getTickDelay());
}
public static function onUpdate(Level $level, $x, $y, $z, $type){
$id = $level->level->getBlockID($x, $y, $z);
$depth = static::getDepth($level, $x, $y, $z);
$flowAdd = (static::$blockID == LAVA) ? 2 : 1;
$flag = true;
if($depth > 0){
static::$sourcesAround = 0;
$highest = static::getHighest($level, $x - 1, $y, $z, -100);
@ -174,19 +174,19 @@ class LiquidBlockDynamic extends LiquidBlock{
if($j1 >= 8 || $highest < 0) $j1 = -1;
$l1 = static::getDepth($level, $x, $y + 1, $z);
if($l1 >= 0) $j1 = ($l1 >= 8 ? $l1 : $l1 + 8);
if(static::$sourcesAround >= 2 && static::$blockID == WATER){
$idBot = $level->level->getBlockID($x, $y - 1, $z);
if($idBot > 0){
if(StaticBlock::getIsSolid($idBot) || (($idBot == WATER || $idBot == STILL_WATER) && $level->level->getBlockDamage($x, $y, $z) == 0)) $j1 = 0;
}
}
//if(static::$blockID == LAVA && $depth < 8 && $j1 < 8 && $j1 > $depth && mt_rand(0, 4) != 0){ TODO fix later
// $j1 = $depth;
// $flag = false;
//}
if($j1 != $depth){
$depth = $j1;
if($depth < 0) $level->fastSetBlockUpdate($x, $y, $z, 0, 0, true);
@ -195,16 +195,16 @@ class LiquidBlockDynamic extends LiquidBlock{
ServerAPI::request()->api->block->scheduleBlockUpdateXYZ($level, $x, $y, $z, BLOCK_UPDATE_SCHEDULED, static::getTickDelay());
$level->updateNeighborsAt($x, $y, $z, static::$blockID); //TODO check is needed
}
}else if($flag){
}elseif($flag){
static::setStatic($level, $x, $y, $z);
}
}else{
static::setStatic($level, $x, $y, $z);
}
if(static::canSpreadTo($level, $x, $y - 1, $z)){
$level->fastSetBlockUpdate($x, $y - 1, $z, static::$blockID, ($depth >= 8 ? $depth : $depth + 8) & 0xf, true);
}else if($depth >= 0 && ($depth == 0 || static::isWaterBlocking($level, $x, $y - 1, $z))){
}elseif($depth >= 0 && ($depth == 0 || static::isWaterBlocking($level, $x, $y - 1, $z))){
$flags = static::getSpread($level, $x, $y, $z);
$k1 = $depth >= 8 ? 1 : ($depth + $flowAdd);
if($k1 >= 8) return;

View file

@ -6,13 +6,13 @@ class LiquidBlockStatic extends LiquidBlock{
}
public static $blockID = 0;
//TODO: tick: try spread fire if lava
public static function setDynamic(Level $level, $x, $y, $z){
[$id, $meta] = $level->level->getBlock($x, $y, $z);
$dynamicID = $id - 1; //very unsafe
$level->fastSetBlockUpdate($x, $y, $z, $dynamicID, $meta);
$level->fastSetBlockUpdate($x, $y, $z, $dynamicID, $meta);
}
public static function neighborChanged(Level $level, $x, $y, $z, $nX, $nY, $nZ, $oldID){
$oldID = $level->level->getBlockID($x, $y, $z);
static::updateLiquid($level, $x, $y, $z);
@ -21,6 +21,5 @@ class LiquidBlockStatic extends LiquidBlock{
static::setDynamic($level, $x, $y, $z);
}
}
}
}

View file

@ -1,4 +1,5 @@
<?php
require_once("LiquidBlockStatic.php"); //TODO class loader?
class StillLavaBlock extends LiquidBlockStatic{
@ -7,9 +8,9 @@ class StillLavaBlock extends LiquidBlockStatic{
parent::__construct(STILL_LAVA, $meta, "Still Lava");
$this->hardness = 500;
}
public static function getTickDelay(){
return 30;
}
}

View file

@ -1,6 +1,5 @@
<?php
/***REM_START***/
require_once("WaterBlock.php"); //TODO class loader?
require_once("LiquidBlockStatic.php"); //TODO class loader?
@ -13,7 +12,7 @@ class StillWaterBlock extends LiquidBlockStatic{
LiquidBlock::__construct(STILL_WATER, $meta, "Still Water");
$this->hardness = 500;
}
public static function getTickDelay(){
return 5;
}

View file

@ -1,19 +1,20 @@
<?php
require_once("LiquidBlockDynamic.php"); //TODO class loader?
class WaterBlock extends LiquidBlockDynamic{
public static $blockID = WATER;
public function __construct($meta = 0){
parent::__construct(WATER, $meta, "Water");
$this->hardness = 500;
}
public function place(Item $item, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){
$ret = $this->level->setBlock($this, $this, true, false, true);
return $ret;
}
public static function getTickDelay(){
return 5;
}

View file

@ -2,7 +2,7 @@
class AirBlock extends TransparentBlock{
public static $blockID;
public function __construct(){
parent::__construct(AIR, 0, "Air");
$this->isActivable = false;
@ -15,7 +15,7 @@ class AirBlock extends TransparentBlock{
$this->isSolid = false;
$this->isFullBlock = true;
$this->hardness = 0;
}
}

View file

@ -20,37 +20,37 @@ class BedBlock extends TransparentBlock{
$this->isFullBlock = false;
$this->hardness = 1;
}
public static function getCollisionBoundingBoxes(Level $level, $x, $y, $z, Entity $entity){
return [static::getAABB($level, $x, $y, $z)];
}
public static function neighborChanged(Level $level, $x, $y, $z, $nX, $nY, $nZ, $oldID){
$meta = $level->level->getBlockDamage($x, $y, $z);
$dir = $meta & 3;
$isHead = ($meta >> 3) & 1;
$offX = self::HEAD_DIRECTION_OFFSETS[$dir][0];
$offZ = self::HEAD_DIRECTION_OFFSETS[$dir][1];
if($isHead){
if($level->level->getBlockID($x - $offX, $y, $z - $offZ) != BED_BLOCK){
$level->fastSetBlockUpdate($x, $y, $z, 0, 0, true);
}
}else if($level->level->getBlockID($x + $offX, $y, $z + $offZ) != BED_BLOCK){
}elseif($level->level->getBlockID($x + $offX, $y, $z + $offZ) != BED_BLOCK){
$level->fastSetBlockUpdate($x, $y, $z, 0, 0, true);
ServerAPI::request()->api->entity->dropRawPos(
$level,
$x + (lcg_value() * 0.7) + 0.15,
$y + (lcg_value() * 0.7) + 0.15,
$z + (lcg_value() * 0.7) + 0.15,
BlockAPI::getItem(BED, 0, 1),
$level,
$x + (lcg_value() * 0.7) + 0.15,
$y + (lcg_value() * 0.7) + 0.15,
$z + (lcg_value() * 0.7) + 0.15,
BlockAPI::getItem(BED, 0, 1),
lcg_value() * 0.2 - 0.1, 0.2, lcg_value() * 0.2 - 0.1
);
}
}
public static function findStandUpPosition(Level $level, $x, $y, $z){
$blockMeta = $level->level->getBlockDamage($x, $y, $z);
@ -60,7 +60,7 @@ class BedBlock extends TransparentBlock{
$minZ = $z - self::HEAD_DIRECTION_OFFSETS[$direction][1] * $v7 - 1;
$maxX = $minX + 2;
$maxZ = $minZ + 2;
for($xCheck = $minX; $xCheck <= $maxX; ++$xCheck){
for($zCheck = $minZ; $zCheck <= $maxZ; ++$zCheck){
$idCheck = $level->level->getBlockID($xCheck, $y - 1, $zCheck);
@ -70,10 +70,10 @@ class BedBlock extends TransparentBlock{
}
}
}
return null;
}
public function onActivate(Item $item, Player $player){
if(ServerAPI::request()->api->time->getPhase($player->level) !== "night"){
$pk = new ChatPacket;
@ -81,12 +81,12 @@ class BedBlock extends TransparentBlock{
$player->dataPacket($pk);
return true;
}
$blockNorth = $this->getSide(2); //Gets the blocks around them
$blockSouth = $this->getSide(3);
$blockEast = $this->getSide(5);
$blockWest = $this->getSide(4);
if(($this->meta & 0x08) === 0x08){ //This is the Top part of bed
if(($this->meta & 0x08) === 0x08){ //This is the Top part of bed
$b = $this;
}else{ //Bottom Part of Bed
if($blockNorth->getID() === $this->id and ($blockNorth->meta & 0x08) === 0x08){
@ -112,11 +112,11 @@ class BedBlock extends TransparentBlock{
}
return true;
}
public function place(Item $item, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){
$down = $this->getSide(0);
if($down->isTransparent === false){
$d = $player->entity->getDirection();
$next = $this->getSide(self::$faces[(($d + 3) % 4)]);
$downNext = $next->getSide(0);
@ -128,15 +128,15 @@ class BedBlock extends TransparentBlock{
}
}
return false;
}
}
public function onBreak(Item $item, Player $player){
$blockNorth = $this->getSide(2); //Gets the blocks around them
$blockSouth = $this->getSide(3);
$blockEast = $this->getSide(5);
$blockWest = $this->getSide(4);
if(($this->meta & 0x08) === 0x08){ //This is the Top part of bed
if(($this->meta & 0x08) === 0x08){ //This is the Top part of bed
switch($this->meta & 0x7){
case 0:
if($blockNorth->id === $this->id) $this->level->setBlock($blockNorth, new AirBlock(), true, false, true);
@ -170,11 +170,11 @@ class BedBlock extends TransparentBlock{
$this->level->setBlock($this, new AirBlock(), true, false, true);
return true;
}
public function getDrops(Item $item, Player $player){
return array(
array(BED, 0, 1),
);
return [
[BED, 0, 1],
];
}
}

View file

@ -4,7 +4,7 @@ class FireBlock extends FlowableBlock implements LightingBlock{
public static $blockID;
public static $flammability = [];
public static $fireCatchingChance = [];
public function __construct($meta = 0){
parent::__construct(FIRE, $meta, "Fire");
$this->isReplaceable = true;
@ -19,39 +19,39 @@ class FireBlock extends FlowableBlock implements LightingBlock{
self::$flammability[$blockID] = $flammability;
self::$fireCatchingChance[$blockID] = $v;
}
public static function canBurn(Level $level, $x, $y, $z){
return self::$flammability[$level->level->getBlockID($x, $y, $z)] > 0;
}
public static function onRandomTick(Level $level, $x, $y, $z){
if($level->level->getBlockID($x, $y - 1, $z) !== NETHERRACK){
$level->fastSetBlockUpdate($x, $y, $z, 0, 0, true);
}
}
public static function onPlace(Level $level, $x, $y, $z){
ServerAPI::request()->api->block->scheduleBlockUpdateXYZ($level, $x, $y, $z, BLOCK_UPDATE_SCHEDULED, 30);
}
public function getDrops(Item $item, Player $player){
return array();
return [];
}
public function getMaxLightValue(){
return 15;
}
public static function neighborChanged(Level $level, $x, $y, $z, $nX, $nY, $nZ, $oldID){
$b = $level->level->getBlockID($x, $y - 1, $z);
if(!StaticBlock::getIsSolid($b)) $level->fastSetBlockUpdate($x, $y, $z, 0, 0, true); //TODO more vanilla later?
}
public static function onUpdate(Level $level, $x, $y, $z, $type){
if($type === BLOCK_UPDATE_SCHEDULED){
$idBelow = $level->level->getBlockID($x, $y - 1, $z);
[$id, $meta] = $level->level->getBlock($x, $y, $z);
$alwaysBurn = $idBelow == NETHERRACK;
if($meta < 15){
$newMeta = $meta + 1; //TODO better formula
if($newMeta > 15) $newMeta = 15;
@ -65,20 +65,19 @@ class FireBlock extends FlowableBlock implements LightingBlock{
}
}
$chance = self::$fireCatchingChance[$idBelow];
if(mt_rand(0, 249) < $chance){
//TODO ignite tnt
$level->fastSetBlockUpdate($x, $y - 1, $z, 0, 0, true);
goto REMOVE_FIRE;
}
ServerAPI::request()->api->block->scheduleBlockUpdateXYZ($level, $x, $y, $z, BLOCK_UPDATE_SCHEDULED, 30); //TODO looks like it also adds mt_rand(0, 9) to it
}
}
public function place(Item $item, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){
parent::place($item, $player, $block, $target, $face, $fx, $fy, $fz);
$this->level->scheduleBlockUpdate($this, 30, BLOCK_UPDATE_SCHEDULED);
}
}

Some files were not shown because too many files have changed in this diff Show more