Merge branch 'master'

# Conflicts:
#	src/API/AchievementAPI.php
#	src/API/BanAPI.php
#	src/API/BlockAPI.php
#	src/API/EntityAPI.php
#	src/API/PlayerAPI.php
#	src/Player.php
#	src/PocketMinecraftServer.php
#	src/config.php
#	src/entity/Animal.php
#	src/entity/Breedable.php
#	src/entity/Creature.php
#	src/entity/Entity.php
#	src/entity/animal/Sheep.php
#	src/entity/monster/Creeper.php
#	src/entity/monster/Zombie.php
#	src/entity/object/Arrow.php
#	src/entity/object/FallingSand.php
#	src/entity/object/ItemEntity.php
#	src/entity/object/Minecart.php
#	src/entity/object/Painting.php
#	src/entity/object/PrimedTNT.php
#	src/material/Block.php
#	src/material/Item.php
#	src/material/Material.php
#	src/material/StaticBlock.php
#	src/material/block/DoorBlock.php
#	src/material/block/GenericBlock.php
#	src/material/block/attachable/WallSignBlock.php
#	src/material/block/liquid/LiquidBlockDynamic.php
#	src/material/block/misc/AirBlock.php
#	src/material/block/misc/BedBlock.php
#	src/material/block/misc/TNTBlock.php
#	src/material/block/nonfull/CarpetBlock.php
#	src/material/block/nonfull/FenceBlock.php
#	src/material/block/nonfull/PoweredRailBlock.php
#	src/material/block/nonfull/RailBlock.php
#	src/material/block/nonfull/SnowLayerBlock.php
#	src/material/block/nonfull/WoodSlabBlock.php
#	src/material/block/plant/BrownMushroomBlock.php
#	src/material/block/plant/DandelionBlock.php
#	src/material/block/plant/MelonStemBlock.php
#	src/material/block/plant/PumpkinStemBlock.php
#	src/material/block/plant/RedMushroomBlock.php
#	src/material/block/plant/SugarcaneBlock.php
#	src/material/block/solid/GrassBlock.php
#	src/material/block/solid/IceBlock.php
#	src/material/block/solid/LeavesBlock.php
#	src/material/block/solid/ObsidianBlock.php
#	src/material/block/solid/PumpkinBlock.php
#	src/material/block/solid/WoolBlock.php
#	src/material/item/base/ItemHoe.php
#	src/material/item/base/ItemTool.php
#	src/material/item/generic/DyeItem.php
#	src/material/item/generic/SpawnEggItem.php
#	src/material/item/tool/FlintSteelItem.php
#	src/material/item/tool/ShearsItem.php
#	src/math/AxisAlignedBB.php
#	src/network/MinecraftInterface.php
#	src/network/UDPSocket.php
#	src/network/protocol/packet/AddItemEntityPacket.php
#	src/network/protocol/packet/ContainerSetContentPacket.php
#	src/network/raknet/RakNetDataPacket.php
#	src/network/raknet/RakNetParser.php
#	src/pmf/PMFLevel.php
#	src/utils/Utils.php
#	src/world/Explosion.php
#	src/world/Level.php
#	src/world/MobSpawner.php
This commit is contained in:
yefengeeeeeeeeeee 2026-04-04 14:52:08 +08:00
commit 3fbab46e60
245 changed files with 6118 additions and 3408 deletions

View file

@ -10,22 +10,24 @@ Supported MCPE versions: 0.3.0 ~ 0.8.1 (maybe 0.8.2)
<h2> Why should you use NostalgiaCore to run a Minecraft Pocket Edition 0.8.1 server?</h2> <h2> Why should you use NostalgiaCore to run a Minecraft Pocket Edition 0.8.1 server?</h2>
• PHP 8 Support, PHAR plugins
• Crafting system was rewritten to hopefully have less problems
• Items are dropping normally. • Items are dropping normally.
• Dupes, that were in PocketMine by mistake are fixed.
• Player hotbar is saved. • Player hotbar is saved.
• Working Nether Reactor.
• Mob AI
• Dupes, that were in PocketMine by mistake are fixed.
• Extra options (like in-game messages to discord) • Extra options (like in-game messages to discord)
• Vector2 is fixed. • Vector2 is fixed.
• Working Nether Reactor.
• PHAR plugins support
• Mob AI
...and etc. ...and etc.
<h3> Download Stable NostalgiaCore</h3> <h3> Download Stable NostalgiaCore</h3>

View file

@ -81,7 +81,7 @@ class AchievementAPI{
], ],
]; ];
/** @var PocketMinecraftServer */
private $server; private $server;
function __construct(){ function __construct(){
@ -91,8 +91,9 @@ class AchievementAPI{
/** /**
* Add an achievement * Add an achievement
* @param string $achievementId * @param string $achievementId
* @param string $achievementName * @param string $achievementName display name
* @return boolean * @param array $requires a list of achievement ids, optional
* @return boolean true if the achievement was added. false if the achievement with this id already exists.
*/ */
public static function addAchievement($achievementId, $achievementName, array $requires = []){ public static function addAchievement($achievementId, $achievementName, array $requires = []){
if(!isset(self::$achievements[$achievementId])){ if(!isset(self::$achievements[$achievementId])){
@ -105,6 +106,12 @@ class AchievementAPI{
return false; return false;
} }
/**
* Gives the achievement to player
* @param Player $player
* @param string $achievementId
* @return boolean
*/
public static function grantAchievement(Player $player, $achievementId){ public static function grantAchievement(Player $player, $achievementId){
if(isset(self::$achievements[$achievementId]) and !self::hasAchievement($player, $achievementId)){ if(isset(self::$achievements[$achievementId]) and !self::hasAchievement($player, $achievementId)){
foreach(self::$achievements[$achievementId]["requires"] as $requerimentId){ foreach(self::$achievements[$achievementId]["requires"] as $requerimentId){
@ -123,6 +130,11 @@ class AchievementAPI{
return false; return false;
} }
/**
* @param Player $player
* @param string $achievementId
* @return boolean
*/
public static function hasAchievement(Player $player, $achievementId){ public static function hasAchievement(Player $player, $achievementId){
if(!isset(self::$achievements[$achievementId]) or !isset($player->achievements)){ if(!isset(self::$achievements[$achievementId]) or !isset($player->achievements)){
$player->achievements = []; $player->achievements = [];
@ -135,6 +147,11 @@ class AchievementAPI{
return true; return true;
} }
/**
* @param Player $player
* @param string $achievementId
* @return boolean
*/
public static function broadcastAchievement(Player $player, $achievementId){ public static function broadcastAchievement(Player $player, $achievementId){
if(isset(self::$achievements[$achievementId])){ if(isset(self::$achievements[$achievementId])){
$result = ServerAPI::request()->api->dhandle("achievement.broadcast", ["player" => $player, "achievementId" => $achievementId]); $result = ServerAPI::request()->api->dhandle("achievement.broadcast", ["player" => $player, "achievementId" => $achievementId]);
@ -150,6 +167,11 @@ class AchievementAPI{
return false; return false;
} }
/**
* Removes achievement from player.
* @param Player $player
* @param string $achievementId
*/
public static function removeAchievement(Player $player, $achievementId){ public static function removeAchievement(Player $player, $achievementId){
if(self::hasAchievement($player, $achievementId)){ if(self::hasAchievement($player, $achievementId)){
$player->achievements[$achievementId] = false; $player->achievements[$achievementId] = false;
@ -191,7 +213,7 @@ class AchievementAPI{
$output .= "{$info["name"]}, "; $output .= "{$info["name"]}, ";
} }
} }
return substr($output, 0, -2); return substr($output, 0, - 2);
} }
public function init(){ public function init(){

View file

@ -1,11 +1,8 @@
<?php <?php
class BanAPI{ class BanAPI{
/** @var PocketMinecraftServer */
private $server; private $server;
/*
* I would use PHPDoc Template here but PHPStorm does not recognise it. - @sekjun9878
*/
/** @var Config */ /** @var Config */
private $whitelist; private $whitelist;
/** @var Config */ /** @var Config */
@ -14,10 +11,14 @@ class BanAPI{
private $ops; private $ops;
/** @var Config */ /** @var Config */
private $bannedIPs; private $bannedIPs;
/**
* Contains commands that can be used by anyone on the server.
* Keys: lowercased command name. Values don't matter.
* @var array
*/
public $cmdWhitelist = [];
public $cmdWhitelist = [];//Command WhiteList public function __construct(){
function __construct(){
$this->server = ServerAPI::request(); $this->server = ServerAPI::request();
} }
@ -56,7 +57,6 @@ class BanAPI{
/** /**
* @param mixed $data * @param mixed $data
* @param string $event * @param string $event
*
* @return boolean * @return boolean
*/ */
public function permissionsCheck($data, $event){ public function permissionsCheck($data, $event){
@ -106,11 +106,11 @@ class BanAPI{
} }
/** /**
* Checks is player op or not
* @param string $username * @param string $username
*
* @return boolean * @return boolean
*/ */
public function isOp($username){//Is a player op? public function isOp($username){
$username = strtolower($username); $username = strtolower($username);
if($this->server->api->dhandle("op.check", $username) === true){ if($this->server->api->dhandle("op.check", $username) === true){
return true; return true;
@ -121,6 +121,7 @@ class BanAPI{
} }
/** /**
* Bans a player.
* @param string $username * @param string $username
*/ */
public function ban($username){ public function ban($username){
@ -316,14 +317,16 @@ class BanAPI{
} }
/** /**
* @param string $username * Kicks a player
* @param string $reason * @param string $username - player's username
* @param string $reason - kick reason, optional
*/ */
public function kick($username, $reason = "No Reason"){ public function kick($username, $reason = "No Reason"){
$this->commandHandler("kick", [$username, $reason], "console", ""); $this->commandHandler("kick", [$username, $reason], "console", "");
} }
/** /**
* Unbans a player
* @param string $username * @param string $username
*/ */
public function pardon($username){ public function pardon($username){
@ -331,6 +334,7 @@ class BanAPI{
} }
/** /**
* Bans some ip
* @param string $ip * @param string $ip
*/ */
public function banIP($ip){ public function banIP($ip){
@ -338,12 +342,16 @@ class BanAPI{
} }
/** /**
* Unbans some ip
* @param string $ip * @param string $ip
*/ */
public function pardonIP($ip){ public function pardonIP($ip){
$this->commandHandler("banip", ["pardon", $ip], "console", ""); $this->commandHandler("banip", ["pardon", $ip], "console", "");
} }
/**
* Rereads ban list, kick list and banip list
*/
public function reload(){ public function reload(){
$this->commandHandler("ban", ["reload"], "console", ""); $this->commandHandler("ban", ["reload"], "console", "");
$this->commandHandler("banip", ["reload"], "console", ""); $this->commandHandler("banip", ["reload"], "console", "");
@ -351,8 +359,8 @@ class BanAPI{
} }
/** /**
* Checks is ip banned or not
* @param string $ip * @param string $ip
*
* @return boolean * @return boolean
*/ */
public function isIPBanned($ip){ public function isIPBanned($ip){
@ -366,8 +374,8 @@ class BanAPI{
} }
/** /**
* Checks is username banned or not.
* @param string $username * @param string $username
*
* @return boolean * @return boolean
*/ */
public function isBanned($username){ public function isBanned($username){
@ -382,8 +390,8 @@ class BanAPI{
} }
/** /**
* Checks is username in the whitelist or not
* @param string $username * @param string $username
*
* @return boolean * @return boolean
*/ */
public function inWhitelist($username){ public function inWhitelist($username){

View file

@ -1,9 +1,9 @@
<?php <?php
class BlockAPI{ class BlockAPI{
public static $creativeHotbarSlots = [];
public static $reverseCreativeLookup = [];
public static $creative = [ public static $creative = [
//Building //Building
[STONE, 0], [STONE, 0],
[COBBLESTONE, 0], [COBBLESTONE, 0],
@ -201,8 +201,33 @@ class BlockAPI{
private $scheduledUpdates = []; private $scheduledUpdates = [];
private $randomUpdates = []; private $randomUpdates = [];
/**
* @param int $id item id
* @param int $meta item metadata
* @return false|int false if item is not accessible from creative mode, otherwise slot id in BlockAPI::$creative
*/
public static function hasCreativeItem($id, $meta){
$rind = ($id << 24) | ($meta);
return static::$reverseCreativeLookup[$rind] ?? false;
}
function __construct(){ function __construct(){
$this->server = ServerAPI::request(); $this->server = ServerAPI::request();
foreach(static::$creative as $slot => [$id, $meta]){
$rind = ($id << 24) | ($meta);
static::$reverseCreativeLookup[$rind] = $slot;
}
self::$creativeHotbarSlots[0] = static::hasCreativeItem(STONE, 0);
self::$creativeHotbarSlots[1] = static::hasCreativeItem(COBBLESTONE, 0);
self::$creativeHotbarSlots[2] = static::hasCreativeItem(DIRT, 0);
self::$creativeHotbarSlots[3] = static::hasCreativeItem(PLANKS, 0);
self::$creativeHotbarSlots[4] = static::hasCreativeItem(PLANKS, 1);
self::$creativeHotbarSlots[5] = static::hasCreativeItem(TORCH, 0);
self::$creativeHotbarSlots[6] = static::hasCreativeItem(BRICK_STAIRS, 0);
self::$creativeHotbarSlots[7] = static::hasCreativeItem(COBBLE_WALL, 0);
self::$creativeHotbarSlots[8] = static::hasCreativeItem(SAPLING, 0);
} }
public static function get($id, $meta = 0, $v = false){ public static function get($id, $meta = 0, $v = false){
@ -341,6 +366,16 @@ class BlockAPI{
return $output; return $output;
} }
public static function blockIDFromString($str){
if(defined(strtoupper($str))){
$ida = explode(":", constant(strtoupper($str)));
if(count($ida) === 2){}
return (int) $ida[0];
}else if(is_numeric($str)){
return (int) $str;
}
}
public static function fromString($str, $multiple = false){ public static function fromString($str, $multiple = false){
if($multiple === true){ if($multiple === true){
$blocks = []; $blocks = [];
@ -393,25 +428,49 @@ class BlockAPI{
} }
} }
if((!$target->isBreakable($item, $player) and $this->server->api->dhandle("player.block.break.invalid", ["player" => $player, "target" => $target, "item" => $item]) !== true) or ($player->gamemode & 0x02) === 0x02 or (($player->lastBreak - $player->getLag() / 1000) + $target->getBreakTime($item, $player) - 0.2) >= microtime(true)){ $currentTime = microtime(true);
$isIndestructible = (!$target->isBreakable($item, $player) && $this->server->api->dhandle("player.block.break.invalid", ["player" => $player, "target" => $target, "item" => $item]) !== true);
$isAdventure = ($player->gamemode & 0x02) === 0x02;
$progress = $target->getDestroyProgress($player);
$tooFast = false;
if($progress == 0 || is_nan($progress)){
$exceptedTimeMS = INF;
$tooFast = true;
}else{
$exceptedTimeMS = ceil(PocketMinecraftServer::$BLOCK_BREAKING_PROGRESS / $progress)*0.05;
}
if($player->gamemode == 1){ //creative
$exceptedTimeMS = 0.05; //1 block/tick
$tooFast = false;
}
$exceptedTimeAfter = $player->lastBreak + $exceptedTimeMS;
if($currentTime < $exceptedTimeAfter) $tooFast = true;
if($isIndestructible || $isAdventure || $tooFast){
if($this->server->api->dhandle("player.block.break.bypass", ["player" => $player, "target" => $target, "item" => $item]) !== true){ if($this->server->api->dhandle("player.block.break.bypass", ["player" => $player, "target" => $target, "item" => $item]) !== true){
if($tooFast){
ConsoleAPI::warn("{$player->username} tried destroying block({$target->getID()} {$target->getMetadata()}) too fast($currentTime < $exceptedTimeAfter)");
}
return $this->cancelAction($target, $player, false); return $this->cancelAction($target, $player, false);
} }
} }
$player->lastBreak = microtime(true); $player->lastBreak = $currentTime;
if($this->server->api->dhandle("player.block.break", ["player" => $player, "target" => $target, "item" => $item]) !== false){ if($this->server->api->dhandle("player.block.break", ["player" => $player, "target" => $target, "item" => $item]) !== false){
$drops = $target->getDrops($item, $player); $drops = $target->getDrops($item, $player);
if($target->onBreak($item, $player) === false){ if($target->onBreak($item, $player) === false){
return $this->cancelAction($target, $player, false); return $this->cancelAction($target, $player, false);
} }
if(($player->gamemode & 0x01) === 0 and $item->useOn($target) and $item->getMetadata() >= $item->getMaxDurability()){
$player->setSlot($player->slot, new Item(AIR, 0, 0), false); $item->mineBlock($target, $player);
}
}else{ }else{
return $this->cancelAction($target, $player, false); return $this->cancelAction($target, $player, false);
} }
if(is_array($drops) && ($player->gamemode & 0x01) === 0x00 and count($drops) > 0){ if(is_array($drops) && ($player->gamemode & 0x01) === 0x00 and count($drops) > 0){
foreach($drops as $drop){ 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])); $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]));
@ -421,15 +480,9 @@ class BlockAPI{
} }
private function cancelAction(Block $block, Player $player, $send = true){ private function cancelAction(Block $block, Player $player, $send = true){
$pk = new UpdateBlockPacket; $player->addBlockUpdateIntoQueue($block->x, $block->y, $block->z, $block->getID(), $block->getMetadata());
$pk->x = $block->x;
$pk->y = $block->y;
$pk->z = $block->z;
$pk->block = $block->getID();
$pk->meta = $block->getMetadata();
$player->dataPacket($pk);
if($send === true){ if($send === true){
$player->sendInventorySlot($player->slot); $player->sendInventory();
} }
return false; return false;
} }
@ -441,7 +494,7 @@ class BlockAPI{
$target = $player->level->getBlock($vector); $target = $player->level->getBlock($vector);
$block = $target->getSide($face); $block = $target->getSide($face);
$item = $player->getSlot($player->slot); $item = $player->getHeldItem();
if($target->getID() === AIR and $this->server->api->dhandle("player.block.place.invalid", ["player" => $player, "block" => $block, "target" => $target, "item" => $item]) !== true){ //If no block exists or not allowed in CREATIVE if($target->getID() === AIR and $this->server->api->dhandle("player.block.place.invalid", ["player" => $player, "block" => $block, "target" => $target, "item" => $item]) !== true){ //If no block exists or not allowed in CREATIVE
if($this->server->api->dhandle("player.block.place.bypass", ["player" => $player, "block" => $block, "target" => $target, "item" => $item]) !== true){ if($this->server->api->dhandle("player.block.place.bypass", ["player" => $player, "block" => $block, "target" => $target, "item" => $item]) !== true){
@ -466,7 +519,7 @@ class BlockAPI{
if(($player->gamemode & 0x02) === 0x02){ //Adventure mode!! if(($player->gamemode & 0x02) === 0x02){ //Adventure mode!!
if($this->server->api->dhandle("player.block.place.bypass", ["player" => $player, "block" => $block, "target" => $target, "item" => $item]) !== true){ if($this->server->api->dhandle("player.block.place.bypass", ["player" => $player, "block" => $block, "target" => $target, "item" => $item]) !== true){
return $this->cancelAction($block, $player, false); return $this->cancelAction($block, $player);
} }
} }
@ -474,10 +527,7 @@ class BlockAPI{
return false; return false;
} }
if($item->isActivable === true and $item->onActivate($player->level, $player, $block, $target, $face, $fx, $fy, $fz) === true){ if($item->isActivable === true && $item->onActivate($player->level, $player, $block, $target, $face, $fx, $fy, $fz) === true){
if($item->count <= 0){
$player->setSlot($player->slot, BlockAPI::getItem(AIR, 0, 0), false);
}
return false; return false;
} }
@ -485,14 +535,14 @@ class BlockAPI{
$hand = $item->getBlock(); $hand = $item->getBlock();
$hand->position($block); $hand->position($block);
}elseif($block->getID() === FIRE){ }elseif($block->getID() === FIRE){
$player->level->setBlock($block, new AirBlock(), true, false, true); $player->level->fastSetBlockUpdate($block->x, $block->y, $block->z, 0, 0, true, false);
return false; return false;
}else{ }else{
return $this->cancelAction($block, $player, false); return $this->cancelAction($block, $player, false);
} }
if(!($block->isReplaceable === true or ($hand->getID() === SLAB and $block->getID() === SLAB))){ if(!($block->isReplaceable === true or ($hand->getID() === SLAB and $block->getID() === SLAB))){
return $this->cancelAction($block, $player, false); return $this->cancelAction($block, $player);
} }
if($target->isReplaceable === true){ if($target->isReplaceable === true){
@ -502,30 +552,30 @@ class BlockAPI{
} }
if($hand->isSolid === true && ($hand->getID() != BED_BLOCK && $hand->getID() != CARPET)){ if($hand->isSolid === true && ($hand->getID() != BED_BLOCK && $hand->getID() != CARPET)){
$aabb = $hand->getAABB($block->level, $block->x, $block->y, $block->z); foreach($block->level->players as $pl){
$playerbb = $player->entity->boundingBox; $aabbs = $hand->getCollisionBoundingBoxes($block->level, $block->x, $block->y, $block->z, $pl->entity);
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)){ foreach($aabbs as $aabb){
return $this->cancelAction($block, $player, false); //Entity in block $playerbb = $pl->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)){
return $this->cancelAction($block, $player); //Entity in block
}
}
} }
} }
if($this->server->api->dhandle("player.block.place", ["player" => $player, "block" => $block, "target" => $target, "item" => $item]) === false){ if($this->server->api->dhandle("player.block.place", ["player" => $player, "block" => $block, "target" => $target, "item" => $item]) === false){
return $this->cancelAction($block, $player); return $this->cancelAction($block, $player);
}elseif($hand->place($item, $player, $block, $target, $face, $fx, $fy, $fz) === false){ }elseif($hand->place($item, $player, $block, $target, $face, $fx, $fy, $fz) === false){
return $this->cancelAction($block, $player, false); return $this->cancelAction($block, $player);
} }
if($hand->getID() === SIGN_POST or $hand->getID() === WALL_SIGN){ if($hand->getID() === SIGN_POST or $hand->getID() === WALL_SIGN){
$t = $this->server->api->tile->addSign($player->level, $block->x, $block->y, $block->z); $t = $this->server->api->tile->addSign($player->level, $block->x, $block->y, $block->z);
$t->data["creator"] = $player->username; $t->data["creator"] = $player->username;
} }
if(($player->gamemode & 0x01) === 0x00){ $player->consumeSingleItem();
--$item->count;
if($item->count <= 0){
$player->setSlot($player->slot, BlockAPI::getItem(AIR, 0, 0), false);
}
}
return false; return false;
} }
@ -540,6 +590,8 @@ class BlockAPI{
return $level; return $level;
} }
public function blockUpdateAround(Position $pos, $type = BLOCK_UPDATE_NORMAL, $delay = false){ public function blockUpdateAround(Position $pos, $type = BLOCK_UPDATE_NORMAL, $delay = false){
if($type == BLOCK_UPDATE_NORMAL){ if($type == BLOCK_UPDATE_NORMAL){
@ -568,6 +620,18 @@ class BlockAPI{
$this->blockUpdate($pos->getSide(5), $type); $this->blockUpdate($pos->getSide(5), $type);
} }
} }
public function removeAllBlockUpdates(Level $level){
$update = $this->server->query("SELECT x,y,z,level,type FROM blockUpdates WHERE level = '{$level->getName()}';");
if($update instanceof SQLite3Result){
while(($up = $update->fetchArray(SQLITE3_ASSOC)) !== false){
$index = $up["x"] . "." . $up["y"] . "." . $up["z"] . "." . $up["level"] . "." . $up["type"];
unset($this->scheduledUpdates[$index]);
}
$this->server->query("DELETE FROM blockUpdates WHERE level = '{$level->getName()}';");
}
}
public function scheduleBlockUpdateXYZ(Level $level, $x, $y, $z, $type = BLOCK_UPDATE_SCHEDULED, $delay = false){ public function scheduleBlockUpdateXYZ(Level $level, $x, $y, $z, $type = BLOCK_UPDATE_SCHEDULED, $delay = false){
$type = (int) $type; $type = (int) $type;
if($delay < 0){ if($delay < 0){
@ -585,41 +649,9 @@ class BlockAPI{
} }
public function scheduleBlockUpdate(Position $pos, $delay, $type = BLOCK_UPDATE_SCHEDULED){ public function scheduleBlockUpdate(Position $pos, $delay, $type = BLOCK_UPDATE_SCHEDULED){
$type = (int) $type; return $this->scheduleBlockUpdateXYZ($pos->level, $pos->x, $pos->y, $pos->z, $type, $delay);
if($delay < 0){
return false;
}
$index = $pos->x . "." . $pos->y . "." . $pos->z . "." . $pos->level->getName() . "." . $type;
$delay = microtime(true) + $delay * 0.05;
if(!isset($this->scheduledUpdates[$index])){
$this->scheduledUpdates[$index] = $pos;
$this->server->query("INSERT INTO blockUpdates (x, y, z, level, type, delay) VALUES (" . $pos->x . ", " . $pos->y . ", " . $pos->z . ", '" . $pos->level->getName() . "', " . $type . ", " . $delay . ");");
return true;
}
return false;
} }
public function nextRandomUpdate(Position $pos){
if(!isset($this->scheduledUpdates[$pos->x . "." . $pos->y . "." . $pos->z . "." . $pos->level->getName() . "." . BLOCK_UPDATE_RANDOM])){
$time = microtime(true);
$offset = 0;
while(true){
$t = $offset + Utils::getRandomUpdateTicks() * 0.05;
$update = $this->server->query("SELECT COUNT(*) FROM blockUpdates WHERE level = '" . $pos->level->getName() . "' AND type = " . BLOCK_UPDATE_RANDOM . " AND delay >= " . ($time + $t - 1) . " AND delay <= " . ($time + $t + 1) . ";");
if($update instanceof SQLite3Result){
$update = $update->fetchArray(SQLITE3_NUM);
if($update[0] < 3){
break;
}
}else{
break;
}
$offset += mt_rand(25, 75);
}
$this->scheduleBlockUpdate($pos, $t / 0.05, BLOCK_UPDATE_RANDOM);
}
}
public function blockUpdateTick(){ public function blockUpdateTick(){
$time = microtime(true); $time = microtime(true);
@ -643,29 +675,9 @@ class BlockAPI{
} }
/** /**
* 方块/物品id转换,防止新版本影响旧版本视觉效果 * @deprecated random updates are handled differently now.
*/ */
public static function convertHighItemIdsToOldItemIds(int $protocolId, int $itemId) : int{ public function nextRandomUpdate(Position $pos){
if ($protocolId >= ProtocolInfo12::CURRENT_PROTOCOL_12) {
return $itemId;
}
$idMap = [ //default for protocol < 12
LIT_PUMPKIN => MELON_BLOCK, //block
PUMPKIN_SEEDS => MELON_SEEDS, //item
PUMPKIN_PIE => BREAD, //item
BEETROOT => BREAD, //item
BEETROOT_SEEDS => SEEDS, //item
];
if ($protocolId < ProtocolInfo9::CURRENT_PROTOCOL_9) {
$idMap += [
NETHERRACK => OBSIDIAN, //block
NETHER_BRICK => BRICK, //item
NETHER_QUARTZ => BRICK, //item
];
}
return $idMap[$itemId] ?? $itemId;
} }
} }

View file

@ -3,18 +3,21 @@
class ChatAPI{ class ChatAPI{
private $server; private $server;
public $lastTells = [];
function __construct(){ function __construct(){
$this->server = ServerAPI::request(); $this->server = ServerAPI::request();
} }
public function init(){ public function init(){
$this->server->api->console->register("tell", "<player> <private message ...>", [$this, "commandHandler"]); $this->server->api->console->register("tell", "<player> <private message ...>", [$this, "commandHandler"]);
$this->server->api->console->register("reply", "<private message ...>", [$this, "commandHandler"]);
$this->server->api->console->register("me", "<action ...>", [$this, "commandHandler"]); $this->server->api->console->register("me", "<action ...>", [$this, "commandHandler"]);
$this->server->api->console->register("say", "<message ...>", [$this, "commandHandler"]); $this->server->api->console->register("say", "<message ...>", [$this, "commandHandler"]);
$this->server->api->console->cmdWhitelist("tell"); $this->server->api->console->cmdWhitelist("tell");
$this->server->api->console->cmdWhitelist("reply");
$this->server->api->console->cmdWhitelist("me"); $this->server->api->console->cmdWhitelist("me");
$this->server->api->console->alias("msg", "tell"); $this->server->api->console->alias("msg", "tell");
$this->server->api->console->alias("r", "reply");
} }
/** /**
@ -26,23 +29,20 @@ class ChatAPI{
* @return string * @return string
*/ */
public function commandHandler($cmd, $params, $issuer, $alias){ public function commandHandler($cmd, $params, $issuer, $alias){
$output = "";
switch($cmd){ switch($cmd){
case "say": case "say":
$s = implode(" ", $params); $s = implode(" ", $params);
if(trim($s) == ""){ if(trim($s) == ""){
$output .= "Usage: /say <message>\n"; return "Usage: /say <message>";
break;
} }
$sender = ($issuer instanceof Player) ? "Server" : ucfirst($issuer); $sender = ($issuer instanceof Player) ? "Server" : ucfirst($issuer);
if(Utils::hasEmoji($s)) return "Your message contains illegal characters!"; if(Player::$disableEmojisInChat && Utils::hasEmoji($s)) return "Your message contains illegal characters!";
$this->server->api->chat->broadcast("[$sender] " . $s); $this->server->api->chat->broadcast("[$sender] " . $s);
break; break;
case "me": case "me":
$s = implode(" ", $params); $s = implode(" ", $params);
if(trim($s) == ""){ if(trim($s) == ""){
$output .= "Usage: /me <message>\n"; return "Usage: /me <message>";
break;
} }
if(!($issuer instanceof Player)){ if(!($issuer instanceof Player)){
if($issuer === "rcon"){ if($issuer === "rcon"){
@ -54,46 +54,62 @@ class ChatAPI{
$sender = $issuer->username; $sender = $issuer->username;
} }
$msg = implode(" ", $params); $msg = implode(" ", $params);
if(Utils::hasEmoji($msg)) return "Your message contains illegal characters!"; if(Player::$disableEmojisInChat && Utils::hasEmoji($msg)) return "Your message contains illegal characters!";
$this->broadcast("* $sender $msg"); $this->broadcast("* $sender $msg");
break; break;
case "tell": case "tell":
if(!isset($params[0]) or !isset($params[1])){ if(!isset($params[0]) or !isset($params[1])) return "Usage: /$cmd <player> <message>\n";
$output .= "Usage: /$cmd <player> <message>\n";
break; if(!($issuer instanceof Player)) $sender = ucfirst($issuer);
} else $sender = $issuer->username;
if(!($issuer instanceof Player)){
$sender = ucfirst($issuer);
}else{
$sender = $issuer->username;
}
$n = array_shift($params); $n = array_shift($params);
$target = $this->server->api->player->get($n); $target = $this->server->api->player->get($n);
if($target instanceof Player){ if($target instanceof Player){
$target = $target->username; $target = $target->username;
}else{ }else{
$target = strtolower($n); $target = strtolower($n);
if($target === "server" or $target === "console" or $target === "rcon"){ if($target === "server" || $target === "console" || $target === "rcon"){
$target = "Console"; $target = "Console";
}else{ }else{
return "The player is offline."; return "$target is offline.";
} }
} }
if(strtolower($target) === strtolower($issuer)){ if(strtolower($target) === strtolower($sender)) return "You can't send message to yourself.";
return "You can't send message to yourself.";
$mes = implode(" ", $params);
if(Utils::hasEmoji($mes)) return "Your message contains illegal characters!";
if($target !== "Console" && $target !== "Rcon") $this->sendTo(false, "$sender whispers to you: $mes", $target);
if($target === "Console" || $sender === "Console") console("[INFO] $sender whispers to $target: $mes");
$this->lastTells[strtolower($target)] = strtolower($sender);
$this->lastTells[strtolower($sender)] = strtolower($target);
return "You're whispering to $target: $mes";
case "reply":
if(!($issuer instanceof Player)) $sender = ucfirst($issuer);
else $sender = $issuer->username;
if(!isset($this->lastTells[strtolower($sender)])) return "You have no one to reply to.";
$target = $this->lastTells[strtolower($sender)];
if($target !== "server" && $target !== "console" && $target !== "rcon"){
if(!($this->server->api->player->get($target) instanceof Player)){
return "$target is offline.";
}
} }
$mes = implode(" ", $params); $mes = implode(" ", $params);
if(Utils::hasEmoji($mes)) return "Your message contains illegal characters!"; if(Utils::hasEmoji($mes)) return "Your message contains illegal characters!";
$output .= "You're whispering to " . $target . ": " . $mes . "\n";
if($target !== "Console" and $target !== "Rcon"){ if($target !== "Console" && $target !== "Rcon") $this->sendTo(false, "$sender whispers to you: $mes", $target);
$this->sendTo(false, $sender . " whispers to you: " . $mes, $target); if($target === "Console" || $sender === "Console") console("[INFO] $sender whispers to $target: $mes");
}
if($target === "Console" or $sender === "Console"){ $this->lastTells[strtolower($target)] = strtolower($sender);
console("[INFO] " . $sender . " whispers to " . $target . ": " . $mes); $this->lastTells[strtolower($sender)] = strtolower($target);
}
break; return "You're whispering to $target: $mes";
} }
return $output;
} }
/** /**

View file

@ -1,7 +1,7 @@
<?php <?php
class ConsoleAPI{ class ConsoleAPI{
private static $loop; //why no Thread::kill in pthreads3 private $loop; //why no Thread::kill in pthreads3. Making it static causes crashes of other threads on some servers(hi nper)
private $server, $event, $help, $cmds, $alias; private $server, $event, $help, $cmds, $alias;
public $last; public $last;
function __construct(){ function __construct(){
@ -15,7 +15,7 @@ class ConsoleAPI{
public function init(){ public function init(){
$this->server->schedule(2, [$this, "handle"], [], true); $this->server->schedule(2, [$this, "handle"], [], true);
if(!defined("NO_THREADS")){ if(!defined("NO_THREADS")){
self::$loop = new ConsoleLoop(); $this->loop = new ConsoleLoop();
} }
$this->register("help", "[page|command name]", [$this, "defaultCommands"]); $this->register("help", "[page|command name]", [$this, "defaultCommands"]);
$this->register("status", "", [$this, "defaultCommands"]); $this->register("status", "", [$this, "defaultCommands"]);
@ -51,8 +51,8 @@ class ConsoleAPI{
function __destruct(){ function __destruct(){
$this->server->deleteEvent($this->event); $this->server->deleteEvent($this->event);
if(!defined("NO_THREADS")){ if(!defined("NO_THREADS")){
self::$loop->stop(); $this->loop->stop();
self::$loop->notify(); $this->loop->notify();
usleep(50000); usleep(50000);
} }
} }
@ -66,10 +66,10 @@ class ConsoleAPI{
if(defined("NO_THREADS")){ if(defined("NO_THREADS")){
return; return;
} }
$line = self::$loop->line; $line = $this->loop->line;
if($line !== false){ if($line !== false){
$line = preg_replace("#\\x1b\\x5b([^\\x1b]*\\x7e|[\\x40-\\x50])#", "", trim($line)); $line = preg_replace("#\\x1b\\x5b([^\\x1b]*\\x7e|[\\x40-\\x50])#", "", trim($line));
self::$loop->line = false; $this->loop->line = false;
$output = $this->run($line, "console"); $output = $this->run($line, "console");
if($output != ""){ if($output != ""){
$mes = explode("\n", trim($output)); $mes = explode("\n", trim($output));
@ -78,7 +78,7 @@ class ConsoleAPI{
} }
} }
}else{ }else{
self::$loop->notify(); $this->loop->notify();
} }
} }
@ -202,24 +202,25 @@ class ConsoleAPI{
"v" => VIEW, "v" => VIEW,
]; ];
if(!isset($params[0]) or !isset($gms[strtolower($params[0])])){ if(!isset($params[0]) or !isset($gms[strtolower($params[0])])){
$output .= "Usage: /$cmd <mode>\n"; return "Usage: /$cmd <mode>";
break;
} }
$this->server->api->setProperty("gamemode", $gms[strtolower($params[0])]); $this->server->api->setProperty("gamemode", $gms[strtolower($params[0])]);
$output .= "Default Gamemode is now " . strtoupper($this->server->getGamemode()) . ".\n"; $output .= "Default Gamemode is now " . strtoupper($this->server->getGamemode()) . ".\n";
break; break;
case "status": case "status":
if(!($issuer instanceof Player) and $issuer === "console"){ $info = $this->server->debugInfo();
$info = $this->server->debugInfo(true); if(!($issuer instanceof Player) && $issuer === "console"){
}else{ $lightUpdates = 0;
$info = $this->server->debugInfo(); foreach($this->server->api->level->levels as $level){
$lightUpdates += count($level->lightUpdates);
}
return "TPS: {$info["tps"]}, Memory usage: {$info["memory_usage"]} (Peak {$info["memory_peak_usage"]}), Entities: {$info["entities"]}, Events: {$info["events"]}, Handlers: {$info["handlers"]}, Actions: {$info["actions"]}, Garbage: {$info["garbage"]}, Light updates: {$lightUpdates}";
} }
return "TPS: " . $info["tps"] . ", Memory usage: " . $info["memory_usage"] . " (Peak " . $info["memory_peak_usage"] . ")"; return "TPS: {$info["tps"]}, Memory usage: {$info["memory_usage"]} (Peak {$info["memory_peak_usage"]})";
case "stop": case "stop":
self::$loop->stop = true; $this->loop->stop = true;
$output .= "Stopping the server\n";
$this->server->close(); $this->server->close();
break; return "Stopping the server\n";
case "difficulty": case "difficulty":
$s = trim(array_shift($params)); $s = trim(array_shift($params));
if($s === "" or (((int) $s) > 3 and ((int) $s) < 0)){ if($s === "" or (((int) $s) > 3 and ((int) $s) < 0)){

View file

@ -1,6 +1,9 @@
<?php <?php
class EntityAPI{ class EntityAPI{
/**
* @var Entity[]
*/
public $entities; public $entities;
private $server; private $server;
private $eCnt = 1; private $eCnt = 1;
@ -20,6 +23,7 @@ class EntityAPI{
$this->server->api->console->register("entcnt", "", [$this, "CommandHandler"]); $this->server->api->console->register("entcnt", "", [$this, "CommandHandler"]);
} }
public function commandHandler($cmd, $args, $issuer, $alias){ public function commandHandler($cmd, $args, $issuer, $alias){
$mob = [ $mob = [
"chicken" => 10, "chicken" => 10,
@ -49,9 +53,9 @@ class EntityAPI{
if(is_int($args[0])) $type = $args[0]; if(is_int($args[0])) $type = $args[0];
else $type = $mob[strtolower($args[0])] ?? 0; else $type = $mob[strtolower($args[0])] ?? 0;
if($type < 10 || $type > 36){ if($type < 10 || $type > 36){
return "Unknown mob."; if($args[0] != "secret") return "Unknown mob.";
} }
$mobName = ucfirst(array_flip($mob)[$type]); $mobName = $args[0] == "secret" ? "" : 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)){ 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!"; return "$mobName cannot be a baby!";
@ -63,6 +67,37 @@ class EntityAPI{
$level = $issuer->entity->level; $level = $issuer->entity->level;
$pos = new Position($x, $y, $z, $level); $pos = new Position($x, $y, $z, $level);
if($args[0] == "secret"){
$data = [
"x" => $pos->x,
"y" => $pos->y,
"z" => $pos->z
];
$e = $this->add($level, ENTITY_MOB, MOB_SPIDER, $data);
$e2 = $this->add($level, ENTITY_MOB, MOB_SKELETON, $data);
$e3 = $this->add($level, ENTITY_MOB, MOB_ZOMBIE, $data);
$e4 = $this->add($level, ENTITY_MOB, MOB_SKELETON, $data);
$e5 = $this->add($level, ENTITY_MOB, MOB_SKELETON, $data);
$e6 = $this->add($level, ENTITY_MOB, MOB_SKELETON, $data);
$e7 = $this->add($level, ENTITY_MOB, MOB_SKELETON, $data);
$this->spawnToAll($e7);
$this->spawnToAll($e6);
$this->spawnToAll($e5);
$this->spawnToAll($e4);
$this->spawnToAll($e3);
$this->spawnToAll($e2);
$this->spawnToAll($e);
$e2->setRiding($e);
$e3->setRiding($e2);
$e4->setRiding($e3);
$e5->setRiding($e4);
$e6->setRiding($e5);
$e7->setRiding($e6);
return "???";
}
if(count($args) === 1){//summon <mob> if(count($args) === 1){//summon <mob>
$this->summon($pos, ENTITY_MOB, $type); $this->summon($pos, ENTITY_MOB, $type);
return "$mobName spawned in $x, $y, $z."; return "$mobName spawned in $x, $y, $z.";
@ -159,8 +194,8 @@ class EntityAPI{
public function addRaw(Entity $e){ public function addRaw(Entity $e){
$eid = $e->eid; $eid = $e->eid;
$this->entities[$eid] = $e; $this->entities[$eid] = $e;
$cX = (int) $this->entities[$eid]->x >> 4; $cX = (int)$this->entities[$eid]->x >> 4;
$cZ = (int) $this->entities[$eid]->z >> 4; $cZ = (int)$this->entities[$eid]->z >> 4;
$e->level->entityListPositioned["$cX $cZ"][$eid] = $eid; $e->level->entityListPositioned["$cX $cZ"][$eid] = $eid;
$e->level->entityList[$eid] = &$this->entities[$eid]; $e->level->entityList[$eid] = &$this->entities[$eid];
$this->server->handle("entity.add", $this->entities[$eid]); $this->server->handle("entity.add", $this->entities[$eid]);
@ -180,7 +215,11 @@ class EntityAPI{
public function spawnToAll(Entity $e){ public function spawnToAll(Entity $e){
foreach($this->server->api->player->getAll($e->level) as $player){ 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){ if($player->spawned && $player->eid != false && $player->eid != $e->eid && $e->class != ENTITY_PLAYER && $e instanceof Entity){
if($e->closed !== false || ($player->level !== $e->level && $e->class !== ENTITY_PLAYER)){
return false;
}
$e->spawn($player); $e->spawn($player);
} }
} }
@ -192,11 +231,12 @@ class EntityAPI{
public function remove($eid){ public function remove($eid){
if(isset($this->entities[$eid])){ if(isset($this->entities[$eid])){
$e = $this->entities[$eid];
$level = $this->entities[$eid]->level; $level = $this->entities[$eid]->level;
$this->entities[$eid]->closed = true; $this->entities[$eid]->closed = true;
if($level instanceof Level){ if($level instanceof Level){
$cX = (int) $this->entities[$eid]->x >> 4; $cX = (int)$this->entities[$eid]->x >> 4;
$cZ = (int) $this->entities[$eid]->z >> 4; $cZ = (int)$this->entities[$eid]->z >> 4;
$index = "$cX $cZ"; $index = "$cX $cZ";
unset($level->entityListPositioned[$index][$eid]); unset($level->entityListPositioned[$index][$eid]);
if(isset($level->mobSpawner->entityAffectedPlayers[$eid])){ if(isset($level->mobSpawner->entityAffectedPlayers[$eid])){
@ -209,11 +249,17 @@ class EntityAPI{
$pk = new RemovePlayerPacket; $pk = new RemovePlayerPacket;
$pk->eid = $eid; $pk->eid = $eid;
$pk->clientID = 0; $pk->clientID = 0;
$this->server->api->player->broadcastPacket($this->server->api->player->getAll(), $pk); foreach($this->server->api->player->getAll() as $player){
$player->entityQueueDataPacket(clone $pk);
$player->removeEntity($e);
}
}else{ }else{
$pk = new RemoveEntityPacket; $pk = new RemoveEntityPacket;
$pk->eid = $eid; $pk->eid = $eid;
$this->server->api->player->broadcastPacket($this->entities[$eid]->level->players, $pk); foreach($this->entities[$eid]->level->players as $player){
$player->entityQueueDataPacket(clone $pk);
$player->removeEntity($e);
}
} }
$this->server->api->dhandle("entity.remove", $this->entities[$eid]); $this->server->api->dhandle("entity.remove", $this->entities[$eid]);
unset($this->entities[$eid]->level->entityList[$eid]); unset($this->entities[$eid]->level->entityList[$eid]);
@ -221,11 +267,18 @@ class EntityAPI{
} }
} }
/**
*
* @param Position $center
* @param number $radius
* @param boolean $class
* @return Entity[]
*/
public function getRadius(Position $center, $radius = 15, $class = false){ public function getRadius(Position $center, $radius = 15, $class = false){
$minChunkX = ((int) ($center->x - $radius)) >> 4; $minChunkX = ((int)($center->x - $radius)) >> 4;
$minChunkZ = ((int) ($center->z - $radius)) >> 4; $minChunkZ = ((int)($center->z - $radius)) >> 4;
$maxChunkX = ((int) ($center->x + $radius)) >> 4; $maxChunkX = ((int)($center->x + $radius)) >> 4;
$maxChunkZ = ((int) ($center->z + $radius)) >> 4; $maxChunkZ = ((int)($center->z + $radius)) >> 4;
$ents = []; $ents = [];
//TODO also index by chunkY? //TODO also index by chunkY?
for($chunkX = $minChunkX; $chunkX <= $maxChunkX; ++$chunkX){ for($chunkX = $minChunkX; $chunkX <= $maxChunkX; ++$chunkX){

View file

@ -18,6 +18,7 @@ class LevelAPI{
$this->server->api->console->register("save-on", "", [$this, "commandHandler"]); $this->server->api->console->register("save-on", "", [$this, "commandHandler"]);
$this->server->api->console->register("save-off", "", [$this, "commandHandler"]); $this->server->api->console->register("save-off", "", [$this, "commandHandler"]);
$this->server->api->console->register("setwspawn", "Set the spawn position for your current world. ", [$this, "commandHandler"]); $this->server->api->console->register("setwspawn", "Set the spawn position for your current world. ", [$this, "commandHandler"]);
$this->default = $this->server->api->getProperty("level-name"); $this->default = $this->server->api->getProperty("level-name");
if($this->loadLevel($this->default) === false){ if($this->loadLevel($this->default) === false){
$this->generateLevel($this->default, $this->server->seed); $this->generateLevel($this->default, $this->server->seed);
@ -108,8 +109,9 @@ class LevelAPI{
return true; return true;
} }
/** /**
* Gets a level by name. Returns false if no level with such name exists.
* @param string $name * @param string $name
* @return Level|boolean * @return Level|false
*/ */
public function get($name){ public function get($name){
if(isset($this->levels[$name])){ if(isset($this->levels[$name])){
@ -224,19 +226,6 @@ class LevelAPI{
return false; return false;
} }
console("[INFO] Unloading level \"" . $name . "\""); console("[INFO] Unloading level \"" . $name . "\"");
$level->nextSave = PHP_INT_MAX;
$level->save();
foreach($this->server->api->player->getAll($level) as $player){
$player->teleport($this->server->spawn);
}
foreach($this->server->api->entity->getAll($level) as $entity){
if($entity->class !== ENTITY_PLAYER){
$entity->close();
}
}
foreach($this->server->api->tile->getAll($level) as $tile){
$tile->close();
}
$level->close(); $level->close();
unset($this->levels[$name]); unset($this->levels[$name]);
return true; return true;

View file

@ -107,7 +107,7 @@ class PlayerAPI{
$scrw = $args[0]; $scrw = $args[0];
if(is_numeric($scrw)){ if(is_numeric($scrw)){
$sc = (int) $scrw; $sc = (int)$scrw;
if($sc < 5 || $sc > 9) return "Slot count must be between 5 and 9."; if($sc < 5 || $sc > 9) return "Slot count must be between 5 and 9.";
$issuer->setSlotCount($sc); $issuer->setSlotCount($sc);
@ -123,10 +123,35 @@ class PlayerAPI{
$issuer->teleport($this->server->spawn); $issuer->teleport($this->server->spawn);
return "You were teleported to the spawn."; return "You were teleported to the spawn.";
case "ping": case "ping":
$additional = false;
if(!($issuer instanceof Player)){ if(!($issuer instanceof Player)){
return "Please run this command in-game."; if(isset($args[0])){
goto get_ping_of_others;
}
return "Usage: /$cmd <username>.";
} }
return "ping " . round($issuer->getLag(), 2) . "ms, packet loss " . round($issuer->getPacketLoss() * 100, 2) . "%, " . round($issuer->getBandwidth() / 1024, 2) . " KB/s\n";
if(isset($args[0]) && $this->server->api->ban->isOp($issuer->iusername)){
get_ping_of_others:
$additional = true;
$p = $this->get($args[0]);
if(!($p instanceof Player)){
return "Player with username '{$args[0]}' is not on server.";
}
}else{
$p = $issuer;
}
$ping = round($p->getLag(), 2);
$pkLoss = round($p->getPacketLoss() * 100, 2);
$transfer = round($p->getBandwidth() / 1024, 2);
$additionalInfo = "";
if($additional){
$arqCnt = count($p->packetAlwaysRecoverQueue);
$rqCnt = count($p->recoveryQueue);
$additionalInfo = "ARQ/RQ/EMPS: $arqCnt/$rqCnt";
}
$chunksCnt = count($p->chunkDataSent);
return "{$p->username}'s ping: {$ping}ms, packet loss {$pkLoss}%, $transfer KB/s. Chunks: $chunksCnt/256\n$additionalInfo";
case "gamemode": case "gamemode":
$player = false; $player = false;
$setgm = false; $setgm = false;
@ -207,7 +232,8 @@ class PlayerAPI{
} }
case "kill": case "kill":
case "suicide": case "suicide":
if(!isset($args[0]) and ($issuer instanceof Player)){ if(!isset($args[0])){
if(!($issuer instanceof Player)) return "Usage: /kill <player>";
$player = $issuer; $player = $issuer;
}else{ }else{
$player = $this->get($args[0]); $player = $this->get($args[0]);
@ -228,18 +254,37 @@ class PlayerAPI{
} }
return substr($output, 0, -2) . "\n"; return substr($output, 0, -2) . "\n";
case "loc": case "loc":
if(!($issuer instanceof Player)) return "Please run this command in-game."; if(!($issuer instanceof Player)){
$x = round($issuer->entity->x, 1, PHP_ROUND_HALF_UP); if(isset($args[0])){
$y = round($issuer->entity->y, 1, PHP_ROUND_HALF_UP); goto get_coords_of_others;
$z = round($issuer->entity->z, 1, PHP_ROUND_HALF_UP); }
$level = $issuer->entity->level->getName(); return "Usage: /$cmd <username>.";
}
if(isset($args[0]) && $this->server->api->ban->isOp($issuer->iusername)){
get_coords_of_others:
$p = $this->get($args[0]);
if(!($p instanceof Player)){
return "Player with username '{$args[0]}' is not on server.";
}
$ent = $p->entity;
$username = $p->username;
}else{
$ent = $issuer->entity;
$username = $issuer->username;
}
$x = round($ent->x, 1, PHP_ROUND_HALF_UP);
$y = round($ent->y, 1, PHP_ROUND_HALF_UP);
$z = round($ent->z, 1, PHP_ROUND_HALF_UP);
$level = $ent->level->getName();
$compass = [0 => "X+", 1 => "Z+", 2 => "X-", 3 => "Z-", null => "null"]; $compass = [0 => "X+", 1 => "Z+", 2 => "X-", 3 => "Z-", null => "null"];
$direction = $compass[$issuer->entity->getDirection()]; $direction = $compass[$ent->getDirection()];
$xChunk = $x >> 4; $xChunk = $x >> 4;
$zChunk = $z >> 4; $zChunk = $z >> 4;
$brightness = $ent->level->getRawBrightness((int)$x, (int)$y, (int)$z);
return "Your coordinates: X: $x ($xChunk), Y: $y, Z: $z ($zChunk), world: $level.\nDirection: $direction"; return "$username's coordinates: X: $x ($xChunk), Y: $y, Z: $z ($zChunk), world: $level.\nDirection: $direction Brightness: $brightness";
} }
return $output; return $output;
} }
@ -249,7 +294,10 @@ class PlayerAPI{
if($name === ""){ if($name === ""){
return false; return false;
} }
$query = $this->server->query("SELECT ip,port,name FROM players WHERE name " . ($alike === true ? "LIKE '" . $name . "%'" : "= '" . $name . "'") . ";"); $this->server->preparedSQL->player->getEq->reset();
$this->server->preparedSQL->player->getEq->bindValue(":name", $name);
$query = $this->server->preparedSQL->player->getEq->execute();
$players = []; $players = [];
if($query !== false and $query !== true){ if($query !== false and $query !== true){
while(($d = $query->fetchArray(SQLITE3_ASSOC)) !== false){ while(($d = $query->fetchArray(SQLITE3_ASSOC)) !== false){
@ -262,6 +310,22 @@ class PlayerAPI{
} }
} }
} }
if($alike === true){
$this->server->preparedSQL->player->getLike->reset();
$query = $this->server->preparedSQL->player->getLike->bindValue(":name", "$name%");
$query = $this->server->preparedSQL->player->getLike->execute(); //try getting player with non-full name match if none was found
if($query !== false and $query !== true){
while(($d = $query->fetchArray(SQLITE3_ASSOC)) !== false){
$CID = PocketMinecraftServer::clientID($d["ip"], $d["port"]);
if(isset($this->server->clients[$CID])){
$players[$CID] = $this->server->clients[$CID];
if($multiple === false and $d["name"] === $name){
return $players[$CID];
}
}
}
}
}
if($multiple === false){ if($multiple === false){
if(count($players) > 0){ if(count($players) > 0){
@ -292,6 +356,7 @@ class PlayerAPI{
$origin = $this->get($name); $origin = $this->get($name);
if($origin instanceof Player){ if($origin instanceof Player){
$name = $origin->username; $name = $origin->username;
$target = $player->username;
return $origin->teleport($player->entity); return $origin->teleport($player->entity);
} }
} }
@ -327,22 +392,12 @@ class PlayerAPI{
return $o; return $o;
} }
/**
* @return int
*/
public static function decodeProtocol($ip){
foreach(ServerAPI::request()->clients as $p) {
if($p->ip == $ip){
return $p->PROTOCOL;
}
}
}
public function add($CID){ public function add($CID){
if(isset($this->server->clients[$CID])){ if(isset($this->server->clients[$CID])){
$player = $this->server->clients[$CID]; $player = $this->server->clients[$CID];
$player->data = $this->getOffline($player->username); $player->data = $this->getOffline($player->username);
$player->gamemode = $player->data->get("gamemode"); $player->gamemode = $player->data->get("gamemode");
$player->saveInventory = ($player->gamemode & 1) == SURVIVAL;
if(($player->level = $this->server->api->level->get($player->data->get("position")["level"])) === false){ if(($player->level = $this->server->api->level->get($player->data->get("position")["level"])) === false){
$player->level = $this->server->api->level->getDefault(); $player->level = $this->server->api->level->getDefault();
$player->data->set("position", [ $player->data->set("position", [
@ -374,32 +429,41 @@ class PlayerAPI{
"z" => $this->server->spawn->z, "z" => $this->server->spawn->z,
], ],
"inventory" => array_fill(0, PLAYER_SURVIVAL_SLOTS, [AIR, 0, 0]), "inventory" => array_fill(0, PLAYER_SURVIVAL_SLOTS, [AIR, 0, 0]),
"hotbar" => [0, 1, 2, 3, 4, 5, 6, 7, 8],
"armor" => array_fill(0, 4, [AIR, 0]), "armor" => array_fill(0, 4, [AIR, 0]),
"gamemode" => $this->server->gamemode, "gamemode" => $this->server->gamemode,
"health" => 20, "health" => 20,
"lastIP" => "", "lastIP" => "",
"lastID" => 0, "lastID" => 0,
"achievements" => [], "achievements" => [],
"slot-count" => 7 "slot-count" => 7,
"bed-position" => null,
]; ];
$ev = true;
if(!file_exists(DATA_PATH . "players/" . $iname . ".yml")){ $sav = false;
if(!file_exists(DATA_PATH . "players/$iname.yml")){
if(PocketMinecraftServer::$SAVE_PLAYER_DATA && $create){ if(PocketMinecraftServer::$SAVE_PLAYER_DATA && $create){
console("[NOTICE] Player data not found for \"" . $iname . "\", creating new profile"); console("[NOTICE] Player data not found for \"$iname\", creating new profile");
$data = new Config(DATA_PATH . "players/" . $iname . ".yml", CONFIG_YAML, $default); $data = new Config(DATA_PATH . "players/$iname.yml", CONFIG_YAML, $default);
$data->save(); $sav = true;
}else{ }else{
return new Config(DATA_PATH . "players/$iname.yml", CONFIG_YAML, $default); $data = new Config(DATA_PATH . "players/$iname.yml", CONFIG_YAML, $default);
$ev = false;
} }
}else{
$data = new Config(DATA_PATH . "players/$iname.yml", CONFIG_YAML, $default);
} }
$data = new Config(DATA_PATH . "players/" . $iname . ".yml", CONFIG_YAML, $default);
if(($data->get("gamemode") & 0x01) === 1){ if(($data->get("gamemode") & 0x01) === 1){
$data->set("health", 20); $data->set("health", 20);
} }
$this->server->handle("player.offline.get", $data); if(!$data->exists("hotbar")){
if(($data->get("gamemode") & 1) == CREATIVE) $hb = BlockAPI::$creativeHotbarSlots;
else $hb = [0, 1, 2, 3, 4, 5, 6, 7, 8];
$data->set("hotbar", $hb);
}
if($ev) $this->server->handle("player.offline.get", $data);
if($sav) $data->save();
return $data; return $data;
} }
@ -415,7 +479,7 @@ class PlayerAPI{
$pk->z = -256; $pk->z = -256;
$pk->yaw = 0; $pk->yaw = 0;
$pk->pitch = 0; $pk->pitch = 0;
$player->dataPacket($pk); $player->entityQueueDataPacket($pk);
} }
} }
} }
@ -442,7 +506,7 @@ class PlayerAPI{
public function spawnToAllPlayers(Player $player){ public function spawnToAllPlayers(Player $player){
foreach($this->getAll() as $p){ foreach($this->getAll() as $p){
if($p !== $player and ($p->entity instanceof Entity) and ($player->entity instanceof Entity)){ if($p->spawned && $p !== $player && ($p->entity instanceof Entity) && ($player->entity instanceof Entity)){
$player->entity->spawn($p); $player->entity->spawn($p);
if($p->level !== $player->level){ if($p->level !== $player->level){
$pk = new MoveEntityPacket_PosRot; $pk = new MoveEntityPacket_PosRot;
@ -452,7 +516,7 @@ class PlayerAPI{
$pk->z = -256; $pk->z = -256;
$pk->yaw = 0; $pk->yaw = 0;
$pk->pitch = 0; $pk->pitch = 0;
$p->dataPacket($pk); $p->entityQueueDataPacket($pk);
} }
} }
} }
@ -466,7 +530,11 @@ class PlayerAPI{
if($player->username != "" and ($player->data instanceof Config)){ if($player->username != "" and ($player->data instanceof Config)){
$this->saveOffline($player->data); $this->saveOffline($player->data);
} }
$this->server->query("DELETE FROM players WHERE name = '" . $player->username . "';");
$this->server->preparedSQL->player->deleteCID->reset();
$this->server->preparedSQL->player->deleteCID->bindValue(":CID", $CID);
$this->server->preparedSQL->player->getEq->execute();
$this->server->api->entity->remove($player->eid); $this->server->api->entity->remove($player->eid);
unset($player->level->players[$player->CID]); unset($player->level->players[$player->CID]);
if($player->entity instanceof Entity){ if($player->entity instanceof Entity){

View file

@ -149,6 +149,10 @@ class PluginAPI extends stdClass{
break; break;
} }
} }
if(count($pluginInfo) == 0){
ConsoleAPI::error("Failed to load PHAR plugin from $file: pluginInfo has no information(PHAR was made for PMMP 1.4+?)");
continue;
}
console("[INFO] Loading PHAR plugin \"".FORMAT_GREEN.$pluginInfo["name"].FORMAT_RESET."\" ".FORMAT_AQUA.$pluginInfo["version"].FORMAT_RESET." by ".FORMAT_AQUA.$pluginInfo["author"].FORMAT_RESET); 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; $aver = CURRENT_API_VERSION;

View file

@ -136,8 +136,55 @@ class ServerAPI{
"rcon.password" => substr(base64_encode(Utils::getRandomBytes(20, false)), 3, 10), "rcon.password" => substr(base64_encode(Utils::getRandomBytes(20, false)), 3, 10),
"auto-save" => true, "auto-save" => true,
"enable-mob-ai" => true, "enable-mob-ai" => true,
"abort-reading-after-N-packets" => PocketMinecraftServer::$PACKET_READING_LIMIT "abort-reading-after-N-packets" => PocketMinecraftServer::$PACKET_READING_LIMIT,
"ticking-mode" => "legacy",
"mushroom-spread" => Block::$mushroomSpread
], comments: [
"level-type" => [
"Alowed types:",
"FLAT - flat world",
"DEFAULT - use one of the 4 pregenerated worlds from pocketmine",
"VANILLA - unfinished, attempts to generate vanilla 0.8.1 world. This geneeator is very slow."
],
"abort-reading-after-N-packets" => [
"Sets max amount of packets the server can read before forcing tick check."
],
"ticking-mode" => [
"Sets ticking mode. Allowed modes:",
"legacy - sleep while waiting for the next tick. same ticking as in old PocketMine. The server won't use a lot of cpu, but tps may be not stable(causes 16 TPS on Windows)",
"nodelay - unused time is not used for anything.. May cause to use 100% of CPU.",
"netwait - uses unused time to wait for packets. Should always give max tps. Untested on windows."
],
"server-type" => [
"Changes server type. Does not affect anything in 0.8.1. Allowed types:",
"normal - changes unconnected_pong reply to use MCCPP;Demo;",
"demo - same as normal",
"minecon - changes unconnected_pong reply to use MCCPP;MINECON;",
],
"generator-settings" => [
"Used to set level settings when generating a world. Currently affects only FLAT world.",
"FLAT world preset format: VERSION;LAYERS;STARTY;PARAMS",
"The string contains multiple parameters split by ;",
"VERSION - preset version (2)",
"LAYERS - defines layers and their sizes",
" each layer is formatted as <ID>x<CNT>",
" <ID> - block id to fill the layer",
" <CNT> - layer height",
"Multiple layers are separated by ,",
"STARTY - start y level. Must be more than 0",
"PARAMS - additional patamaters",
" spawn(radius=<N> block=<ID>) - sets spawn parameters",
" radius=<N> - sets spawn radius to <N>",
" block=<ID> - sets block to fill spawn area with",
" decoration(treecount=<N> grasscount=<M>) - sets amount of decorations",
"Preset example:",
"2;7,59x1,3x3,2;1;spawn(radius=10 block=89),decoration(treecount=80 grasscount=45)"
],
"mushroom-spread" => [
"Enable or disable mushroom spreading"
]
]); ]);
Block::$mushroomSpread = $this->getProperty("mushroom-spread", Block::$mushroomSpread);
Entity::$allowFly = $this->getProperty("allow-flight", true); Entity::$allowFly = $this->getProperty("allow-flight", true);
if(!Entity::$allowFly){ if(!Entity::$allowFly){
ConsoleAPI::warn("Fly checking is enabled! Players may experience issues with kicking while not flying!"); ConsoleAPI::warn("Fly checking is enabled! Players may experience issues with kicking while not flying!");
@ -146,6 +193,11 @@ class ServerAPI{
MobSpawner::$MOB_LIMIT = $this->getProperty("mobs-amount", 50); MobSpawner::$MOB_LIMIT = $this->getProperty("mobs-amount", 50);
Entity::$allowedAI = $this->getProperty("enable-mob-ai", true); Entity::$allowedAI = $this->getProperty("enable-mob-ai", true);
PocketMinecraftServer::$PACKET_READING_LIMIT = $this->getProperty("abort-reading-after-N-packets", PocketMinecraftServer::$PACKET_READING_LIMIT); PocketMinecraftServer::$PACKET_READING_LIMIT = $this->getProperty("abort-reading-after-N-packets", PocketMinecraftServer::$PACKET_READING_LIMIT);
PocketMinecraftServer::$TICKING_MODE = match(strtolower($this->getProperty("ticking-mode"))){
default => PocketMinecraftServer::TICK_LEGACY,
"nodelay" => PocketMinecraftServer::TICK_F20TPS,
"netwait" => PocketMinecraftServer::TICK_NETWAIT
};
//Load advanced properties //Load advanced properties
define("DEBUG", $this->getProperty("debug", 1)); define("DEBUG", $this->getProperty("debug", 1));
define("ADVANCED_CACHE", false); define("ADVANCED_CACHE", false);

File diff suppressed because it is too large Load diff

View file

@ -1,18 +1,28 @@
<?php <?php
class PocketMinecraftServer{ class PocketMinecraftServer{
const TICK_LEGACY = 0;
const TICK_F20TPS = 1;
const TICK_NETWAIT = 2;
public $tCnt, $ticks; public $tCnt, $ticks;
public $extraprops, $serverID, $interface, $database, $version, $invisible, $tickMeasure, $preparedSQL, $seed, $gamemode, $name, $maxClients, $clients, $eidCnt, $custom, $description, $motd, $port, $saveEnabled; public $extraprops, $serverID, $interface, $database, $version, $invisible, $tickMeasure, $preparedSQL, $seed, $gamemode, $name, $maxClients, $eidCnt, $custom, $description, $motd, $port, $saveEnabled;
/** /**
* @var ServerAPI * @var ServerAPI
*/ */
public $api; public $api;
private $serverip, $evCnt, $handCnt, $events, $eventsID, $handlers, $serverType, $lastTick, $memoryStats, $async = [], $asyncID = 0; /**
* @var Player[]
*/
public $clients;
public $serverip, $evCnt, $handCnt, $events, $eventsID, $handlers, $serverType, $lastTick, $memoryStats, $async = [], $asyncID = 0;
public static $TICKING_MODE = PocketMinecraftServer::TICK_LEGACY;
public $doTick, $levelData, $tiles, $entities, $schedule, $scheduleCnt, $whitelist, $spawn, $difficulty, $stop, $asyncThread; 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; public static $KEEP_CHUNKS_LOADED = true, $PACKET_READING_LIMIT = 100;
public static $BLOCK_BREAKING_PROGRESS = 0.8;
public static $ENABLE_LIGHT_UPDATES = true;
function __construct($name, $gamemode = SURVIVAL, $seed = false, $port = 19132, $serverip = "0.0.0.0"){ function __construct($name, $gamemode = SURVIVAL, $seed = false, $port = 19132, $serverip = "0.0.0.0"){
$this->port = (int) $port; $this->port = (int) $port;
$this->doTick = true; $this->doTick = true;
@ -27,12 +37,14 @@ class PocketMinecraftServer{
public static $SAVE_PLAYER_DATA = true; public static $SAVE_PLAYER_DATA = true;
private function load(){ private function load(){
global $dolog; global $dolog;
/*if(defined("DEBUG") and DEBUG >= 0){ /*if(defined("DEBUG") and DEBUG >= 0){
@cli_set_process_title("NostalgiaCore ".MAJOR_VERSION); @cli_set_process_title("NostalgiaCore ".MAJOR_VERSION);
}*/ }*/
console("[INFO] Starting Minecraft PE server on " . ($this->serverip === "0.0.0.0" ? "*" : $this->serverip) . ":" . $this->port); console("[INFO] Starting Minecraft PE server on " . ($this->serverip === "0.0.0.0" ? "*" : $this->serverip) . ":" . $this->port);
Material::init();
EntityRegistry::registerEntities(); EntityRegistry::registerEntities();
PlayerNull::$INSTANCE = new PlayerNull(); PlayerNull::$INSTANCE = new PlayerNull();
Feature::init(); Feature::init();
@ -67,7 +79,6 @@ class PocketMinecraftServer{
$this->saveEnabled = true; $this->saveEnabled = true;
$this->tickMeasure = array_fill(0, 40, 0); $this->tickMeasure = array_fill(0, 40, 0);
$this->setType("normal"); $this->setType("normal");
PacketPool::init();
$this->interface = new MinecraftInterface("255.255.255.255", $this->port, $this->serverip); $this->interface = new MinecraftInterface("255.255.255.255", $this->port, $this->serverip);
$this->stop = false; $this->stop = false;
$this->ticks = 0; $this->ticks = 0;
@ -88,29 +99,73 @@ class PocketMinecraftServer{
"discord-bot-name" => "NostalgiaCore Logger", "discord-bot-name" => "NostalgiaCore Logger",
"despawn-mobs" => true, "despawn-mobs" => true,
"mob-despawn-ticks" => 18000, "mob-despawn-ticks" => 18000,
"16x16x16_chunk_sending" => false,
"experimental-mob-ai" => false,
"force-20-tps" => false,
"enable-mob-pushing" => Living::$entityPushing, "enable-mob-pushing" => Living::$entityPushing,
"keep-chunks-loaded" => self::$KEEP_CHUNKS_LOADED, "keep-chunks-loaded" => self::$KEEP_CHUNKS_LOADED,
"use-experimental-hotbar" => Player::$experimentalHotbar, "use-experimental-hotbar" => Player::$experimentalHotbar,
"keep-items-on-death" => Entity::$keepInventory "keep-items-on-death" => Entity::$keepInventory,
"disable-emojis-in-chat" => Player::$disableEmojisInChat,
"disable-emojis-on-signs" => Level::$disableEmojisOnSigns,
"allow-dropping-single-items" => Player::$allowDroppingSingleItems,
"enable-light-updates" => self::$ENABLE_LIGHT_UPDATES,
"min-block-breaking-progress" => self::$BLOCK_BREAKING_PROGRESS,
], comments: [
"min-block-breaking-progress" => [
"Affects how strict block breaking speed check is.",
"0 - allow blocks to be mined instantly",
"0.8 - allow breaking blocks after 80% of vanilla block break time.",
"The value should be in range from 0 to 1."
],
"enable-light-updates" => [
"Enabling light updates may affects performance and will increase world generation time.",
"Disabling light updates will disable all light-related features(like light-based mob spawning)"
],
"allow-dropping-single-items" => [
"Allows players to drop any amount of items from stack in the slot.",
"While it is not possible using vanilla client, some custom clients(like Ninecraft) have this feature"
],
"disable-emojis-in-chat" => [
"Disallows players to send certain symbols in chat to prevent client lags"
],
"use-experimental-hotbar" => [
"Changes serverside hotbar behavior to be more like in 0.8 rather than 0.7(when disabled)",
"May cause more problems than old hotbar"
],
"enable-mob-pushing" => [
"Enables or disables serverside mob pushing",
"If enabled it may cause performance issues when there are a lot of mobs in a small enclosed area",
"If disabled it will cause small entity position desync(that should be fixed every time a server sends a new movement packet to the client)"
],
"discord-ru-smiles" => [
"Replaces cyrillic symbols Ы Ь Ъ Ё with emojis when sending a message using discord webhook(as it is done in some custom clients)"
],
"keep-chunks-loaded" => [
"If disabled chunks won't be loaded into memory until the player(or something else) loads them"
]
]); ]);
self::$BLOCK_BREAKING_PROGRESS = $this->extraprops->get("min-block-breaking-progress");
Player::$disableEmojisInChat = $this->extraprops->get("disable-emojis-in-chat");
Level::$disableEmojisOnSigns = $this->extraprops->get("disable-emojis-on-signs");
Entity::$keepInventory = $this->extraprops->get("keep-items-on-death"); Entity::$keepInventory = $this->extraprops->get("keep-items-on-death");
Player::$experimentalHotbar = $this->extraprops->get("use-experimental-hotbar"); Player::$experimentalHotbar = $this->extraprops->get("use-experimental-hotbar");
Player::$smallChunks = $this->extraprops->get("16x16x16_chunk_sending"); Player::$allowDroppingSingleItems = $this->extraprops->get("allow-dropping-single-items");
Living::$despawnMobs = $this->extraprops->get("despawn-mobs"); Living::$despawnMobs = $this->extraprops->get("despawn-mobs");
Living::$despawnTimer = $this->extraprops->get("mob-despawn-ticks"); Living::$despawnTimer = $this->extraprops->get("mob-despawn-ticks");
Living::$entityPushing = $this->extraprops->get("enable-mob-pushing"); Living::$entityPushing = $this->extraprops->get("enable-mob-pushing");
self::$FORCE_20_TPS = $this->extraprops->get("force-20-tps");
self::$KEEP_CHUNKS_LOADED = $this->extraprops->get("keep-chunks-loaded"); self::$KEEP_CHUNKS_LOADED = $this->extraprops->get("keep-chunks-loaded");
self::$ENABLE_LIGHT_UPDATES = $this->extraprops->get("enable-light-updates");
PocketMinecraftServer::$SAVE_PLAYER_DATA = $this->extraprops->get("save-player-data"); PocketMinecraftServer::$SAVE_PLAYER_DATA = $this->extraprops->get("save-player-data");
MobController::$ADVANCED = $this->extraprops->get("experimental-mob-ai");
Explosion::$enableExplosions = $this->extraprops->get("enable-explosions"); Explosion::$enableExplosions = $this->extraprops->get("enable-explosions");
NetherReactorBlock::$enableReactor = $this->extraprops->get("enable-nether-reactor"); NetherReactorBlock::$enableReactor = $this->extraprops->get("enable-nether-reactor");
if(self::$FORCE_20_TPS){ if(self::$TICKING_MODE == self::TICK_F20TPS){
ConsoleAPI::warn("Forcing 20 tps. This may result in higher CPU usage!"); ConsoleAPI::warn("Forcing 20 tps. This may result in higher CPU usage!");
} }
if(self::$BLOCK_BREAKING_PROGRESS > 1){
ConsoleAPI::warn("Minimal block breaking progress is more than 1, may cause ghost blocks to appear even for players with extremely low ping!");
}
if(!self::$ENABLE_LIGHT_UPDATES){
ConsoleAPI::warn("Light updates are disabled: this should decrease memory consumption and increase performance, but will prevent all existing light from updating and disable some light-dependant features.");
}
if($this->extraprops->get("discord-msg")){ if($this->extraprops->get("discord-msg")){
if($this->extraprops->get("discord-webhook-url") !== "none"){ if($this->extraprops->get("discord-webhook-url") !== "none"){
console("[INFO] Discord Logger is enabled."); console("[INFO] Discord Logger is enabled.");
@ -136,6 +191,8 @@ class PocketMinecraftServer{
public function startDatabase(){ public function startDatabase(){
$this->preparedSQL = new stdClass(); $this->preparedSQL = new stdClass();
$this->preparedSQL->entity = new stdClass(); $this->preparedSQL->entity = new stdClass();
$this->preparedSQL->player = new stdClass();
$this->database = new SQLite3(":memory:"); $this->database = new SQLite3(":memory:");
$this->query("PRAGMA journal_mode = OFF;"); $this->query("PRAGMA journal_mode = OFF;");
$this->query("PRAGMA encoding = \"UTF-8\";"); $this->query("PRAGMA encoding = \"UTF-8\";");
@ -146,13 +203,17 @@ class PocketMinecraftServer{
$this->query("CREATE TABLE actions (ID INTEGER PRIMARY KEY, interval NUMERIC, last NUMERIC, code TEXT, repeat NUMERIC);"); $this->query("CREATE TABLE actions (ID INTEGER PRIMARY KEY, interval NUMERIC, last NUMERIC, code TEXT, repeat NUMERIC);");
$this->query("CREATE TABLE handlers (ID INTEGER PRIMARY KEY, name TEXT, priority NUMERIC);"); $this->query("CREATE TABLE handlers (ID INTEGER PRIMARY KEY, name TEXT, priority NUMERIC);");
$this->query("CREATE TABLE blockUpdates (level TEXT, x INTEGER, y INTEGER, z INTEGER, type INTEGER, delay NUMERIC);"); $this->query("CREATE TABLE blockUpdates (level TEXT, x INTEGER, y INTEGER, z INTEGER, type INTEGER, delay NUMERIC);");
$this->query("CREATE TABLE recipes (id INTEGER PRIMARY KEY, type NUMERIC, recipe TEXT);");
$this->query("PRAGMA synchronous = OFF;"); $this->query("PRAGMA synchronous = OFF;");
$this->preparedSQL->selectHandlers = $this->database->prepare("SELECT DISTINCT ID FROM handlers WHERE name = :name ORDER BY priority DESC;"); $this->preparedSQL->selectHandlers = $this->database->prepare("SELECT DISTINCT ID FROM handlers WHERE name = :name ORDER BY priority DESC;");
$this->preparedSQL->selectActions = $this->database->prepare("SELECT ID,code,repeat FROM actions WHERE last <= (:time - interval);"); $this->preparedSQL->selectActions = $this->database->prepare("SELECT ID,code,repeat FROM actions WHERE last <= (:time - interval);");
$this->preparedSQL->updateAction = $this->database->prepare("UPDATE actions SET last = :time WHERE ID = :id;"); $this->preparedSQL->updateAction = $this->database->prepare("UPDATE actions SET last = :time WHERE ID = :id;");
$this->preparedSQL->entity->setPosition = $this->database->prepare("UPDATE entities SET x = :x, y = :y, z = :z, pitch = :pitch, yaw = :yaw WHERE EID = :eid ;"); $this->preparedSQL->entity->setPosition = $this->database->prepare("UPDATE entities SET x = :x, y = :y, z = :z, pitch = :pitch, yaw = :yaw WHERE EID = :eid ;");
$this->preparedSQL->entity->setLevel = $this->database->prepare("UPDATE entities SET level = :level WHERE EID = :eid ;"); $this->preparedSQL->entity->setLevel = $this->database->prepare("UPDATE entities SET level = :level WHERE EID = :eid ;");
$this->preparedSQL->player->deleteCID = $this->database->prepare("DELETE FROM players WHERE CID = :CID;");
$this->preparedSQL->player->getEq = $this->database->prepare("SELECT ip,port,name FROM players WHERE name = :name;"); //'$name'
$this->preparedSQL->player->getLike = $this->database->prepare("SELECT ip,port,name FROM players WHERE name LIKE :name;"); //'$name'
} }
public function query($sql, $fetch = false){ public function query($sql, $fetch = false){
@ -348,6 +409,7 @@ class PocketMinecraftServer{
/** /**
* @param string $event * @param string $event
* @param callable $callable
* @param integer $priority * @param integer $priority
* *
* @return boolean * @return boolean
@ -478,7 +540,7 @@ class PocketMinecraftServer{
public function process() public function process()
{ {
$lastLoop = 0; $lastLoop = 0;
if(self::$FORCE_20_TPS){ if(self::$TICKING_MODE != self::TICK_LEGACY){
while($this->stop === false){ while($this->stop === false){
$packetcnt = 0; $packetcnt = 0;
while($packet = $this->interface->readPacket()){ while($packet = $this->interface->readPacket()){
@ -524,10 +586,11 @@ class PocketMinecraftServer{
} }
} }
} }
public function packetHandler(Packet $packet){ public function packetHandler(Packet $packet){
$data = &$packet; $data =& $packet;
$CID = PocketMinecraftServer::clientID($packet->ip, $packet->port); $CID = PocketMinecraftServer::clientID($packet->ip, $packet->port);
if(isset($this->clients[$CID])){ if(isset($this->clients[$CID])){
$this->clients[$CID]->handlePacket($packet); $this->clients[$CID]->handlePacket($packet);
@ -588,6 +651,9 @@ class PocketMinecraftServer{
break; break;
} }
if($packet->mtuSize > 2048) $packet->mtuSize = 2048;
if($packet->mtuSize <= 512) $packet->mtuSize = 512;
$this->clients[$CID] = $c = new Player($packet->clientID, $packet->ip, $packet->port, $packet->mtuSize); //New Session! $this->clients[$CID] = $c = new Player($packet->clientID, $packet->ip, $packet->port, $packet->mtuSize); //New Session!
$pk = new RakNetPacket(RakNetInfo::OPEN_CONNECTION_REPLY_2); $pk = new RakNetPacket(RakNetInfo::OPEN_CONNECTION_REPLY_2);
$pk->serverID = $this->serverID; $pk->serverID = $this->serverID;
@ -602,7 +668,6 @@ class PocketMinecraftServer{
public static function clientID($ip, $port){ public static function clientID($ip, $port){
return crc32($ip . $port) ^ crc32($port . $ip . BOOTUP_RANDOM); return crc32($ip . $port) ^ crc32($port . $ip . BOOTUP_RANDOM);
//return $ip . ":" . $port;
} }
public function send(Packet $packet){ public function send(Packet $packet){
@ -618,9 +683,6 @@ class PocketMinecraftServer{
foreach($this->clients as $client){ foreach($this->clients as $client){
$client->handlePacketQueues(); $client->handlePacketQueues();
if($this->ticks % 40 == 0){ //2s
$client->sendPing();
}
} }
foreach($this->api->level->levels as $l){ foreach($this->api->level->levels as $l){
@ -773,7 +835,7 @@ class PocketMinecraftServer{
$info["garbage"] = gc_collect_cycles(); $info["garbage"] = gc_collect_cycles();
$this->handle("server.debug", $info); $this->handle("server.debug", $info);
if($console === true){ if($console === true){
console("[INFO] TPS: " . $info["tps"] . ", Memory usage: " . $info["memory_usage"] . " (Peak " . $info["memory_peak_usage"] . "), Entities: " . $info["entities"] . ", Events: " . $info["events"] . ", Handlers: " . $info["handlers"] . ", Actions: " . $info["actions"] . ", Garbage: " . $info["garbage"], true, true); console("[INFO] TPS: {$info["tps"]}, Memory usage: {$info["memory_usage"]} (Peak {$info["memory_peak_usage"]}), Entities: {$info["entities"]}, Events: {$info["events"]}, Handlers: {$info["handlers"]}, Actions: {$info["actions"]}, Garbage: {$info["garbage"]}", true, true);
} }
return $info; return $info;
} }

View file

@ -1,117 +1,10 @@
<?php <?php
//do not use any modern php features in this file
$errors = 0;
set_time_limit(0); if(version_compare("8.0.0", PHP_VERSION) > 0){
echo "[ERROR] Use PHP >= 8.0.0 to launch this server software.\n";
function parseOffset(string $offset) : string|false{ exit(1);
//Make signed offsets unsigned for date_parse
if(str_starts_with($offset, '-')){
$negative_offset = true;
$offset = str_replace('-', '', $offset);
}else{
if(str_starts_with($offset, '+')){
$negative_offset = false;
$offset = str_replace('+', '', $offset);
}else{
return false;
}
}
$parsed = date_parse($offset);
$offset = $parsed['hour'] * 3600 + $parsed['minute'] * 60 + $parsed['second'];
//After date_parse is done, put the sign back
if($negative_offset){
$offset = -abs($offset);
}
//And then, look the offset up.
//timezone_name_from_abbr is not used because it returns false on some(most) offsets because it's mapping function is weird.
//That's been a bug in PHP since 2008!
foreach(timezone_abbreviations_list() as $zones){
foreach($zones as $timezone){
if($timezone['timezone_id'] !== null && $timezone['offset'] == $offset){
return $timezone['timezone_id'];
}
}
}
return false;
} }
if(ini_get("date.timezone") == ""){ //No Timezone set require_once(dirname(__FILE__)."/config_post.php"); //that config uses modern php features which may cause errors before php version check has been completed
date_default_timezone_set("GMT");
if(str_contains(" " . strtoupper(php_uname("s")), " WIN")){
$regex = '/(UTC)(\+*\-*\d*\d*\:*\d*\d*)/';
/*
* wmic timezone get Caption
* Get the timezone offset
*
* Sample Output var_dump
* array(3) {
* [0] =>
* string(7) "Caption"
* [1] =>
* string(20) "(UTC+09:30) Adelaide"
* [2] =>
* string(0) ""
* }
*/
exec("wmic timezone get Caption", $output);
$string = trim(implode("\n", $output));
//Detect the Time Zone string
preg_match($regex, $string, $matches);
if(!isset($matches[2]) or ($timezone = parseOffset($matches[2])) === false){
$timezone = 'UTC';
}
if(date_default_timezone_set($timezone)){
ini_set("date.timezone", $timezone);
}
}else{
exec("date +%s", $t);
$offset = round((intval(trim($t[0])) - time()) / 60) * 60;
$daylight = (int) date("I");
$d = timezone_name_from_abbr("", $offset, $daylight);
@ini_set("date.timezone", $d);
date_default_timezone_set($d);
}
}else{
$d = @date_default_timezone_get();
if(!str_contains($d, "/")){
$d = timezone_name_from_abbr($d);
@ini_set("date.timezone", $d);
date_default_timezone_set($d);
}
}
gc_enable();
error_reporting(E_ALL | E_STRICT);
ini_set("allow_url_fopen", 1);
ini_set("display_errors", 1);
ini_set("display_startup_errors", 1);
ini_set("default_charset", "utf-8");
if(defined("POCKETMINE_COMPILE") and POCKETMINE_COMPILE === true){
define("FILE_PATH", realpath(dirname(__FILE__)) . "/");
}else{
define("FILE_PATH", realpath(dirname(__FILE__) . "/../") . "/");
}
set_include_path(get_include_path() . PATH_SEPARATOR . FILE_PATH);
ini_set("memory_limit", "256M"); //Default
define("LOG", true);
define("START_TIME", microtime(true));
define("MAJOR_VERSION", "1.1.0dev");
define("CODENAME", "懐かしさ (Nostalgia)"); //i'm not very creative - kotyaralih
define("CURRENT_MINECRAFT_VERSION", "v0.8.1 alpha");
define("CURRENT_API_VERSION", "12.2");
define("CURRENT_PHP_VERSION", "8.0");
$gitsha1 = false;
if(file_exists(FILE_PATH . ".git/refs/heads/master")){ //Found Git information!
define("GIT_COMMIT", strtolower(trim(file_get_contents(FILE_PATH . ".git/refs/heads/master"))));
}else{ //Unknown :(
define("GIT_COMMIT", str_repeat("00", 20));
}

116
src/config_post.php Normal file
View file

@ -0,0 +1,116 @@
<?php
set_time_limit(0);
function parseOffset(string $offset) : string|false{
//Make signed offsets unsigned for date_parse
if(str_starts_with($offset, '-')){
$negative_offset = true;
$offset = str_replace('-', '', $offset);
}else{
if(str_starts_with($offset, '+')){
$negative_offset = false;
$offset = str_replace('+', '', $offset);
}else{
return false;
}
}
$parsed = date_parse($offset);
$offset = $parsed['hour'] * 3600 + $parsed['minute'] * 60 + $parsed['second'];
//After date_parse is done, put the sign back
if($negative_offset){
$offset = -abs($offset);
}
//And then, look the offset up.
//timezone_name_from_abbr is not used because it returns false on some(most) offsets because it\'s mapping function is weird.
//That\'s been a bug in PHP since 2008!
foreach(timezone_abbreviations_list() as $zones){
foreach($zones as $timezone){
if($timezone["timezone_id"] !== null && $timezone["offset"] == $offset){
return $timezone["timezone_id"];
}
}
}
return false;
}
if(ini_get("date.timezone") == ""){ //No Timezone set
date_default_timezone_set("GMT");
if(str_contains(" " . strtoupper(php_uname("s")), " WIN")){
$regex = '/(UTC)(\+*\-*\d*\d*\:*\d*\d*)/';
/*
* wmic timezone get Caption
* Get the timezone offset
*
* Sample Output var_dump
* array(3) {
* [0] =>
* string(7) "Caption"
* [1] =>
* string(20) "(UTC+09:30) Adelaide"
* [2] =>
* string(0) ""
* }
*/
exec("wmic timezone get Caption", $output);
$string = trim(implode("\n", $output));
//Detect the Time Zone string
preg_match($regex, $string, $matches);
if(!isset($matches[2]) or ($timezone = parseOffset($matches[2])) === false){
$timezone = 'UTC';
}
if(date_default_timezone_set($timezone)){
ini_set("date.timezone", $timezone);
}
}else{
exec("date +%s", $t);
$offset = round((intval(trim($t[0])) - time()) / 60) * 60;
$daylight = (int) date("I");
$d = timezone_name_from_abbr("", $offset, $daylight);
@ini_set("date.timezone", $d);
date_default_timezone_set($d);
}
}else{
$d = @date_default_timezone_get();
if(!str_contains($d, "/")){
$d = timezone_name_from_abbr($d);
@ini_set("date.timezone", $d);
date_default_timezone_set($d);
}
}
gc_enable();
error_reporting(E_ALL | E_STRICT);
ini_set("allow_url_fopen", 1);
ini_set("display_errors", 1);
ini_set("display_startup_errors", 1);
ini_set("default_charset", "utf-8");
if(defined("POCKETMINE_COMPILE") and POCKETMINE_COMPILE === true){
define("FILE_PATH", realpath(dirname(__FILE__)) . "/");
}else{
define("FILE_PATH", realpath(dirname(__FILE__) . "/../") . "/");
}
set_include_path(get_include_path() . PATH_SEPARATOR . FILE_PATH);
ini_set("memory_limit", "256M"); //Default
define("LOG", true);
define("START_TIME", microtime(true));
define("MAJOR_VERSION", "1.1.1dev");
define("CODENAME", "Nostalgia"); //i\'m not very creative - kotyaralih, yeah - tema1d.
define("CURRENT_MINECRAFT_VERSION", "v0.8.1 alpha");
define("CURRENT_API_VERSION", "12.2");
define("CURRENT_PHP_VERSION", "8.0");
$gitsha1 = false;
if(file_exists(FILE_PATH . ".git/refs/heads/master")){ //Found Git information!
define("GIT_COMMIT", strtolower(trim(file_get_contents(FILE_PATH . ".git/refs/heads/master"))));
}else{ //Unknown :(
define("GIT_COMMIT", str_repeat("00", 20));
}

View file

@ -105,7 +105,7 @@ define("SUGARCANE_BLOCK", 83);
define("FENCE", 85); define("FENCE", 85);
define("PUMPKIN", 86); define("PUMPKIN", 86);
define("NETHERRACK", 87); define("NETHERRACK", 87);
define("SOUL_SAND", 88); define("SOUL_SAND", 88); //doesnt exist
define("GLOWSTONE", 89); define("GLOWSTONE", 89);
define("GLOWSTONE_BLOCK", 89); define("GLOWSTONE_BLOCK", 89);
@ -135,7 +135,7 @@ define("NETHER_BRICKS", 112);
define("NETHER_BRICK_BLOCK", 112); define("NETHER_BRICK_BLOCK", 112);
define("NETHER_BRICKS_STAIRS", 114); define("NETHER_BRICKS_STAIRS", 114);
//TODO missing tile: 126 dt 0.500000 h 2.500000 b CakeTile n activatorRail, mat cake
define("SANDSTONE_STAIRS", 128); define("SANDSTONE_STAIRS", 128);
define("SPRUCE_WOOD_STAIRS", 134); define("SPRUCE_WOOD_STAIRS", 134);

View file

@ -17,11 +17,6 @@ set_error_handler("error_handler", E_ALL);
$errors = 0; $errors = 0;
if(version_compare("8.0.0", PHP_VERSION) > 0){
console("[ERROR] Use PHP >= 8.0.0", true, true, 0);
++$errors;
}
if(php_sapi_name() !== "cli"){ if(php_sapi_name() !== "cli"){
console("[ERROR] You must run NostalgiaCore using the CLI.", true, true, 0); console("[ERROR] You must run NostalgiaCore using the CLI.", true, true, 0);
++$errors; ++$errors;

View file

@ -7,6 +7,8 @@ abstract class Animal extends Creature implements Ageable, Breedable{
public $age; public $age;
public $loveTimeout; public $loveTimeout;
public $closestPlayerThatCanFeedEID = false; public $closestPlayerThatCanFeedEID = false;
public $closestPlayerThatCanFeedDist = INF; public $closestPlayerThatCanFeedDist = INF;
@ -31,7 +33,7 @@ abstract class Animal extends Creature implements Ageable, Breedable{
$this->closestPlayerThatCanFeedEID = false; $this->closestPlayerThatCanFeedEID = false;
$this->closestPlayerThatCanFeedDist = INF; $this->closestPlayerThatCanFeedDist = INF;
}else{ }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; $this->closestPlayerThatCanFeedDist = $dist;
} }
} }
@ -59,9 +61,9 @@ abstract class Animal extends Creature implements Ageable, Breedable{
return $this->getAge() < 0; return $this->getAge() < 0;
} }
public function breed(){ public function breed($mate){
if($this->server->dhandle("entity.animal.breed", ["parent" => $this]) !== false){ if($this->server->dhandle("entity.animal.breed", ["parent" => $this, "parent2" => $mate]) !== false){
$c = $this->spawnChild(); $c = $this->spawnChild($mate);
$c->parent = $this; //TODO save eid to avoid memory leaks? $c->parent = $this; //TODO save eid to avoid memory leaks?
$this->server->api->entity->spawnToAll($c); $this->server->api->entity->spawnToAll($c);
return $c; return $c;
@ -106,7 +108,7 @@ abstract class Animal extends Creature implements Ageable, Breedable{
$this->age = $i; $this->age = $i;
} }
public function spawnChild() public function spawnChild($mate)
{ {
return $this->server->api->entity->add($this->level, $this->class, $this->type, [ return $this->server->api->entity->add($this->level, $this->class, $this->type, [
"x" => $this->x + lcg_value() * mt_rand(-1, 1), "x" => $this->x + lcg_value() * mt_rand(-1, 1),
@ -138,9 +140,7 @@ abstract class Animal extends Creature implements Ageable, Breedable{
if($e->isPlayer() && $action === InteractPacket::ACTION_HOLD){ if($e->isPlayer() && $action === InteractPacket::ACTION_HOLD){
$slot = $e->player->getHeldItem(); $slot = $e->player->getHeldItem();
if($this->isFood($slot->getID()) && $this->inLove <= 0 && !$this->isBaby() && $this->loveTimeout <= 0){ if($this->isFood($slot->getID()) && $this->inLove <= 0 && !$this->isBaby() && $this->loveTimeout <= 0){
if(($e->player->gamemode & 0x01) === SURVIVAL){ $e->player->consumeSingleItem();
$e->player->removeItem($slot->getID(), $slot->getMetadata(), 1);
}
$this->inLove = 600; $this->inLove = 600;
return true; return true;
} }

View file

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

View file

@ -7,10 +7,11 @@ abstract class Creature extends Living{
public $closestPlayerEID = false; public $closestPlayerEID = false;
public $closestPlayerDist = INF; public $closestPlayerDist = INF;
public function __construct(Level $level, $eid, $class, $type = 0, $data = []){ public function __construct(Level $level, $eid, $class, $type = 0, $data = []){
$this->inPanic = false; //force for now $this->inPanic = false; //force for now
parent::__construct($level, $eid, $class, $type, $data); parent::__construct($level, $eid, $class, $type, $data);
$this->setHealth($this->data["Health"] ?? 1, "generic"); $this->setHealth($this->data["Health"] ?? 1, "generic", allowHarm: false);
$this->enableAutojump = true; $this->enableAutojump = true;
$this->searchForClosestPlayers = true; $this->searchForClosestPlayers = true;
} }
@ -20,6 +21,7 @@ abstract class Creature extends Living{
return parent::update($now); return parent::update($now);
} }
public function handlePrePlayerSearcher(){ public function handlePrePlayerSearcher(){
parent::handlePrePlayerSearcher(); parent::handlePrePlayerSearcher();
if($this->closestPlayerEID !== false){ if($this->closestPlayerEID !== false){
@ -28,7 +30,7 @@ abstract class Creature extends Living{
$this->closestPlayerEID = false; $this->closestPlayerEID = false;
$this->closestPlayerDist = INF; $this->closestPlayerDist = INF;
}else{ }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; $this->closestPlayerDist = $dist;
} }
} }
@ -54,34 +56,33 @@ abstract class Creature extends Living{
public function getArmorValue(){ public function getArmorValue(){
return 0; return 0;
} }
public function spawn($player){ public function spawn(Player $player){
if(!($player instanceof Player)){
$player = $this->server->api->player->get($player);
}
if($player->eid === $this->eid or $this->closed !== false or ($player->level !== $this->level and $this->class !== ENTITY_PLAYER)){ if($player->eid === $this->eid or $this->closed !== false or ($player->level !== $this->level and $this->class !== ENTITY_PLAYER)){
return false; return false;
} }
$pk = new AddMobPacket; if(!$player->hasEntity($this)){
$pk->eid = $this->eid; $player->addEntity($this);
$pk->type = $this->type; $pk = new AddMobPacket;
$pk->x = $this->x; $pk->eid = $this->eid;
$pk->y = $this->y; $pk->type = $this->type;
$pk->z = $this->z; $pk->x = $this->x;
$pk->yaw = $this->yaw; $pk->y = $this->y;
$pk->pitch = $this->pitch; $pk->z = $this->z;
$pk->metadata = $this->getMetadata(); $pk->yaw = $this->yaw;
$player->dataPacket($pk); $pk->pitch = $this->pitch;
$pk->metadata = $this->getMetadata();
$player->entityQueueDataPacket($pk);
$pk = new SetEntityMotionPacket; $pk = new SetEntityMotionPacket;
$pk->eid = $this->eid; $pk->eid = $this->eid;
$pk->speedX = $this->speedX; $pk->speedX = $this->speedX;
$pk->speedY = $this->speedY; $pk->speedY = $this->speedY;
$pk->speedZ = $this->speedZ; $pk->speedZ = $this->speedZ;
$player->dataPacket($pk); $player->entityQueueDataPacket($pk);
$this->sendLinkPackets($player);
if($this->linkedEntity != 0 && $this->isRider){ return true;
$player->eventHandler(["rider" => $this->eid, "riding" => $this->linkedEntity, "type" => 0], "entity.link");
} }
return false;
} }
} }

File diff suppressed because it is too large Load diff

View file

@ -78,7 +78,7 @@ abstract class Projectile extends Entity{
$this->lastSpeedY = $this->speedY; $this->lastSpeedY = $this->speedY;
$this->lastSpeedZ = $this->speedZ; $this->lastSpeedZ = $this->speedZ;
$this->needsUpdate = true; $this->needsUpdate = true;
$this->handleWaterMovement(); //TODO: maybe just call parent::update(); ? $this->handleWaterMovement();
if($this->fire > 0){ if($this->fire > 0){
if(!$this->isImmuneToFire){ if(!$this->isImmuneToFire){
if(($this->fire % 20) == 0){ if(($this->fire % 20) == 0){
@ -199,19 +199,26 @@ abstract class Projectile extends Entity{
return $data; return $data;
} }
public function spawn($player)
public function spawn(Player $player)
{ {
$pk = new AddEntityPacket(); if(!$player->hasEntity($this)){
$pk->eid = $this->eid; $player->addEntity($this);
$pk->type = $this->type; $pk = new AddEntityPacket();
$pk->x = $this->x; $pk->eid = $this->eid;
$pk->y = $this->y; $pk->type = $this->type;
$pk->z = $this->z; $pk->x = $this->x;
$pk->speedX = $this->speedX; $pk->y = $this->y;
$pk->speedY = $this->speedY; $pk->z = $this->z;
$pk->speedZ = $this->speedZ; $pk->speedX = $this->speedX;
$pk->did = 0; $pk->speedY = $this->speedY;
$player->dataPacket($pk); $pk->speedZ = $this->speedZ;
$pk->did = 0;
$player->entityQueueDataPacket($pk);
$this->sendLinkPackets($player);
return true;
}
return false;
} }
} }

View file

@ -2,7 +2,6 @@
class MobController class MobController
{ {
public static $ADVANCED = false;
public static $AUTOJUMP = false; public static $AUTOJUMP = false;
public static $landed = false; public static $landed = false;
public static $DANGEROUS_BLOCKS = [ public static $DANGEROUS_BLOCKS = [
@ -92,6 +91,7 @@ class MobController
public function movementTick(){ public function movementTick(){
$this->entity->moveForward = 0; $this->entity->moveForward = 0;
if($this->updateMove){ if($this->updateMove){
$this->updateMove = false; $this->updateMove = false;
$v1 = floor($this->entity->boundingBox->minY + 0.5); $v1 = floor($this->entity->boundingBox->minY + 0.5);

View file

@ -5,7 +5,9 @@ class TaskEatTileGoal extends TaskBase
public function onStart(EntityAI $ai) public function onStart(EntityAI $ai)
{ {
$this->selfCounter = 40; $this->selfCounter = 40;
$ai->entity->server->api->player->broadcastPacket($ai->entity->level->players, new EntityEventPacket($ai->entity->eid, EntityEventPacket::ENTITY_ANIM_10)); foreach($ai->entity->level->players as $player){
if($player->hasEntity($ai->entity)) $player->entityQueueDataPacket(new EntityEventPacket($ai->entity->eid, EntityEventPacket::ENTITY_ANIM_10));
}
} }
public function onEnd(EntityAI $ai) public function onEnd(EntityAI $ai)

View file

@ -2,6 +2,7 @@
class TaskFollowParent extends TaskBase class TaskFollowParent extends TaskBase
{ {
public $speedMultiplier;
public function __construct($speed){ public function __construct($speed){
$this->speedMultiplier = $speed; $this->speedMultiplier = $speed;
} }

View file

@ -2,6 +2,7 @@
class TaskMate extends TaskBase class TaskMate extends TaskBase
{ {
public $speedMultiplier;
public function __construct($speed){ public function __construct($speed){
$this->speedMultiplier = $speed; $this->speedMultiplier = $speed;
} }
@ -41,7 +42,7 @@ class TaskMate extends TaskBase
/** /**
* @var Animal $baby * @var Animal $baby
*/ */
$baby = $ai->entity->breed(); $baby = $ai->entity->breed($entpar2);
//this.theAnimal.setGrowingAge(6000); TODO growing age? //this.theAnimal.setGrowingAge(6000); TODO growing age?
//this.targetMate.setGrowingAge(6000); //this.targetMate.setGrowingAge(6000);

View file

@ -5,6 +5,7 @@ class TaskRangedAttack extends \TaskBase
public $server; public $server;
public $attackCounter = 0; public $attackCounter = 0;
public $seenTicks = 0; public $seenTicks = 0;
public $rangeSquared = 0;
public function __construct($speed, $range){ public function __construct($speed, $range){
$this->speedMultiplier = $speed; $this->speedMultiplier = $speed;
$this->rangeSquared = $range * $range; $this->rangeSquared = $range * $range;
@ -14,7 +15,6 @@ class TaskRangedAttack extends \TaskBase
public function onStart(EntityAI $ai) public function onStart(EntityAI $ai)
{ {
$this->selfCounter = 1; $this->selfCounter = 1;
$this->ticksNoSeen = 0;
} }
public function onEnd(EntityAI $ai) public function onEnd(EntityAI $ai)
@ -67,7 +67,7 @@ class TaskRangedAttack extends \TaskBase
$arrow = $this->server->api->entity->add($selfEntity->level, ENTITY_OBJECT, OBJECT_ARROW, $d); $arrow = $this->server->api->entity->add($selfEntity->level, ENTITY_OBJECT, OBJECT_ARROW, $d);
$arrow->shotByEntity = true; $arrow->shotByEntity = true;
$arrow->shooterEID = $selfEntity->eid; $arrow->shooterEID = $selfEntity->eid;
$posY = ($target->y + $target->getEyeHeight() - 0.1); $posY = ($selfEntity->y + $selfEntity->getEyeHeight() - 0.1);
$diffX = $target->x - $selfEntity->x; $diffX = $target->x - $selfEntity->x;
$diffY = ($target->boundingBox->minY + ($target->height / 3)) - $posY; $diffY = ($target->boundingBox->minY + ($target->height / 3)) - $posY;
$diffZ = $target->z - $selfEntity->z; $diffZ = $target->z - $selfEntity->z;

View file

@ -2,6 +2,8 @@
class TaskTempt extends TaskBase class TaskTempt extends TaskBase
{ {
public $speedMultiplier;
public $targetDistance;
public function __construct($speed){ public function __construct($speed){
$this->speedMultiplier = $speed; $this->speedMultiplier = $speed;
$this->targetDistance = 10 * 10; $this->targetDistance = 10 * 10;

View file

@ -7,7 +7,7 @@ class Chicken extends Animal{
$this->timeUntilEgg = mt_rand(0,6000) + 6000; $this->timeUntilEgg = mt_rand(0,6000) + 6000;
$this->setSize(0.4, 0.7); $this->setSize(0.4, 0.7);
parent::__construct($level, $eid, $class, $type, $data); parent::__construct($level, $eid, $class, $type, $data);
$this->setHealth($this->data["Health"] ?? 4, "generic"); $this->setHealth($this->data["Health"] ?? 4, "generic", allowHarm: false);
$this->setName('Chicken'); $this->setName('Chicken');
$this->setSpeed(0.25); $this->setSpeed(0.25);

View file

@ -5,7 +5,7 @@ class Cow extends Animal{
function __construct(Level $level, $eid, $class, $type = 0, $data = []){ function __construct(Level $level, $eid, $class, $type = 0, $data = []){
$this->setSize(0.9, 1.3); $this->setSize(0.9, 1.3);
parent::__construct($level, $eid, $class, $type, $data); parent::__construct($level, $eid, $class, $type, $data);
$this->setHealth($this->data["Health"] ?? 10, "generic"); $this->setHealth($this->data["Health"] ?? 10, "generic", allowHarm: false);
$this->setName("Cow"); $this->setName("Cow");
$this->setSpeed(0.2); $this->setSpeed(0.2);
$this->ai->addTask(new TaskRandomWalk(0.8)); $this->ai->addTask(new TaskRandomWalk(0.8));
@ -26,7 +26,7 @@ class Cow extends Animal{
if($e->isPlayer() && $action === InteractPacket::ACTION_HOLD){ if($e->isPlayer() && $action === InteractPacket::ACTION_HOLD){
$slot = $e->player->getHeldItem(); $slot = $e->player->getHeldItem();
if($slot->getID() === BUCKET && $slot->getMetadata() === 0){ if($slot->getID() === BUCKET && $slot->getMetadata() === 0){
$e->player->removeItem($slot->getID(), $slot->getMetadata(), 1, true); //remove only 1 bucket $e->player->consumeSingleItem();
$e->player->addItem(BUCKET, 1, 1, true); $e->player->addItem(BUCKET, 1, 1, true);
return true; return true;
} }

View file

@ -6,7 +6,7 @@ class Pig extends Animal implements Rideable{
public function __construct(Level $level, $eid, $class, $type = 0, $data = []){ public function __construct(Level $level, $eid, $class, $type = 0, $data = []){
$this->setSize(0.9, 0.9); $this->setSize(0.9, 0.9);
parent::__construct($level, $eid, $class, $type, $data); parent::__construct($level, $eid, $class, $type, $data);
$this->setHealth($this->data["Health"] ?? 10, "generic"); $this->setHealth($this->data["Health"] ?? 10, "generic", allowHarm: false);
$this->server = ServerAPI::request(); $this->server = ServerAPI::request();
$this->setName("Pig"); $this->setName("Pig");
$this->setSpeed(0.25); $this->setSpeed(0.25);
@ -35,7 +35,7 @@ class Pig extends Animal implements Rideable{
} }
public function canRide($e){ public function canRide($e){
return $this->isSaddled() && $this->linkedEntity == 0 && $e->linkedEntity == 0; return $this->isSaddled() && $this->rider == 0;
} }
public function updateEntityMovement(){ public function updateEntityMovement(){
@ -63,7 +63,7 @@ class Pig extends Animal implements Rideable{
if($slot->getID() === SADDLE){ if($slot->getID() === SADDLE){
if(!$this->isSaddled()){ if(!$this->isSaddled()){
$e->player->removeItem($slot->getID(), 0, 1); $e->player->consumeSingleItem(send: true);
$this->setSaddled(1); $this->setSaddled(1);
} }
return true; //avoid further interactions return true; //avoid further interactions

View file

@ -7,7 +7,7 @@ class Sheep extends Animal{
function __construct(Level $level, $eid, $class, $type = 0, $data = []){ function __construct(Level $level, $eid, $class, $type = 0, $data = []){
$this->setSize(0.9, 1.3); $this->setSize(0.9, 1.3);
parent::__construct($level, $eid, $class, $type, $data); parent::__construct($level, $eid, $class, $type, $data);
$this->setHealth($this->data["Health"] ?? 8, "generic"); $this->setHealth($this->data["Health"] ?? 8, "generic", allowHarm: false);
$this->setName("Sheep"); $this->setName("Sheep");
$this->data["Sheared"] = $this->data["Sheared"] ?? 0; $this->data["Sheared"] = $this->data["Sheared"] ?? 0;
$this->data["Color"] = $this->data["Color"] ?? $this->sheepColor(); $this->data["Color"] = $this->data["Color"] ?? $this->sheepColor();
@ -24,6 +24,19 @@ class Sheep extends Animal{
$this->ai->addTask(new TaskFollowParent(1.0)); $this->ai->addTask(new TaskFollowParent(1.0));
} }
public function spawnChild($mate)
{
$child = parent::spawnChild($mate);
if($child instanceof Sheep){
if($mate instanceof Sheep){
$child->setColor(mt_rand(0, 1) == 0 ? $this->getColor() : $mate->getColor());
}else{
$child->setColor($this->getColor());
}
}
return $child;
}
public function createSaveData(){ public function createSaveData(){
$data = parent::createSaveData(); $data = parent::createSaveData();
$data["Color"] = @$this->data["Color"]; $data["Color"] = @$this->data["Color"];
@ -75,25 +88,18 @@ class Sheep extends Animal{
$slot = $e->player->getHeldItem(); $slot = $e->player->getHeldItem();
if($slot->getID() === SHEARS){ if($slot->getID() === SHEARS){
if(!$this->isSheared() && !$this->isBaby()){ if(!$this->isSheared() && !$this->isBaby()){
if($e->player->gamemode != 1) $slot->useOn($this);
$this->setSheared(1); $this->setSheared(1);
$speedX = (lcg_value() * 0.2 - 0.1) + (lcg_value() - lcg_value()) * 0.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; $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); $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()){ $slot->hurtAndBreak(1, $e->player);
$e->player->removeItem($slot->getID(), $slot->getMetadata(), $slot->count, true);
}else{
$e->player->setSlot($e->player->slot, $slot);
}
} }
return true; return true;
}elseif($slot->getID() === DYE){ }elseif($slot->getID() === DYE){
$this->setColor($this->switchColorMeta($slot->getMetadata())); $this->setColor($this->switchColorMeta($slot->getMetadata()));
if(($e->player->gamemode & 0x01) === SURVIVAL){ $e->player->consumeSingleItem();
$e->player->removeItem($slot->getID(), $slot->getMetadata(), 1, true);
}
} }
} }
return parent::interactWith($e, $action); return parent::interactWith($e, $action);

View file

@ -1,5 +1,4 @@
<?php <?php
class Creeper extends Monster{ class Creeper extends Monster{
const TYPE = MOB_CREEPER; const TYPE = MOB_CREEPER;
const EXPL_TIME = 30; const EXPL_TIME = 30;
@ -8,7 +7,7 @@ class Creeper extends Monster{
function __construct(Level $level, $eid, $class, $type = 0, $data = []){ function __construct(Level $level, $eid, $class, $type = 0, $data = []){
$this->setSize(0.6, 1.7); $this->setSize(0.6, 1.7);
parent::__construct($level, $eid, $class, $type, $data); parent::__construct($level, $eid, $class, $type, $data);
$this->setHealth($this->data["Health"] ?? 16, "generic"); $this->setHealth($this->data["Health"] ?? 16, "generic", allowHarm: false);
$this->setName("Creeper"); $this->setName("Creeper");
$this->ignited = 0; $this->ignited = 0;
$this->setSpeed(0.25); $this->setSpeed(0.25);
@ -39,11 +38,7 @@ class Creeper extends Monster{
if($e->isPlayer() && $action === InteractPacket::ACTION_HOLD){ if($e->isPlayer() && $action === InteractPacket::ACTION_HOLD){
$slot = $e->player->getHeldItem(); $slot = $e->player->getHeldItem();
if($slot->getID() === FLINT_AND_STEEL && !$this->isIgnited()){ if($slot->getID() === FLINT_AND_STEEL && !$this->isIgnited()){
if($slot->useOn($this) && $slot->getMetadata() >= $slot->getMaxDurability()){ $slot->hurtAndBreak(1, $e->player);
$e->player->removeItem($slot->getID(), $slot->getMetadata(), $slot->count, true);
}else{
$e->player->setSlot($e->player->slot, $slot);
}
$this->ignite(); $this->ignite();
return true; return true;
} }

View file

@ -5,7 +5,7 @@ class PigZombie extends Monster{ //TODO extends zombie
function __construct(Level $level, $eid, $class, $type = 0, $data = []){ function __construct(Level $level, $eid, $class, $type = 0, $data = []){
$this->setSize(0.3, 1.95); $this->setSize(0.3, 1.95);
parent::__construct($level, $eid, $class, $type, $data); parent::__construct($level, $eid, $class, $type, $data);
$this->setHealth($this->data["Health"] ?? 12, "generic"); $this->setHealth($this->data["Health"] ?? 12, "generic", allowHarm: false);
$this->setName("Pigman"); $this->setName("Pigman");
$this->setSpeed(0.25); $this->setSpeed(0.25);
$this->isImmuneToFire = true; $this->isImmuneToFire = true;

View file

@ -5,7 +5,7 @@ class Skeleton extends Monster{
function __construct(Level $level, $eid, $class, $type = 0, $data = []){ function __construct(Level $level, $eid, $class, $type = 0, $data = []){
$this->setSize(0.6, 1.99); $this->setSize(0.6, 1.99);
parent::__construct($level, $eid, $class, $type, $data); parent::__construct($level, $eid, $class, $type, $data);
$this->setHealth($this->data["Health"] ?? 10, "generic"); $this->setHealth($this->data["Health"] ?? 10, "generic", allowHarm: false);
$this->setName("Skeleton"); $this->setName("Skeleton");
$this->ai->removeTask("TaskAttackPlayer"); $this->ai->removeTask("TaskAttackPlayer");
$this->setSpeed(0.25); $this->setSpeed(0.25);

View file

@ -6,7 +6,7 @@ class Spider extends Monster{
function __construct(Level $level, $eid, $class, $type = 0, $data = []){ function __construct(Level $level, $eid, $class, $type = 0, $data = []){
$this->setSize(1.4, 0.9); $this->setSize(1.4, 0.9);
parent::__construct($level, $eid, $class, $type, $data); parent::__construct($level, $eid, $class, $type, $data);
$this->setHealth($this->data["Health"] ?? 8, "generic"); $this->setHealth($this->data["Health"] ?? 8, "generic", allowHarm: false);
$this->setName("Spider"); $this->setName("Spider");
$this->setSpeed(0.3); $this->setSpeed(0.3);
$this->ai->addTask(new TaskRandomWalk(1.2)); $this->ai->addTask(new TaskRandomWalk(1.2));

View file

@ -1,11 +1,10 @@
<?php <?php
class Zombie extends Monster{ class Zombie extends Monster{
const TYPE = MOB_ZOMBIE; const TYPE = MOB_ZOMBIE;
function __construct(Level $level, $eid, $class, $type = 0, $data = []){ function __construct(Level $level, $eid, $class, $type = 0, $data = array()){
$this->setSize(0.6, 1.85); $this->setSize(0.6, 1.85);
parent::__construct($level, $eid, $class, $type, $data); parent::__construct($level, $eid, $class, $type, $data);
$this->setHealth($this->data["Health"] ?? 12, "generic"); $this->setHealth($this->data["Health"] ?? 12, "generic", allowHarm: false);
$this->setName("Zombie"); $this->setName("Zombie");
$this->setSpeed(0.23); $this->setSpeed(0.23);
@ -24,16 +23,16 @@ class Zombie extends Monster{
return false; return false;
} }
//bad fix for burning in water //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){ if($block == WATER || $block == STILL_WATER){
$v16 = ((int) $this->y + 1) - LiquidBlock::getPercentAir($meta); $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))){ 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; 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); $block = $this->level->level->getBlockID(floor($this->x), $y, floor($this->z));
if(StaticBlock::getIsSolid($block)){ if(StaticBlock::getIsSolid($block)){
return false; return false;
} }

View file

@ -13,6 +13,7 @@ class Arrow extends Entity{
public $criticial = false; public $criticial = false;
public $groundTicks = 0; public $groundTicks = 0;
public $shotByPlayer = false; public $shotByPlayer = false;
public $shotByEntity = false;
function __construct(Level $level, $eid, $class, $type = 0, $data = []){ function __construct(Level $level, $eid, $class, $type = 0, $data = []){
parent::__construct($level, $eid, $class, $type, $data); parent::__construct($level, $eid, $class, $type, $data);
@ -47,16 +48,6 @@ class Arrow extends Entity{
$data["shotByPlayer"] = $this->shotByPlayer; $data["shotByPlayer"] = $this->shotByPlayer;
return $data; return $data;
} }
public function handleUpdate(){
$pk = new MoveEntityPacket_PosRot;
$pk->eid = $this->eid;
$pk->x = $this->x;
$pk->y = $this->y;
$pk->z = $this->z;
$pk->yaw = $this->yaw;
$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 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); $f2 = sqrt($d * $d + $d1 * $d1 + $d2 * $d2);
@ -111,7 +102,7 @@ class Arrow extends Entity{
if(!$this->isImmuneToFire){ if(!$this->isImmuneToFire){
$this->harm(4, "fire"); $this->harm(4, "fire");
$oldOnFire = $this->fire; $oldOnFire = $this->fire;
if($oldOnFire < 20 * 30) $this->fire = 20 * 30; //30 seconds if($oldOnFire < 20*30) $this->fire = 20*30; //30 seconds
} }
} }
@ -120,8 +111,9 @@ class Arrow extends Entity{
} }
//Entity::update end //Entity::update end
if($this->lastPitch == $this->lastYaw && $this->lastYaw == 0){ 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->lastYaw = $this->yaw = atan2($this->speedX, $this->speedZ) * 180 / M_PI;
$this->lastPitch = $this->pitch = atan2($this->speedY, $v1) * 180 / M_PI; $this->lastPitch = $this->pitch = atan2($this->speedY, $v1) * 180 / M_PI;
} }
@ -162,6 +154,7 @@ class Arrow extends Entity{
$end = new Vector3($this->x + $this->speedX, $this->y + $this->speedY, $this->z + $this->speedZ); $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)); $entities = $this->level->getEntitiesInAABB($this->boundingBox->addCoord($this->speedX, $this->speedY, $this->speedZ)->expand(1, 1, 1));
$bestDist = 0; $bestDist = 0;
$bestEnt = null; $bestEnt = null;
@ -188,13 +181,14 @@ class Arrow extends Entity{
if($v4 != null){ if($v4 != null){
if($v4->entityHit != null){ if($v4->entityHit != null){
$v49 = sqrt($this->speedY * $this->speedY + $this->speedX * $this->speedX + $this->speedZ * $this->speedZ); $v49 = sqrt($this->speedY*$this->speedY + $this->speedX*$this->speedX + $this->speedZ*$this->speedZ);
$damage = ceil($v49 + $v49); $damage = ceil($v49+$v49);
if($this->criticial){ if($this->criticial){
$damage += mt_rand(0, $damage / 2 + 1); $damage += mt_rand(0, $damage / 2 + 1);
} }
if($v4->entityHit->harm($damage, $this->eid)){ if($v4->entityHit->harm($damage, $this->eid)){
//vanilla seems to increase arrow count if $v4->entity is mob //vanilla seems to increase arrow count if $v4->entity is mob
$this->close(); $this->close();
@ -217,7 +211,7 @@ class Arrow extends Entity{
$this->speedY = $v4->hitVector->y - $this->y; $this->speedY = $v4->hitVector->y - $this->y;
$this->speedZ = $v4->hitVector->z - $this->z; $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){ if($v21 != 0){
$this->x -= $this->speedX / $v21 * 0.05; $this->x -= $this->speedX / $v21 * 0.05;
$this->y -= $this->speedY / $v21 * 0.05; $this->y -= $this->speedY / $v21 * 0.05;
@ -233,7 +227,7 @@ class Arrow extends Entity{
$this->x += $this->speedX; $this->x += $this->speedX;
$this->y += $this->speedY; $this->y += $this->speedY;
$this->z += $this->speedZ; $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->yaw = atan2($this->speedX, $this->speedZ) * 180 / M_PI;
$this->pitch = atan2($this->speedY, $v21) * 180 / M_PI; $this->pitch = atan2($this->speedY, $v21) * 180 / M_PI;
@ -252,11 +246,12 @@ class Arrow extends Entity{
$this->doBlocksCollision(); $this->doBlocksCollision();
} }
} }
public function spawn($player){ public function spawn(Player $player){
if($this->type === OBJECT_ARROW){ if(!($this->type == OBJECT_ARROW)) return false;
if(!$player->hasEntity($this)){
$player->addEntity($this);
$pk = new AddEntityPacket; $pk = new AddEntityPacket;
$pk->eid = $this->eid; $pk->eid = $this->eid;
$pk->type = $this->type; $pk->type = $this->type;
@ -267,7 +262,10 @@ class Arrow extends Entity{
$pk->speedX = $this->speedX; $pk->speedX = $this->speedX;
$pk->speedY = $this->speedY; $pk->speedY = $this->speedY;
$pk->speedZ = $this->speedZ; $pk->speedZ = $this->speedZ;
$player->dataPacket($pk); $player->entityQueueDataPacket($pk);
$this->sendLinkPackets($player);
return true;
} }
return false;
} }
} }

View file

@ -8,7 +8,7 @@ class FallingSand extends Entity{
public function __construct($level, $eid, $class, $type = 0, $data = []){ public function __construct($level, $eid, $class, $type = 0, $data = []){
parent::__construct($level, $eid, $class, $type, $data); parent::__construct($level, $eid, $class, $type, $data);
$this->setHealth(PHP_INT_MAX, "generic"); $this->setHealth(PHP_INT_MAX, "generic", allowHarm: false);
$this->height = 0.98; $this->height = 0.98;
$this->width = 0.98; $this->width = 0.98;
$this->yOffset = $this->height / 2; $this->yOffset = $this->height / 2;
@ -19,6 +19,26 @@ class FallingSand extends Entity{
public function isPickable(){ public function isPickable(){
return !$this->dead; return !$this->dead;
} }
public function spawn($player)
{
if(!$player->hasEntity($this)){
$player->addEntity($this);
$pk = new AddEntityPacket();
$pk->eid = $this->eid;
$pk->type = $this->type;
$pk->x = $this->x;
$pk->y = $this->y;
$pk->z = $this->z;
$pk->speedX = $this->speedX;
$pk->speedY = $this->speedY;
$pk->speedZ = $this->speedZ;
$pk->did = -$this->data["Tile"];
$player->entityQueueDataPacket($pk);
$this->sendLinkPackets($player);
return true;
}
return false;
}
public function update($now){ public function update($now){
if($this->closed) return; if($this->closed) return;
@ -62,7 +82,6 @@ class FallingSand extends Entity{
return; return;
} }
} }
if($this->onGround){ if($this->onGround){
$this->speedX *= 0.7; $this->speedX *= 0.7;
$this->speedZ *= 0.7; $this->speedZ *= 0.7;

View file

@ -7,7 +7,7 @@ class ItemEntity extends Entity{
public $meta, $stack, $itemID; public $meta, $stack, $itemID;
public function __construct(Level $level, $eid, $class, $type = 0, $data = []) public function __construct(Level $level, $eid, $class, $type = 0, $data = array())
{ {
parent::__construct($level, $eid, $class, $type, $data); parent::__construct($level, $eid, $class, $type, $data);
$this->setSize(0.25, 0.25); $this->setSize(0.25, 0.25);
@ -22,7 +22,7 @@ class ItemEntity extends Entity{
$this->itemID = (int) $data["itemID"]; $this->itemID = (int) $data["itemID"];
} }
$this->hasGravity = true; $this->hasGravity = true;
$this->setHealth(5, "generic"); $this->setHealth(5, "generic", allowHarm: false);
$this->gravity = 0.04; $this->gravity = 0.04;
$this->delayBeforePickup = 40; //in vanilla it is 0 by default $this->delayBeforePickup = 40; //in vanilla it is 0 by default
$this->stepHeight = 0; $this->stepHeight = 0;
@ -42,28 +42,28 @@ class ItemEntity extends Entity{
} }
public function spawn($player) public function spawn(Player $player)
{ {
$pk = new AddItemEntityPacket(); if(!$player->hasEntity($this)){
$pk->eid = $this->eid; $player->addEntity($this);
$pk->x = $this->x; $pk = new AddItemEntityPacket();
$pk->y = $this->y; $pk->eid = $this->eid;
$pk->z = $this->z; $pk->x = $this->x;
$pk->yaw = $this->yaw; $pk->y = $this->y;
$pk->pitch = $this->pitch; $pk->z = $this->z;
$pk->roll = 0; $pk->speedX = $this->speedX;
$pk->item = BlockAPI::getItem($this->itemID, $this->meta, $this->stack); $pk->speedY = $this->speedY;
$pk->metadata = $this->getMetadata(); $pk->speedZ = $this->speedZ;
$player->dataPacket($pk); $pk->item = BlockAPI::getItem($this->itemID, $this->meta, $this->stack);
$pk->metadata = $this->getMetadata();
$pk = new SetEntityMotionPacket(); $player->entityQueueDataPacket($pk);
$pk->eid = $this->eid; $this->sendLinkPackets($player);
$pk->speedX = $this->speedX; return true;
$pk->speedY = $this->speedY; }
$pk->speedZ = $this->speedZ; return false;
$player->dataPacket($pk);
} }
public function tryCombining(Entity $another){ public function tryCombining(Entity $another){
if($another->eid == $this->eid) return false; if($another->eid == $this->eid) return false;
@ -86,25 +86,26 @@ class ItemEntity extends Entity{
$id = $this->level->level->getBlockID($xFloor, $yFloor, $zFloor); $id = $this->level->level->getBlockID($xFloor, $yFloor, $zFloor);
if(StaticBlock::getIsSolid($id)){ if(StaticBlock::getIsSolid($id) && StaticBlock::getIsFullBlock($id)){
$xDiff = $x - $xFloor; $xDiff = $x - $xFloor;
$id = $this->level->level->getBlockID($xFloor - 1, $yFloor, $zFloor); $id = $this->level->level->getBlockID($xFloor - 1, $yFloor, $zFloor);
$xNeg = StaticBlock::getIsSolid($id); $xNeg = StaticBlock::getIsSolid($id) && StaticBlock::getIsFullBlock($id);
$id = $this->level->level->getBlockID($xFloor + 1, $yFloor, $zFloor); $id = $this->level->level->getBlockID($xFloor + 1, $yFloor, $zFloor);
$xPos = StaticBlock::getIsSolid($id); $xPos = StaticBlock::getIsSolid($id) && StaticBlock::getIsFullBlock($id);
$id = $this->level->level->getBlockID($xFloor, $yFloor - 1, $zFloor); $id = $this->level->level->getBlockID($xFloor, $yFloor - 1, $zFloor);
$yNeg = StaticBlock::getIsSolid($id); $yNeg = StaticBlock::getIsSolid($id) && StaticBlock::getIsFullBlock($id);
$id = $this->level->level->getBlockID($xFloor, $yFloor + 1, $zFloor); $id = $this->level->level->getBlockID($xFloor, $yFloor + 1, $zFloor);
$yPos = StaticBlock::getIsSolid($id); $yPos = StaticBlock::getIsSolid($id) && StaticBlock::getIsFullBlock($id);
$id = $this->level->level->getBlockID($xFloor - 1, $yFloor, $zFloor - 1); $id = $this->level->level->getBlockID($xFloor, $yFloor, $zFloor - 1);
$zNeg = StaticBlock::getIsSolid($id); $zNeg = StaticBlock::getIsSolid($id) && StaticBlock::getIsFullBlock($id);
$zPos = $this->level->level->getBlockID($xFloor + 1, $yFloor, $zFloor + 1); $id = $this->level->level->getBlockID($xFloor, $yFloor, $zFloor + 1);
$zPos = StaticBlock::getIsSolid($id) && StaticBlock::getIsFullBlock($id);
if($xNeg || $xDiff >= 9999.0){ //TODO not needed check? if($xNeg || $xDiff >= 9999.0){ //TODO not needed check?
$v15 = 9999.0; $v15 = 9999.0;
@ -143,7 +144,7 @@ class ItemEntity extends Entity{
$v16 = 4; $v16 = 4;
} }
if(!StaticBlock::getIsSolid($zPos) && ((1.0 - $zDiff) < $v15)){ if(!$zPos && ((1.0 - $zDiff) < $v15)){
$v16 = 5; $v16 = 5;
} }
@ -171,7 +172,7 @@ class ItemEntity extends Entity{
} }
public function handleWaterMovement(){ public function handleWaterMovement(){
return $this->level->handleMaterialAcceleration($this->boundingBox, 0, $this); return $this->level->handleMaterialAcceleration($this->boundingBox, Material::$water, $this);
} }
public function updateEntityMovement(){ public function updateEntityMovement(){
@ -181,7 +182,7 @@ class ItemEntity extends Entity{
$this->checkInTile($this->x, $this->y, $this->z); $this->checkInTile($this->x, $this->y, $this->z);
$this->move($this->speedX, $this->speedY, $this->speedZ); $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){ if($var1 || $this->counter % 25 == 0){
$blockIDAt = $this->level->level->getBlockID(floor($this->x), floor($this->y), floor($this->z)); $blockIDAt = $this->level->level->getBlockID(floor($this->x), floor($this->y), floor($this->z));
@ -199,7 +200,7 @@ class ItemEntity extends Entity{
$friction = 0.98; $friction = 0.98;
if($this->onGround){ if($this->onGround){
$friction = 0.588; $friction = 0.588;
$v3 = $this->level->level->getBlockID($this->x, floor($this->boundingBox->minY) - 1, $this->z); $v3 = $this->level->level->getBlockID(floor($this->x), floor($this->boundingBox->minY) - 1, floor($this->z));
if($v3 > 0) $friction = StaticBlock::getSlipperiness($v3); if($v3 > 0) $friction = StaticBlock::getSlipperiness($v3);
} }

View file

@ -62,7 +62,7 @@ class Minecart extends Vehicle{
$this->x = $this->data["TileX"] ?? $this->x; $this->x = $this->data["TileX"] ?? $this->x;
$this->y = $this->data["TileY"] ?? $this->y; $this->y = $this->data["TileY"] ?? $this->y;
$this->z = $this->data["TileZ"] ?? $this->z; $this->z = $this->data["TileZ"] ?? $this->z;
$this->setHealth(1, "generic"); //orig: 3 $this->setHealth(1, "generic", allowHarm: false); //orig: 3
$this->setSize(0.98, 0.7); $this->setSize(0.98, 0.7);
$this->yOffset = $this->height / 2; $this->yOffset = $this->height / 2;
$this->stepHeight = 0; $this->stepHeight = 0;
@ -72,6 +72,10 @@ class Minecart extends Vehicle{
return !$this->dead; return !$this->dead;
} }
public function getRideHeight(){
return ($this->height * 0) - 0.3;
}
public function getDrops(){ public function getDrops(){
return [ return [
[MINECART, 0, 1] [MINECART, 0, 1]
@ -107,13 +111,13 @@ class Minecart extends Vehicle{
if($v27 == 0){ if($v27 == 0){
$x = $blockX + 0.5; $x = $blockX + 0.5;
$v13 = $z - $blockZ; $v13 = $z - $blockZ;
}elseif($v31 == 0){ }else if($v31 == 0){
$z = $blockZ + 0.5; $z = $blockZ + 0.5;
$v13 = $x - $blockX; $v13 = $x - $blockX;
}else{ }else{
$v33 = $x - $v15; $v33 = $x - $v15;
$v35 = $z - $v19; $v35 = $z - $v19;
$v13 = ($v33 * $v27 + $v35 * $v31) * 2; $v13 = ($v33*$v27 + $v35*$v31) * 2;
} }
$x = $v15 + $v27 * $v13; $x = $v15 + $v27 * $v13;
@ -155,27 +159,27 @@ class Minecart extends Vehicle{
$mat = self::$matrix[$meta]; $mat = self::$matrix[$meta];
$matXDiff = $mat[1][0] - $mat[0][0]; $matXDiff = $mat[1][0] - $mat[0][0];
$matZDiff = $mat[1][2] - $mat[0][2]; $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){ if(($this->speedZ * $matZDiff + $this->speedX * $matXDiff) < 0){
$matXDiff = -$matXDiff; $matXDiff = -$matXDiff;
$matZDiff = -$matZDiff; $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; if($speedTotal > 2) $speedTotal = 2;
$this->speedX = ($speedTotal * $matXDiff) / $matDiffTotal; $this->speedX = ($speedTotal * $matXDiff) / $matDiffTotal;
$this->speedZ = ($speedTotal * $matZDiff) / $matDiffTotal; $this->speedZ = ($speedTotal * $matZDiff) / $matDiffTotal;
if($this->linkedEntity != 0 && !$this->isRider){ if($this->rider != 0){
$rider = $this->level->entityList[$this->linkedEntity] ?? false; $rider = $this->level->entityList[$this->rider] ?? false;
if($rider instanceof Entity && ($rider->isPlayer() || $rider->class == ENTITY_MOB)){ if($rider instanceof Entity && ($rider->isPlayer() || $rider->class == ENTITY_MOB)){
if($rider->moveForward > 0){ if($rider->moveForward > 0){
$v32 = sin($this->yaw * M_PI / 180); $v32 = sin($this->yaw * M_PI / 180);
$v33 = cos($this->yaw * M_PI / 180); $v33 = cos($this->yaw * M_PI / 180);
if($this->speedZ * $this->speedZ + $this->speedX * $this->speedX < 0.01){ if($this->speedZ*$this->speedZ + $this->speedX*$this->speedX < 0.01){
$this->speedX -= $v32 * 0.1; $this->speedX -= $v32*0.1;
$this->speedZ += $v33 * 0.1; $this->speedZ += $v33*0.1;
} }
} }
} }
@ -188,7 +192,7 @@ class Minecart extends Vehicle{
if($v40 == 0){ if($v40 == 0){
$v42 = $this->z - $z; $v42 = $this->z - $z;
}elseif($v41 == 0){ }else if($v41 == 0){
$v42 = $this->x - $x; $v42 = $this->x - $x;
}else{ }else{
$v44 = (($this->z - $v39) * $v41) + (($this->x - $v38) * $v40); $v44 = (($this->z - $v39) * $v41) + (($this->x - $v38) * $v40);
@ -201,26 +205,26 @@ class Minecart extends Vehicle{
$this->setPos($this->x, $this->y + $this->yOffset + 0.00001, $this->z); $this->setPos($this->x, $this->y + $this->yOffset + 0.00001, $this->z);
$dx = $this->speedX; $dx = $this->speedX;
$dz = $this->speedZ; $dz = $this->speedZ;
if($this->linkedEntity != 0 && !$this->isRider){ if($this->rider != 0){
$dx *= 0.75; $dx *= 0.75;
$dz *= 0.75; $dz *= 0.75;
} }
if($dx < -$maxSpeed) $dx = -$maxSpeed; if($dx < -$maxSpeed) $dx = -$maxSpeed;
elseif($dx > $maxSpeed) $dx = $maxSpeed; else if($dx > $maxSpeed) $dx = $maxSpeed;
if($dz < -$maxSpeed) $dz = -$maxSpeed; if($dz < -$maxSpeed) $dz = -$maxSpeed;
elseif($dz > $maxSpeed) $dz = $maxSpeed; else if($dz > $maxSpeed) $dz = $maxSpeed;
$this->move($dx, 0, $dz); $this->move($dx, 0, $dz);
if($mat[0][1]){ if($mat[0][1]){
if((floor($this->x) - $x) == $mat[0][0] && (floor($this->z) - $z) == $mat[0][2]){ 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); $this->setPos($this->x, $mat[0][1] + $this->y, $this->z);
}elseif($mat[1][1]){ }else if($mat[1][1]){
goto mat_1_1; goto mat_1_1;
} }
}elseif($mat[1][1]){ }else if($mat[1][1]){
mat_1_1: mat_1_1:
if((floor($this->x) - $x) == $mat[1][0] && (floor($this->z) - $z) == $mat[1][2]){ 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->setPos($this->x, $mat[1][1] + $this->y, $this->z);
@ -231,7 +235,7 @@ class Minecart extends Vehicle{
$vec2 = $this->getPos($this->x, $this->y, $this->z); $vec2 = $this->getPos($this->x, $this->y, $this->z);
if($vec2 !== false && $vec !== false){ if($vec2 !== false && $vec !== false){
$yDiff = ($vec[1] - $vec2[1]) * 0.05; $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){ if($totalSpeed > 0){
$this->speedX = ($this->speedX / $totalSpeed) * ($totalSpeed + $yDiff); $this->speedX = ($this->speedX / $totalSpeed) * ($totalSpeed + $yDiff);
@ -241,13 +245,13 @@ class Minecart extends Vehicle{
} }
if(floor($this->x) != $x || floor($this->z) != $z){ //this breaks everything 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->speedX = (floor($this->x) - $x) * $totalSpeed;
$this->speedZ = (floor($this->z) - $z) * $totalSpeed; $this->speedZ = (floor($this->z) - $z) * $totalSpeed;
} }
if($id == POWERED_RAIL){ 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){ if($totalSpeed > 0.01){
$this->speedX += (($this->speedX / $totalSpeed) * 0.06); $this->speedX += (($this->speedX / $totalSpeed) * 0.06);
$this->speedZ += (($this->speedZ / $totalSpeed) * 0.06); $this->speedZ += (($this->speedZ / $totalSpeed) * 0.06);
@ -265,7 +269,7 @@ class Minecart extends Vehicle{
$v63 = -0.02; $v63 = -0.02;
} }
$this->speedX = $v63; $this->speedX = $v63;
}elseif($meta == 0){ }else if($meta == 0){
//TODO Level::isSolidBlockingTile //TODO Level::isSolidBlockingTile
if(StaticBlock::getIsSolid($this->level->level->getBlockID($x, $y, $z - 1))){ if(StaticBlock::getIsSolid($this->level->level->getBlockID($x, $y, $z - 1))){
return; return;
@ -281,8 +285,9 @@ class Minecart extends Vehicle{
} }
public function applyNaturalSlowdown(){ public function applyNaturalSlowdown(){
$mult = $this->linkedEntity != 0 && !$this->isRider ? 0.997 : 0.96; $mult = $this->rider != 0 ? 0.997 : 0.96;
$this->speedX *= $mult; $this->speedX *= $mult;
$this->speedY = 0; $this->speedY = 0;
@ -291,10 +296,10 @@ class Minecart extends Vehicle{
public function comeOffTrack($topSpeed){ public function comeOffTrack($topSpeed){
if($this->speedX < -$topSpeed) $this->speedX = -$topSpeed; if($this->speedX < -$topSpeed) $this->speedX = -$topSpeed;
elseif($this->speedX > $topSpeed) $this->speedX = $topSpeed; else if($this->speedX > $topSpeed) $this->speedX = $topSpeed;
if($this->speedZ < -$topSpeed) $this->speedZ = -$topSpeed; if($this->speedZ < -$topSpeed) $this->speedZ = -$topSpeed;
elseif($this->speedZ > $topSpeed) $this->speedZ = $topSpeed; else if($this->speedZ > $topSpeed) $this->speedZ = $topSpeed;
if($this->onGround){ if($this->onGround){
$this->speedX *= 0.5; $this->speedX *= 0.5;
@ -314,7 +319,7 @@ class Minecart extends Vehicle{
public function applyCollision(Entity $collided){ public function applyCollision(Entity $collided){
$diffX = $collided->x - $this->x; $diffX = $collided->x - $this->x;
$diffZ = $collided->z - $this->z; $diffZ = $collided->z - $this->z;
$dist = $diffX * $diffX + $diffZ * $diffZ; $dist = $diffX*$diffX + $diffZ*$diffZ;
if($dist >= 0.0001){ if($dist >= 0.0001){
$sqrtMax = sqrt($dist); $sqrtMax = sqrt($dist);
$diffX /= $sqrtMax; $diffX /= $sqrtMax;
@ -366,7 +371,7 @@ class Minecart extends Vehicle{
$diffX = $this->lastX - $this->x; $diffX = $this->lastX - $this->x;
$diffZ = $this->lastZ - $this->z; $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; $this->yaw = atan2($diffZ, $diffX) * 180 / M_PI;
if($this->isInReverse) $this->yaw += 180; if($this->isInReverse) $this->yaw += 180;
@ -382,10 +387,10 @@ class Minecart extends Vehicle{
} }
$bb = $this->boundingBox->expand(0.2, 0, 0.2); $bb = $this->boundingBox->expand(0.2, 0, 0.2);
$minChunkX = ((int) ($bb->minX - 2)) >> 4; $minChunkX = ((int)($bb->minX - 2)) >> 4;
$minChunkZ = ((int) ($bb->minZ - 2)) >> 4; $minChunkZ = ((int)($bb->minZ - 2)) >> 4;
$maxChunkX = ((int) ($bb->minX + 2)) >> 4; $maxChunkX = ((int)($bb->minX + 2)) >> 4;
$maxChunkZ = ((int) ($bb->minZ + 2)) >> 4; $maxChunkZ = ((int)($bb->minZ + 2)) >> 4;
//TODO also index by chunkY? //TODO also index by chunkY?
for($chunkX = $minChunkX; $chunkX <= $maxChunkX; ++$chunkX){ for($chunkX = $minChunkX; $chunkX <= $maxChunkX; ++$chunkX){
@ -393,7 +398,7 @@ class Minecart extends Vehicle{
$ind = "$chunkX $chunkZ"; $ind = "$chunkX $chunkZ";
foreach($this->level->entityListPositioned[$ind] ?? [] as $entid){ foreach($this->level->entityListPositioned[$ind] ?? [] as $entid){
$e = ($this->level->entityList[$entid] ?? null); $e = ($this->level->entityList[$entid] ?? null);
if($e instanceof Entity && $e->eid != $this->eid && $e->eid != $this->linkedEntity){ if($e instanceof Entity && $e->eid != $this->eid && $e->eid != $this->rider){
if($e->isPushable() && $e->boundingBox->intersectsWith($bb)){ if($e->isPushable() && $e->boundingBox->intersectsWith($bb)){
if($e->isPlayer()){ if($e->isPlayer()){
$this->applyCollision($e); $this->applyCollision($e);
@ -411,37 +416,35 @@ class Minecart extends Vehicle{
public function close() public function close()
{ {
parent::close(); parent::close();
if($this->linkedEntity != 0){
$ent = $this->level->entityList[$this->linkedEntity] ?? false;
if($ent instanceof Entity){
$ent->stopRiding();
}else{
ConsoleAPI::warn("$this is being ridden by invalid entity {$this->linkedEntity}");
}
}
} }
public function isPushable(){ public function isPushable(){
return false; //TODO replace with true return false; //TODO replace with true
} }
public function spawn($player){ public function spawn(Player $player){
$pk = new AddEntityPacket; if(!$player->hasEntity($this)){
$pk->eid = $this->eid; $player->addEntity($this);
$pk->type = $this->type; $pk = new AddEntityPacket;
$pk->x = $this->x; $pk->eid = $this->eid;
$pk->y = $this->y; //+ $this->yOffset; $pk->type = $this->type;
$pk->z = $this->z; $pk->x = $this->x;
$pk->yaw = $this->yaw; $pk->y = $this->y; //+ $this->yOffset;
$pk->pitch = $this->pitch; $pk->z = $this->z;
$player->dataPacket($pk); $pk->yaw = $this->yaw;
$pk->pitch = $this->pitch;
$player->entityQueueDataPacket($pk);
$pk = new SetEntityMotionPacket; $pk = new SetEntityMotionPacket;
$pk->eid = $this->eid; $pk->eid = $this->eid;
$pk->speedX = $this->speedX; $pk->speedX = $this->speedX;
$pk->speedY = $this->speedY; $pk->speedY = $this->speedY;
$pk->speedZ = $this->speedZ; $pk->speedZ = $this->speedZ;
$player->dataPacket($pk); $player->entityQueueDataPacket($pk);
$this->sendLinkPackets($player);
return true;
}
return false;
} }
public function interactWith(Entity $e, $action){ public function interactWith(Entity $e, $action){
@ -449,14 +452,14 @@ class Minecart extends Vehicle{
$e->setRiding($this); $e->setRiding($this);
return true; return true;
} }
if($action === InteractPacket::ACTION_ATTACK && $e->eid == $this->linkedEntity){ if($action === InteractPacket::ACTION_ATTACK && $e->eid == $this->rider){
return false; //TODO more vanilla way? return false; //TODO more vanilla way?
} }
parent::interactWith($e, $action); parent::interactWith($e, $action);
} }
public function canRide($e) public function canRide($e)
{ {
return $this->linkedEntity == 0 && $e->linkedEntity == 0; return $this->rider == 0;
} }
} }

View file

@ -16,9 +16,9 @@ class Painting extends Entity{
$this->y = $this->data["TileY"] ?? $this->y; $this->y = $this->data["TileY"] ?? $this->y;
$this->z = $this->data["TileZ"] ?? $this->z; $this->z = $this->data["TileZ"] ?? $this->z;
$this->xPos = $this->data["xPos"] ?? (int) $this->x; $this->xPos = $this->data["xPos"] ?? (int)$this->x;
$this->zPos = $this->data["zPos"] ?? (int) $this->z; $this->zPos = $this->data["zPos"] ?? (int)$this->z;
$this->yPos = $this->data["yPos"] ?? (int) $this->y; $this->yPos = $this->data["yPos"] ?? (int)$this->y;
$this->health = 1; $this->health = 1;
$this->canBeAttacked = true; $this->canBeAttacked = true;
@ -41,14 +41,14 @@ class Painting extends Entity{
} }
} }
public $counter = 0; public $scounter = 0;
public function update($now){ public function update($now){
if($this->closed === true){ if($this->closed === true){
return false; return false;
} }
if(++$this->counter >= 100){ if(++$this->scounter >= 100){
$this->counter = 0; $this->scounter = 0;
if(!$this->survives() && !$this->dead){ //maybe dont check entity collision? if(!$this->survives() && !$this->dead){ //maybe dont check entity collision?
$this->makeDead("nosurvive"); $this->makeDead("nosurvive");
} }
@ -68,7 +68,7 @@ class Painting extends Entity{
} }
} }
if(count($tochoose) > 0){ if(count($tochoose) > 0){
$ind = mt_rand(0, count($tochoose) - 1); $ind = mt_rand(0, count($tochoose)-1);
}else{ }else{
$this->isValid = false; $this->isValid = false;
return; return;
@ -87,9 +87,9 @@ class Painting extends Entity{
public function setDirection($dir){ public function setDirection($dir){
$this->direction = $dir; $this->direction = $dir;
$this->lastYaw = $this->yaw = $dir * 90; $this->lastYaw = $this->yaw = $dir * 90;
$size = PaintingItem::$motives[$this->motive] ?? [1, 1]; $size = PaintingItem::$motives[$this->motive] ?? array(1, 1);
$width = $size[0] * 16; $width = $size[0]*16;
$height = $size[1] * 16; $height = $size[1]*16;
if($dir == 2 || $dir == 0){ if($dir == 2 || $dir == 0){
$v10 = 2; $v10 = 2;
$v9 = $width; $v9 = $width;
@ -109,10 +109,10 @@ class Painting extends Entity{
if($dir == 2){ if($dir == 2){
$v17 = $v17 - 0.5625; $v17 = $v17 - 0.5625;
$v15 = $v15 - self::offs($width); $v15 = $v15 - self::offs($width);
}elseif($dir == 1){ }else if($dir == 1){
$v15 = $v15 - 0.5625; $v15 = $v15 - 0.5625;
$v17 = $v17 + self::offs($width); $v17 = $v17 + self::offs($width);
}elseif($dir == 3){ }else if($dir == 3){
$v15 = $v15 + 0.5625; $v15 = $v15 + 0.5625;
$v17 = $v17 - self::offs($width); $v17 = $v17 - self::offs($width);
}else{ }else{
@ -144,11 +144,11 @@ class Painting extends Entity{
$cubes = $this->level->getCubes($this, $this->boundingBox); $cubes = $this->level->getCubes($this, $this->boundingBox);
if(count($cubes) == 0){ if(count($cubes) == 0){
$size = PaintingItem::$motives[$this->motive] ?? [1, 1]; $size = PaintingItem::$motives[$this->motive] ?? array(1, 1);
$width = $size[0]; $width = $size[0];
$width2 = $width * 16 / 32; $width2 = $width*16/32;
$height = $size[1]; $height = $size[1];
$height2 = $height * 16 / 32; $height2 = $height*16/32;
if($width < 1) $width = 1; if($width < 1) $width = 1;
if($height < 1) $height = 1; if($height < 1) $height = 1;
$positionX = $this->xPos; $positionX = $this->xPos;
@ -197,14 +197,20 @@ class Painting extends Entity{
return $data; return $data;
} }
public function spawn($player){ public function spawn(Player $player){
$pk = new AddPaintingPacket; if(!$player->hasEntity($this)){
$pk->eid = $this->eid; $player->addEntity($this);
$pk->x = (int) $this->xPos; $pk = new AddPaintingPacket;
$pk->y = (int) $this->yPos; $pk->eid = $this->eid;
$pk->z = (int) $this->zPos; $pk->x = (int) $this->xPos;
$pk->direction = $this->direction; $pk->y = (int) $this->yPos;
$pk->title = $this->motive; $pk->z = (int) $this->zPos;
$player->dataPacket($pk); $pk->direction = $this->direction;
$pk->title = $this->motive;
$player->entityQueueDataPacket($pk);
$this->sendLinkPackets($player);
return true;
}
return false;
} }
} }

View file

@ -12,7 +12,7 @@ class PrimedTNT extends Entity{
$this->gravity = 0.04; $this->gravity = 0.04;
$this->setSize(0.98, 0.98); $this->setSize(0.98, 0.98);
$this->yOffset = $this->height / 2; $this->yOffset = $this->height / 2;
$this->setHealth(10000000, "generic"); $this->setHealth(10000000, "generic", allowHarm: false);
} }
public function isPickable(){ public function isPickable(){
@ -41,7 +41,7 @@ class PrimedTNT extends Entity{
$this->speedY -= 0.04; $this->speedY -= 0.04;
$this->move($this->speedX, $this->speedY, $this->speedZ); $this->move($this->speedX, $this->speedY, $this->speedZ);
$this->speedX * -0.98; $this->speedX *- 0.98;
$this->speedY *= 0.98; $this->speedY *= 0.98;
$this->speedZ *= 0.98; $this->speedZ *= 0.98;
@ -65,17 +65,24 @@ class PrimedTNT extends Entity{
$this->lastUpdate = $now; $this->lastUpdate = $now;
} }
public function spawn($player){ public function spawn(Player $player){
$pk = new AddEntityPacket; if(!$player->hasEntity($this)){
$pk->eid = $this->eid; $player->addEntity($this);
$pk->type = $this->type; $pk = new AddEntityPacket;
$pk->x = $this->x; $pk->eid = $this->eid;
$pk->y = $this->y; $pk->type = $this->type;
$pk->z = $this->z; $pk->x = $this->x;
$pk->did = 1; $pk->y = $this->y;
$pk->speedX = $this->speedX; $pk->z = $this->z;
$pk->speedY = $this->speedY; $pk->did = 1;
$pk->speedZ = $this->speedZ; $pk->speedX = $this->speedX;
$player->dataPacket($pk); $pk->speedY = $this->speedY;
$pk->speedZ = $this->speedZ;
$player->entityQueueDataPacket($pk);
$this->sendLinkPackets($player);
return true;
}
return false;
} }
} }

View file

@ -5,7 +5,7 @@ class TripodCamera extends Entity{
function __construct(Level $level, $eid, $class, $type = 0, $data = []){ function __construct(Level $level, $eid, $class, $type = 0, $data = []){
parent::__construct($level, $eid, $class, $type, $data); parent::__construct($level, $eid, $class, $type, $data);
$this->setHealth(PHP_INT_MAX, "generic"); $this->setHealth(PHP_INT_MAX, "generic", allowHarm: false);
} }
public function isPickable(){ public function isPickable(){

View file

@ -0,0 +1,9 @@
<?php
/*value - durability*/
class ArmorMaterial{
const LEATHER = 5; //when enums
const CHAIN = 15;
const GOLD = 7;
const IRON = 15;
const DIAMOND = 33;
}

View file

@ -1,144 +1,152 @@
<?php <?php
abstract class Block extends Position{ abstract class Block extends Position{
public static $class = [ public static $mushroomSpread = true;
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", public static $class = array(
CHEST => "ChestBlock", 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",
DIAMOND_ORE => "DiamondOreBlock", WOOD_STAIRS => "WoodStairsBlock",
DIAMOND_BLOCK => "DiamondBlock", CHEST => "ChestBlock",
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", DIAMOND_ORE => "DiamondOreBlock",
REDSTONE_ORE => "RedstoneOreBlock", DIAMOND_BLOCK => "DiamondBlock",
GLOWING_REDSTONE_ORE => "GlowingRedstoneOreBlock", 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",
SNOW_LAYER => "SnowLayerBlock", IRON_DOOR_BLOCK => "IronDoorBlock",
ICE => "IceBlock", REDSTONE_ORE => "RedstoneOreBlock",
SNOW_BLOCK => "SnowBlock", GLOWING_REDSTONE_ORE => "GlowingRedstoneOreBlock",
CACTUS => "CactusBlock",
CLAY_BLOCK => "ClayBlock",
SUGARCANE_BLOCK => "SugarcaneBlock",
FENCE => "FenceBlock", SNOW_LAYER => "SnowLayerBlock",
PUMPKIN => "PumpkinBlock", ICE => "IceBlock",
NETHERRACK => "NetherrackBlock", SNOW_BLOCK => "SnowBlock",
SOUL_SAND => "SoulSandBlock", CACTUS => "CactusBlock",
GLOWSTONE_BLOCK => "GlowstoneBlock", CLAY_BLOCK => "ClayBlock",
SUGARCANE_BLOCK => "SugarcaneBlock",
LIT_PUMPKIN => "LitPumpkinBlock", FENCE => "FenceBlock",
INVISIBLE_BEDROCK => "InvisibleBedrockBlock", PUMPKIN => "PumpkinBlock",
NETHERRACK => "NetherrackBlock",
SOUL_SAND => "SoulSandBlock",
GLOWSTONE_BLOCK => "GlowstoneBlock",
CAKE_BLOCK => "CakeBlock", LIT_PUMPKIN => "LitPumpkinBlock",
INVISIBLE_BEDROCK => "InvisibleBedrockBlock",
TRAPDOOR => "TrapdoorBlock", CAKE_BLOCK => "CakeBlock",
STONE_BRICKS => "StoneBricksBlock", TRAPDOOR => "TrapdoorBlock",
IRON_BARS => "IronBarsBlock", STONE_BRICKS => "StoneBricksBlock",
GLASS_PANE => "GlassPaneBlock",
MELON_BLOCK => "MelonBlock",
PUMPKIN_STEM => "PumpkinStemBlock",
MELON_STEM => "MelonStemBlock",
FENCE_GATE => "FenceGateBlock", IRON_BARS => "IronBarsBlock",
BRICK_STAIRS => "BrickStairsBlock", GLASS_PANE => "GlassPaneBlock",
STONE_BRICK_STAIRS => "StoneBrickStairsBlock", MELON_BLOCK => "MelonBlock",
PUMPKIN_STEM => "PumpkinStemBlock",
MELON_STEM => "MelonStemBlock",
NETHER_BRICKS => "NetherBricksBlock", FENCE_GATE => "FenceGateBlock",
BRICK_STAIRS => "BrickStairsBlock",
STONE_BRICK_STAIRS => "StoneBrickStairsBlock",
NETHER_BRICKS_STAIRS => "NetherBricksStairsBlock", NETHER_BRICKS => "NetherBricksBlock",
SANDSTONE_STAIRS => "SandstoneStairsBlock", NETHER_BRICKS_STAIRS => "NetherBricksStairsBlock",
SPRUCE_WOOD_STAIRS => "SpruceWoodStairsBlock", SANDSTONE_STAIRS => "SandstoneStairsBlock",
BIRCH_WOOD_STAIRS => "BirchWoodStairsBlock",
JUNGLE_WOOD_STAIRS => "JungleWoodStairsBlock",
STONE_WALL => "StoneWallBlock",
CARROT_BLOCK => "CarrotBlock", SPRUCE_WOOD_STAIRS => "SpruceWoodStairsBlock",
POTATO_BLOCK => "PotatoBlock", BIRCH_WOOD_STAIRS => "BirchWoodStairsBlock",
JUNGLE_WOOD_STAIRS => "JungleWoodStairsBlock",
STONE_WALL => "StoneWallBlock",
QUARTZ_BLOCK => "QuartzBlock", CARROT_BLOCK => "CarrotBlock",
QUARTZ_STAIRS => "QuartzStairsBlock", POTATO_BLOCK => "PotatoBlock",
DOUBLE_WOOD_SLAB => "DoubleWoodSlabBlock",
WOOD_SLAB => "WoodSlabBlock",
HAY_BALE => "HayBaleBlock", QUARTZ_BLOCK => "QuartzBlock",
CARPET => "CarpetBlock", QUARTZ_STAIRS => "QuartzStairsBlock",
DOUBLE_WOOD_SLAB => "DoubleWoodSlabBlock",
WOOD_SLAB => "WoodSlabBlock",
COAL_BLOCK => "CoalBlock", 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",
);
/**
* @var Material
*/
public $material;
BEETROOT_BLOCK => "BeetrootBlock",
STONECUTTER => "StonecutterBlock",
GLOWING_OBSIDIAN => "GlowingObsidianBlock",
NETHER_REACTOR => "NetherReactorBlock",
INFO_UPDATE => "InfoUpdateBlock",
INFO_UPDATE2 => "InfoUpdate2Block",
RESERVED6 => "Reserved6Block",
];
public $id; public $id;
public $meta; public $meta;
public $name; public $name;
public $breakTime;
public $boundingBox; public $boundingBox;
public $hardness; public $hardness;
public $breakTime = 0;
public $isActivable = false; public $isActivable = false;
public $breakable = true; public $breakable = true;
public $isFlowable = false; public $isFlowable = false;
@ -154,6 +162,10 @@ abstract class Block extends Position{
public $y = 0; public $y = 0;
public $z = 0; public $z = 0;
public $slipperiness; public $slipperiness;
public $lightEmission = 0;
public $lightBlock = 0;
public static function interact(Level $level, $x, $y, $z, Player $player){} 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 neighborChanged(Level $level, $x, $y, $z, $nX, $nY, $nZ, $oldID){}
@ -230,9 +242,10 @@ abstract class Block extends Position{
} }
public static function onEntityCollidedWithBlock(Level $level, $x, $y, $z, Entity $entity){} public static function onEntityCollidedWithBlock(Level $level, $x, $y, $z, Entity $entity){}
public function __construct($id, $meta = 0, $name = "Unknown"){ public function __construct($id, $meta = 0, $name = "Unknown"){
$this->id = (int) $id; $this->id = (int) $id;
$this->meta = (int) $meta; $this->meta = ((int) $meta) & 0xf;
$this->name = $name; $this->name = $name;
$this->breakTime = 0.20; $this->breakTime = 0.20;
$this->hardness = 10; $this->hardness = 10;
@ -258,6 +271,18 @@ abstract class Block extends Position{
return $this->meta & 0x0F; return $this->meta & 0x0F;
} }
public function getDestroyProgress(Player $player){
if($this->breakTime < 0) return 0;
if($this->breakTime == 0) return INF; //instabreak
$id = $this->getID();
$meta = $this->getMetadata();
if($player->canDestroy($id, $meta)){
return $player->getDestroySpeed($id, $meta) / $this->breakTime / 30;
}
return (1 / $this->breakTime) / 100;
}
final public function position(Position $v){ final public function position(Position $v){
$this->level = $v->level; $this->level = $v->level;
$this->x = (int) $v->x; $this->x = (int) $v->x;
@ -268,18 +293,20 @@ abstract class Block extends Position{
public function getDrops(Item $item, Player $player){ public function getDrops(Item $item, Player $player){
if(!isset(Block::$class[$this->id])){ //Unknown blocks if(!isset(Block::$class[$this->id])){ //Unknown blocks
return []; return array();
}else{ }else{
return [ return array(
[$this->id, $this->meta, 1], array($this->id, $this->meta, 1),
]; );
} }
} }
public function getBreakTime(Item $item, Player $player){ public function getBreakTime(Item $item, Player $player){
if($this->hardness < 0) return INF;
if(($player->gamemode & 0x01) === 0x01){ if(($player->gamemode & 0x01) === 0x01){
return 0.15; return 0.15;
} }
if($player->canDestroy($this->getID(), $this->getMetadata()))
return $this->breakTime; return $this->breakTime;
} }
@ -295,7 +322,9 @@ abstract class Block extends Position{
return "Block ". $this->name ." (".$this->id.":".$this->meta.")"; return "Block ". $this->name ." (".$this->id.":".$this->meta.")";
} }
abstract function isBreakable(Item $item, Player $player); public function isBreakable(Item $item, Player $player){
return $this->hardness >= 0;
}
abstract function onBreak(Item $item, Player $player); abstract function onBreak(Item $item, Player $player);

View file

@ -9,7 +9,7 @@ class Item{
const DEF_DAMAGE = 1; const DEF_DAMAGE = 1;
public static $class = [ public static $class = array(
//armor //armor
LEATHER_CAP => "LeatherCapItem", LEATHER_CAP => "LeatherCapItem",
@ -128,7 +128,7 @@ class Item{
CLOCK => "ClockItem", CLOCK => "ClockItem",
SHEARS => "ShearsItem", SHEARS => "ShearsItem",
]; );
public $block; public $block;
public $id; public $id;
public $meta; public $meta;
@ -144,10 +144,11 @@ class Item{
public function __construct($id, $meta = 0, $count = 1, $name = "Unknown"){ public function __construct($id, $meta = 0, $count = 1, $name = "Unknown"){
$this->id = (int) $id; $this->id = (int) $id;
$this->meta = (int) $meta; $this->meta = ((int) $meta) & 0xffff;
$this->count = (int) $count; $this->count = (int) $count;
$this->name = $name; $this->name = $name;
if(!isset($this->block) and $this->id <= 0xff and isset(Block::$class[$this->id])){ if(!isset($this->block) && $this->id <= 0xff && isset(Block::$class[$this->id])){
$this->meta &= 0xf;
$this->block = BlockAPI::get($this->id, $this->meta); $this->block = BlockAPI::get($this->id, $this->meta);
$this->name = $this->block->getName(); $this->name = $this->block->getName();
} }
@ -156,6 +157,14 @@ class Item{
} }
} }
public function canDestroySpecial($id, $meta){
return false;
}
public function getDestroySpeed($id, $meta){
return 1.0;
}
public function isPickaxe(){ public function isPickaxe(){
return false; return false;
} }
@ -219,18 +228,39 @@ class Item{
} }
public function useOn($object, $force = false){ /**
if($force){ * @param int $dmg - damage dealt to item
if(($object instanceof Entity) and !$this->isSword()){ * @param Player $player - player who used the item
$this->meta += 2; * @param boolean $helditem - modify player's helditem state or not - should be false if using by non-held item(armor damaging for example)
*/
public function hurtAndBreak($dmg, Player $player, $helditem = true){
if(($player->gamemode & 1) !== 0) return; //dont break items in creative
if($this->getMaxDurability() !== false){
$this->meta += $dmg;
if($helditem){
$player->setSlot($player->slot, $this, send: false);
if($this->meta > $this->getMaxDurability()){
$player->consumeSingleItem();
}
}else{ }else{
$this->meta++; if($this->meta > $this->getMaxDurability()){
--$this->count;
}
} }
return true;
} }
}
public function hurtEnemy(Entity $target, Player $attacker){
}
public function mineBlock(Block $block, Player $player){
return false; return false;
} }
public function isTool(){ public function isTool(){
return false; return false;
} }
@ -240,15 +270,15 @@ class Item{
return false; return false;
} }
$levels = [ //TODO rewrite(item usage too) $levels = [
2 => 33, //GOLD 2 => 32, //GOLD
1 => 60, //WOODEN 1 => 59, //WOODEN
3 => 132, //STONE 3 => 131, //STONE
4 => 251, //IRON 4 => 250, //IRON
5 => 1562, //DIAMOND(called EMERALD in disassembled code) 5 => 1561, //DIAMOND(called EMERALD in disassembled code)
FLINT_STEEL => 65, //lets assume it is correct FLINT_STEEL => 64,
SHEARS => 239, //x2 SHEARS => 238,
BOW => 385 //x3 BOW => 384
]; ];
if(($type = $this->getLevel()) === false){ if(($type = $this->getLevel()) === false){
@ -263,7 +293,7 @@ class Item{
//TODO remove? //TODO remove?
public function getPickaxeLevel(){ //Returns false or level of the pickaxe public function getPickaxeLevel(){ //Returns false or level of the pickaxe
return match ($this->id) { return match ($this->id) {
WOODEN_PICKAXE => 1, WOODEN_PICKAXE => 1,
GOLDEN_PICKAXE => 2, GOLDEN_PICKAXE => 2,
STONE_PICKAXE => 3, STONE_PICKAXE => 3,
@ -294,17 +324,13 @@ class Item{
} }
public function __toString(){ public function __toString(){
return "Item ". $this->name ." (".$this->id.":".$this->meta.")"; return "Item ". $this->name ." (".$this->id.":".$this->meta."x{$this->count})";
} }
public function getDamageAgainstOf($e){ public function getDamageAgainstOf($e){
return Item::DEF_DAMAGE; 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){ public function onActivate(Level $level, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){
return false; return false;
} }
@ -333,4 +359,11 @@ class Item{
}; };
} }
/**
* @deprecated Item damaging changed. Use hurtAndBreak to damage the item and update it in the client's inventory correctly.
*/
public function useOn($object, $force = false){
return false;
}
} }

View file

@ -1,10 +1,84 @@
<?php <?php
/*value - durability*/ class Material
class Material{ {
const LEATHER = 5; //when enums public static $air, $dirt, $wood, $stone, $metal, $water, $lava, $leaves;
const CHAIN = 15; public static $plant, $replaceable_plant, $sponge, $cloth, $fire, $sand;
const GOLD = 7; public static $decoration, $glass, $explosive, $coral, $ice, $topSnow;
const IRON = 15; public static $snow, $cactus, $clay, $vegetable, $portal, $cake, $web;
const DIAMOND = 33;
public $alwaysDestroyable, $flammable, $translucent, $replaceable;
public $blocksLight, $blocksMotion, $isLiquid, $isSolid;
public function __construct(){
$this->alwaysDestroyable = true;
$this->flammable = false;
$this->translucent = false;
$this->replaceable = false;
$this->blocksLight = true;
$this->blocksMotion = true;
$this->isLiquid = false;
$this->isSolid = true;
}
public function isSolidBlocking(){
if($this->translucent) return false;
return $this->blocksMotion;
}
public function letsWaterThrough(){
if($this->isLiquid) return false;
return !$this->isSolid;
}
public static function init(){
self::$air = new GasMaterial();
self::$dirt = new Material();
self::$wood = new Material();
self::$wood->flammable = true;
self::$stone = new Material();
self::$stone->alwaysDestroyable = false;
self::$metal = new Material();
self::$metal->alwaysDestroyable = false;
self::$water = new LiquidMaterial();
self::$lava = new LiquidMaterial();
self::$leaves = new Material();
self::$leaves->flammable = true;
self::$leaves->translucent = true;
self::$plant = new DecorationMaterial();
self::$replaceable_plant = new DecorationMaterial();
self::$replaceable_plant->replaceable = true;
self::$replaceable_plant->flammable = true;
self::$sponge = new Material();
self::$cloth = new Material();
self::$cloth->flammable = true;
self::$fire = new GasMaterial();
self::$fire->replaceable = true;
self::$sand = new Material();
self::$decoration = new DecorationMaterial();
self::$glass = new Material();
self::$glass->translucent = true;
self::$explosive = new Material();
self::$explosive->flammable = true;
self::$explosive->translucent = true;
self::$coral = new Material();
self::$ice = new Material();
self::$ice->translucent = true;
self::$topSnow = new DecorationMaterial();
self::$topSnow->translucent = true;
self::$topSnow->replaceable = true;
self::$topSnow->alwaysDestroyable = false;
self::$snow = new Material();
self::$snow->alwaysDestroyable = false;
self::$cactus = new Material();
self::$cactus->translucent = true;
self::$clay = new Material();
self::$vegetable = new Material();
self::$portal = new Material();
self::$cake = new Material();
self::$web = new Material();
self::$web->alwaysDestroyable = false;
self::$web->blocksMotion = false;
}
} }

View file

@ -17,14 +17,18 @@ class StaticBlock
public static $hasPhysics = []; public static $hasPhysics = [];
public static $isLiquid = []; public static $isLiquid = [];
public static $isFullBlock = []; public static $isFullBlock = [];
public static $material = [];
public static $hardness = []; public static $hardness = [];
public static $destroyTime = [];
public static $slipperiness = []; public static $slipperiness = [];
public static $boundingBoxes = []; public static $boundingBoxes = [];
public static $lightBlock = [];
public static $lightEmission = [];
public static $minXs = [], $minYs = [], $minZs = [], $maxXs = [], $maxYs = [], $maxZs = []; public static $minXs = [], $minYs = [], $minZs = [], $maxXs = [], $maxYs = [], $maxZs = [];
public static function init(){ public static function init(){
self::$NULL_BOUNDS = new AxisAlignedBB(0, 0, 0, 0, 0, 0); self::$NULL_BOUNDS = new AxisAlignedBB(0, 0, 0, 0, 0, 0);
for($i = 0; $i < 256; ++$i) self::$lightBlock[$i] = self::$lightEmission[$i] = 0;
foreach(Block::$class as $nonstaticname){ foreach(Block::$class as $nonstaticname){
/**@var Block $b*/ /**@var Block $b*/
$b = new $nonstaticname(); $b = new $nonstaticname();
@ -40,6 +44,10 @@ class StaticBlock
self::$slipperiness[$b->getID()] = $b->slipperiness; self::$slipperiness[$b->getID()] = $b->slipperiness;
self::$boundingBoxes[$b->getID()] = $b->boundingBox; self::$boundingBoxes[$b->getID()] = $b->boundingBox;
self::$hardness[$b->getID()] = $b->getHardness(); self::$hardness[$b->getID()] = $b->getHardness();
self::$destroyTime[$b->getID()] = $b->breakTime;
self::$material[$b->getID()] = $b->material;
self::$lightBlock[$b->getID()] = $b->lightBlock;
self::$lightEmission[$b->getID()] = $b->lightEmission;
self::$prealloc[$b->getID()] = $b; self::$prealloc[$b->getID()] = $b;
$b::$blockID = $b->getID(); $b::$blockID = $b->getID();
FireBlock::setFlammabilityAndCatchingChance($b->getID(), 0, 0); FireBlock::setFlammabilityAndCatchingChance($b->getID(), 0, 0);
@ -102,6 +110,10 @@ class StaticBlock
FireBlock::setFlammabilityAndCatchingChance(SPONGE, 30, 60); FireBlock::setFlammabilityAndCatchingChance(SPONGE, 30, 60);
} }
public static function getMaterial($blockID){
return self::$material[$blockID] ?? Material::$air;
}
public static function setBlockBounds($blockID, $minX, $minY, $minZ, $maxX, $maxY, $maxZ){ public static function setBlockBounds($blockID, $minX, $minY, $minZ, $maxX, $maxY, $maxZ){
self::$maxXs[$blockID] = $maxX; self::$maxXs[$blockID] = $maxX;
self::$maxYs[$blockID] = $maxY; self::$maxYs[$blockID] = $maxY;
@ -121,7 +133,7 @@ class StaticBlock
} }
public static function getHardness($id){ 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 //TODO: use static block min/max
@ -135,6 +147,7 @@ class StaticBlock
return $bb->setBounds($x + $bb->minX, $y + $bb->minY, $z + $bb->minZ, $x + $bb->maxX, $y + $bb->maxY, $z + $bb->maxZ); 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){ public static function getSlipperiness($id){
return self::$slipperiness[$id] ?? StaticBlock::DEFAULT_SLIPPERINESS; return self::$slipperiness[$id] ?? StaticBlock::DEFAULT_SLIPPERINESS;
} }
@ -160,7 +173,7 @@ class StaticBlock
} }
public static function getHasPhysics($id){ public static function getHasPhysics($id){
return self::$hasPhysics[$id] ?? false; return self::$hasPhysics[$id] ?? false;
} }
public static function getIsLiquid($id){ public static function getIsLiquid($id){

View file

@ -87,6 +87,7 @@ class DoorBlock extends TransparentBlock{
break; break;
} }
return [$aabb->offset($x, $y, $z)]; return [$aabb->offset($x, $y, $z)];
} }
@ -104,13 +105,17 @@ class DoorBlock extends TransparentBlock{
return $metaLower & 7 | (($myMeta & 8) != 0 ? 8 : 0) | (($metaUpper & 1 != 0) ? 16 : 0); 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)); public static function neighborChanged(Level $level, $x, $y, $z, $nX, $nY, $nZ, $oldID){
elseif($id == 71) ServerAPI::request()->api->entity->drop(new Position($x + 0.5, $y, $z + 0.5, $level), BlockAPI::getItem(330, 0, 1)); if($level->level->getBlockID($x, $y - 1, $z) == AIR){
[$id, $meta] = $level->level->getBlock($x, $y, $z);
$level->fastSetBlockUpdate($x, $y, $z, 0, 0);
if(($meta & 8) == 0){
if($id == DOOR_BLOCK) ServerAPI::request()->api->entity->drop(new Position($x+0.5, $y, $z+0.5, $level), BlockAPI::getItem(WOODEN_DOOR, 0, 1));
elseif($id == IRON_DOOR_BLOCK) ServerAPI::request()->api->entity->drop(new Position($x+0.5, $y, $z+0.5, $level), BlockAPI::getItem(IRON_DOOR, 0, 1));
}
$top = $level->level->getBlockID($x, $y + 1, $z); $top = $level->level->getBlockID($x, $y + 1, $z);
if($top == IRON_DOOR_BLOCK || $top == DOOR_BLOCK){ if($top == IRON_DOOR_BLOCK || $top == DOOR_BLOCK){
@ -119,7 +124,12 @@ class DoorBlock extends TransparentBlock{
} }
} }
/** /**
* @param Item $item
* @param Player $player
* @param Block $block
* @param Block $target
* @param integer $face * @param integer $face
* @param integer $fx * @param integer $fx
* @param integer $fy * @param integer $fy
@ -135,12 +145,12 @@ class DoorBlock extends TransparentBlock{
return false; return false;
} }
$direction = $player->entity->getDirection(); $direction = $player->entity->getDirection();
$face = [ $face = array(
0 => 3, 0 => 3,
1 => 4, 1 => 4,
2 => 2, 2 => 2,
3 => 5, 3 => 5,
]; );
$next = $this->getSide($face[(($direction + 2) % 4)]); $next = $this->getSide($face[(($direction + 2) % 4)]);
$next2 = $this->getSide($face[$direction]); $next2 = $this->getSide($face[$direction]);
$metaUp = 0x08; $metaUp = 0x08;
@ -157,6 +167,8 @@ class DoorBlock extends TransparentBlock{
} }
/** /**
* @param Item $item
* @param Player $player
* *
* @return boolean * @return boolean
*/ */
@ -177,6 +189,8 @@ class DoorBlock extends TransparentBlock{
} }
/** /**
* @param Item $item
* @param Player $player
* *
* @return boolean * @return boolean
*/ */
@ -194,7 +208,7 @@ class DoorBlock extends TransparentBlock{
$pk->z = $this->z; $pk->z = $this->z;
$pk->evid = 1003; $pk->evid = 1003;
$pk->data = 0; $pk->data = 0;
ServerAPI::request()->api->player->broadcastPacket($players, $pk); ServerAPI::request()->api->player->broadcastPacket($players, $pk); //TODO use block queue?
return true; return true;
} }
return false; return false;

View file

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

View file

@ -23,11 +23,18 @@ class LadderBlock extends TransparentBlock{
return parent::getAABB($level, $x, $y, $z); return parent::getAABB($level, $x, $y, $z);
} }
public static function getCollisionBoundingBoxes(Level $level, $x, $y, $z, Entity $entity){
return [static::getAABB($level, $x, $y, $z)];
}
public function __construct($meta = 0){ public function __construct($meta = 0){
parent::__construct(LADDER, $meta, "Ladder"); parent::__construct(LADDER, $meta, "Ladder");
$this->isSolid = false; $this->isSolid = false;
$this->isFullBlock = false; $this->isFullBlock = false;
$this->hardness = 2; $this->hardness = 2;
$this->breakTime = 0.4;
$this->material = Material::$decoration;
} }
public function place(Item $item, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){ public function place(Item $item, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){
if($face === 0 || $face === 1){ if($face === 0 || $face === 1){

View file

@ -16,10 +16,12 @@ class SignPostBlock extends TransparentBlock{
$this->isSolid = false; $this->isSolid = false;
$this->isFullBlock = false; $this->isFullBlock = false;
$this->hardness = 5; $this->hardness = 5;
$this->breakTime = 1;
$this->material = Material::$wood;
} }
public function place(Item $item, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){ 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(($target->isSolid || $target->getID() === SIGN_POST || $target->getID() === WALL_SIGN || $target->getID() === GLASS_PANE || $target->getID() === IRON_BARS || $target->getID() === STONE_WALL) && $face !== 0){
if(!isset(self::$faces[$face])){ if(!isset(self::$faces[$face])){
$this->meta = floor((($player->entity->yaw + 180) * 16 / 360) + 0.5) & 0x0F; $this->meta = floor((($player->entity->yaw + 180) * 16 / 360) + 0.5) & 0x0F;
$this->level->setBlock($block, BlockAPI::get(SIGN_POST, $this->meta), true, false, true); $this->level->setBlock($block, BlockAPI::get(SIGN_POST, $this->meta), true, false, true);

View file

@ -5,6 +5,9 @@ class TorchBlock extends FlowableBlock implements LightingBlock{
public function __construct($meta = 0){ public function __construct($meta = 0){
parent::__construct(TORCH, $meta, "Torch"); parent::__construct(TORCH, $meta, "Torch");
$this->hardness = 0; $this->hardness = 0;
$this->breakTime = 0;
$this->material = Material::$decoration;
$this->lightEmission = 14;
} }
public function getMaxLightValue(){ public function getMaxLightValue(){

View file

@ -11,6 +11,8 @@ class TrapdoorBlock extends TransparentBlock{
$this->isFullBlock = true; $this->isFullBlock = true;
} }
$this->hardness = 15; $this->hardness = 15;
$this->breakTime = 3;
$this->material = Material::$wood;
} }
public function canAttachTo(Block $target){ public function canAttachTo(Block $target){

View file

@ -9,6 +9,9 @@ class WallSignBlock extends SignPostBlock{
public function __construct($meta = 0){ public function __construct($meta = 0){
TransparentBlock::__construct(WALL_SIGN, $meta, "Wall Sign"); TransparentBlock::__construct(WALL_SIGN, $meta, "Wall Sign");
$this->isSolid = false; $this->isSolid = false;
$this->breakTime = 1;
$this->hardness = 5;
$this->material = Material::$wood;
} }
public static function neighborChanged(Level $level, $x, $y, $z, $nX, $nY, $nZ, $oldID){ public static function neighborChanged(Level $level, $x, $y, $z, $nX, $nY, $nZ, $oldID){
@ -20,7 +23,7 @@ class WallSignBlock extends SignPostBlock{
default => WALL_SIGN default => WALL_SIGN
}; };
if(!StaticBlock::getIsSolid($attached) && $attached != SIGN_POST && $attached != WALL_SIGN){ if(!StaticBlock::getIsSolid($attached) && $attached != SIGN_POST && $attached != WALL_SIGN && $attached != GLASS_PANE && $attached != IRON_BARS && $attached != STONE_WALL){
$level->fastSetBlockUpdate($x, $y, $z, 0, 0, true, true); $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)); (ServerAPI::request())->api->entity->drop(new Position($x + 0.5, $y + 0.5, $z + 0.5, $level), BlockAPI::getItem(SIGN, 0, 1));
} }

View file

@ -6,7 +6,11 @@ class LavaBlock extends LiquidBlockDynamic implements LightingBlock{
public static $blockID = LAVA; public static $blockID = LAVA;
public function __construct($meta = 0){ public function __construct($meta = 0){
parent::__construct(LAVA, $meta, "Lava"); parent::__construct(LAVA, $meta, "Lava");
$this->hardness = 500; $this->hardness = 500; //0 in vanilla
$this->breakTime = -1; //in vanilla it is 0, but you cant interact with the block so it is not possible to destroy it
$this->material = Material::$lava;
$this->lightEmission = 15;
$this->lightBlock = 255;
} }
public function place(Item $item, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){ public function place(Item $item, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){

View file

@ -33,9 +33,9 @@ class LiquidBlockDynamic extends LiquidBlock{
if($id == CARPET || $id == SNOW_LAYER || $id == RAIL || $id == POWERED_RAIL) return false; //TODO Tile::getThickness() > 0 if($id == CARPET || $id == SNOW_LAYER || $id == RAIL || $id == POWERED_RAIL) return false; //TODO Tile::getThickness() > 0
//TODO materials $mat = StaticBlock::getMaterial($id);
//if(!StaticBlock::getIsFlowable($id)) return true; if($mat->blocksMotion) return true;
return StaticBlock::getIsSolid($id); return $mat->isSolid;
} }
public static function canSpreadTo(Level $level, $x, $y, $z){ public static function canSpreadTo(Level $level, $x, $y, $z){
@ -89,7 +89,7 @@ class LiquidBlockDynamic extends LiquidBlock{
public static function getSlopeDistance(Level $level, $x, $y, $z, $l, $i1){ public static function getSlopeDistance(Level $level, $x, $y, $z, $l, $i1){
$j1 = 1000; $j1 = 1000;
for($k1 = 0; $k1 < 4; ++$k1){ 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; continue;
} }
@ -195,7 +195,7 @@ class LiquidBlockDynamic extends LiquidBlock{
ServerAPI::request()->api->block->scheduleBlockUpdateXYZ($level, $x, $y, $z, BLOCK_UPDATE_SCHEDULED, static::getTickDelay()); 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 $level->updateNeighborsAt($x, $y, $z, static::$blockID); //TODO check is needed
} }
}elseif($flag){ }else if($flag){
static::setStatic($level, $x, $y, $z); static::setStatic($level, $x, $y, $z);
} }
}else{ }else{
@ -204,7 +204,7 @@ class LiquidBlockDynamic extends LiquidBlock{
if(static::canSpreadTo($level, $x, $y - 1, $z)){ if(static::canSpreadTo($level, $x, $y - 1, $z)){
$level->fastSetBlockUpdate($x, $y - 1, $z, static::$blockID, ($depth >= 8 ? $depth : $depth + 8) & 0xf, true); $level->fastSetBlockUpdate($x, $y - 1, $z, static::$blockID, ($depth >= 8 ? $depth : $depth + 8) & 0xf, true);
}elseif($depth >= 0 && ($depth == 0 || static::isWaterBlocking($level, $x, $y - 1, $z))){ }else if($depth >= 0 && ($depth == 0 || static::isWaterBlocking($level, $x, $y - 1, $z))){
$flags = static::getSpread($level, $x, $y, $z); $flags = static::getSpread($level, $x, $y, $z);
$k1 = $depth >= 8 ? 1 : ($depth + $flowAdd); $k1 = $depth >= 8 ? 1 : ($depth + $flowAdd);
if($k1 >= 8) return; if($k1 >= 8) return;

View file

@ -7,6 +7,10 @@ class StillLavaBlock extends LiquidBlockStatic{
public function __construct($meta = 0){ public function __construct($meta = 0){
parent::__construct(STILL_LAVA, $meta, "Still Lava"); parent::__construct(STILL_LAVA, $meta, "Still Lava");
$this->hardness = 500; $this->hardness = 500;
$this->breakTime = -1; //in vanilla it is 100, but you cant interact with the block so it is not possible to destroy it
$this->material = Material::$lava;
$this->lightEmission = 15;
$this->lightBlock = 255;
} }
public static function getTickDelay(){ public static function getTickDelay(){

View file

@ -11,6 +11,9 @@ class StillWaterBlock extends LiquidBlockStatic{
public function __construct($meta = 0){ public function __construct($meta = 0){
LiquidBlock::__construct(STILL_WATER, $meta, "Still Water"); LiquidBlock::__construct(STILL_WATER, $meta, "Still Water");
$this->hardness = 500; $this->hardness = 500;
$this->breakTime = -1; //in vanilla it is 100, but you cant interact with the block so it is not possible to destroy it
$this->material = Material::$water;
$this->lightBlock = 3;
} }
public static function getTickDelay(){ public static function getTickDelay(){

View file

@ -8,6 +8,9 @@ class WaterBlock extends LiquidBlockDynamic{
public function __construct($meta = 0){ public function __construct($meta = 0){
parent::__construct(WATER, $meta, "Water"); parent::__construct(WATER, $meta, "Water");
$this->hardness = 500; $this->hardness = 500;
$this->breakTime = -1; //in vanilla it is 100, but you cant interact with the block so it is not possible to destroy it
$this->material = Material::$water;
$this->lightBlock = 3;
} }
public function place(Item $item, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){ public function place(Item $item, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){

View file

@ -15,6 +15,7 @@ class AirBlock extends TransparentBlock{
$this->isSolid = false; $this->isSolid = false;
$this->isFullBlock = true; $this->isFullBlock = true;
$this->hardness = 0; $this->hardness = 0;
$this->material = Material::$air;
} }

View file

@ -14,11 +14,15 @@ class BedBlock extends TransparentBlock{
[0, -1], [0, -1],
[1, 0] [1, 0]
]; ];
const PLAYER_BED_OFFS_X = [0.5, 0.1, 0.5, 0.9];
const PLAYER_BED_OFFS_Z = [0.9, 0.5, 0.1, 0.5];
public function __construct($type = 0){ public function __construct($type = 0){
parent::__construct(BED_BLOCK, $type, "Bed Block"); parent::__construct(BED_BLOCK, $type, "Bed Block");
$this->isActivable = true; $this->isActivable = true;
$this->isFullBlock = false; $this->isFullBlock = false;
$this->hardness = 1; $this->hardness = 1;
$this->breakTime = 0.2;
$this->material = Material::$cloth;
} }
public static function getCollisionBoundingBoxes(Level $level, $x, $y, $z, Entity $entity){ public static function getCollisionBoundingBoxes(Level $level, $x, $y, $z, Entity $entity){
@ -37,7 +41,7 @@ class BedBlock extends TransparentBlock{
if($level->level->getBlockID($x - $offX, $y, $z - $offZ) != BED_BLOCK){ if($level->level->getBlockID($x - $offX, $y, $z - $offZ) != BED_BLOCK){
$level->fastSetBlockUpdate($x, $y, $z, 0, 0, true); $level->fastSetBlockUpdate($x, $y, $z, 0, 0, true);
} }
}elseif($level->level->getBlockID($x + $offX, $y, $z + $offZ) != BED_BLOCK){ }else if($level->level->getBlockID($x + $offX, $y, $z + $offZ) != BED_BLOCK){
$level->fastSetBlockUpdate($x, $y, $z, 0, 0, true); $level->fastSetBlockUpdate($x, $y, $z, 0, 0, true);
ServerAPI::request()->api->entity->dropRawPos( ServerAPI::request()->api->entity->dropRawPos(
@ -65,7 +69,7 @@ class BedBlock extends TransparentBlock{
for($zCheck = $minZ; $zCheck <= $maxZ; ++$zCheck){ for($zCheck = $minZ; $zCheck <= $maxZ; ++$zCheck){
$idCheck = $level->level->getBlockID($xCheck, $y - 1, $zCheck); $idCheck = $level->level->getBlockID($xCheck, $y - 1, $zCheck);
if(!StaticBlock::getIsTransparent($idCheck) && $level->level->getBlockID($xCheck, $y, $zCheck) == 0 && $level->level->getBlockID($xCheck, $y + 1, $zCheck) == 0){ if(!StaticBlock::getIsTransparent($idCheck) && $level->level->getBlockID($xCheck, $y, $zCheck) == 0 && $level->level->getBlockID($xCheck, $y + 1, $zCheck) == 0){
return new Vector3($xCheck, $y, $zCheck); return new Position($xCheck, $y, $zCheck, $level);
} }
} }
} }
@ -76,39 +80,24 @@ class BedBlock extends TransparentBlock{
public function onActivate(Item $item, Player $player){ public function onActivate(Item $item, Player $player){
if(ServerAPI::request()->api->time->getPhase($player->level) !== "night"){ if(ServerAPI::request()->api->time->getPhase($player->level) !== "night"){
$pk = new ChatPacket; $player->sendChat("You can only sleep at night");
$pk->message = "You can only sleep at night";
$player->dataPacket($pk);
return true; 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; $b = $this;
}else{ //Bottom Part of Bed }else{ //Bottom Part of Bed
if($blockNorth->getID() === $this->id and ($blockNorth->meta & 0x08) === 0x08){ $dir = ($this->meta & 3);
$b = $blockNorth; $o = BedBlock::HEAD_DIRECTION_OFFSETS[$dir];
}elseif($blockSouth->getID() === $this->id and ($blockSouth->meta & 0x08) === 0x08){ $b = $this->level->getBlockWithoutVector($this->x + $o[0], $this->y, $this->z + $o[1]);
$b = $blockSouth; if($b->getID() != BED_BLOCK){
}elseif($blockEast->getID() === $this->id and ($blockEast->meta & 0x08) === 0x08){ $player->sendChat("This bed is incomplete");
$b = $blockEast;
}elseif($blockWest->getID() === $this->id and ($blockWest->meta & 0x08) === 0x08){
$b = $blockWest;
}else{
$pk = new ChatPacket;
$pk->message = "This bed is incomplete";
$player->dataPacket($pk);
return true; return true;
} }
} }
if($player->sleepOn($b) === false){ if($player->sleepOn($b) === false){
$pk = new ChatPacket; $player->sendChat("This bed is occupied");
$pk->message = "This bed is occupied";
$player->dataPacket($pk);
} }
return true; return true;
} }
@ -172,9 +161,9 @@ class BedBlock extends TransparentBlock{
} }
public function getDrops(Item $item, Player $player){ public function getDrops(Item $item, Player $player){
return [ return array(
[BED, 0, 1], array(BED, 0, 1),
]; );
} }
} }

View file

@ -11,6 +11,9 @@ class FireBlock extends FlowableBlock implements LightingBlock{
$this->breakable = false; $this->breakable = false;
$this->isFullBlock = true; $this->isFullBlock = true;
$this->hardness = 0; $this->hardness = 0;
$this->breakTime = 0;
$this->material = Material::$fire;
$this->lightEmission = 15;
} }
public static function getAABB(Level $level, $x, $y, $z){ public static function getAABB(Level $level, $x, $y, $z){
return null; return null;

View file

@ -6,6 +6,10 @@ class NetherReactorBlock extends SolidBlock{
public function __construct($meta = 0){ public function __construct($meta = 0){
parent::__construct(NETHER_REACTOR, $meta, "Nether Reactor"); parent::__construct(NETHER_REACTOR, $meta, "Nether Reactor");
$this->isActivable = true; $this->isActivable = true;
$this->hardness = 15;
$this->breakTime = 3;
$this->material = Material::$metal;
$this->lightBlock = 255;
} }
public function onActivate(Item $item, Player $player){ public function onActivate(Item $item, Player $player){

View file

@ -5,21 +5,22 @@ class TNTBlock extends SolidBlock{
public function __construct(){ public function __construct(){
parent::__construct(TNT, 0, "TNT"); parent::__construct(TNT, 0, "TNT");
$this->hardness = 0; $this->hardness = 0;
$this->breakTime = 0;
$this->isActivable = true; $this->isActivable = true;
$this->material = Material::$explosive;
$this->lightBlock = 255;
} }
public function onActivate(Item $item, Player $player){ public function onActivate(Item $item, Player $player){
if($item->getID() === FLINT_STEEL){ if($item->getID() === FLINT_STEEL){
if(($player->gamemode & 0x01) === 0){ $item->hurtAndBreak(1, $player);
$item->useOn($this); $data = array(
}
$data = [
"x" => $this->x + 0.5, "x" => $this->x + 0.5,
"y" => $this->y, "y" => $this->y,
"z" => $this->z + 0.5, "z" => $this->z + 0.5,
"power" => 3, "power" => 3,
"fuse" => 20 * 4, //4 seconds "fuse" => 20 * 4, //4 seconds
]; );
$this->level->fastSetBlockUpdate($this->x, $this->y, $this->z, 0, 0, true); $this->level->fastSetBlockUpdate($this->x, $this->y, $this->z, 0, 0, true);
$e = ServerAPI::request()->api->entity->add($this->level, ENTITY_OBJECT, OBJECT_PRIMEDTNT, $data); $e = ServerAPI::request()->api->entity->add($this->level, ENTITY_OBJECT, OBJECT_PRIMEDTNT, $data);
ServerAPI::request()->api->entity->spawnToAll($e); ServerAPI::request()->api->entity->spawnToAll($e);

View file

@ -8,6 +8,8 @@ class CakeBlock extends TransparentBlock{
$this->isActivable = true; $this->isActivable = true;
$this->meta = $meta & 0x07; $this->meta = $meta & 0x07;
$this->hardness = 2.5; $this->hardness = 2.5;
$this->breakTime = 0.5;
$this->material = Material::$cake;
} }
public static function getCollisionBoundingBoxes(Level $level, $x, $y, $z, Entity $entity){ public static function getCollisionBoundingBoxes(Level $level, $x, $y, $z, Entity $entity){

View file

@ -4,7 +4,7 @@ class CarpetBlock extends FlowableBlock{
public static $blockID; public static $blockID;
public function __construct($meta = 0){ public function __construct($meta = 0){
parent::__construct(CARPET, $meta, "Carpet"); parent::__construct(CARPET, $meta, "Carpet");
$names = [ $names = array(
0 => "White Carpet", 0 => "White Carpet",
1 => "Orange Carpet", 1 => "Orange Carpet",
2 => "Magenta Carpet", 2 => "Magenta Carpet",
@ -21,11 +21,13 @@ class CarpetBlock extends FlowableBlock{
13 => "Green Carpet", 13 => "Green Carpet",
14 => "Red Carpet", 14 => "Red Carpet",
15 => "Black Carpet", 15 => "Black Carpet",
]; );
$this->name = $names[$this->meta]; $this->name = $names[$this->meta];
$this->hardness = 0; $this->hardness = 0.5;
$this->breakTime = 0.1;
$this->isFullBlock = false; $this->isFullBlock = false;
$this->isSolid = true; $this->isSolid = true;
$this->material = Material::$cloth;
} }
public static function getCollisionBoundingBoxes(Level $level, $x, $y, $z, Entity $entity){ public static function getCollisionBoundingBoxes(Level $level, $x, $y, $z, Entity $entity){
return [static::getAABB($level, $x, $y, $z)]; return [static::getAABB($level, $x, $y, $z)];

View file

@ -7,6 +7,8 @@ class ChestBlock extends TransparentBlock{
$this->isActivable = true; $this->isActivable = true;
$this->isFullBlock = false; $this->isFullBlock = false;
$this->hardness = 15; $this->hardness = 15;
$this->breakTime = 2.5;
$this->material = Material::$wood;
} }
public static function getCollisionBoundingBoxes(Level $level, $x, $y, $z, Entity $entity){ public static function getCollisionBoundingBoxes(Level $level, $x, $y, $z, Entity $entity){
return [new AxisAlignedBB($x + 0.025, $y, $z + 0.025, $x + 0.975, $y + 0.95, $z + 0.975)]; return [new AxisAlignedBB($x + 0.025, $y, $z + 0.025, $x + 0.975, $y + 0.95, $z + 0.975)];

View file

@ -6,7 +6,10 @@ class CobwebBlock extends FlowableBlock{
parent::__construct(COBWEB, 0, "Cobweb"); parent::__construct(COBWEB, 0, "Cobweb");
$this->isSolid = true; $this->isSolid = true;
$this->isFullBlock = false; $this->isFullBlock = false;
$this->hardness = 25; $this->hardness = 30;
$this->breakTime = 4;
$this->material = Material::$web;
$this->lightBlock = 1;
} }
public static function getAABB(Level $level, $x, $y, $z){ public static function getAABB(Level $level, $x, $y, $z){

View file

@ -5,6 +5,8 @@ class FarmlandBlock extends TransparentBlock{
public function __construct($meta = 0){ public function __construct($meta = 0){
parent::__construct(FARMLAND, $meta, "Farmland"); parent::__construct(FARMLAND, $meta, "Farmland");
$this->hardness = 3; $this->hardness = 3;
$this->breakTime = 0.6;
$this->material = Material::$dirt;
} }
public function getDrops(Item $item, Player $player){ public function getDrops(Item $item, Player $player){
return [ return [
@ -24,7 +26,7 @@ class FarmlandBlock extends TransparentBlock{
public static function fallOn(Level $level, $x, $y, $z, Entity $entity, $fallDistance){ public static function fallOn(Level $level, $x, $y, $z, Entity $entity, $fallDistance){
$rv = lcg_value(); $rv = lcg_value();
if($rv < ($fallDistance - 0.5)){ if($rv < ($fallDistance - 0.5)){
$level->fastSetBlockUpdate($x, $y, $z, DIRT, 0); $level->fastSetBlockUpdate($x, $y, $z, DIRT, 0, true);
} }
} }

View file

@ -6,13 +6,22 @@ class FenceBlock extends TransparentBlock{
parent::__construct(FENCE, 0, "Fence"); parent::__construct(FENCE, 0, "Fence");
$this->isFullBlock = false; $this->isFullBlock = false;
$this->hardness = 15; $this->hardness = 15;
$this->breakTime = 2;
$this->material = Material::$wood;
} }
public static function canConnectTo(Level $level, $x, $y, $z){ public static function canConnectTo(Level $level, $x, $y, $z){
$id = $level->level->getBlockID($x, $y, $z); $id = $level->level->getBlockID($x, $y, $z);
/*if($id == FENCE || $id == FENCE_GATE) return true;
if($id == 0) return false;
$mat = StaticBlock::getMaterial($id);
if($mat->isSolidBlocking() && tile->isCubeShaped()){ //TODO tile->isCubeShaped
return $mat != Material::$vegetable;
}
return false;*/
if($id != FENCE && $id != FENCE_GATE){ if($id != FENCE && $id != FENCE_GATE){
return StaticBlock::getIsSolid($id) && $id != PUMPKIN; //TODO check var6 != null && var6.blockMaterial.isOpaque() && var6.renderAsNormalBlock() ? var6.blockMaterial != Material.pumpkin : false; return StaticBlock::getIsSolid($id) && $id != PUMPKIN;
} }
return true; return true;
} }

View file

@ -31,6 +31,8 @@ class FenceGateBlock extends TransparentBlock{
$this->isFullBlock = false; $this->isFullBlock = false;
} }
$this->hardness = 15; $this->hardness = 15;
$this->breakTime = 2;
$this->material = Material::$wood;
} }
public function place(Item $item, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){ public function place(Item $item, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){
$faces = [ $faces = [
@ -73,7 +75,7 @@ class FenceGateBlock extends TransparentBlock{
$pk->z = $this->z; $pk->z = $this->z;
$pk->evid = 1003; $pk->evid = 1003;
$pk->data = 0; $pk->data = 0;
ServerAPI::request()->api->player->broadcastPacket($players, $pk); ServerAPI::request()->api->player->broadcastPacket($players, $pk); //TODO use blok queue?
return true; return true;
} }
} }

View file

@ -6,6 +6,9 @@ class GlassPaneBlock extends TransparentBlock{
parent::__construct(GLASS_PANE, 0, "Glass Pane"); parent::__construct(GLASS_PANE, 0, "Glass Pane");
$this->isFullBlock = false; $this->isFullBlock = false;
$this->isSolid = false; $this->isSolid = false;
$this->breakTime = 0.3;
$this->hardness = 0.3*5;
$this->material = Material::$glass;
} }
public static function updateShape(Level $level, $x, $y, $z){ public static function updateShape(Level $level, $x, $y, $z){
$id = $level->level->getBlockID($x, $y, $z); $id = $level->level->getBlockID($x, $y, $z);

View file

@ -6,6 +6,9 @@ class IronBarsBlock extends TransparentBlock{
parent::__construct(IRON_BARS, 0, "Iron Bars"); parent::__construct(IRON_BARS, 0, "Iron Bars");
$this->isFullBlock = false; $this->isFullBlock = false;
$this->isSolid = false; $this->isSolid = false;
$this->breakTime = 5;
$this->hardness = 30;
$this->material = Material::$metal;
} }
public static function updateShape(Level $level, $x, $y, $z){ public static function updateShape(Level $level, $x, $y, $z){

View file

@ -6,6 +6,8 @@ class IronDoorBlock extends DoorBlock{
parent::__construct(IRON_DOOR_BLOCK, $meta, "Iron Door Block"); parent::__construct(IRON_DOOR_BLOCK, $meta, "Iron Door Block");
//$this->isActivable = true; //$this->isActivable = true;
$this->hardness = 25; $this->hardness = 25;
$this->breakTime = 5;
$this->material = Material::$metal;
} }
public function getBreakTime(Item $item, Player $player){ public function getBreakTime(Item $item, Player $player){

View file

@ -1,13 +1,14 @@
<?php <?php
require_once("RailBaseBlock.php"); require_once("RailBaseBlock.php");
class PoweredRailBlock extends RailBaseBlock{ class PoweredRailBlock extends RailBaseBlock{
public static $blockID; public static $blockID;
public function __construct($meta = 0){ public function __construct($meta = 0){
parent::__construct(POWERED_RAIL, 0, "PoweredRailBlock"); parent::__construct(POWERED_RAIL, 0, "PoweredRailBlock");
$this->hardness = 0.7;
$this->isFullBlock = false; $this->isFullBlock = false;
$this->isSolid = false; $this->isSolid = false;
$this->hardness = 3.5;
$this->breakTime = 0.7;
$this->material = Material::$decoration;
} }
} }

View file

@ -1,13 +1,14 @@
<?php <?php
require_once("RailBaseBlock.php"); require_once("RailBaseBlock.php");
class RailBlock extends RailBaseBlock{ class RailBlock extends RailBaseBlock{
public static $blockID; public static $blockID;
public function __construct($meta = 0){ public function __construct($meta = 0){
parent::__construct(RAIL, $meta, "Rail"); parent::__construct(RAIL, $meta, "Rail");
$this->hardness = 0.7; $this->hardness = 0.7*5;
$this->breakTime = 0.7;
$this->isFullBlock = false; $this->isFullBlock = false;
$this->isSolid = false; $this->isSolid = false;
$this->material = Material::$decoration;
} }
public function updateState(){ public function updateState(){

View file

@ -22,6 +22,8 @@ class SlabBlock extends TransparentBlock{
$this->isFullBlock = false; $this->isFullBlock = false;
} }
$this->hardness = 30; $this->hardness = 30;
$this->breakTime = 2;
$this->material = Material::$stone;
} }
public static function updateShape(Level $level, $x, $y, $z){ public static function updateShape(Level $level, $x, $y, $z){

View file

@ -8,6 +8,8 @@ class SnowLayerBlock extends FlowableBlock{
$this->isSolid = false; $this->isSolid = false;
$this->isFullBlock = false; $this->isFullBlock = false;
$this->hardness = 0.5; $this->hardness = 0.5;
$this->breakTime = 0.1;
$this->material = Material::$topSnow;
} }
public static function getAABB(Level $level, $x, $y, $z){ public static function getAABB(Level $level, $x, $y, $z){
return null; return null;
@ -27,13 +29,19 @@ class SnowLayerBlock extends FlowableBlock{
} }
} }
public static function onRandomTick(Level $level, $x, $y, $z){
if($level->level->getBlockLight($x, $y, $z) > 11){
$level->fastSetBlockUpdate($x, $y, $z, 0, true);
}
}
public function getDrops(Item $item, Player $player){ public function getDrops(Item $item, Player $player){
if($item->isShovel() !== false){ if($item->isShovel() !== false){
return [ return array(
[SNOWBALL, 0, 1], array(SNOWBALL, 0, 1),
]; );
} }
return []; return array();
} }
} }

View file

@ -7,7 +7,9 @@ class StoneWallBlock extends TransparentBlock{
parent::__construct(STONE_WALL, $meta & 0x01, $meta === 1 ? "Mossy Cobblestone Wall" : "Cobblestone Wall"); parent::__construct(STONE_WALL, $meta & 0x01, $meta === 1 ? "Mossy Cobblestone Wall" : "Cobblestone Wall");
$this->isFullBlock = false; $this->isFullBlock = false;
$this->isSolid = false; $this->isSolid = false;
$this->hardness = 30; $this->hardness = 50;
$this->breakTime = 10;
$this->material = Material::$stone;
} }
public function getDrops(Item $item, Player $player){ public function getDrops(Item $item, Player $player){
if($item->isPickaxe()){ if($item->isPickaxe()){

View file

@ -6,6 +6,8 @@ class WoodDoorBlock extends DoorBlock{
parent::__construct(WOOD_DOOR_BLOCK, $meta, "Wood Door Block"); parent::__construct(WOOD_DOOR_BLOCK, $meta, "Wood Door Block");
$this->isActivable = true; $this->isActivable = true;
$this->hardness = 15; $this->hardness = 15;
$this->breakTime = 3;
$this->material = Material::$wood;
} }
public function getDrops(Item $item, Player $player){ public function getDrops(Item $item, Player $player){

View file

@ -1,23 +1,24 @@
<?php <?php
//TODO make it extend SlabBlock //TODO make it extend SlabBlock
class WoodSlabBlock extends TransparentBlock{ class WoodSlabBlock extends TransparentBlock{
public static $blockID; public static $blockID;
public function __construct($meta = 0){ public function __construct($meta = 0){
parent::__construct(WOOD_SLAB, $meta, "Wooden Slab"); parent::__construct(WOOD_SLAB, $meta, "Wooden Slab");
$names = [ $names = array(
0 => "Oak", 0 => "Oak",
1 => "Spruce", 1 => "Spruce",
2 => "Birch", 2 => "Birch",
3 => "Jungle", 3 => "Jungle",
]; );
$this->name = (($this->meta & 0x08) === 0x08 ? "Upper ":"") . $names[$this->meta & 0x07] . " Wooden Slab"; $this->name = (($this->meta & 0x08) === 0x08 ? "Upper ":"") . $names[$this->meta & 0x07] . " Wooden Slab";
if(($this->meta & 0x08) === 0x08){ if(($this->meta & 0x08) === 0x08){
$this->isFullBlock = true; $this->isFullBlock = true;
}else{ }else{
$this->isFullBlock = false; $this->isFullBlock = false;
} }
$this->hardness = 15; $this->hardness = 30;
$this->breakTime = 2;
$this->material = Material::$wood;
} }
public static function updateShape(Level $level, $x, $y, $z){ public static function updateShape(Level $level, $x, $y, $z){
@ -91,7 +92,9 @@ class WoodSlabBlock extends TransparentBlock{
if(($player->gamemode & 0x01) === 0x01){ if(($player->gamemode & 0x01) === 0x01){
return 0.20; return 0.20;
} }
return match ($item->isAxe()) { if(!$item->isAxe()) return 3;
return match ($item->getLevel()) {
5 => 0.4, 5 => 0.4,
4 => 0.5, 4 => 0.5,
3 => 0.75, 3 => 0.75,
@ -102,8 +105,8 @@ class WoodSlabBlock extends TransparentBlock{
} }
public function getDrops(Item $item, Player $player){ public function getDrops(Item $item, Player $player){
return [ return array(
[$this->id, $this->meta & 0x07, 1], array($this->id, $this->meta & 0x07, 1),
]; );
} }
} }

View file

@ -4,6 +4,9 @@ class BirchWoodStairsBlock extends StairBlock{
public static $blockID; public static $blockID;
public function __construct($meta = 0){ public function __construct($meta = 0){
parent::__construct(BIRCH_WOOD_STAIRS, $meta, "Birch Wood Stairs"); parent::__construct(BIRCH_WOOD_STAIRS, $meta, "Birch Wood Stairs");
$this->hardness = 15;
$this->breakTime = 2;
$this->material = Material::$wood;
} }
public function getDrops(Item $item, Player $player){ public function getDrops(Item $item, Player $player){

View file

@ -4,6 +4,9 @@ class BrickStairsBlock extends StairBlock{
public static $blockID; public static $blockID;
public function __construct($meta = 0){ public function __construct($meta = 0){
parent::__construct(BRICK_STAIRS, $meta, "Brick Stairs"); parent::__construct(BRICK_STAIRS, $meta, "Brick Stairs");
$this->breakTime = 2;
$this->hardness = 30;
$this->material = Material::$stone;
} }
} }

View file

@ -4,6 +4,9 @@ class CobblestoneStairsBlock extends StairBlock{
public static $blockID; public static $blockID;
public function __construct($meta = 0){ public function __construct($meta = 0){
parent::__construct(COBBLESTONE_STAIRS, $meta, "Cobblestone Stairs"); parent::__construct(COBBLESTONE_STAIRS, $meta, "Cobblestone Stairs");
$this->breakTime = 2;
$this->hardness = 30;
$this->material = Material::$stone;
} }
} }

View file

@ -4,6 +4,9 @@ class JungleWoodStairsBlock extends StairBlock{
public static $blockID; public static $blockID;
public function __construct($meta = 0){ public function __construct($meta = 0){
parent::__construct(JUNGLE_WOOD_STAIRS, $meta, "Jungle Wood Stairs"); parent::__construct(JUNGLE_WOOD_STAIRS, $meta, "Jungle Wood Stairs");
$this->hardness = 15;
$this->breakTime = 2;
$this->material = Material::$wood;
} }
public function getDrops(Item $item, Player $player){ public function getDrops(Item $item, Player $player){

View file

@ -4,6 +4,9 @@ class NetherBricksStairsBlock extends StairBlock{
public static $blockID; public static $blockID;
public function __construct($meta = 0){ public function __construct($meta = 0){
parent::__construct(NETHER_BRICKS_STAIRS, $meta, "Nether Bricks Stairs"); parent::__construct(NETHER_BRICKS_STAIRS, $meta, "Nether Bricks Stairs");
$this->hardness = 30;
$this->breakTime = 2;
$this->material = Material::$stone;
} }
} }

View file

@ -4,6 +4,9 @@ class QuartzStairsBlock extends StairBlock{
public static $blockID; public static $blockID;
public function __construct($meta = 0){ public function __construct($meta = 0){
parent::__construct(QUARTZ_STAIRS, $meta, "Quartz Stairs"); parent::__construct(QUARTZ_STAIRS, $meta, "Quartz Stairs");
$this->breakTime = 0.8;
$this->hardness = 4;
$this->material = Material::$stone;
} }
} }

View file

@ -4,6 +4,9 @@ class SandstoneStairsBlock extends StairBlock{
public static $blockID; public static $blockID;
public function __construct($meta = 0){ public function __construct($meta = 0){
parent::__construct(SANDSTONE_STAIRS, $meta, "Sandstone Stairs"); parent::__construct(SANDSTONE_STAIRS, $meta, "Sandstone Stairs");
$this->hardness = 0.8*5;
$this->breakTime = 0.8;
$this->material = Material::$stone;
} }
} }

View file

@ -4,6 +4,9 @@ class SpruceWoodStairsBlock extends StairBlock{
public static $blockID; public static $blockID;
public function __construct($meta = 0){ public function __construct($meta = 0){
parent::__construct(SPRUCE_WOOD_STAIRS, $meta, "Spruce Wood Stairs"); parent::__construct(SPRUCE_WOOD_STAIRS, $meta, "Spruce Wood Stairs");
$this->hardness = 15;
$this->breakTime = 2;
$this->material = Material::$wood;
} }
public function getDrops(Item $item, Player $player){ public function getDrops(Item $item, Player $player){

View file

@ -4,6 +4,9 @@ class StoneBrickStairsBlock extends StairBlock{
public static $blockID; public static $blockID;
public function __construct($meta = 0){ public function __construct($meta = 0){
parent::__construct(STONE_BRICK_STAIRS, $meta, "Stone Brick Stairs"); parent::__construct(STONE_BRICK_STAIRS, $meta, "Stone Brick Stairs");
$this->hardness = 30;
$this->breakTime = 1.5;
$this->material = Material::$stone;
} }
} }

View file

@ -4,13 +4,17 @@ class WoodStairsBlock extends StairBlock{
public static $blockID; public static $blockID;
public function __construct($meta = 0){ public function __construct($meta = 0){
parent::__construct(WOOD_STAIRS, $meta, "Wood Stairs"); parent::__construct(WOOD_STAIRS, $meta, "Wood Stairs");
$this->breakTime = 2;
$this->material = Material::$wood;
} }
public function getBreakTime(Item $item, Player $player){ public function getBreakTime(Item $item, Player $player){
if(($player->gamemode & 0x01) === 0x01){ if(($player->gamemode & 0x01) === 0x01){
return 0.20; return 0.20;
} }
return match ($item->isAxe()) { if(!$item->isAxe()) return 3;
return match ($item->getLevel()) {
5 => 0.4, 5 => 0.4,
4 => 0.5, 4 => 0.5,
3 => 0.75, 3 => 0.75,

View file

@ -5,6 +5,9 @@ class CoalOreBlock extends SolidBlock{
public function __construct(){ public function __construct(){
parent::__construct(COAL_ORE, 0, "Coal Ore"); parent::__construct(COAL_ORE, 0, "Coal Ore");
$this->hardness = 15; $this->hardness = 15;
$this->breakTime = 3.0;
$this->material = Material::$stone;
$this->lightBlock = 255;
} }
public function getBreakTime(Item $item, Player $player){ public function getBreakTime(Item $item, Player $player){

View file

@ -5,6 +5,9 @@ class DiamondOreBlock extends SolidBlock{
public function __construct(){ public function __construct(){
parent::__construct(DIAMOND_ORE, 0, "Diamond Ore"); parent::__construct(DIAMOND_ORE, 0, "Diamond Ore");
$this->hardness = 15; $this->hardness = 15;
$this->breakTime = 3;
$this->material = Material::$stone;
$this->lightBlock = 255;
} }
public function getBreakTime(Item $item, Player $player){ public function getBreakTime(Item $item, Player $player){

View file

@ -5,6 +5,10 @@ class GlowingRedstoneOreBlock extends SolidBlock implements LightingBlock{
public function __construct(){ public function __construct(){
parent::__construct(GLOWING_REDSTONE_ORE, 0, "Glowing Redstone Ore"); parent::__construct(GLOWING_REDSTONE_ORE, 0, "Glowing Redstone Ore");
$this->hardness = 15; $this->hardness = 15;
$this->breakTime = 3;
$this->material = Material::$stone;
$this->lightBlock = 255;
$this->lightEmission = 9;
} }
public static function onRandomTick(Level $level, $x, $y, $z){ public static function onRandomTick(Level $level, $x, $y, $z){

View file

@ -5,6 +5,9 @@ class GoldOreBlock extends SolidBlock{
public function __construct(){ public function __construct(){
parent::__construct(GOLD_ORE, 0, "Gold Ore"); parent::__construct(GOLD_ORE, 0, "Gold Ore");
$this->hardness = 15; $this->hardness = 15;
$this->breakTime = 3.0;
$this->material = Material::$stone;
$this->lightBlock = 255;
} }
public function getBreakTime(Item $item, Player $player){ public function getBreakTime(Item $item, Player $player){

View file

@ -5,6 +5,9 @@ class IronOreBlock extends SolidBlock{
public function __construct(){ public function __construct(){
parent::__construct(IRON_ORE, 0, "Iron Ore"); parent::__construct(IRON_ORE, 0, "Iron Ore");
$this->hardness = 15; $this->hardness = 15;
$this->breakTime = 3.0;
$this->material = Material::$stone;
$this->lightBlock = 255;
} }
public function getBreakTime(Item $item, Player $player){ public function getBreakTime(Item $item, Player $player){

View file

@ -5,6 +5,9 @@ class LapisOreBlock extends SolidBlock{
public function __construct(){ public function __construct(){
parent::__construct(LAPIS_ORE, 0, "Lapis Ore"); parent::__construct(LAPIS_ORE, 0, "Lapis Ore");
$this->hardness = 15; $this->hardness = 15;
$this->breakTime = 3.0;
$this->material = Material::$stone;
$this->lightBlock = 255;
} }
public function getBreakTime(Item $item, Player $player){ public function getBreakTime(Item $item, Player $player){

View file

@ -5,6 +5,9 @@ class RedstoneOreBlock extends SolidBlock{
public function __construct(){ public function __construct(){
parent::__construct(REDSTONE_ORE, 0, "Redstone Ore"); parent::__construct(REDSTONE_ORE, 0, "Redstone Ore");
$this->hardness = 15; $this->hardness = 15;
$this->breakTime = 3;
$this->material = Material::$stone;
$this->lightBlock = 255;
} }
public static function interact(Level $level, $x, $y, $z, Player $player){ public static function interact(Level $level, $x, $y, $z, Player $player){

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