From d4036d8ac922ad0fc2ff0960d8d6f87510b65f3c Mon Sep 17 00:00:00 2001 From: GameHerobrine Date: Wed, 25 Jun 2025 03:22:24 +0300 Subject: [PATCH 01/16] tile entity related packets use block update queue, cleaned up unused code, some phpdocs --- src/API/AchievementAPI.php | 29 +++- src/API/BanAPI.php | 38 ++-- src/Player.php | 164 ++++++++++-------- src/material/block/plant/BeetrootBlock.php | 1 - src/material/block/plant/CactusBlock.php | 1 - src/material/block/plant/CarrotBlock.php | 1 - src/material/block/plant/MelonStemBlock.php | 1 - src/material/block/plant/PotatoBlock.php | 1 - src/material/block/plant/PumpkinStemBlock.php | 1 - src/material/block/plant/SaplingBlock.php | 1 - src/material/block/plant/WheatBlock.php | 1 - src/material/block/solid/IceBlock.php | 1 - .../protocol/packet/EntityEventPacket.php | 4 + src/world/Explosion.php | 18 +- src/world/Tile.php | 15 +- 15 files changed, 165 insertions(+), 112 deletions(-) diff --git a/src/API/AchievementAPI.php b/src/API/AchievementAPI.php index beabe308..9f5d6e0d 100644 --- a/src/API/AchievementAPI.php +++ b/src/API/AchievementAPI.php @@ -81,7 +81,7 @@ class AchievementAPI{ ], ]; - + /** @var PocketMinecraftServer */ private $server; function __construct(){ @@ -91,9 +91,9 @@ class AchievementAPI{ /** * Add an achievement * @param string $achievementId - * @param string $achievementName - * @param array $requires - * @return boolean + * @param string $achievementName display name + * @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 = []){ if(!isset(self::$achievements[$achievementId])){ @@ -106,6 +106,12 @@ class AchievementAPI{ return false; } + /** + * Gives the achievement to player + * @param Player $player + * @param string $achievementId + * @return boolean + */ public static function grantAchievement(Player $player, $achievementId){ if(isset(self::$achievements[$achievementId]) and !self::hasAchievement($player, $achievementId)){ foreach(self::$achievements[$achievementId]["requires"] as $requerimentId){ @@ -124,6 +130,11 @@ class AchievementAPI{ return false; } + /** + * @param Player $player + * @param string $achievementId + * @return boolean + */ public static function hasAchievement(Player $player, $achievementId){ if(!isset(self::$achievements[$achievementId]) or !isset($player->achievements)){ $player->achievements = []; @@ -136,6 +147,11 @@ class AchievementAPI{ return true; } + /** + * @param Player $player + * @param string $achievementId + * @return boolean + */ public static function broadcastAchievement(Player $player, $achievementId){ if(isset(self::$achievements[$achievementId])){ $result = ServerAPI::request()->api->dhandle("achievement.broadcast", ["player" => $player, "achievementId" => $achievementId]); @@ -151,6 +167,11 @@ class AchievementAPI{ return false; } + /** + * Removes achievement from player. + * @param Player $player + * @param string $achievementId + */ public static function removeAchievement(Player $player, $achievementId){ if(self::hasAchievement($player, $achievementId)){ $player->achievements[$achievementId] = false; diff --git a/src/API/BanAPI.php b/src/API/BanAPI.php index 7ab128b6..ecd2f7be 100644 --- a/src/API/BanAPI.php +++ b/src/API/BanAPI.php @@ -1,11 +1,8 @@ server = ServerAPI::request(); } @@ -56,7 +57,6 @@ class BanAPI{ /** * @param mixed $data * @param string $event - * * @return boolean */ public function permissionsCheck($data, $event){ @@ -106,11 +106,11 @@ class BanAPI{ } /** + * Checks is player op or not * @param string $username - * * @return boolean */ - public function isOp($username){//Is a player op? + public function isOp($username){ $username = strtolower($username); if($this->server->api->dhandle("op.check", $username) === true){ return true; @@ -121,6 +121,7 @@ class BanAPI{ } /** + * Bans a player. * @param string $username */ public function ban($username){ @@ -316,14 +317,16 @@ class BanAPI{ } /** - * @param string $username - * @param string $reason + * Kicks a player + * @param string $username - player's username + * @param string $reason - kick reason, optional */ public function kick($username, $reason = "No Reason"){ $this->commandHandler("kick", [$username, $reason], "console", ""); } /** + * Unbans a player * @param string $username */ public function pardon($username){ @@ -331,6 +334,7 @@ class BanAPI{ } /** + * Bans some ip * @param string $ip */ public function banIP($ip){ @@ -338,12 +342,16 @@ class BanAPI{ } /** + * Unbans some ip * @param string $ip */ public function pardonIP($ip){ $this->commandHandler("banip", ["pardon", $ip], "console", ""); } + /** + * Rereads ban list, kick list and banip list + */ public function reload(){ $this->commandHandler("ban", ["reload"], "console", ""); $this->commandHandler("banip", ["reload"], "console", ""); @@ -351,8 +359,8 @@ class BanAPI{ } /** + * Checks is ip banned or not * @param string $ip - * * @return boolean */ public function isIPBanned($ip){ @@ -366,8 +374,8 @@ class BanAPI{ } /** + * Checks is username banned or not. * @param string $username - * * @return boolean */ public function isBanned($username){ @@ -382,8 +390,8 @@ class BanAPI{ } /** + * Checks is username in the whitelist or not * @param string $username - * * @return boolean */ public function inWhitelist($username){ diff --git a/src/Player.php b/src/Player.php index cf6fc528..25738e78 100755 --- a/src/Player.php +++ b/src/Player.php @@ -38,7 +38,6 @@ class Player{ public $lastCorrect; public $craftingItems = []; public $toCraft = []; - public $lastCraft = 0; public $loginData = []; /** @var Level */ public $level; @@ -95,6 +94,7 @@ class Player{ public $entityMovementQueue; public $entityMovementQueuePrevSentCnt = 0; public $entityMovementQueueLength = 0; + /** * Used only for statistic in ping command. * @var integer @@ -104,13 +104,13 @@ class Player{ public $blockUpdateQueue; public $blockUpdateQueueLength = 0; - public $blockUpdateQueuePrevSentCnt = 0; public $blockUpdateQueueOrderIndex = 0; public $chatMessagesQueue; public $chatMessagesQueueLength = 0; - public $chatMessagesQueuePrevSentCnt = 0; public $chatMessagesOrderIndex = 0; + + public $chunkDataSent = []; /** @@ -408,10 +408,32 @@ class Player{ } /** - * @param integer $id - * @param array $data - * - * @return array|bool + * Sends data packet that wont be buffered. Packets are not ordered. + * @param RakNetDataPacket $packet + * @param int $reliability=0 unused + * @param bool $recover=true can the packet be recovered or not. If true the packet will be recovered only once. Otherwise, it won't be recovered at all. + * @returns int[]|false - array with seqNumber of the packet. false if player is not connected. empty array if cancelled by DataPacketSendEvent. + */ + public function directDataPacket(RakNetDataPacket $packet, $reliability = 0, $recover = true){ + if($this->connected === false) return false; + if(EventHandler::callEvent(new DataPacketSendEvent($this, $packet)) === BaseEvent::DENY) return []; + + $packet->encode(); + $pk = new RakNetPacket(RakNetInfo::DATA_PACKET_0); + $pk->data[] = $packet; + $pk->seqNumber = $this->counter[0]++; + $pk->sendtime = microtime(true); + if($recover !== false){ + $this->recoveryQueue[$pk->seqNumber] = $pk; + } + + $this->send($pk); + return [$pk->seqNumber]; + } + + /** + * Sends data packet that will be recovered only once. Packet MAY not arrive at all or arrive out of order. + * @param RakNetDataPacket $packet */ public function dataPacket(RakNetDataPacket $packet){ if($this->connected === false) return false; @@ -435,9 +457,13 @@ class Player{ return []; } + /** + * Sends data packet that will always be recovered. Packets MAY arrive out of order. + * @param RakNetDataPacket $packet + */ public function dataPacketAlwaysRecover(RakNetDataPacket $packet){ if($this->connected === false) return false; - if(EventHandler::callEvent(new DataPacketSendEvent($this, $packet)) === BaseEvent::DENY) return; + if(EventHandler::callEvent(new DataPacketSendEvent($this, $packet)) === BaseEvent::DENY) return false; $pk = new RakNetPacket(RakNetInfo::DATA_PACKET_0); $pk->data[] = $packet; @@ -459,11 +485,7 @@ class Player{ return [$pk->seqNumber]; } - public function sendChunkDataPacket(RakNetDataPacket $pk){ - if($this->connected === false) return false; - if(EventHandler::callEvent(new DataPacketSendEvent($this, $pk)) === BaseEvent::DENY) return; - - $pk->encode(); + public function blockQueueDataPacket_big(RakNetDataPacket $pk){ $sendtime = microtime(true); $size = $this->MTU - 34; if($size <= 0) return false; @@ -719,7 +741,7 @@ class Player{ $pk->chunkX = $X; $pk->chunkZ = $Z; $pk->data = $this->level->getOrderedChunk($X, $Z, $Yndex); - $cnt = $this->sendChunkDataPacket($pk); + $cnt = $this->blockQueueDataPacket($pk); $this->chunkDataSent["$X:$Z"] = true; $tiles = $this->server->query("SELECT ID FROM tiles WHERE spawnable = 1 AND level = '{$this->level->getName()}' AND x >= $minX AND x <= $maxX AND z >= $minZ AND z <= $maxZ;"); @@ -816,7 +838,7 @@ class Player{ $pk->chunkX = $X; $pk->chunkZ = $Z; $pk->data = $this->level->getOrderedChunk($X, $Z, $Yndex); - $cnt = $this->sendChunkDataPacket($pk); + $cnt = $this->blockQueueDataPacket($pk); $this->chunkDataSent["$X:$Z"] = true; if($cnt === false){ @@ -934,13 +956,13 @@ class Player{ $pk->windowid = $id; $pk->property = 0; //Smelting $pk->value = floor($data->data["CookTime"]); - $this->dataPacket($pk); + $this->blockQueueDataPacket($pk); $pk = new ContainerSetDataPacket; $pk->windowid = $id; $pk->property = 1; //Fire icon $pk->value = $data->data["BurnTicks"]; - $this->dataPacket($pk); + $this->blockQueueDataPacket($pk); } } } @@ -954,7 +976,7 @@ class Player{ $pk->windowid = $id; $pk->slot = $data["slot"] + ($data["offset"] ?? 0); $pk->item = $data["slotdata"]; - $this->dataPacket($pk); + $this->blockQueueDataPacket($pk); } } } @@ -1029,7 +1051,6 @@ class Player{ $this->dataPacket($pk); break; case "entity.animate": - $pk = new AnimatePacket; $pk->eid = $data["eid"]; $pk->action = $data["action"]; //1 swing arm, @@ -1495,12 +1516,48 @@ class Player{ $this->blockUpdateQueue->data = []; } + /** + * Sends packet in block order channel. Packets are always delivered and ordered. + * Used for sending tileentity data, chunk data, updateblock packets. + * @param RakNetPacket $pk + */ + public function blockQueueDataPacket(RakNetDataPacket $pk){ + if($this->connected === false) return false; + if(EventHandler::callEvent(new DataPacketSendEvent($this, $pk)) === BaseEvent::DENY) return; + + $pk->encode(); + + $len = 1 + strlen($pk->buffer); + $MTU = $this->MTU - 24; + if($len > $MTU) return $this->blockQueueDataPacket_big($pk); + + if(($this->blockUpdateQueueLength + $len) >= $MTU){ + $this->sendBlockUpdateQueue(); + } + + $pk->messageIndex = $this->counter[3]++; + $pk->reliability = 3; + $pk->orderChannel = Player::BLOCKUPDATE_ORDER_CHANNEL; + $pk->orderIndex = $this->blockUpdateQueueOrderIndex++; + @$this->blockUpdateQueue->data[] = $pk; + $this->blockUpdateQueueLength += 10 + $len; + } + + /** + * Adds block update into queue. Does nothing if chunk wasnt loaded. + * @param int $x + * @param int $y + * @param int $z + * @param int $id + * @param int $meta + * @return boolean + */ public function addBlockUpdateIntoQueue($x, $y, $z, $id, $meta){ $xC = $x >> 4; $zC = $z >> 4; if(!isset($this->chunkDataSent["$xC:$zC"])){ ConsoleAPI::debug("Ignoring block update $x $y $z $id $meta: chunk data was not sent."); - return; //dont send updateblockpacket as it will be buffered and updated only after all chunks will load + return false; //dont send updateblockpacket as it will be buffered and updated only after all chunks will load } $packet = new UpdateBlockPacket(); $packet->x = $x; @@ -1508,21 +1565,7 @@ class Player{ $packet->z = $z; $packet->block = $id; $packet->meta = $meta; - $packet->encode(); - - $len = 1 + strlen($packet->buffer); - $MTU = $this->MTU - 24; - - if(($this->blockUpdateQueueLength + $len) >= $MTU){ - $this->sendBlockUpdateQueue(); - } - - $packet->messageIndex = $this->counter[3]++; - $packet->reliability = 3; - $packet->orderChannel = Player::BLOCKUPDATE_ORDER_CHANNEL; - $packet->orderIndex = $this->blockUpdateQueueOrderIndex++; - @$this->blockUpdateQueue->data[] = $packet; - $this->blockUpdateQueueLength += 10 + $len; + $this->blockQueueDataPacket($packet); } public function addEntityMovementUpdateToQueue(Entity $e){ @@ -1699,28 +1742,12 @@ class Player{ $this->data->set("gamemode", $this->gamemode); } } - - public function directDataPacket(RakNetDataPacket $packet, $reliability = 0, $recover = true){ - if($this->connected === false) return false; - if(EventHandler::callEvent(new DataPacketSendEvent($this, $packet)) === BaseEvent::DENY) return []; - - $packet->encode(); - $pk = new RakNetPacket(RakNetInfo::DATA_PACKET_0); - $pk->data[] = $packet; - $pk->seqNumber = $this->counter[0]++; - $pk->sendtime = microtime(true); - if($recover !== false){ - $this->recoveryQueue[$pk->seqNumber] = $pk; - } - - $this->send($pk); - return [$pk->seqNumber]; - } public function sendChatMessagePacket(RakNetDataPacket $packet){ if($this->connected === false) return false; if(EventHandler::callEvent(new DataPacketSendEvent($this, $packet)) === BaseEvent::DENY) return false; + //TODO big chat messages support $packet->encode(); $len = strlen($packet->buffer) + 1; $MTU = $this->MTU - 24; @@ -2271,7 +2298,6 @@ class Player{ if($slotItem !== false){ if($slotItem->count == 1) $this->inventory[$this->slot] = BlockAPI::getItem(AIR, 0, 0); else $slotItem->count -= 1; - //$this->sendInventory(); } } @@ -2516,7 +2542,7 @@ class Player{ if($this->entity->getHealth() < 20 && $foodHeal != 0){ $pk = new EntityEventPacket; $pk->eid = 0; - $pk->event = 9; + $pk->event = EntityEventPacket::ENTITY_COMPLETE_USING_ITEM; $this->dataPacket($pk); $this->entity->heal($foodHeal, "eating"); @@ -2743,18 +2769,18 @@ class Player{ $slot = $tile->getSlot($slotn); if($this->server->api->dhandle("player.container.slot", [ - "tile" => $tile, - "slot" => $packet->slot, - "offset" => $offset, - "slotdata" => $slot, - "itemdata" => $item, - "player" => $this - ]) === false){ + "tile" => $tile, + "slot" => $packet->slot, + "offset" => $offset, + "slotdata" => $slot, + "itemdata" => $item, + "player" => $this + ]) === false){ $pk = new ContainerSetSlotPacket; $pk->windowid = $packet->windowid; $pk->slot = $packet->slot; $pk->item = $slot; - $this->dataPacket($pk); + $this->blockQueueDataPacket($pk); break; } @@ -2782,17 +2808,17 @@ class Player{ $slot = $tile->getSlot($packet->slot); if($this->server->api->dhandle("player.container.slot", [ - "tile" => $tile, - "slot" => $packet->slot, - "slotdata" => $slot, - "itemdata" => $item, - "player" => $this, - ]) === false){ + "tile" => $tile, + "slot" => $packet->slot, + "slotdata" => $slot, + "itemdata" => $item, + "player" => $this, + ]) === false){ $pk = new ContainerSetSlotPacket; $pk->windowid = $packet->windowid; $pk->slot = $packet->slot; $pk->item = $slot; - $this->dataPacket($pk); + $this->blockQueueDataPacket($pk); break; } diff --git a/src/material/block/plant/BeetrootBlock.php b/src/material/block/plant/BeetrootBlock.php index 05d2c646..312b63bd 100644 --- a/src/material/block/plant/BeetrootBlock.php +++ b/src/material/block/plant/BeetrootBlock.php @@ -14,7 +14,6 @@ class BeetrootBlock extends FlowableBlock{ $down = $this->getSide(0); if($down->getID() === FARMLAND){ $this->level->setBlock($block, $this, true, false, true); - $this->level->scheduleBlockUpdate(new Position($this, 0, 0, $this->level), Utils::getRandomUpdateTicks(), BLOCK_UPDATE_RANDOM); return true; } return false; diff --git a/src/material/block/plant/CactusBlock.php b/src/material/block/plant/CactusBlock.php index b218d8b9..5c6bdd6b 100644 --- a/src/material/block/plant/CactusBlock.php +++ b/src/material/block/plant/CactusBlock.php @@ -62,7 +62,6 @@ class CactusBlock extends TransparentBlock{ $block3 = $this->getSide(5); if($block0->isFlowable === true and $block1->isFlowable === true and $block2->isFlowable === true and $block3->isFlowable === true){ $this->level->setBlock($this, $this, true, false, true); - $this->level->scheduleBlockUpdate(new Position($this, 0, 0, $this->level), Utils::getRandomUpdateTicks(), BLOCK_UPDATE_RANDOM); ServerAPI::request()->api->block->scheduleBlockUpdate(clone $this, 10, BLOCK_UPDATE_NORMAL); return true; } diff --git a/src/material/block/plant/CarrotBlock.php b/src/material/block/plant/CarrotBlock.php index 98717892..4bcd86b9 100644 --- a/src/material/block/plant/CarrotBlock.php +++ b/src/material/block/plant/CarrotBlock.php @@ -14,7 +14,6 @@ class CarrotBlock extends FlowableBlock{ $down = $this->getSide(0); if($down->getID() === FARMLAND){ $this->level->setBlock($block, $this, true, false, true); - $this->level->scheduleBlockUpdate(new Position($this, 0, 0, $this->level), Utils::getRandomUpdateTicks(), BLOCK_UPDATE_RANDOM); return true; } return false; diff --git a/src/material/block/plant/MelonStemBlock.php b/src/material/block/plant/MelonStemBlock.php index 10500032..c98d8677 100644 --- a/src/material/block/plant/MelonStemBlock.php +++ b/src/material/block/plant/MelonStemBlock.php @@ -13,7 +13,6 @@ class MelonStemBlock extends FlowableBlock{ $down = $this->getSide(0); if($down->getID() === FARMLAND){ $this->level->setBlock($block, $this, true, false, true); - $this->level->scheduleBlockUpdate(new Position($this, 0, 0, $this->level), Utils::getRandomUpdateTicks(), BLOCK_UPDATE_RANDOM); return true; } return false; diff --git a/src/material/block/plant/PotatoBlock.php b/src/material/block/plant/PotatoBlock.php index d8f86f38..15866171 100644 --- a/src/material/block/plant/PotatoBlock.php +++ b/src/material/block/plant/PotatoBlock.php @@ -14,7 +14,6 @@ class PotatoBlock extends FlowableBlock{ $down = $this->getSide(0); if($down->getID() === FARMLAND){ $this->level->setBlock($block, $this, true, false, true); - $this->level->scheduleBlockUpdate(new Position($this, 0, 0, $this->level), Utils::getRandomUpdateTicks(), BLOCK_UPDATE_RANDOM); return true; } return false; diff --git a/src/material/block/plant/PumpkinStemBlock.php b/src/material/block/plant/PumpkinStemBlock.php index ac34ed7d..c662af3a 100644 --- a/src/material/block/plant/PumpkinStemBlock.php +++ b/src/material/block/plant/PumpkinStemBlock.php @@ -13,7 +13,6 @@ class PumpkinStemBlock extends FlowableBlock{ $down = $this->getSide(0); if($down->getID() === FARMLAND){ $this->level->setBlock($block, $this, true, false, true); - $this->level->scheduleBlockUpdate(new Position($this, 0, 0, $this->level), Utils::getRandomUpdateTicks(), BLOCK_UPDATE_RANDOM); return true; } return false; diff --git a/src/material/block/plant/SaplingBlock.php b/src/material/block/plant/SaplingBlock.php index bd5635d0..49ae119e 100644 --- a/src/material/block/plant/SaplingBlock.php +++ b/src/material/block/plant/SaplingBlock.php @@ -29,7 +29,6 @@ class SaplingBlock extends FlowableBlock{ $down = $this->getSide(0); if($down->getID() === GRASS or $down->getID() === DIRT or $down->getID() === FARMLAND){ $this->level->setBlock($block, $this, true, false, true); - $this->level->scheduleBlockUpdate(new Position($this, 0, 0, $this->level), Utils::getRandomUpdateTicks(), BLOCK_UPDATE_RANDOM); return true; } return false; diff --git a/src/material/block/plant/WheatBlock.php b/src/material/block/plant/WheatBlock.php index 97f3d39f..3e25d2ea 100644 --- a/src/material/block/plant/WheatBlock.php +++ b/src/material/block/plant/WheatBlock.php @@ -14,7 +14,6 @@ class WheatBlock extends FlowableBlock{ $down = $this->getSide(0); if($down->getID() === FARMLAND){ $this->level->setBlock($block, $this, true, false, true); - $this->level->scheduleBlockUpdate(new Position($this, 0, 0, $this->level), Utils::getRandomUpdateTicks(), BLOCK_UPDATE_RANDOM); return true; } return false; diff --git a/src/material/block/solid/IceBlock.php b/src/material/block/solid/IceBlock.php index 52079e10..3b74cab2 100644 --- a/src/material/block/solid/IceBlock.php +++ b/src/material/block/solid/IceBlock.php @@ -17,7 +17,6 @@ class IceBlock extends TransparentBlock{ public function place(Item $item, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){ $ret = $this->level->setBlock($this, $this, true, false, true); - $this->level->scheduleBlockUpdate(new Position($this, 0, 0, $this->level), Utils::getRandomUpdateTicks(), BLOCK_UPDATE_RANDOM); return $ret; } diff --git a/src/network/protocol/packet/EntityEventPacket.php b/src/network/protocol/packet/EntityEventPacket.php index 05cf7770..44e9b06a 100644 --- a/src/network/protocol/packet/EntityEventPacket.php +++ b/src/network/protocol/packet/EntityEventPacket.php @@ -6,6 +6,10 @@ class EntityEventPacket extends RakNetDataPacket{ const ENTITY_DAMAGE = 2; const ENTITY_DEAD = 3; + /** + * Works only for player entities + */ + const ENTITY_COMPLETE_USING_ITEM = 9; const ENTITY_ANIM_10 = 10; public function __construct($eid = null, $event = null){ diff --git a/src/world/Explosion.php b/src/world/Explosion.php index e44c7bd3..0a8e041d 100644 --- a/src/world/Explosion.php +++ b/src/world/Explosion.php @@ -1,16 +1,10 @@ DIRT, - STONE => COBBLESTONE, - COAL_ORE => COAL, - DIAMOND_ORE => DIAMOND, - REDSTONE_ORE => REDSTONE, - ]; public static $enableExplosions = true; - public $level; //Rays + /** @var Level */ + public $level; + /** @var Position */ public $source; public $size; public $affectedBlocks = []; @@ -222,4 +216,10 @@ class Explosion{ $pk->records = $send; $server->api->player->broadcastPacket($this->level->players, $pk); } + + + /** + * @deprecated unused + */ + public static $specialDrops = []; } diff --git a/src/world/Tile.php b/src/world/Tile.php index 66b20280..5f4714a5 100644 --- a/src/world/Tile.php +++ b/src/world/Tile.php @@ -283,7 +283,10 @@ class Tile extends Position{ $pk->z = $this->z; $pk->case1 = 1; $pk->case2 = 2; - $this->server->api->player->broadcastPacket($this->server->api->player->getAll($this->level), $pk); + foreach($this->level->players as $player){ + $player->blockQueueDataPacket(clone $pk); + } + for($s = 0; $s < CHEST_SLOTS; ++$s){ $slot = $this->getSlot($s); if($slot->getID() > AIR and $slot->count > 0){ @@ -297,7 +300,7 @@ class Tile extends Position{ $pk = new ContainerSetContentPacket; $pk->windowid = $id; $pk->slots = $slots; - $player->dataPacket($pk); + $player->blockQueueDataPacket($pk); return true; }elseif($this->class === TILE_FURNACE){ $player->windowCnt++; @@ -311,7 +314,7 @@ class Tile extends Position{ $pk->x = $this->x; $pk->y = $this->y; $pk->z = $this->z; - $player->dataPacket($pk); + $player->blockQueueDataPacket($pk); $slots = []; for($s = 0; $s < FURNACE_SLOTS; ++$s){ @@ -325,7 +328,7 @@ class Tile extends Position{ $pk = new ContainerSetContentPacket; $pk->windowid = $id; $pk->slots = $slots; - $player->dataPacket($pk); + $player->blockQueueDataPacket($pk); return true; } } @@ -375,7 +378,7 @@ class Tile extends Position{ $pk->y = $this->y; $pk->z = $this->z; $pk->namedtag = $nbt->binary; - $player->dataPacketAlwaysRecover($pk); + $player->blockQueueDataPacket($pk); break; case TILE_SIGN: $nbt = new NBT(); @@ -420,7 +423,7 @@ class Tile extends Position{ $pk->y = $this->y; $pk->z = $this->z; $pk->namedtag = $nbt->binary; - $player->dataPacketAlwaysRecover($pk); + $player->blockQueueDataPacket($pk); break; } } From 37e2919f46db18c52622165dc383281be9cb13f9 Mon Sep 17 00:00:00 2001 From: GameHerobrine Date: Thu, 26 Jun 2025 04:57:12 +0300 Subject: [PATCH 02/16] entity data packets are sent as ordered reliable packets in entity queue, explosions dont send what blocks they exploded in ExplosionPacket --- src/API/EntityAPI.php | 10 ++ src/API/PlayerAPI.php | 7 +- src/Player.php | 211 +++++++++++++++------------- src/entity/Creature.php | 8 +- src/entity/Entity.php | 17 +-- src/entity/Projectile.php | 4 +- src/entity/object/Arrow.php | 2 +- src/entity/object/FallingSand.php | 2 +- src/entity/object/ItemEntity.php | 4 +- src/entity/object/Minecart.php | 4 +- src/entity/object/Painting.php | 2 +- src/entity/object/PrimedTNT.php | 2 +- src/network/raknet/RakNetPacket.php | 4 +- src/world/Explosion.php | 25 ++-- 14 files changed, 166 insertions(+), 136 deletions(-) diff --git a/src/API/EntityAPI.php b/src/API/EntityAPI.php index 6d64f453..4c0fe8a6 100644 --- a/src/API/EntityAPI.php +++ b/src/API/EntityAPI.php @@ -1,6 +1,9 @@ x - $radius)) >> 4; $minChunkZ = ((int)($center->z - $radius)) >> 4; diff --git a/src/API/PlayerAPI.php b/src/API/PlayerAPI.php index 75dd7055..9e74f1ca 100644 --- a/src/API/PlayerAPI.php +++ b/src/API/PlayerAPI.php @@ -148,8 +148,7 @@ class PlayerAPI{ if($additional){ $arqCnt = count($p->packetAlwaysRecoverQueue); $rqCnt = count($p->recoveryQueue); - $emps = $p->entityMovementPacketsPerSecond; - $additionalInfo = "ARQ/RQ/EMPS: $arqCnt/$rqCnt/$emps"; + $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"; @@ -452,7 +451,7 @@ class PlayerAPI{ $pk->z = -256; $pk->yaw = 0; $pk->pitch = 0; - $player->dataPacketAlwaysRecover($pk); + $player->entityQueueDataPacket($pk); } } } @@ -489,7 +488,7 @@ class PlayerAPI{ $pk->z = -256; $pk->yaw = 0; $pk->pitch = 0; - $p->dataPacket($pk); + $p->entityQueueDataPacket($pk); } } } diff --git a/src/Player.php b/src/Player.php index 25738e78..9b60e5c9 100755 --- a/src/Player.php +++ b/src/Player.php @@ -3,6 +3,7 @@ class Player{ const CHATMESSAGE_ORDER_CHANNEL = 1; const BLOCKUPDATE_ORDER_CHANNEL = 2; + const ENTITY_ORDER_CHANNEL = 3; public static $experimentalHotbar = false; public static $allowDroppingSingleItems = true; @@ -88,19 +89,11 @@ class Player{ public $bedPosition = null; /** - * DataPacket that is used as a buffer for all non-player entity movement packets * @var RakNetPacket */ - public $entityMovementQueue; - public $entityMovementQueuePrevSentCnt = 0; - public $entityMovementQueueLength = 0; - - /** - * Used only for statistic in ping command. - * @var integer - */ - public $entityMovementPacketsPerSecond = 0; - public $lastEntityMovementPacketsPerSecondRecordedTime = 0; + public $entityDataQueue; + public $entityDataQueueLength = 0; + public $entityDataQueueOrderIndex = 0; public $blockUpdateQueue; public $blockUpdateQueueLength = 0; @@ -160,8 +153,8 @@ class Player{ $this->buffer = new RakNetPacket(RakNetInfo::DATA_PACKET_0); $this->buffer->data = []; - $this->entityMovementQueue = new RakNetPacket(RakNetInfo::DATA_PACKET_0); - $this->entityMovementQueue->data = []; + $this->entityDataQueue = new RakNetPacket(RakNetInfo::DATA_PACKET_0); + $this->entityDataQueue->data = []; $this->blockUpdateQueue = new RakNetPacket(RakNetInfo::DATA_PACKET_0); $this->blockUpdateQueue->data = []; @@ -283,7 +276,7 @@ class Player{ $pk->yaw = 0; $pk->pitch = 0; $pk->bodyYaw = 0; - $e->player->dataPacketAlwaysRecover($pk); + $e->player->entityQueueDataPacket($pk); $pk = new MovePlayerPacket(); $pk->eid = $e->eid; @@ -293,7 +286,7 @@ class Player{ $pk->yaw = 0; $pk->pitch = 0; $pk->bodyYaw = 0; - $this->dataPacketAlwaysRecover($pk); + $this->entityQueueDataPacket($pk); }else{ $pk = new MoveEntityPacket_PosRot(); @@ -303,7 +296,7 @@ class Player{ $pk->z = -256; $pk->yaw = 0; $pk->pitch = 0; - $this->dataPacketAlwaysRecover($pk); + $this->entityQueueDataPacket($pk); } } } @@ -328,7 +321,7 @@ class Player{ $pk->z = $e->z; $pk->yaw = $e->yaw; $pk->pitch = $e->pitch; - $this->dataPacketAlwaysRecover($pk); + $this->entityQueueDataPacket($pk); } } } @@ -346,14 +339,14 @@ class Player{ $pk->z = $player->entity->z; $pk->yaw = $player->entity->yaw; $pk->pitch = $player->entity->pitch; - $this->dataPacketAlwaysRecover($pk); + $this->entityQueueDataPacket($pk); $pk = new PlayerEquipmentPacket; $pk->eid = $this->eid; $pk->item = $this->getSlot($this->slot)->getID(); $pk->meta = $this->getSlot($this->slot)->getMetadata(); $pk->slot = 0; - $player->dataPacket($pk); + $player->entityQueueDataPacket($pk); $this->sendArmor($player); $pk = new PlayerEquipmentPacket; @@ -361,7 +354,7 @@ class Player{ $pk->item = $player->getSlot($player->slot)->getID(); $pk->meta = $player->getSlot($player->slot)->getMetadata(); $pk->slot = 0; - $this->dataPacket($pk); + $this->entityQueueDataPacket($pk); $player->sendArmor($this); } } @@ -394,7 +387,7 @@ class Player{ $pk->speedX = 0; $pk->speedY = 0; $pk->speedZ = 0; - $this->dataPacket($pk); + $this->entityQueueDataPacket($pk); $pk = new MovePlayerPacket; $pk->eid = 0; @@ -404,7 +397,7 @@ class Player{ $pk->bodyYaw = $yaw; $pk->pitch = $pitch; $pk->yaw = $yaw; - $this->dataPacket($pk); + $this->entityQueueDataPacket($pk); } /** @@ -523,6 +516,44 @@ class Player{ return $cnts; } + public function entityQueueDataPacket_big(RakNetDataPacket $pk){ + $sendtime = microtime(true); + $size = $this->MTU - 34; + if($size <= 0) return false; + $buffer = str_split($pk->buffer, $size); + $bigCnt = $this->bigCnt; + $this->bigCnt = ($this->bigCnt + 1) % 0x10000; + $cnts = []; + $bufCount = count($buffer); + + $orderIndex = $this->entityDataQueueOrderIndex++; + foreach($buffer as $i => $buf){ + $cnts[] = $count = $this->counter[0]++; + + $pk = new UnknownPacket; + $pk->packetID = $pk->pid(); + $pk->reliability = 3; + + $pk->orderChannel = Player::ENTITY_ORDER_CHANNEL; + $pk->orderIndex = $orderIndex; + + $pk->hasSplit = true; + $pk->splitCount = $bufCount; + $pk->splitID = $bigCnt; + $pk->splitIndex = $i; + $pk->buffer = $buf; + $pk->messageIndex = $this->counter[3]++; + + $rk = new RakNetPacket(RakNetInfo::DATA_PACKET_0); + $rk->data[] = $pk; + $rk->seqNumber = $count; + $rk->sendtime = $sendtime; + $this->packetAlwaysRecoverQueue[$count] = $rk; + $this->send($rk); + } + return $cnts; + } + public function sendBigPacketAlwaysRecover(RakNetDataPacket $pk){ if($this->connected === false) return false; if(EventHandler::callEvent(new DataPacketSendEvent($this, $pk)) === BaseEvent::DENY) return; @@ -675,12 +706,12 @@ class Player{ $pk = new ContainerSetContentPacket; $pk->windowid = 0x78; //Armor window id $pk->slots = $this->armor; - $this->dataPacket($pk); + $this->entityQueueDataPacket($pk); }else{ $pk = new PlayerArmorEquipmentPacket; $pk->eid = $this->eid; $pk->slots = $data["slots"]; - $player->dataPacket($pk); + $player->entityQueueDataPacket($pk); } }else{ $this->server->api->dhandle("player.armor", $data); @@ -945,7 +976,7 @@ class Player{ $pk->rider = $data["rider"] == $this->entity->eid ? 0 : $data["rider"]; $pk->riding = $data["riding"] == $this->entity->eid ? 0 : $data["riding"]; $pk->type = 0; - $this->dataPacket($pk); + $this->entityQueueDataPacket($pk); break; case "tile.update": if($data->level === $this->level){ @@ -990,7 +1021,7 @@ class Player{ $pk = new PlayerArmorEquipmentPacket; $pk->eid = $data["eid"]; $pk->slots = $data["slots"]; - $this->dataPacket($pk); + $this->entityQueueDataPacket($pk); } break; case "player.pickup": @@ -999,7 +1030,7 @@ class Player{ $pk = new TakeItemEntityPacket; $pk->eid = 0; $pk->target = $data["entity"]->eid; - $this->dataPacket($pk); + $this->entityQueueDataPacket($pk); if(($this->gamemode & 0x01) === 0x00){ $this->addItem($data["entity"]->itemID, $data["entity"]->meta, $data["entity"]->stack, false); @@ -1019,7 +1050,7 @@ class Player{ $pk = new TakeItemEntityPacket; $pk->eid = $data["eid"]; $pk->target = $data["entity"]->eid; - $this->dataPacket($pk); + $this->entityQueueDataPacket($pk); } break; case "player.equipment.change": @@ -1033,7 +1064,7 @@ class Player{ $pk->item = $data["item"]->getID(); $pk->meta = $data["item"]->getMetadata(); $pk->slot = $data["slot"]; - $this->dataPacket($pk); + $this->entityQueueDataPacket($pk); break; case "entity.motion": @@ -1048,13 +1079,13 @@ class Player{ $pk->speedX = $data->speedX; $pk->speedY = $data->speedY; $pk->speedZ = $data->speedZ; - $this->dataPacket($pk); + $this->entityQueueDataPacket($pk); break; case "entity.animate": $pk = new AnimatePacket; $pk->eid = $data["eid"]; $pk->action = $data["action"]; //1 swing arm, - $this->dataPacket($pk); + $this->entityQueueDataPacket($pk); break; case "entity.metadata": if($data->eid === $this->eid){ @@ -1066,7 +1097,7 @@ class Player{ $pk = new SetEntityDataPacket; $pk->eid = $eid; $pk->metadata = $data->getMetadata(); - $this->dataPacket($pk); + $this->entityQueueDataPacket($pk); } break; case "entity.event": @@ -1079,7 +1110,7 @@ class Player{ $pk = new EntityEventPacket; $pk->eid = $eid; $pk->event = $data["event"]; - $this->dataPacket($pk); + $this->entityQueueDataPacket($pk); } break; case "server.chat": @@ -1175,9 +1206,10 @@ class Player{ } public function makeInvisibleForOnePlayer(Player $player){ + //TODO rewrite how invisibility is handled $pk = new RemoveEntityPacket; $pk->eid = $this->entity->eid; - $player->dataPacket($pk); + $player->entityQueueDataPacket($pk); } public function makeInvisibleForAllPlayers(){ $pk = new RemoveEntityPacket; @@ -1392,11 +1424,6 @@ class Player{ $this->ackQueue = []; } - if($time - $this->lastEntityMovementPacketsPerSecondRecordedTime > 1){ - $this->entityMovementPacketsPerSecond = 0; - $this->lastEntityMovementPacketsPerSecondRecordedTime = $time; - } - if($this->sendingInventoryRequired){ //console("inv resent"); if(($this->gamemode & 0x01) !== CREATIVE){ @@ -1465,7 +1492,8 @@ class Player{ } foreach($this->packetAlwaysRecoverQueue as $cnt => $data){ - if($time - $data->sendtime >= 5){ + $maxDelay = (isset($this->chunkCount[$cnt])) ? 1 : 5; + if($time - $data->sendtime >= $maxDelay){ $this->resendQueue[$cnt] = $data; } } @@ -1495,13 +1523,13 @@ class Player{ } public function sendEntityMovementUpdateQueue(){ - if($this->entityMovementQueueLength > 0 && $this->entityMovementQueue instanceof RakNetPacket){ - $this->entityMovementQueue->seqNumber = $this->counter[0]++; - $this->send($this->entityMovementQueue); + if($this->entityDataQueueLength > 0 && $this->entityDataQueue instanceof RakNetPacket){ + $this->entityDataQueue->seqNumber = $this->counter[0]++; + $this->send($this->entityDataQueue); } - $this->entityMovementQueueLength = 0; - $this->entityMovementQueue = new RakNetPacket(RakNetInfo::DATA_PACKET_0); - $this->entityMovementQueue->data = []; + $this->entityDataQueueLength = 0; + $this->entityDataQueue = new RakNetPacket(RakNetInfo::DATA_PACKET_0); + $this->entityDataQueue->data = []; } public function sendBlockUpdateQueue(){ @@ -1543,6 +1571,32 @@ class Player{ $this->blockUpdateQueueLength += 10 + $len; } + /** + * Sends a packet in entity order channel. Packets are always delivered and ordered. + * + */ + public function entityQueueDataPacket(RakNetDataPacket $pk){ + if($this->connected === false) return false; + if(EventHandler::callEvent(new DataPacketSendEvent($this, $pk)) === BaseEvent::DENY) return; + + $pk->encode(); + + $len = 1 + strlen($pk->buffer); + $MTU = $this->MTU - 24; + if($len > $MTU) return $this->entityQueueDataPacket_big($pk); + + if(($this->entityDataQueueLength + $len) >= $MTU){ + $this->sendEntityMovementUpdateQueue(); + } + + $pk->messageIndex = $this->counter[3]++; + $pk->reliability = 3; + $pk->orderChannel = Player::ENTITY_ORDER_CHANNEL; + $pk->orderIndex = $this->entityDataQueueOrderIndex++; + @$this->entityDataQueue->data[] = $pk; + $this->entityDataQueueLength += 10 + $len; + } + /** * Adds block update into queue. Does nothing if chunk wasnt loaded. * @param int $x @@ -1569,11 +1623,6 @@ class Player{ } public function addEntityMovementUpdateToQueue(Entity $e){ - $len = 0; - $packets = 0; - $motionSent = false; - $moveSent = false; - $headSent = false; $svdYSpeed = $e->speedY; if($e->modifySpeedY){ $e->speedY = $e->modifedSpeedY; @@ -1585,10 +1634,7 @@ class Player{ $motion->speedX = $e->speedX; $motion->speedY = $e->speedY; $motion->speedZ = $e->speedZ; - $motion->encode(); - $len += 1 + strlen($motion->buffer); - ++$packets; - $motionSent = true; + $this->entityQueueDataPacket($motion); } } if($e->modifySpeedY){ @@ -1606,7 +1652,7 @@ class Player{ $move->yaw = $e->yaw; $move->pitch = $e->pitch; $move->bodyYaw = $e->headYaw; - $move->encode(); + $this->entityQueueDataPacket($move); }else{ $move = new MoveEntityPacket_PosRot(); $move->eid = $e->eid; @@ -1615,45 +1661,14 @@ class Player{ $move->z = $e->z; $move->yaw = $e->yaw; $move->pitch = $e->pitch; - $move->encode(); + $this->entityQueueDataPacket($move); } - - $len += strlen($move->buffer) + 1; - ++$packets; - $moveSent = true; }else if($e->headYaw != $e->lastHeadYaw){ $headyaw = new RotateHeadPacket(); $headyaw->eid = $e->eid; $headyaw->yaw = $e->headYaw; - $headyaw->encode(); - $len += strlen($headyaw->buffer) + 1; - ++$packets; - $headSent = true; + $this->entityQueueDataPacket($headyaw); } - if($packets <= 0) return; - //console("Update {$e}: $packets, mot: $motionSent, mov: $moveSent, hed: $headSent"); - $MTU = $this->MTU - 24; - if(($this->entityMovementQueueLength + $len) >= $MTU){ - $this->sendEntityMovementUpdateQueue(); - } - if($motionSent){ - $motion->messageIndex = 0; //force 0 cuz reliability 0 - $motion->reliability = 0; - $this->entityMovementQueue->data[] = $motion; - } - if($moveSent){ - $move->messageIndex = 0; - $move->reliability = 0; - $this->entityMovementQueue->data[] = $move; - } - if($headSent){ - $headyaw->messageIndex = 0; - $headyaw->reliability = 0; - $this->entityMovementQueue->data[] = $headyaw; - } - - $this->entityMovementQueueLength += 6*$packets + $len; - $this->entityMovementPacketsPerSecond += $packets; } /** @@ -2007,13 +2022,8 @@ class Player{ $this->lastMeasure = microtime(true); $this->server->schedule(50, [$this, "measureLag"], [], true); - $pk = new SetTimePacket; - $pk->time = $this->level->getTime(); - $pk->started = !$this->level->isTimeStopped(); - $this->dataPacket($pk); - - console("[INFO] " . FORMAT_AQUA . $this->username . FORMAT_RESET . "[/" . $this->ip . ":" . $this->port . "] logged in with entity id " . $this->eid . " at (" . $this->entity->level->getName() . ", " . round($this->entity->x, 2) . ", " . round($this->entity->y, 2) . ", " . round($this->entity->z, 2) . ")"); + console("[INFO] " . FORMAT_AQUA . $this->username . FORMAT_RESET . "[/" . $this->ip . ":" . $this->port . "] logged in with entity id " . $this->eid . " at (" . $this->entity->level->getName() . ", " . round($this->entity->x, 2) . ", " . round($this->entity->y, 2) . ", " . round($this->entity->z, 2) . ") MTU: {$this->MTU}"); break; case ProtocolInfo::READY_PACKET: if($this->loggedIn === false){ @@ -2025,6 +2035,12 @@ class Player{ break; } + $pk = new SetTimePacket; + $pk->time = $this->level->getTime(); + $pk->started = !$this->level->isTimeStopped(); + $this->dataPacketAlwaysRecover($pk); + console($this->level->getTime()); + $pos = new Position($this->entity->x, $this->entity->y, $this->entity->z, $this->level); $pData = $this->data->get("position"); $this->entity->setHealth($this->data->get("health"), "spawn", true, allowHarm: false); @@ -2504,7 +2520,7 @@ class Player{ $pk->bodyYaw = $this->entity->headYaw; foreach($this->entity->level->players as $player){ if($player->entity->eid != $this->entity->eid){ - $player->dataPacket(clone $pk); + $player->entityQueueDataPacket(clone $pk); } } @@ -2543,7 +2559,7 @@ class Player{ $pk = new EntityEventPacket; $pk->eid = 0; $pk->event = EntityEventPacket::ENTITY_COMPLETE_USING_ITEM; - $this->dataPacket($pk); + $this->entityQueueDataPacket($pk); $this->entity->heal($foodHeal, "eating"); --$slot->count; @@ -3144,6 +3160,7 @@ class Player{ foreach($packet->packets as $count){ if(isset($this->packetAlwaysRecoverQueue[$count])){ $this->lag[] = $time - $this->packetAlwaysRecoverQueue[$count]->sendtime; + unset($this->packetAlwaysRecoverQueue[$count]); unset($this->chunkCount[$count]); }else if(isset($this->recoveryQueue[$count])){ diff --git a/src/entity/Creature.php b/src/entity/Creature.php index b472686d..a3254b6a 100644 --- a/src/entity/Creature.php +++ b/src/entity/Creature.php @@ -57,9 +57,6 @@ abstract class Creature extends Living{ return 0; } public function spawn($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)){ return false; } @@ -72,18 +69,19 @@ abstract class Creature extends Living{ $pk->yaw = $this->yaw; $pk->pitch = $this->pitch; $pk->metadata = $this->getMetadata(); - $player->dataPacketAlwaysRecover($pk); + $player->entityQueueDataPacket($pk); $pk = new SetEntityMotionPacket; $pk->eid = $this->eid; $pk->speedX = $this->speedX; $pk->speedY = $this->speedY; $pk->speedZ = $this->speedZ; - $player->dataPacket($pk); + $player->entityQueueDataPacket($pk); if($this->linkedEntity != 0 && $this->isRider){ $player->eventHandler(["rider" => $this->eid, "riding" => $this->linkedEntity, "type" => 0], "entity.link"); } + return true; } } diff --git a/src/entity/Entity.php b/src/entity/Entity.php index 7ed6fcca..214b2307 100644 --- a/src/entity/Entity.php +++ b/src/entity/Entity.php @@ -1132,11 +1132,12 @@ class Entity extends Position $this->server->api->dhandle("entity.metadata", $this); } + /** + * @param Player $player + * @return boolean + */ public function spawn($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)){ return false; } @@ -1160,14 +1161,14 @@ class Entity extends Position $pk->itemID = 0; $pk->itemAuxValue = 0; $pk->metadata = $this->getMetadata(); - $player->dataPacketAlwaysRecover($pk, 2, true); + $player->entityQueueDataPacket($pk, 2, true); $pk = new PlayerEquipmentPacket(); $pk->eid = $this->eid; $pk->item = $this->player->getSlot($this->player->slot)->getID(); $pk->meta = $this->player->getSlot($this->player->slot)->getMetadata(); $pk->slot = 0; - $player->dataPacket($pk); + $player->entityQueueDataPacket($pk); $this->player->sendArmor($player); break; } @@ -1600,9 +1601,9 @@ class Entity extends Position if(($p->entity instanceof Entity) && $p->entity->eid == $this->eid){ $pk2 = clone $pk; $pk2->eid = 0; - $p->dataPacket($pk2); + $p->entityQueueDataPacket($pk2); }else{ - $p->dataPacket(clone $pk); + $p->entityQueueDataPacket(clone $pk); } } } @@ -1610,7 +1611,7 @@ class Entity extends Position if($this->player instanceof Player){ $pk = new SetHealthPacket(); $pk->health = $this->health; - $this->player->dataPacket($pk); + $this->player->entityQueueDataPacket($pk); } if($this->health <= 0 and $this->dead === false){ $this->makeDead($cause); diff --git a/src/entity/Projectile.php b/src/entity/Projectile.php index 534d5473..7042daa1 100644 --- a/src/entity/Projectile.php +++ b/src/entity/Projectile.php @@ -198,6 +198,7 @@ abstract class Projectile extends Entity{ return $data; } + public function spawn($player) { $pk = new AddEntityPacket(); @@ -210,7 +211,8 @@ abstract class Projectile extends Entity{ $pk->speedY = $this->speedY; $pk->speedZ = $this->speedZ; $pk->did = 0; - $player->dataPacketAlwaysRecover($pk); + $player->entityQueueDataPacket($pk); + return true; } } \ No newline at end of file diff --git a/src/entity/object/Arrow.php b/src/entity/object/Arrow.php index 216afc49..f55a49cd 100644 --- a/src/entity/object/Arrow.php +++ b/src/entity/object/Arrow.php @@ -272,7 +272,7 @@ class Arrow extends Entity{ $pk->speedX = $this->speedX; $pk->speedY = $this->speedY; $pk->speedZ = $this->speedZ; - $player->dataPacketAlwaysRecover($pk); + $player->entityQueueDataPacket($pk); } } } diff --git a/src/entity/object/FallingSand.php b/src/entity/object/FallingSand.php index 3c040340..8481830e 100644 --- a/src/entity/object/FallingSand.php +++ b/src/entity/object/FallingSand.php @@ -31,7 +31,7 @@ class FallingSand extends Entity{ $pk->speedY = $this->speedY; $pk->speedZ = $this->speedZ; $pk->did = -$this->data["Tile"]; - $player->dataPacketAlwaysRecover($pk); + $player->entityQueueDataPacket($pk); } public function update($now){ diff --git a/src/entity/object/ItemEntity.php b/src/entity/object/ItemEntity.php index 2f44ee25..e24726fe 100644 --- a/src/entity/object/ItemEntity.php +++ b/src/entity/object/ItemEntity.php @@ -54,14 +54,14 @@ class ItemEntity extends Entity{ $pk->roll = 0; $pk->item = BlockAPI::getItem($this->itemID, $this->meta, $this->stack); $pk->metadata = $this->getMetadata(); - $player->dataPacketAlwaysRecover($pk); + $player->entityQueueDataPacket($pk); $pk = new SetEntityMotionPacket(); $pk->eid = $this->eid; $pk->speedX = $this->speedX; $pk->speedY = $this->speedY; $pk->speedZ = $this->speedZ; - $player->dataPacket($pk); + $player->entityQueueDataPacket($pk); } diff --git a/src/entity/object/Minecart.php b/src/entity/object/Minecart.php index ab48a67a..326e6adc 100644 --- a/src/entity/object/Minecart.php +++ b/src/entity/object/Minecart.php @@ -435,14 +435,14 @@ class Minecart extends Vehicle{ $pk->z = $this->z; $pk->yaw = $this->yaw; $pk->pitch = $this->pitch; - $player->dataPacketAlwaysRecover($pk); + $player->entityQueueDataPacket($pk); $pk = new SetEntityMotionPacket; $pk->eid = $this->eid; $pk->speedX = $this->speedX; $pk->speedY = $this->speedY; $pk->speedZ = $this->speedZ; - $player->dataPacket($pk); + $player->entityQueueDataPacket($pk); } public function interactWith(Entity $e, $action){ diff --git a/src/entity/object/Painting.php b/src/entity/object/Painting.php index 6a49d48a..20bb25e9 100644 --- a/src/entity/object/Painting.php +++ b/src/entity/object/Painting.php @@ -205,6 +205,6 @@ class Painting extends Entity{ $pk->z = (int) $this->zPos; $pk->direction = $this->direction; $pk->title = $this->motive; - $player->dataPacketAlwaysRecover($pk); + $player->entityQueueDataPacket($pk); } } diff --git a/src/entity/object/PrimedTNT.php b/src/entity/object/PrimedTNT.php index 75a8825d..2585e917 100644 --- a/src/entity/object/PrimedTNT.php +++ b/src/entity/object/PrimedTNT.php @@ -76,6 +76,6 @@ class PrimedTNT extends Entity{ $pk->speedX = $this->speedX; $pk->speedY = $this->speedY; $pk->speedZ = $this->speedZ; - $player->dataPacketAlwaysRecover($pk); + $player->entityQueueDataPacket($pk); } } \ No newline at end of file diff --git a/src/network/raknet/RakNetPacket.php b/src/network/raknet/RakNetPacket.php index d97f8812..870a2733 100644 --- a/src/network/raknet/RakNetPacket.php +++ b/src/network/raknet/RakNetPacket.php @@ -3,7 +3,9 @@ class RakNetPacket extends Packet{ public $packetID; - + public $seqNumber; + public $sendtime; + public function __construct($packetID){ $this->packetID = (int) $packetID; } diff --git a/src/world/Explosion.php b/src/world/Explosion.php index 0a8e041d..25a05aef 100644 --- a/src/world/Explosion.php +++ b/src/world/Explosion.php @@ -85,18 +85,20 @@ class Explosion{ $pk->speedX = $entity->speedX; $pk->speedY = $entity->speedY; $pk->speedZ = $entity->speedZ; - $entity->player->dataPacket($pk); + $entity->player->entityQueueDataPacket($pk); } } } } - $pk = new ExplodePacket; //sound fix + $pk = new ExplodePacket; $pk->x = $this->source->x; $pk->y = $this->source->y; $pk->z = $this->source->z; $pk->radius = $this->size; - $pk->records = []; - $server->api->player->broadcastPacket($this->level->players, $pk); + $pk->records = []; //ExplodePacket doesnt seem to use the records provided by this packet, so no need to send more data + foreach ($this->level->players as $player){ + $player->blockQueueDataPacket($pk); + } return; } if($this->size < 0.1 or $server->api->dhandle("entity.explosion", [ @@ -147,10 +149,7 @@ class Explosion{ $this->sub_expl($i, $mRays, $j, $k); } } - //if($i == 0 or $i == $mRays or $j == 0 or $j == $mRays or $k == 0 or $k == $mRays){ - - $send = []; foreach($server->api->entity->getRadius($this->source, $radius) as $entity){ $distance = $this->source->distance($entity); $distByRad = $distance / $this->size; @@ -173,7 +172,7 @@ class Explosion{ $pk->speedX = $entity->speedX; $pk->speedY = $entity->speedY; $pk->speedZ = $entity->speedZ; - $entity->player->dataPacket($pk); + $entity->player->entityQueueDataPacket($pk); } } } @@ -185,7 +184,7 @@ class Explosion{ $x = $xyz >> 16; $z = $xyz >> 8 & 0xff; $y = $xyz & 0xff; - //console("$x $y $z $id $meta"); + if($id === TNT){ $data = [ "x" => $x + 0.5, @@ -206,15 +205,17 @@ class Explosion{ } } $this->level->fastSetBlockUpdate($x, $y, $z, 0, 0, true); - $send[] = $xyz; } + $pk = new ExplodePacket; $pk->x = $this->source->x; $pk->y = $this->source->y; $pk->z = $this->source->z; $pk->radius = $this->size; - $pk->records = $send; - $server->api->player->broadcastPacket($this->level->players, $pk); + $pk->records = []; //ExplodePacket doesnt seem to use the records provided by this packet, so no need to send more data + foreach ($this->level->players as $player){ + $player->blockQueueDataPacket($pk); + } } From 756c597e47837808c735be564704d92c6c143048 Mon Sep 17 00:00:00 2001 From: GameHerobrine Date: Thu, 26 Jun 2025 08:17:14 +0300 Subject: [PATCH 03/16] rewritten pumpkin and melon growth, fixed new world generation --- src/entity/Entity.php | 3 +- src/material/block/plant/MelonStemBlock.php | 103 +++++++++++----- src/material/block/plant/PumpkinStemBlock.php | 112 ++++++++++++------ src/pmf/PMFLevel.php | 1 + 4 files changed, 149 insertions(+), 70 deletions(-) diff --git a/src/entity/Entity.php b/src/entity/Entity.php index 214b2307..f13e36b5 100644 --- a/src/entity/Entity.php +++ b/src/entity/Entity.php @@ -118,7 +118,7 @@ class Entity extends Position public $moveStrafing, $moveForward; - function __construct(Level $level, $eid, $class, $type = 0, $data = []) + public function __construct(Level $level, $eid, $class, $type = 0, $data = []) { $this->random = new XorShift128Random(); $this->last = [&$this->lastX, &$this->lastY, &$this->lastZ, &$this->lastYaw, &$this->lastPitch, &$this->lastTime]; //pointers to variables @@ -202,6 +202,7 @@ class Entity extends Position $this->outOfWorld(); } } + public function handlePrePlayerSearcher(){ } diff --git a/src/material/block/plant/MelonStemBlock.php b/src/material/block/plant/MelonStemBlock.php index c98d8677..8042d889 100644 --- a/src/material/block/plant/MelonStemBlock.php +++ b/src/material/block/plant/MelonStemBlock.php @@ -17,34 +17,79 @@ class MelonStemBlock extends FlowableBlock{ } return false; } + + public static function getGrowthSpeed(Level $level, $x, $y, $z){ + $zneg = $level->level->getBlockID($x, $y, $z-1); + $zpos = $level->level->getBlockID($x, $y, $z+1); + $xneg = $level->level->getBlockID($x-1, $y, $z); + $xpos = $level->level->getBlockID($x+1, $y, $z); + $znxn = $level->level->getBlockID($x-1, $y, $z-1); + $znxp = $level->level->getBlockID($x+1, $y, $z-1); + $zpxp = $level->level->getBlockID($x+1, $y, $z+1); + $zpxn = $level->level->getBlockID($x-1, $y, $z+1); + $xEqual = $xneg == MELON_STEM || $xpos == MELON_STEM; + $zEqual = $zneg == MELON_STEM || $zpos == MELON_STEM; + $xzEqual = $znxn == MELON_STEM || $znxp == MELON_STEM || $zpxn == MELON_STEM || $zpxp == MELON_STEM; + + $speed = 1; + for($xx = $x-1; $xx >= $x+1; ++$xx){ + for($zz = $z-1; $zz >= $z+1; ++$zz){ + [$id, $meta] = $level->level->getBlock($x, $y, $z); + $v18 = 0; + if($id == FARMLAND) $v18 = $meta > 0 ? 3 : 1; + if($xx != $x || $zz != $z) $v18 *= 0.25; + $speed += $v18; + } + } + if($xzEqual || ($xEqual && $zEqual)) return $speed*0.5; + return $speed; + } + public static function onRandomTick(Level $level, $x, $y, $z){ - if(mt_rand(0, 2) == 1){ - $block = $level->level->getBlock($x, $y, $z); - if($block[1] < 0x07){ - //++$this->meta; - //$this->level->setBlock($this, $this, true, false, true); - $level->fastSetBlockUpdate($x, $y, $z, $block[0], $block[1] + 1); - }else{ - - $position = new AirBlock(); //feke block - $position->x = $x; - $position->y = $y; - $position->z = $z; - $position->level = $level; - for($side = 2; $side <= 5; ++$side){ - $b = $position->getSide($side); - if($b->getID() === MELON_BLOCK){ - return; - } - } - $side = $position->getSide(mt_rand(2,5)); - $d = $side->getSide(0); - if($side->getID() === AIR and ($d->getID() === FARMLAND or $d->getID() === GRASS or $d->getID() === DIRT)){ - $level->setBlock($side, new MelonBlock(), true, false, true); - } + //TODO checkAlive + //if ( Level::getRawBrightness(a2, a3, a4 + 1, a5) > 8 ) TODO - skylight + + $growSpeed = static::getGrowthSpeed($level, $x, $y, $z); + $rand = mt_rand(0, (int)(25/$growSpeed)); + if($rand != 0) return; + + $meta = $level->level->getBlockDamage($x, $y, $z); + if($meta <= 6){ + $level->fastSetBlockUpdateMeta($x, $y, $z, $meta+1); + return; + } + + $xn = $level->level->getBlockID($x-1, $y, $z); + $xp = $level->level->getBlockID($x+1, $y, $z); + $zn = $level->level->getBlockID($x, $y, $z-1); + $zp = $level->level->getBlockID($x, $y, $z+1); + if($xn != MELON_BLOCK && $xp != MELON_BLOCK && $zn != MELON_BLOCK && $zp != MELON_BLOCK){ + $below = $level->level->getBlockID($x-1, $y-1, $z); + if($level->level->getBlockID($x-1, $y, $z) == 0 && ($below == FARMLAND || $below == DIRT || $below == GRASS)){ + $level->fastSetBlockUpdate($x-1, $y, $z, MELON_BLOCK, 0); + return; + } + + $below = $level->level->getBlockID($x+1, $y-1, $z); + if($level->level->getBlockID($x+1, $y, $z) == 0 && ($below == FARMLAND || $below == DIRT || $below == GRASS)){ + $level->fastSetBlockUpdate($x+1, $y, $z, MELON_BLOCK, 0); + return; + } + + $below = $level->level->getBlockID($x, $y-1, $z-1); + if($level->level->getBlockID($x, $y, $z-1) == 0 && ($below == FARMLAND || $below == DIRT || $below == GRASS)){ + $level->fastSetBlockUpdate($x, $y, $z-1, MELON_BLOCK, 0); + return; + } + + $below = $level->level->getBlockID($x, $y-1, $z+1); + if($level->level->getBlockID($x, $y, $z+1) == 0 && ($below == FARMLAND || $below == DIRT || $below == GRASS)){ + $level->fastSetBlockUpdate($x, $y, $z+1, MELON_BLOCK, 0); + return; } } } + public static function neighborChanged(Level $level, $x, $y, $z, $nX, $nY, $nZ, $oldID){ if($level->level->getBlockID($x, $y - 1, $z) != FARMLAND){ ServerAPI::request()->api->entity->drop(new Position($x+0.5, $y, $z+0.5, $level), BlockAPI::getItem(MELON_SEEDS, 0, mt_rand(0, 2))); @@ -67,14 +112,8 @@ class MelonStemBlock extends FlowableBlock{ public function getDrops(Item $item, Player $player){ $drops = []; - if($this->meta >= 0x07){ - $drops[] = [MELON_SEEDS, 0, mt_rand(1, 2)]; - } - elseif($this->meta >= 0x01 and $this->meta <= 0x07){ - $drops[] = [MELON_SEEDS, 0, 1]; - } - else{ - $drops[] = [MELON_SEEDS, 0, 0]; + for($i = 0; $i < 3; ++$i){ + if(mt_rand(0, 15) <= $this->meta) $drops[] = [MELON_SEEDS, 0, 1]; } return $drops; } diff --git a/src/material/block/plant/PumpkinStemBlock.php b/src/material/block/plant/PumpkinStemBlock.php index c662af3a..874e1a8e 100644 --- a/src/material/block/plant/PumpkinStemBlock.php +++ b/src/material/block/plant/PumpkinStemBlock.php @@ -10,38 +10,82 @@ class PumpkinStemBlock extends FlowableBlock{ $this->material = Material::$plant; } public function place(Item $item, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){ - $down = $this->getSide(0); - if($down->getID() === FARMLAND){ - $this->level->setBlock($block, $this, true, false, true); - return true; - } + $down = $this->getSide(0); + if($down->getID() === FARMLAND){ + $this->level->setBlock($block, $this, true, false, true); + return true; + } return false; } + + public static function getGrowthSpeed(Level $level, $x, $y, $z){ + $zneg = $level->level->getBlockID($x, $y, $z-1); + $zpos = $level->level->getBlockID($x, $y, $z+1); + $xneg = $level->level->getBlockID($x-1, $y, $z); + $xpos = $level->level->getBlockID($x+1, $y, $z); + $znxn = $level->level->getBlockID($x-1, $y, $z-1); + $znxp = $level->level->getBlockID($x+1, $y, $z-1); + $zpxp = $level->level->getBlockID($x+1, $y, $z+1); + $zpxn = $level->level->getBlockID($x-1, $y, $z+1); + $xEqual = $xneg == PUMPKIN_STEM || $xpos == PUMPKIN_STEM; + $zEqual = $zneg == PUMPKIN_STEM || $zpos == PUMPKIN_STEM; + $xzEqual = $znxn == PUMPKIN_STEM || $znxp == PUMPKIN_STEM || $zpxn == PUMPKIN_STEM || $zpxp == PUMPKIN_STEM; + + $speed = 1; + for($xx = $x-1; $xx >= $x+1; ++$xx){ + for($zz = $z-1; $zz >= $z+1; ++$zz){ + [$id, $meta] = $level->level->getBlock($x, $y, $z); + if($id == FARMLAND) $v18 = $meta > 0 ? 3 : 1; + else $v18 = 0; + if($xx != $x || $zz != $z) $v18 *= 0.25; + $speed += $v18; + } + } + if($xzEqual || ($xEqual && $zEqual)) return $speed*0.5; + return $speed; + } + public static function onRandomTick(Level $level, $x, $y, $z){ - if(mt_rand(0, 2) == 1){ - $block = $level->level->getBlock($x, $y, $z); - if($block[1] < 0x07){ - //++$this->meta; - //$this->level->setBlock($this, $this, true, false, true); - $level->fastSetBlockUpdate($x, $y, $z, $block[0], $block[1] + 1); - }else{ - - $position = new AirBlock(); //feke block - $position->x = $x; - $position->y = $y; - $position->z = $z; - $position->level = $level; - for($side = 2; $side <= 5; ++$side){ - $b = $position->getSide($side); - if($b->getID() === PUMPKIN){ - return; - } - } - $side = $position->getSide(mt_rand(2,5)); - $d = $side->getSide(0); - if($side->getID() === AIR and ($d->getID() === FARMLAND or $d->getID() === GRASS or $d->getID() === DIRT)){ - $level->setBlock($side, new PumpkinBlock(), true, false, true); - } + //TODO checkAlive + //if ( Level::getRawBrightness(a2, a3, a4 + 1, a5) > 8 ) TODO - skylight + + $growSpeed = static::getGrowthSpeed($level, $x, $y, $z); + $rand = mt_rand(0, (int)(25/$growSpeed)); + if($rand != 0) return; + + $meta = $level->level->getBlockDamage($x, $y, $z); + if($meta <= 6){ + $level->fastSetBlockUpdateMeta($x, $y, $z, $meta+1); + return; + } + + $xn = $level->level->getBlockID($x-1, $y, $z); + $xp = $level->level->getBlockID($x+1, $y, $z); + $zn = $level->level->getBlockID($x, $y, $z-1); + $zp = $level->level->getBlockID($x, $y, $z+1); + if($xn != PUMPKIN && $xp != PUMPKIN && $zn != PUMPKIN && $zp != PUMPKIN){ + $below = $level->level->getBlockID($x-1, $y-1, $z); + if($level->level->getBlockID($x-1, $y, $z) == 0 && ($below == FARMLAND || $below == DIRT || $below == GRASS)){ + $level->fastSetBlockUpdate($x-1, $y, $z, PUMPKIN, 0); + return; + } + + $below = $level->level->getBlockID($x+1, $y-1, $z); + if($level->level->getBlockID($x+1, $y, $z) == 0 && ($below == FARMLAND || $below == DIRT || $below == GRASS)){ + $level->fastSetBlockUpdate($x+1, $y, $z, PUMPKIN, 0); + return; + } + + $below = $level->level->getBlockID($x, $y-1, $z-1); + if($level->level->getBlockID($x, $y, $z-1) == 0 && ($below == FARMLAND || $below == DIRT || $below == GRASS)){ + $level->fastSetBlockUpdate($x, $y, $z-1, PUMPKIN, 0); + return; + } + + $below = $level->level->getBlockID($x, $y-1, $z+1); + if($level->level->getBlockID($x, $y, $z+1) == 0 && ($below == FARMLAND || $below == DIRT || $below == GRASS)){ + $level->fastSetBlockUpdate($x, $y, $z+1, PUMPKIN, 0); + return; } } } @@ -67,14 +111,8 @@ class PumpkinStemBlock extends FlowableBlock{ public function getDrops(Item $item, Player $player){ $drops = []; - if($this->meta >= 0x07){ - $drops[] = [PUMPKIN_SEEDS, 0, mt_rand(1, 2)]; - } - elseif($this->meta >= 0x01 and $this->meta <= 0x07){ - $drops[] = [PUMPKIN_SEEDS, 0, 1]; - } - else{ - $drops[] = [PUMPKIN_SEEDS, 0, 0]; + for($i = 0; $i < 3; ++$i){ + if(mt_rand(0, 15) <= $this->meta) $drops[] = [PUMPKIN_SEEDS, 0, 1]; } return $drops; } diff --git a/src/pmf/PMFLevel.php b/src/pmf/PMFLevel.php index 2e56276c..af575251 100644 --- a/src/pmf/PMFLevel.php +++ b/src/pmf/PMFLevel.php @@ -45,6 +45,7 @@ class PMFLevel extends PMF{ @mkdir($dirname , 0755); } + $this->hasLight = str_repeat("\x00", 16*16); for($index = 0; $index < $cnt; ++$index){ $this->chunks[$index] = false; $this->chunkChange[$index] = false; From 30eae88ebb255952c2f88aaca84b6def6afbb46c Mon Sep 17 00:00:00 2001 From: GameHerobrine Date: Thu, 26 Jun 2025 11:11:35 +0300 Subject: [PATCH 04/16] block update queue and entity data queue will be sent every tick if it contains any packets --- src/Player.php | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/Player.php b/src/Player.php index 9b60e5c9..33107ae6 100755 --- a/src/Player.php +++ b/src/Player.php @@ -1425,7 +1425,6 @@ class Player{ } if($this->sendingInventoryRequired){ - //console("inv resent"); if(($this->gamemode & 0x01) !== CREATIVE){ $hotbar = []; foreach($this->hotbar as $slot){ @@ -1481,6 +1480,14 @@ class Player{ if($this->bufferLen > 0){ $this->sendBuffer(); } + + if($this->blockUpdateQueueLength > 0){ + $this->sendBlockUpdateQueue(); + } + + if($this->entityDataQueueLength > 0){ + $this->sendEntityMovementUpdateQueue(); + } $limit = $time - 5; //max lag foreach($this->recoveryQueue as $count => $data){ From 52b09f1cf71201ef80e3cd3dca424a71549e35a5 Mon Sep 17 00:00:00 2001 From: GameHerobrine Date: Fri, 27 Jun 2025 02:21:15 +0300 Subject: [PATCH 05/16] fixed entity data packets not being added into always recover queue --- src/Player.php | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Player.php b/src/Player.php index 33107ae6..0460d378 100755 --- a/src/Player.php +++ b/src/Player.php @@ -1532,6 +1532,7 @@ class Player{ public function sendEntityMovementUpdateQueue(){ if($this->entityDataQueueLength > 0 && $this->entityDataQueue instanceof RakNetPacket){ $this->entityDataQueue->seqNumber = $this->counter[0]++; + $this->packetAlwaysRecoverQueue[$this->entityDataQueue->seqNumber] = $this->entityDataQueue; $this->send($this->entityDataQueue); } $this->entityDataQueueLength = 0; From 1ea54bc95b7b24e3d5399c1ad8b005e4fdc8fc73 Mon Sep 17 00:00:00 2001 From: GameHerobrine Date: Fri, 27 Jun 2025 02:37:34 +0300 Subject: [PATCH 06/16] fixed ping displaying incorrect ping --- src/Player.php | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Player.php b/src/Player.php index 0460d378..6bebe452 100755 --- a/src/Player.php +++ b/src/Player.php @@ -1533,6 +1533,7 @@ class Player{ if($this->entityDataQueueLength > 0 && $this->entityDataQueue instanceof RakNetPacket){ $this->entityDataQueue->seqNumber = $this->counter[0]++; $this->packetAlwaysRecoverQueue[$this->entityDataQueue->seqNumber] = $this->entityDataQueue; + $this->entityDataQueue->sendtime = microtime(true); $this->send($this->entityDataQueue); } $this->entityDataQueueLength = 0; From 565a9420fda2883aed6c609b87f319aa464ba02d Mon Sep 17 00:00:00 2001 From: GameHerobrine Date: Sat, 28 Jun 2025 22:32:47 +0300 Subject: [PATCH 07/16] local entity ids --- src/API/EntityAPI.php | 17 ++- src/Player.php | 165 +++++++++++++++++++------- src/entity/Creature.php | 1 + src/entity/Entity.php | 9 +- src/entity/Projectile.php | 2 + src/entity/object/Arrow.php | 1 + src/entity/object/FallingSand.php | 1 + src/entity/object/ItemEntity.php | 1 + src/entity/object/Minecart.php | 1 + src/entity/object/Painting.php | 1 + src/entity/object/PrimedTNT.php | 1 + src/network/protocol/ProtocolInfo.php | 29 ++++- src/world/Level.php | 1 + 13 files changed, 179 insertions(+), 51 deletions(-) diff --git a/src/API/EntityAPI.php b/src/API/EntityAPI.php index 4c0fe8a6..5b9d3983 100644 --- a/src/API/EntityAPI.php +++ b/src/API/EntityAPI.php @@ -184,7 +184,11 @@ class EntityAPI{ public function spawnToAll(Entity $e){ foreach($this->server->api->player->getAll($e->level) as $player){ - if($player->eid !== false and $player->eid !== $e->eid and $e->class !== ENTITY_PLAYER and $e instanceof Entity){ + if($player->eid != false and $player->eid != $e->eid and $e->class != ENTITY_PLAYER and $e instanceof Entity){ + if($e->closed !== false or ($player->level !== $e->level and $e->class !== ENTITY_PLAYER)){ + return false; + } + $e->spawn($player); } } @@ -196,6 +200,7 @@ class EntityAPI{ public function remove($eid){ if(isset($this->entities[$eid])){ + $e = $this->entities[$eid]; $level = $this->entities[$eid]->level; $this->entities[$eid]->closed = true; if($level instanceof Level){ @@ -213,11 +218,17 @@ class EntityAPI{ $pk = new RemovePlayerPacket; $pk->eid = $eid; $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{ $pk = new RemoveEntityPacket; $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]); unset($this->entities[$eid]->level->entityList[$eid]); diff --git a/src/Player.php b/src/Player.php index 6bebe452..83b4e065 100755 --- a/src/Player.php +++ b/src/Player.php @@ -125,6 +125,24 @@ class Player{ private $lastPing = -1; + /** + * Stores local entity ids. Format: global => local. + * Should be modified only by Player::addEntity or Player::removeEntity. + * @var array + */ + public $global2localEID = []; + /** + * Stores global entity ids. Format: local => global. + * Should be modified only by Player::addEntity or Player::removeEntity. + * @var array + */ + public $local2GlobalEID = []; + /** + * Stores last local entity id. Increments every time Player::addEntity is called. + * @var array + */ + public $lastLocalEID = -1; + /** * @param integer $clientID * @param string $ip @@ -168,6 +186,37 @@ class Player{ console("[DEBUG] New Session started with $ip:$port. MTU {$this->MTU}, Client ID {$this->clientID}", true, true, 2); } + /** + * Gives a new local id for entity. + * @param Entity $e + * @return boolean + */ + public function addEntity(Entity $e){ + $local = ++$this->lastLocalEID; + $this->global2localEID[$e->eid] = $local; + $this->local2GlobalEID[$local] = $e->eid; + ConsoleAPI::info("Adding Entity {$e->eid} => {$local}"); + return true; + } + + public function hasEntity(Entity $e){ + return isset($this->global2localEID[$e->eid]); + } + + /** + * Removes an entity. + * @param Entity $e + * @return boolean + */ + public function removeEntity(Entity $e){ + $local = $this->global2localEID[$e->eid] ?? null; + if($local == null) return false; + unset($this->global2localEID[$e->eid]); + unset($this->local2GlobalEID[$local]); + ConsoleAPI::info("Removing Entity {$e->eid} => {$local}"); + return true; + } + public function __get($name){ if(isset($this->{$name})){ return ($this->{$name}); @@ -289,14 +338,10 @@ class Player{ $this->entityQueueDataPacket($pk); }else{ - $pk = new MoveEntityPacket_PosRot(); + $pk = new RemoveEntityPacket(); $pk->eid = $e->eid; - $pk->x = -256; - $pk->y = 128; - $pk->z = -256; - $pk->yaw = 0; - $pk->pitch = 0; $this->entityQueueDataPacket($pk); + $this->removeEntity($e); } } } @@ -314,14 +359,7 @@ class Player{ foreach($this->level->entityList as $e){ if($e->eid !== $this->entity->eid){ if(!$e->isPlayer()){ - $pk = new MoveEntityPacket_PosRot(); - $pk->eid = $e->eid; - $pk->x = $e->x; - $pk->y = $e->y; - $pk->z = $e->z; - $pk->yaw = $e->yaw; - $pk->pitch = $e->pitch; - $this->entityQueueDataPacket($pk); + $e->spawn($this); } } } @@ -383,14 +421,14 @@ class Player{ } $pk = new SetEntityMotionPacket(); - $pk->eid = 0; + $pk->eid = $this->eid; $pk->speedX = 0; $pk->speedY = 0; $pk->speedZ = 0; $this->entityQueueDataPacket($pk); $pk = new MovePlayerPacket; - $pk->eid = 0; + $pk->eid = $this->eid; $pk->x = $pos->x; $pk->y = $pos->y; $pk->z = $pos->z; @@ -410,6 +448,7 @@ class Player{ public function directDataPacket(RakNetDataPacket $packet, $reliability = 0, $recover = true){ if($this->connected === false) return false; if(EventHandler::callEvent(new DataPacketSendEvent($this, $packet)) === BaseEvent::DENY) return []; + if(isset(ProtocolInfo::EID_PACKETS[$packet->pid()])) if(!$this->convertToLocalEIDPacket($packet)) return false; $packet->encode(); $pk = new RakNetPacket(RakNetInfo::DATA_PACKET_0); @@ -431,6 +470,7 @@ class Player{ public function dataPacket(RakNetDataPacket $packet){ if($this->connected === false) return false; if(EventHandler::callEvent(new DataPacketSendEvent($this, $packet)) === BaseEvent::DENY) return; + if(isset(ProtocolInfo::EID_PACKETS[$packet->pid()])) if(!$this->convertToLocalEIDPacket($packet)) return false; $packet->encode(); $len = strlen($packet->buffer) + 1; @@ -457,6 +497,7 @@ class Player{ public function dataPacketAlwaysRecover(RakNetDataPacket $packet){ if($this->connected === false) return false; if(EventHandler::callEvent(new DataPacketSendEvent($this, $packet)) === BaseEvent::DENY) return false; + if(isset(ProtocolInfo::EID_PACKETS[$packet->pid()])) if(!$this->convertToLocalEIDPacket($packet)) return false; $pk = new RakNetPacket(RakNetInfo::DATA_PACKET_0); $pk->data[] = $packet; @@ -467,7 +508,7 @@ class Player{ $len = strlen($packet->buffer) + 1; $MTU = $this->MTU - 24; if($len > $MTU){ - return $this->sendBigPacketAlwaysRecover($packet); + return $this->sendBigPacketAlwaysRecover($packet); //TODO fix } $packet->messageIndex = $this->counter[3]++; @@ -557,6 +598,7 @@ class Player{ public function sendBigPacketAlwaysRecover(RakNetDataPacket $pk){ if($this->connected === false) return false; if(EventHandler::callEvent(new DataPacketSendEvent($this, $pk)) === BaseEvent::DENY) return; + if(isset(ProtocolInfo::EID_PACKETS[$pk->pid()])) if(!$this->convertToLocalEIDPacket($pk)) return false; $pk->encode(); $sendtime = microtime(true); @@ -1026,9 +1068,8 @@ class Player{ break; case "player.pickup": if($data["eid"] === $this->eid){ - $data["eid"] = 0; $pk = new TakeItemEntityPacket; - $pk->eid = 0; + $pk->eid = $data["eid"]; $pk->target = $data["entity"]->eid; $this->entityQueueDataPacket($pk); @@ -1068,7 +1109,7 @@ class Player{ break; case "entity.motion": - if($data->eid === $this->eid or $data->level !== $this->level){ + if($data->eid === $this->eid || $data->level !== $this->level){ break; } if(($data->speedX === 0 && $data->speedY === 0 && $data->speedZ === 0) || ($data->speedX === $data->lastSpeedX && $data->speedY === $data->lastSpeedY && $data->lastSpeedZ === $data->speedZ)){ @@ -1088,11 +1129,7 @@ class Player{ $this->entityQueueDataPacket($pk); break; case "entity.metadata": - if($data->eid === $this->eid){ - $eid = 0; - }else{ - $eid = $data->eid; - } + $eid = $data->eid; if($data->level === $this->level){ $pk = new SetEntityDataPacket; $pk->eid = $eid; @@ -1101,11 +1138,7 @@ class Player{ } break; case "entity.event": - if($data["entity"]->eid === $this->eid){ - $eid = 0; - }else{ - $eid = $data["entity"]->eid; - } + $eid = $data["entity"]->eid; if($data["entity"]->level === $this->level){ $pk = new EntityEventPacket; $pk->eid = $eid; @@ -1561,6 +1594,7 @@ class Player{ public function blockQueueDataPacket(RakNetDataPacket $pk){ if($this->connected === false) return false; if(EventHandler::callEvent(new DataPacketSendEvent($this, $pk)) === BaseEvent::DENY) return; + if(isset(ProtocolInfo::EID_PACKETS[$pk->pid()])) if(!$this->convertToLocalEIDPacket($pk)) return false; $pk->encode(); @@ -1580,14 +1614,49 @@ class Player{ $this->blockUpdateQueueLength += 10 + $len; } + public function convertToGlobalEIDPacket(RakNetDataPacket $pk){ + $local = $pk->eid; + $pk->eid = $this->local2GlobalEID[$local] ?? false; + if($pk->eid === false){ + PRINT_STACK_TRACE: + ConsoleAPI::warn("Attempting to convert eids to global in entity packet {$pk->pid()} but global eid is incorrect! (Global: $local, Player: {$this->ip}:{$this->port}). Stacktrace: "); + foreach(explode("\n", (new Exception())->getTraceAsString()) as $s) ConsoleAPI::warn($s); + return false; + } + if($pk->pid() == ProtocolInfo::INTERACT_PACKET){ + $local = $pk->target; + $pk->target = $this->local2GlobalEID[$local] ?? false; + if($pk->target === false){ + ConsoleAPI::warn("Attempting to convert target eid to global in entity packet {$pk->pid()} but global eid is incorrect! (Global: $local, Player: {$this->ip}:{$this->port}). Stacktrace: "); + foreach(explode("\n", (new Exception())->getTraceAsString()) as $s) ConsoleAPI::warn($s); + return false; + } + } + return true; + } + public function convertToLocalEIDPacket(RakNetDataPacket $pk){ + if(!isset($pk->_localeid) || !$pk->_localeid){ + $global = $pk->eid; + $pk->eid = $this->global2localEID[$global] ?? false; + $pk->_localeid = true; + if($pk->eid === false){ + ConsoleAPI::warn("Attempting to convert eids to local in entity packet {$pk->pid()} but local eid is incorrect! (Global: $global, Player: {$this->ip}:{$this->port}). Stacktrace: "); + foreach(explode("\n", (new Exception())->getTraceAsString()) as $s) ConsoleAPI::warn($s); + return false; + } + return true; + } + } + /** * Sends a packet in entity order channel. Packets are always delivered and ordered. - * + * @param RakNetDataPacket $pk + * @return void|boolean|boolean|number[] */ public function entityQueueDataPacket(RakNetDataPacket $pk){ if($this->connected === false) return false; if(EventHandler::callEvent(new DataPacketSendEvent($this, $pk)) === BaseEvent::DENY) return; - + if(isset(ProtocolInfo::EID_PACKETS[$pk->pid()])) if(!$this->convertToLocalEIDPacket($pk)) return false; $pk->encode(); $len = 1 + strlen($pk->buffer); @@ -1599,6 +1668,7 @@ class Player{ } $pk->messageIndex = $this->counter[3]++; + $pk->reliability = 3; $pk->orderChannel = Player::ENTITY_ORDER_CHANNEL; $pk->orderIndex = $this->entityDataQueueOrderIndex++; @@ -1770,6 +1840,7 @@ class Player{ public function sendChatMessagePacket(RakNetDataPacket $packet){ if($this->connected === false) return false; if(EventHandler::callEvent(new DataPacketSendEvent($this, $packet)) === BaseEvent::DENY) return false; + if(isset(ProtocolInfo::EID_PACKETS[$packet->pid()])) if(!$this->convertToLocalEIDPacket($packet)) return false; //TODO big chat messages support $packet->encode(); @@ -1821,6 +1892,7 @@ class Player{ if($this->connected === false){ return; } + if(isset(ProtocolInfo::EID_PACKETS[$packet->pid()])) if(!$this->convertToGlobalEIDPacket($packet)) return; if(EventHandler::callEvent(new DataPacketReceiveEvent($this, $packet)) === BaseEvent::DENY){ return; @@ -1962,16 +2034,6 @@ class Player{ $pk = new LoginStatusPacket; $pk->status = 0; $this->dataPacket($pk); - - $pk = new StartGamePacket; - $pk->seed = $this->level->getSeed(); - $pk->x = $this->data->get("position")["x"]; - $pk->y = ceil($this->data->get("position")["y"])+1; - $pk->z = $this->data->get("position")["z"]; - $pk->generator = 0; - $pk->gamemode = $this->gamemode & 0x01; - $pk->eid = 0; - $this->dataPacket($pk); if(($this->gamemode & 0x01) === 0x01){ $this->slot = 0; @@ -2002,9 +2064,24 @@ class Player{ $this->entity = $this->server->api->entity->add($this->level, ENTITY_PLAYER, 0, ["player" => $this]); $this->eid = $this->entity->eid; $this->server->query("UPDATE players SET EID = " . $this->eid . " WHERE CID = " . $this->CID . ";"); + + $this->addEntity($this->entity); + + $pk = new StartGamePacket; + $pk->seed = $this->level->getSeed(); + $pk->x = $this->data->get("position")["x"]; + $pk->y = ceil($this->data->get("position")["y"])+1; + $pk->z = $this->data->get("position")["z"]; + $pk->generator = 0; + $pk->gamemode = $this->gamemode & 0x01; + $pk->eid = $this->entity->eid; + $this->entity->x = $pk->x; $this->entity->y = $pk->y-0.9; $this->entity->z = $pk->z; + $this->dataPacket($pk); + + if(($level = $this->server->api->level->get($this->data->get("spawn")["level"])) !== false){ $this->spawnPosition = new Position($this->data->get("spawn")["x"], $this->data->get("spawn")["y"], $this->data->get("spawn")["z"], $level); @@ -2032,7 +2109,7 @@ class Player{ $this->server->schedule(50, [$this, "measureLag"], [], true); - console("[INFO] " . FORMAT_AQUA . $this->username . FORMAT_RESET . "[/" . $this->ip . ":" . $this->port . "] logged in with entity id " . $this->eid . " at (" . $this->entity->level->getName() . ", " . round($this->entity->x, 2) . ", " . round($this->entity->y, 2) . ", " . round($this->entity->z, 2) . ") MTU: {$this->MTU}"); + console("[INFO] " . FORMAT_AQUA . $this->username . FORMAT_RESET . "[/{$this->ip}:{$this->port}] logged in with entity id {$this->eid} at ({$this->entity->level->getName()}, " . round($this->entity->x, 2) . ", " . round($this->entity->y, 2) . ", " . round($this->entity->z, 2) . ") MTU: {$this->MTU}"); break; case ProtocolInfo::READY_PACKET: if($this->loggedIn === false){ @@ -2566,7 +2643,7 @@ class Player{ $foodHeal = Item::getFoodHeal($slot->getID()); if($this->entity->getHealth() < 20 && $foodHeal != 0){ $pk = new EntityEventPacket; - $pk->eid = 0; + $pk->eid = $this->eid; $pk->event = EntityEventPacket::ENTITY_COMPLETE_USING_ITEM; $this->entityQueueDataPacket($pk); diff --git a/src/entity/Creature.php b/src/entity/Creature.php index a3254b6a..f0e1e28d 100644 --- a/src/entity/Creature.php +++ b/src/entity/Creature.php @@ -60,6 +60,7 @@ abstract class Creature extends Living{ if($player->eid === $this->eid or $this->closed !== false or ($player->level !== $this->level and $this->class !== ENTITY_PLAYER)){ return false; } + $player->addEntity($this); $pk = new AddMobPacket; $pk->eid = $this->eid; $pk->type = $this->type; diff --git a/src/entity/Entity.php b/src/entity/Entity.php index f13e36b5..c1107ac5 100644 --- a/src/entity/Entity.php +++ b/src/entity/Entity.php @@ -1150,6 +1150,9 @@ class Entity extends Position if($this->player->gamemode === SPECTATOR){ break; } + + $player->addEntity($this); + $pk = new AddPlayerPacket(); $pk->clientID = 0; // $this->player->clientID; $pk->username = $this->player->username; @@ -1162,8 +1165,8 @@ class Entity extends Position $pk->itemID = 0; $pk->itemAuxValue = 0; $pk->metadata = $this->getMetadata(); - $player->entityQueueDataPacket($pk, 2, true); - + $player->entityQueueDataPacket($pk); + $pk = new PlayerEquipmentPacket(); $pk->eid = $this->eid; $pk->item = $this->player->getSlot($this->player->slot)->getID(); @@ -1517,7 +1520,7 @@ class Entity extends Position public function sendMoveUpdate() { if($this->class === ENTITY_PLAYER){ - $this->player->teleport(new Vector3($this->x, $this->y, $this->z), false, false, true, false); + //$this->player->teleport(new Vector3($this->x, $this->y, $this->z), false, false, true, false); } } diff --git a/src/entity/Projectile.php b/src/entity/Projectile.php index 7042daa1..e68ff77e 100644 --- a/src/entity/Projectile.php +++ b/src/entity/Projectile.php @@ -201,6 +201,8 @@ abstract class Projectile extends Entity{ public function spawn($player) { + $player->addEntity($this); + $pk = new AddEntityPacket(); $pk->eid = $this->eid; $pk->type = $this->type; diff --git a/src/entity/object/Arrow.php b/src/entity/object/Arrow.php index f55a49cd..5915c4cf 100644 --- a/src/entity/object/Arrow.php +++ b/src/entity/object/Arrow.php @@ -262,6 +262,7 @@ class Arrow extends Entity{ public function spawn($player){ if($this->type === OBJECT_ARROW){ + $player->addEntity($this); $pk = new AddEntityPacket; $pk->eid = $this->eid; $pk->type = $this->type; diff --git a/src/entity/object/FallingSand.php b/src/entity/object/FallingSand.php index 8481830e..41c59d8a 100644 --- a/src/entity/object/FallingSand.php +++ b/src/entity/object/FallingSand.php @@ -21,6 +21,7 @@ class FallingSand extends Entity{ } public function spawn($player) { + $player->addEntity($this); $pk = new AddEntityPacket(); $pk->eid = $this->eid; $pk->type = $this->type; diff --git a/src/entity/object/ItemEntity.php b/src/entity/object/ItemEntity.php index e24726fe..43d42808 100644 --- a/src/entity/object/ItemEntity.php +++ b/src/entity/object/ItemEntity.php @@ -44,6 +44,7 @@ class ItemEntity extends Entity{ public function spawn($player) { + $player->addEntity($this); $pk = new AddItemEntityPacket(); $pk->eid = $this->eid; $pk->x = $this->x; diff --git a/src/entity/object/Minecart.php b/src/entity/object/Minecart.php index 326e6adc..cdd29dbb 100644 --- a/src/entity/object/Minecart.php +++ b/src/entity/object/Minecart.php @@ -427,6 +427,7 @@ class Minecart extends Vehicle{ } public function spawn($player){ + $player->addEntity($this); $pk = new AddEntityPacket; $pk->eid = $this->eid; $pk->type = $this->type; diff --git a/src/entity/object/Painting.php b/src/entity/object/Painting.php index 20bb25e9..8c2794eb 100644 --- a/src/entity/object/Painting.php +++ b/src/entity/object/Painting.php @@ -198,6 +198,7 @@ class Painting extends Entity{ } public function spawn($player){ + $player->addEntity($this); $pk = new AddPaintingPacket; $pk->eid = $this->eid; $pk->x = (int) $this->xPos; diff --git a/src/entity/object/PrimedTNT.php b/src/entity/object/PrimedTNT.php index 2585e917..0544eb69 100644 --- a/src/entity/object/PrimedTNT.php +++ b/src/entity/object/PrimedTNT.php @@ -66,6 +66,7 @@ class PrimedTNT extends Entity{ } public function spawn($player){ + $player->addEntity($this); $pk = new AddEntityPacket; $pk->eid = $this->eid; $pk->type = $this->type; diff --git a/src/network/protocol/ProtocolInfo.php b/src/network/protocol/ProtocolInfo.php index fc6c6b8f..118975fa 100644 --- a/src/network/protocol/ProtocolInfo.php +++ b/src/network/protocol/ProtocolInfo.php @@ -70,7 +70,34 @@ abstract class ProtocolInfo{ const ADVENTURE_SETTINGS_PACKET = 0xb7; const ENTITY_DATA_PACKET = 0xb8; const PLAYER_INPUT_PACKET = 0xb9; - + + const EID_PACKETS = [ + self::ADD_MOB_PACKET => true, + self::ADD_ITEM_ENTITY_PACKET => true, + self::RESPAWN_PACKET => true, + self::SET_ENTITY_MOTION_PACKET => true, + self::USE_ITEM_PACKET => true, + self::SET_ENTITY_DATA_PACKET => true, + self::PLAYER_ARMOR_EQUIPMENT_PACKET => true, + self::ROTATE_HEAD_PACKET => true, + self::PLAYER_EQUIPMENT_PACKET => true, + self::SEND_INVENTORY_PACKET => true, + self::INTERACT_PACKET => true, + self::ENTITY_EVENT_PACKET => true, + self::PLAYER_ACTION_PACKET => true, + self::REMOVE_ENTITY_PACKET => true, + self::ANIMATE_PACKET => true, + self::ADD_PLAYER_PACKET => true, + self::TAKE_ITEM_ENTITY_PACKET => true, + self::START_GAME_PACKET => true, + self::ADD_PAINTING_PACKET => true, + self::REMOVE_PLAYER_PACKET => true, + self::MOVE_ENTITY_PACKET_POSROT => true, + self::ADD_ENTITY_PACKET => true, + self::REMOVE_BLOCK_PACKET => true, + self::MOVE_PLAYER_PACKET => true, + self::DROP_ITEM_PACKET => true + ]; } /*Unused: * 0xb5 diff --git a/src/world/Level.php b/src/world/Level.php index ed779bb2..d3729af5 100644 --- a/src/world/Level.php +++ b/src/world/Level.php @@ -817,6 +817,7 @@ class Level{ foreach($this->players as $player){ + if(!$player->spawned) continue; foreach($post as $eid){ $e = $this->entityList[$eid] ?? false; if(!($e instanceof Entity)){ From f9646e7e897b7da18d68a91eb3387b6f38f74609 Mon Sep 17 00:00:00 2001 From: GameHerobrine Date: Sun, 29 Jun 2025 00:10:13 +0300 Subject: [PATCH 08/16] movement queue readded + entity movement is now unreliable --- src/Player.php | 75 +++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 68 insertions(+), 7 deletions(-) diff --git a/src/Player.php b/src/Player.php index 83b4e065..76ece8c3 100755 --- a/src/Player.php +++ b/src/Player.php @@ -88,6 +88,10 @@ class Player{ public $slotCount = 7; public $bedPosition = null; + public $entityMovementQueue; + public $entityMovementQueueLength = 0; + public $entityMovementQueueOrderIndex = 0; + /** * @var RakNetPacket */ @@ -174,6 +178,9 @@ class Player{ $this->entityDataQueue = new RakNetPacket(RakNetInfo::DATA_PACKET_0); $this->entityDataQueue->data = []; + $this->entityMovementQueue = new RakNetPacket(RakNetInfo::DATA_PACKET_0); + $this->entityMovementQueue->data = []; + $this->blockUpdateQueue = new RakNetPacket(RakNetInfo::DATA_PACKET_0); $this->blockUpdateQueue->data = []; @@ -195,7 +202,7 @@ class Player{ $local = ++$this->lastLocalEID; $this->global2localEID[$e->eid] = $local; $this->local2GlobalEID[$local] = $e->eid; - ConsoleAPI::info("Adding Entity {$e->eid} => {$local}"); + //ConsoleAPI::info("Adding Entity {$e->eid} => {$local}"); return true; } @@ -213,7 +220,7 @@ class Player{ if($local == null) return false; unset($this->global2localEID[$e->eid]); unset($this->local2GlobalEID[$local]); - ConsoleAPI::info("Removing Entity {$e->eid} => {$local}"); + //ConsoleAPI::info("Removing Entity {$e->eid} => {$local}"); return true; } @@ -1519,6 +1526,10 @@ class Player{ } if($this->entityDataQueueLength > 0){ + $this->sendEntityDataQueue(); + } + + if($this->entityMovementQueueLength > 0){ $this->sendEntityMovementUpdateQueue(); } @@ -1563,6 +1574,17 @@ class Player{ } public function sendEntityMovementUpdateQueue(){ + if($this->entityMovementQueueLength > 0 && $this->entityMovementQueue instanceof RakNetPacket){ + $this->entityMovementQueue->seqNumber = $this->counter[0]++; + $this->entityMovementQueue->sendtime = microtime(true); + $this->send($this->entityMovementQueue); + } + $this->entityMovementQueueLength = 0; + $this->entityMovementQueue = new RakNetPacket(RakNetInfo::DATA_PACKET_0); + $this->entityMovementQueue->data = []; + } + + public function sendEntityDataQueue(){ if($this->entityDataQueueLength > 0 && $this->entityDataQueue instanceof RakNetPacket){ $this->entityDataQueue->seqNumber = $this->counter[0]++; $this->packetAlwaysRecoverQueue[$this->entityDataQueue->seqNumber] = $this->entityDataQueue; @@ -1664,7 +1686,7 @@ class Player{ if($len > $MTU) return $this->entityQueueDataPacket_big($pk); if(($this->entityDataQueueLength + $len) >= $MTU){ - $this->sendEntityMovementUpdateQueue(); + $this->sendEntityDataQueue(); } $pk->messageIndex = $this->counter[3]++; @@ -1702,6 +1724,11 @@ class Player{ } public function addEntityMovementUpdateToQueue(Entity $e){ + $len = 0; + $packets = 0; + $motionSent = false; + $moveSent = false; + $headSent = false; $svdYSpeed = $e->speedY; if($e->modifySpeedY){ $e->speedY = $e->modifedSpeedY; @@ -1713,7 +1740,10 @@ class Player{ $motion->speedX = $e->speedX; $motion->speedY = $e->speedY; $motion->speedZ = $e->speedZ; - $this->entityQueueDataPacket($motion); + $motion->encode(); + $len += 1 + strlen($motion->buffer); + ++$packets; + $motionSent = true; } } if($e->modifySpeedY){ @@ -1731,7 +1761,7 @@ class Player{ $move->yaw = $e->yaw; $move->pitch = $e->pitch; $move->bodyYaw = $e->headYaw; - $this->entityQueueDataPacket($move); + $move->encode(); }else{ $move = new MoveEntityPacket_PosRot(); $move->eid = $e->eid; @@ -1740,14 +1770,45 @@ class Player{ $move->z = $e->z; $move->yaw = $e->yaw; $move->pitch = $e->pitch; - $this->entityQueueDataPacket($move); + $move->encode(); } + + $len += strlen($move->buffer) + 1; + ++$packets; + $moveSent = true; }else if($e->headYaw != $e->lastHeadYaw){ $headyaw = new RotateHeadPacket(); $headyaw->eid = $e->eid; $headyaw->yaw = $e->headYaw; - $this->entityQueueDataPacket($headyaw); + $headyaw->encode(); + $len += strlen($headyaw->buffer) + 1; + ++$packets; + $headSent = true; } + if($packets <= 0) return; + //console("Update {$e}: $packets, mot: $motionSent, mov: $moveSent, hed: $headSent"); + $MTU = $this->MTU - 24; + if(($this->entityMovementQueueLength + $len) >= $MTU){ + $this->sendEntityMovementUpdateQueue(); + } + if($motionSent){ + $motion->messageIndex = 0; //force 0 cuz reliability 0 + $motion->reliability = 0; + $this->entityMovementQueue->data[] = $motion; + } + if($moveSent){ + $move->messageIndex = 0; + $move->reliability = 0; + $this->entityMovementQueue->data[] = $move; + } + if($headSent){ + $headyaw->messageIndex = 0; + $headyaw->reliability = 0; + $this->entityMovementQueue->data[] = $headyaw; + } + + $this->entityMovementQueueLength += 6*$packets + $len; + $this->entityMovementPacketsPerSecond += $packets; } /** From 62819f8b12d1f363ac8f761efc3215c8381cf221 Mon Sep 17 00:00:00 2001 From: GameHerobrine Date: Sun, 29 Jun 2025 00:22:56 +0300 Subject: [PATCH 09/16] fixes --- src/Player.php | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/src/Player.php b/src/Player.php index 76ece8c3..cefe1f21 100755 --- a/src/Player.php +++ b/src/Player.php @@ -1729,6 +1729,13 @@ class Player{ $motionSent = false; $moveSent = false; $headSent = false; + $localeid = $this->global2localEID[$e->eid] ?? false; + if($localeid === false){ + ConsoleAPI::warn("Attempting to convert global eid to local failed! (Global: {$e->eid}, Player: {$this->ip}:{$this->port}). Stacktrace: "); + foreach(explode("\n", (new Exception())->getTraceAsString()) as $s) ConsoleAPI::warn($s); + return false; + } + $svdYSpeed = $e->speedY; if($e->modifySpeedY){ $e->speedY = $e->modifedSpeedY; @@ -1736,7 +1743,7 @@ class Player{ if($e->speedX != 0 || $e->speedY != 0 || $e->speedZ != 0 || $e->speedY != $e->lastSpeedY || $e->speedX != $e->lastSpeedX || $e->speedZ != $e->lastSpeedZ){ if(!($e->speedY < 0 && $e->onGround) || $e->speedX != 0 || $e->speedZ != 0 || $e->speedY != $e->lastSpeedY || $e->speedX != $e->lastSpeedX || $e->speedZ != $e->lastSpeedZ){ $motion = new SetEntityMotionPacket(); - $motion->eid = $e->eid; + $motion->eid = $localeid; $motion->speedX = $e->speedX; $motion->speedY = $e->speedY; $motion->speedZ = $e->speedZ; @@ -1754,7 +1761,7 @@ class Player{ if($e->x != $e->lastX || $e->y != $e->lastY || $e->z != $e->lastZ || $e->yaw != $e->lastYaw || $e->pitch != $e->lastPitch){ if($e->headYaw != $e->lastHeadYaw){ $move = new MovePlayerPacket(); - $move->eid = $e->eid; + $move->eid = $localeid; $move->x = $e->x; $move->y = $e->y + $e->yOffset; $move->z = $e->z; @@ -1764,7 +1771,7 @@ class Player{ $move->encode(); }else{ $move = new MoveEntityPacket_PosRot(); - $move->eid = $e->eid; + $move->eid = $localeid; $move->x = $e->x; $move->y = $e->y + $e->yOffset; $move->z = $e->z; @@ -1778,7 +1785,7 @@ class Player{ $moveSent = true; }else if($e->headYaw != $e->lastHeadYaw){ $headyaw = new RotateHeadPacket(); - $headyaw->eid = $e->eid; + $headyaw->eid = $localeid; $headyaw->yaw = $e->headYaw; $headyaw->encode(); $len += strlen($headyaw->buffer) + 1; From 21f8796e8963b1d389a961069e9a02c411e5cc45 Mon Sep 17 00:00:00 2001 From: GameHerobrine Date: Sun, 29 Jun 2025 03:12:24 +0300 Subject: [PATCH 10/16] better(?) way to handle eid translation, local eid 0 is not used now, some additional fixes --- src/Player.php | 43 ++++++------------- src/entity/Entity.php | 12 ++---- src/network/protocol/ProtocolInfo.php | 3 +- .../protocol/packet/AddEntityPacket.php | 9 ++++ .../protocol/packet/AddItemEntityPacket.php | 9 +++- src/network/protocol/packet/AddMobPacket.php | 10 ++++- .../protocol/packet/AddPaintingPacket.php | 10 ++++- .../protocol/packet/AddPlayerPacket.php | 10 ++++- src/network/protocol/packet/AnimatePacket.php | 17 ++++++++ .../protocol/packet/DropItemPacket.php | 10 ++++- .../protocol/packet/EntityEventPacket.php | 18 +++++++- .../protocol/packet/InteractPacket.php | 21 ++++++++- .../packet/MoveEntityPacket_PosRot.php | 16 +++++++ .../protocol/packet/MovePlayerPacket.php | 16 +++++++ .../protocol/packet/PlayerActionPacket.php | 10 ++++- .../packet/PlayerArmorEquipmentPacket.php | 19 +++++++- .../protocol/packet/PlayerEquipmentPacket.php | 19 +++++++- .../protocol/packet/RemoveBlockPacket.php | 8 ++++ .../protocol/packet/RemoveEntityPacket.php | 10 ++++- .../protocol/packet/RemovePlayerPacket.php | 8 ++++ src/network/protocol/packet/RespawnPacket.php | 9 +++- .../protocol/packet/RotateHeadPacket.php | 17 ++++++++ .../protocol/packet/SendInventoryPacket.php | 18 ++++++++ .../protocol/packet/SetEntityDataPacket.php | 8 ++++ .../protocol/packet/SetEntityLinkPacket.php | 19 ++++++++ .../protocol/packet/SetEntityMotionPacket.php | 9 +++- .../protocol/packet/StartGamePacket.php | 10 ++++- .../protocol/packet/TakeItemEntityPacket.php | 10 +++++ src/network/protocol/packet/UseItemPacket.php | 8 ++++ src/network/raknet/RakNetDataPacket.php | 12 +++++- src/network/raknet/RakNetParser.php | 1 + src/world/Level.php | 2 +- 32 files changed, 345 insertions(+), 56 deletions(-) diff --git a/src/Player.php b/src/Player.php index cefe1f21..5b99f7a3 100755 --- a/src/Player.php +++ b/src/Player.php @@ -132,20 +132,21 @@ class Player{ /** * Stores local entity ids. Format: global => local. * Should be modified only by Player::addEntity or Player::removeEntity. + * Entity ID 0 is reserved for non-existent entities. * @var array */ - public $global2localEID = []; + public $global2localEID = [0 => 0]; /** * Stores global entity ids. Format: local => global. * Should be modified only by Player::addEntity or Player::removeEntity. * @var array */ - public $local2GlobalEID = []; + public $local2GlobalEID = [0 => 0]; /** * Stores last local entity id. Increments every time Player::addEntity is called. * @var array */ - public $lastLocalEID = -1; + public $lastLocalEID = 0; /** * @param integer $clientID @@ -1022,8 +1023,8 @@ class Player{ switch($event){ case "entity.link": $pk = new SetEntityLinkPacket(); - $pk->rider = $data["rider"] == $this->entity->eid ? 0 : $data["rider"]; - $pk->riding = $data["riding"] == $this->entity->eid ? 0 : $data["riding"]; + $pk->rider = $data["rider"]; + $pk->riding = $data["riding"]; $pk->type = 0; $this->entityQueueDataPacket($pk); break; @@ -1136,6 +1137,7 @@ class Player{ $this->entityQueueDataPacket($pk); break; case "entity.metadata": + if(!$this->hasEntity($data)) break; $eid = $data->eid; if($data->level === $this->level){ $pk = new SetEntityDataPacket; @@ -1637,37 +1639,20 @@ class Player{ } public function convertToGlobalEIDPacket(RakNetDataPacket $pk){ - $local = $pk->eid; - $pk->eid = $this->local2GlobalEID[$local] ?? false; - if($pk->eid === false){ - PRINT_STACK_TRACE: - ConsoleAPI::warn("Attempting to convert eids to global in entity packet {$pk->pid()} but global eid is incorrect! (Global: $local, Player: {$this->ip}:{$this->port}). Stacktrace: "); + if(!$pk->eidsToGlobal($this)){ + ConsoleAPI::warn("Failed to convert eids to global in {$pk->pid()}! (Player: {$this->ip}:{$this->port}). Stacktrace: "); foreach(explode("\n", (new Exception())->getTraceAsString()) as $s) ConsoleAPI::warn($s); return false; } - if($pk->pid() == ProtocolInfo::INTERACT_PACKET){ - $local = $pk->target; - $pk->target = $this->local2GlobalEID[$local] ?? false; - if($pk->target === false){ - ConsoleAPI::warn("Attempting to convert target eid to global in entity packet {$pk->pid()} but global eid is incorrect! (Global: $local, Player: {$this->ip}:{$this->port}). Stacktrace: "); - foreach(explode("\n", (new Exception())->getTraceAsString()) as $s) ConsoleAPI::warn($s); - return false; - } - } return true; } public function convertToLocalEIDPacket(RakNetDataPacket $pk){ - if(!isset($pk->_localeid) || !$pk->_localeid){ - $global = $pk->eid; - $pk->eid = $this->global2localEID[$global] ?? false; - $pk->_localeid = true; - if($pk->eid === false){ - ConsoleAPI::warn("Attempting to convert eids to local in entity packet {$pk->pid()} but local eid is incorrect! (Global: $global, Player: {$this->ip}:{$this->port}). Stacktrace: "); - foreach(explode("\n", (new Exception())->getTraceAsString()) as $s) ConsoleAPI::warn($s); - return false; - } - return true; + if(!$pk->eidsToLocal($this)){ + ConsoleAPI::warn("Failed to convert eids to local in {$pk->pid()}! (Player: {$this->ip}:{$this->port}). Stacktrace: "); + foreach(explode("\n", (new Exception())->getTraceAsString()) as $s) ConsoleAPI::warn($s); + return false; } + return true; } /** diff --git a/src/entity/Entity.php b/src/entity/Entity.php index c1107ac5..975fb90c 100644 --- a/src/entity/Entity.php +++ b/src/entity/Entity.php @@ -1466,8 +1466,8 @@ class Entity extends Position if(isset($this->level->entityList[$this->linkedEntity])){ $e = $this->level->entityList[$this->linkedEntity]; if(!$e->dead && !$e->closed){ - $this->server->api->dhandle("entity.link", ["rider" => $this->eid, "riding" => -1, "type" => 1]); - $this->server->api->dhandle("entity.link", ["rider" => $this->linkedEntity, "riding" => -1, "type" => 1]); + $this->server->api->dhandle("entity.link", ["rider" => $this->eid, "riding" => 0, "type" => 1]); + $this->server->api->dhandle("entity.link", ["rider" => $this->linkedEntity, "riding" => 0, "type" => 1]); $this->isRider = false; $this->linkedEntity = 0; $e->linkedEntity = 0; @@ -1602,13 +1602,7 @@ class Entity extends Position $pk->eid = $this->eid; $pk->event = EntityEventPacket::ENTITY_DAMAGE; foreach($this->level->players as $p){ - if(($p->entity instanceof Entity) && $p->entity->eid == $this->eid){ - $pk2 = clone $pk; - $pk2->eid = 0; - $p->entityQueueDataPacket($pk2); - }else{ - $p->entityQueueDataPacket(clone $pk); - } + $p->entityQueueDataPacket(clone $pk); } } diff --git a/src/network/protocol/ProtocolInfo.php b/src/network/protocol/ProtocolInfo.php index 118975fa..c2e9ebfb 100644 --- a/src/network/protocol/ProtocolInfo.php +++ b/src/network/protocol/ProtocolInfo.php @@ -96,7 +96,8 @@ abstract class ProtocolInfo{ self::ADD_ENTITY_PACKET => true, self::REMOVE_BLOCK_PACKET => true, self::MOVE_PLAYER_PACKET => true, - self::DROP_ITEM_PACKET => true + self::DROP_ITEM_PACKET => true, + self::SET_ENTITY_LINK_PACKET => true ]; } /*Unused: diff --git a/src/network/protocol/packet/AddEntityPacket.php b/src/network/protocol/packet/AddEntityPacket.php index ac2c1a75..36d7848b 100644 --- a/src/network/protocol/packet/AddEntityPacket.php +++ b/src/network/protocol/packet/AddEntityPacket.php @@ -33,5 +33,14 @@ class AddEntityPacket extends RakNetDataPacket{ $this->putShort((int)($this->speedZ * 8000)); } } + + public function eidsToLocal(Player $p){ + if(!$this->localEids){ + $this->localEids = true; + $this->eid = $p->global2localEID[$this->eid] ?? false; + if($this->eid === false) return false; + } + return true; + } } \ No newline at end of file diff --git a/src/network/protocol/packet/AddItemEntityPacket.php b/src/network/protocol/packet/AddItemEntityPacket.php index fb68f60a..4c250c8d 100644 --- a/src/network/protocol/packet/AddItemEntityPacket.php +++ b/src/network/protocol/packet/AddItemEntityPacket.php @@ -29,5 +29,12 @@ class AddItemEntityPacket extends RakNetDataPacket{ $this->putByte($this->pitch); $this->putByte($this->roll); } - + public function eidsToLocal(Player $p){ + if(!$this->localEids){ + $this->localEids = true; + $this->eid = $p->global2localEID[$this->eid] ?? false; + if($this->eid === false) return false; + } + return true; + } } \ No newline at end of file diff --git a/src/network/protocol/packet/AddMobPacket.php b/src/network/protocol/packet/AddMobPacket.php index 5b2d9a90..56620be3 100644 --- a/src/network/protocol/packet/AddMobPacket.php +++ b/src/network/protocol/packet/AddMobPacket.php @@ -29,5 +29,13 @@ class AddMobPacket extends RakNetDataPacket{ $this->putByte($this->pitch); $this->put(Utils::writeMetadata($this->metadata)); } - + + public function eidsToLocal(Player $p){ + if(!$this->localEids){ + $this->localEids = true; + $this->eid = $p->global2localEID[$this->eid] ?? false; + if($this->eid === false) return false; + } + return true; + } } \ No newline at end of file diff --git a/src/network/protocol/packet/AddPaintingPacket.php b/src/network/protocol/packet/AddPaintingPacket.php index bd50ab0a..60337c46 100644 --- a/src/network/protocol/packet/AddPaintingPacket.php +++ b/src/network/protocol/packet/AddPaintingPacket.php @@ -25,5 +25,13 @@ class AddPaintingPacket extends RakNetDataPacket{ $this->putInt($this->direction); $this->putString($this->title); } - + + public function eidsToLocal(Player $p){ + if(!$this->localEids){ + $this->localEids = true; + $this->eid = $p->global2localEID[$this->eid] ?? false; + if($this->eid === false) return false; + } + return true; + } } \ No newline at end of file diff --git a/src/network/protocol/packet/AddPlayerPacket.php b/src/network/protocol/packet/AddPlayerPacket.php index 044f119a..166a27e1 100644 --- a/src/network/protocol/packet/AddPlayerPacket.php +++ b/src/network/protocol/packet/AddPlayerPacket.php @@ -46,5 +46,13 @@ class AddPlayerPacket extends RakNetDataPacket{ $this->putShort($this->itemAuxValue); //Example: bow shooting power $this->put(Utils::writeMetadata($this->metadata)); } - + + public function eidsToLocal(Player $p){ + if(!$this->localEids){ + $this->localEids = true; + $this->eid = $p->global2localEID[$this->eid] ?? false; + if($this->eid === false) return false; + } + return true; + } } \ No newline at end of file diff --git a/src/network/protocol/packet/AnimatePacket.php b/src/network/protocol/packet/AnimatePacket.php index a8ea6820..e8ce1225 100644 --- a/src/network/protocol/packet/AnimatePacket.php +++ b/src/network/protocol/packet/AnimatePacket.php @@ -22,4 +22,21 @@ class AnimatePacket extends RakNetDataPacket{ $this->putInt($this->eid); } + public function eidsToGlobal(Player $p){ + if($this->localEids){ + $this->localEids = false; + $this->eid = $p->local2GlobalEID[$this->eid] ?? false; + if($this->eid === false) return false; + } + return true; + } + + public function eidsToLocal(Player $p){ + if(!$this->localEids){ + $this->localEids = true; + $this->eid = $p->global2localEID[$this->eid] ?? false; + if($this->eid === false) return false; + } + return true; + } } \ No newline at end of file diff --git a/src/network/protocol/packet/DropItemPacket.php b/src/network/protocol/packet/DropItemPacket.php index 41531160..30c487bf 100644 --- a/src/network/protocol/packet/DropItemPacket.php +++ b/src/network/protocol/packet/DropItemPacket.php @@ -18,5 +18,13 @@ class DropItemPacket extends RakNetDataPacket{ public function encode(){ } - + + public function eidsToGlobal(Player $p){ + if($this->localEids){ + $this->localEids = false; + $this->eid = $p->local2GlobalEID[$this->eid] ?? false; + if($this->eid === false) return false; + } + return true; + } } \ No newline at end of file diff --git a/src/network/protocol/packet/EntityEventPacket.php b/src/network/protocol/packet/EntityEventPacket.php index 44e9b06a..daa00929 100644 --- a/src/network/protocol/packet/EntityEventPacket.php +++ b/src/network/protocol/packet/EntityEventPacket.php @@ -31,5 +31,21 @@ class EntityEventPacket extends RakNetDataPacket{ $this->putInt($this->eid); $this->putByte($this->event); } - + + public function eidsToLocal(Player $p){ + if(!$this->localEids){ + $this->localEids = true; + $this->eid = $p->global2localEID[$this->eid] ?? false; + if($this->eid === false) return false; + } + return true; + } + + public function eidsToGlobal(Player $p){ + if($this->localEids){ + $this->localEids = false; + $this->eid = $p->local2GlobalEID[$this->eid] ?? false; + if($this->eid === false) return false; + } + } } \ No newline at end of file diff --git a/src/network/protocol/packet/InteractPacket.php b/src/network/protocol/packet/InteractPacket.php index 2d33773d..dcc7f53c 100644 --- a/src/network/protocol/packet/InteractPacket.php +++ b/src/network/protocol/packet/InteractPacket.php @@ -24,5 +24,24 @@ class InteractPacket extends RakNetDataPacket{ $this->putInt($this->eid); $this->putInt($this->target); } - + + public function eidsToLocal(Player $p){ + if(!$this->localEids){ + $this->localEids = true; + $this->eid = $p->global2localEID[$this->eid] ?? false; + $this->target = $p->global2localEID[$this->target] ?? false; + if($this->eid === false || $this->target === false) return false; + } + return true; + } + + public function eidsToGlobal(Player $p){ + if($this->localEids){ + $this->localEids = false; + $this->eid = $p->local2GlobalEID[$this->eid] ?? false; + $this->target = $p->local2GlobalEID[$this->target] ?? false; + if($this->eid === false || $this->target === false) return false; + } + return true; + } } \ No newline at end of file diff --git a/src/network/protocol/packet/MoveEntityPacket_PosRot.php b/src/network/protocol/packet/MoveEntityPacket_PosRot.php index c2143c18..02930e1f 100644 --- a/src/network/protocol/packet/MoveEntityPacket_PosRot.php +++ b/src/network/protocol/packet/MoveEntityPacket_PosRot.php @@ -32,4 +32,20 @@ class MoveEntityPacket_PosRot extends RakNetDataPacket{ $this->putFloat($this->pitch); } + public function eidsToLocal(Player $p){ + if(!$this->localEids){ + $this->localEids = true; + $this->eid = $p->global2localEID[$this->eid] ?? false; + if($this->eid === false) return false; + } + return true; + } + public function eidsToGlobal(Player $p){ + if($this->localEids){ + $this->localEids = false; + $this->eid = $p->local2GlobalEID[$this->eid] ?? false; + if($this->eid === false) return false; + } + return true; + } } \ No newline at end of file diff --git a/src/network/protocol/packet/MovePlayerPacket.php b/src/network/protocol/packet/MovePlayerPacket.php index 5325cf76..dc234b51 100644 --- a/src/network/protocol/packet/MovePlayerPacket.php +++ b/src/network/protocol/packet/MovePlayerPacket.php @@ -34,4 +34,20 @@ class MovePlayerPacket extends RakNetDataPacket{ $this->putFloat($this->bodyYaw); } + public function eidsToLocal(Player $p){ + if(!$this->localEids){ + $this->localEids = true; + $this->eid = $p->global2localEID[$this->eid] ?? false; + if($this->eid === false) return false; + } + return true; + } + public function eidsToGlobal(Player $p){ + if($this->localEids){ + $this->localEids = false; + $this->eid = $p->local2GlobalEID[$this->eid] ?? false; + if($this->eid === false) return false; + } + return true; + } } \ No newline at end of file diff --git a/src/network/protocol/packet/PlayerActionPacket.php b/src/network/protocol/packet/PlayerActionPacket.php index cdcc64ad..743bf674 100644 --- a/src/network/protocol/packet/PlayerActionPacket.php +++ b/src/network/protocol/packet/PlayerActionPacket.php @@ -24,5 +24,13 @@ class PlayerActionPacket extends RakNetDataPacket{ public function encode(){ } - + + public function eidsToGlobal(Player $p){ + if($this->localEids){ + $this->localEids = false; + $this->eid = $p->local2GlobalEID[$this->eid] ?? false; + if($this->eid === false) return false; + } + return true; + } } \ No newline at end of file diff --git a/src/network/protocol/packet/PlayerArmorEquipmentPacket.php b/src/network/protocol/packet/PlayerArmorEquipmentPacket.php index d32be316..c867232c 100644 --- a/src/network/protocol/packet/PlayerArmorEquipmentPacket.php +++ b/src/network/protocol/packet/PlayerArmorEquipmentPacket.php @@ -24,5 +24,22 @@ class PlayerArmorEquipmentPacket extends RakNetDataPacket{ $this->putByte($this->slots[2]); $this->putByte($this->slots[3]); } - + + public function eidsToGlobal(Player $p){ + if($this->localEids){ + $this->localEids = false; + $this->eid = $p->local2GlobalEID[$this->eid] ?? false; + if($this->eid === false) return false; + } + return true; + } + + public function eidsToLocal(Player $p){ + if(!$this->localEids){ + $this->localEids = true; + $this->eid = $p->global2localEID[$this->eid] ?? false; + if($this->eid === false) return false; + } + return true; + } } \ No newline at end of file diff --git a/src/network/protocol/packet/PlayerEquipmentPacket.php b/src/network/protocol/packet/PlayerEquipmentPacket.php index 06e65fee..62af566e 100644 --- a/src/network/protocol/packet/PlayerEquipmentPacket.php +++ b/src/network/protocol/packet/PlayerEquipmentPacket.php @@ -24,5 +24,22 @@ class PlayerEquipmentPacket extends RakNetDataPacket{ $this->putShort($this->meta); $this->putByte($this->slot); } - + + public function eidsToGlobal(Player $p){ + if($this->localEids){ + $this->localEids = false; + $this->eid = $p->local2GlobalEID[$this->eid] ?? false; + if($this->eid === false) return false; + } + return true; + } + + public function eidsToLocal(Player $p){ + if(!$this->localEids){ + $this->localEids = true; + $this->eid = $p->global2localEID[$this->eid] ?? false; + if($this->eid === false) return false; + } + return true; + } } \ No newline at end of file diff --git a/src/network/protocol/packet/RemoveBlockPacket.php b/src/network/protocol/packet/RemoveBlockPacket.php index d3e3a969..c314c20b 100644 --- a/src/network/protocol/packet/RemoveBlockPacket.php +++ b/src/network/protocol/packet/RemoveBlockPacket.php @@ -21,4 +21,12 @@ class RemoveBlockPacket extends RakNetDataPacket{ } + public function eidsToGlobal(Player $p){ + if($this->localEids){ + $this->localEids = false; + $this->eid = $p->local2GlobalEID[$this->eid] ?? false; + if($this->eid === false) return false; + } + return true; + } } \ No newline at end of file diff --git a/src/network/protocol/packet/RemoveEntityPacket.php b/src/network/protocol/packet/RemoveEntityPacket.php index 27d6c42b..fded3c76 100644 --- a/src/network/protocol/packet/RemoveEntityPacket.php +++ b/src/network/protocol/packet/RemoveEntityPacket.php @@ -15,5 +15,13 @@ class RemoveEntityPacket extends RakNetDataPacket{ $this->reset(); $this->putInt($this->eid); } - + + public function eidsToLocal(Player $p){ + if(!$this->localEids){ + $this->localEids = true; + $this->eid = $p->global2localEID[$this->eid] ?? false; + if($this->eid === false) return false; + } + return true; + } } \ No newline at end of file diff --git a/src/network/protocol/packet/RemovePlayerPacket.php b/src/network/protocol/packet/RemovePlayerPacket.php index f23cd4df..4847aff6 100644 --- a/src/network/protocol/packet/RemovePlayerPacket.php +++ b/src/network/protocol/packet/RemovePlayerPacket.php @@ -18,4 +18,12 @@ class RemovePlayerPacket extends RakNetDataPacket{ $this->putLong($this->clientID); } + public function eidsToLocal(Player $p){ + if(!$this->localEids){ + $this->localEids = true; + $this->eid = $p->global2localEID[$this->eid] ?? false; + if($this->eid === false) return false; + } + return true; + } } \ No newline at end of file diff --git a/src/network/protocol/packet/RespawnPacket.php b/src/network/protocol/packet/RespawnPacket.php index 1d3c208e..7fc4fad6 100644 --- a/src/network/protocol/packet/RespawnPacket.php +++ b/src/network/protocol/packet/RespawnPacket.php @@ -24,5 +24,12 @@ class RespawnPacket extends RakNetDataPacket{ $this->putFloat($this->y); $this->putFloat($this->z); } - + public function eidsToLocal(Player $p){ + if(!$this->localEids){ + $this->localEids = true; + $this->eid = $p->global2localEID[$this->eid] ?? false; + if($this->eid === false) return false; + } + return true; + } } \ No newline at end of file diff --git a/src/network/protocol/packet/RotateHeadPacket.php b/src/network/protocol/packet/RotateHeadPacket.php index 21cc7cf0..78157858 100644 --- a/src/network/protocol/packet/RotateHeadPacket.php +++ b/src/network/protocol/packet/RotateHeadPacket.php @@ -26,4 +26,21 @@ class RotateHeadPacket extends RakNetDataPacket{ $this->putByte($this->rawYaw ? $this->yaw : ($this->yaw / 360 / 0.0039062)); //wraps 360 angle to 0xff } + public function eidsToGlobal(Player $p){ + if($this->localEids){ + $this->localEids = false; + $this->eid = $p->local2GlobalEID[$this->eid] ?? false; + if($this->eid === false) return false; + } + return true; + } + + public function eidsToLocal(Player $p){ + if(!$this->localEids){ + $this->localEids = true; + $this->eid = $p->global2localEID[$this->eid] ?? false; + if($this->eid === false) return false; + } + return true; + } } \ No newline at end of file diff --git a/src/network/protocol/packet/SendInventoryPacket.php b/src/network/protocol/packet/SendInventoryPacket.php index 1bddca97..375b7032 100644 --- a/src/network/protocol/packet/SendInventoryPacket.php +++ b/src/network/protocol/packet/SendInventoryPacket.php @@ -38,5 +38,23 @@ class SendInventoryPacket extends RakNetDataPacket{ } } } + + public function eidsToGlobal(Player $p){ + if($this->localEids){ + $this->localEids = false; + $this->eid = $p->local2GlobalEID[$this->eid] ?? false; + if($this->eid === false) return false; + } + return true; + } + + public function eidsToLocal(Player $p){ + if(!$this->localEids){ + $this->localEids = true; + $this->eid = $p->global2localEID[$this->eid] ?? false; + if($this->eid === false) return false; + } + return true; + } } \ No newline at end of file diff --git a/src/network/protocol/packet/SetEntityDataPacket.php b/src/network/protocol/packet/SetEntityDataPacket.php index 8626885d..c30f35c9 100644 --- a/src/network/protocol/packet/SetEntityDataPacket.php +++ b/src/network/protocol/packet/SetEntityDataPacket.php @@ -17,5 +17,13 @@ class SetEntityDataPacket extends RakNetDataPacket{ $this->putInt($this->eid); $this->put(Utils::writeMetadata($this->metadata)); } + public function eidsToLocal(Player $p){ + if(!$this->localEids){ + $this->localEids = true; + $this->eid = $p->global2localEID[$this->eid] ?? false; + if($this->eid === false) return false; + } + return true; + } } \ No newline at end of file diff --git a/src/network/protocol/packet/SetEntityLinkPacket.php b/src/network/protocol/packet/SetEntityLinkPacket.php index 5dca8516..e01fa40a 100644 --- a/src/network/protocol/packet/SetEntityLinkPacket.php +++ b/src/network/protocol/packet/SetEntityLinkPacket.php @@ -28,4 +28,23 @@ class SetEntityLinkPacket extends RakNetDataPacket{ return ProtocolInfo::SET_ENTITY_LINK_PACKET; } + public function eidsToGlobal(Player $p){ + if($this->localEids){ + $this->localEids = false; + $this->rider = $p->local2GlobalEID[$this->rider] ?? false; + $this->riding = $p->local2GlobalEID[$this->riding] ?? false; + if($this->rider === false || $this->riding === false) return false; + } + return true; + } + + public function eidsToLocal(Player $p){ + if(!$this->localEids){ + $this->localEids = true; + $this->rider = $p->global2localEID[$this->rider] ?? false; + $this->riding = $p->global2localEID[$this->riding] ?? false; + if($this->rider === false || $this->riding === false) return false; + } + return true; + } } \ No newline at end of file diff --git a/src/network/protocol/packet/SetEntityMotionPacket.php b/src/network/protocol/packet/SetEntityMotionPacket.php index e4cf70b9..bc8ff9a1 100644 --- a/src/network/protocol/packet/SetEntityMotionPacket.php +++ b/src/network/protocol/packet/SetEntityMotionPacket.php @@ -21,5 +21,12 @@ class SetEntityMotionPacket extends RakNetDataPacket{ $this->putShort((int) ($this->speedY * 8000)); $this->putShort((int) ($this->speedZ * 8000)); } - + public function eidsToLocal(Player $p){ + if(!$this->localEids){ + $this->localEids = true; + $this->eid = $p->global2localEID[$this->eid] ?? false; + if($this->eid === false) return false; + } + return true; + } } \ No newline at end of file diff --git a/src/network/protocol/packet/StartGamePacket.php b/src/network/protocol/packet/StartGamePacket.php index a746ea3a..293a1b23 100644 --- a/src/network/protocol/packet/StartGamePacket.php +++ b/src/network/protocol/packet/StartGamePacket.php @@ -27,5 +27,13 @@ class StartGamePacket extends RakNetDataPacket{ $this->putFloat($this->y); $this->putFloat($this->z); } - + + public function eidsToLocal(Player $p){ + if(!$this->localEids){ + $this->localEids = true; + $this->eid = $p->global2localEID[$this->eid] ?? false; + if($this->eid === false) return false; + } + return true; + } } \ No newline at end of file diff --git a/src/network/protocol/packet/TakeItemEntityPacket.php b/src/network/protocol/packet/TakeItemEntityPacket.php index 85221c38..c64095d9 100644 --- a/src/network/protocol/packet/TakeItemEntityPacket.php +++ b/src/network/protocol/packet/TakeItemEntityPacket.php @@ -18,4 +18,14 @@ class TakeItemEntityPacket extends RakNetDataPacket{ $this->putInt($this->eid); } + //TODO convert + public function eidsToLocal(Player $p){ + if(!$this->localEids){ + $this->localEids = true; + $this->eid = $p->global2localEID[$this->eid] ?? false; + $this->target = $p->global2localEID[$this->eid] ?? false; + if($this->eid === false || $this->target === false) return false; + } + return true; + } } \ No newline at end of file diff --git a/src/network/protocol/packet/UseItemPacket.php b/src/network/protocol/packet/UseItemPacket.php index 32e2c651..6c2875da 100644 --- a/src/network/protocol/packet/UseItemPacket.php +++ b/src/network/protocol/packet/UseItemPacket.php @@ -38,5 +38,13 @@ class UseItemPacket extends RakNetDataPacket{ public function encode(){ } + public function eidsToGlobal(Player $p){ + if($this->localEids){ + $this->localEids = false; + $this->eid = $p->local2GlobalEID[$this->eid] ?? false; + if($this->eid === false) return false; + } + return true; + } } diff --git a/src/network/raknet/RakNetDataPacket.php b/src/network/raknet/RakNetDataPacket.php index 5f64ac47..25fd2e93 100755 --- a/src/network/raknet/RakNetDataPacket.php +++ b/src/network/raknet/RakNetDataPacket.php @@ -13,10 +13,18 @@ abstract class RakNetDataPacket extends stdClass{ public $splitIndex; private $offset = 0; - abstract public function encode(); + public abstract function encode(); - abstract public function decode(); + public abstract function decode(); + public $localEids = false; + public function eidsToLocal(Player $p){ + return true; + } + public function eidsToGlobal(Player $p){ + return true; + } + public function getBuffer(){ return $this->buffer; } diff --git a/src/network/raknet/RakNetParser.php b/src/network/raknet/RakNetParser.php index 764bf64f..900280a4 100644 --- a/src/network/raknet/RakNetParser.php +++ b/src/network/raknet/RakNetParser.php @@ -228,6 +228,7 @@ class RakNetParser{ $data->splitCount = $splitCount; $data->splitID = $splitID; $data->splitIndex = $splitIndex; + $data->localEids = true; $data->setBuffer($buf); } return $data; diff --git a/src/world/Level.php b/src/world/Level.php index d3729af5..b07569f1 100644 --- a/src/world/Level.php +++ b/src/world/Level.php @@ -395,7 +395,7 @@ class Level{ $this->server->api->time->set("day", $this); } foreach($this->players as $p){ - $p->stopSleep(); + if($p->isSleeping) $p->stopSleep(); } } From 6d10cfd896988c71d10492ea34db75bced068579 Mon Sep 17 00:00:00 2001 From: GameHerobrine Date: Sun, 29 Jun 2025 11:44:39 +0300 Subject: [PATCH 11/16] replaced more stuff with entity queue, added a limit to how many packets can be resent per tick --- src/Player.php | 11 +++++++++-- src/PocketMinecraftServer.php | 10 ++++++---- src/entity/Entity.php | 16 +++++++++++----- src/entity/ai/tasks/TaskEatTileGoal.php | 4 +++- src/entity/object/Arrow.php | 10 ---------- src/material/block/DoorBlock.php | 2 +- src/material/block/nonfull/FenceGateBlock.php | 2 +- 7 files changed, 31 insertions(+), 24 deletions(-) diff --git a/src/Player.php b/src/Player.php index 5b99f7a3..63bfc393 100755 --- a/src/Player.php +++ b/src/Player.php @@ -433,7 +433,7 @@ class Player{ $pk->speedX = 0; $pk->speedY = 0; $pk->speedZ = 0; - $this->entityQueueDataPacket($pk); + $this->dataPacketAlwaysRecover($pk); $pk = new MovePlayerPacket; $pk->eid = $this->eid; @@ -443,7 +443,7 @@ class Player{ $pk->bodyYaw = $yaw; $pk->pitch = $pitch; $pk->yaw = $yaw; - $this->entityQueueDataPacket($pk); + $this->dataPacketAlwaysRecover($pk); } /** @@ -1439,6 +1439,10 @@ class Player{ } public function handlePacketQueues(){ + if($this->server->ticks % 40 == 0){ //2s + $this->sendPing(); + } + if($this->connected === false){ return false; } @@ -1552,7 +1556,9 @@ class Player{ } if(($resendCnt = count($this->resendQueue)) > 0){ + $maxResendCnt = $resendCnt > 25 ? 25 : $resendCnt; foreach($this->resendQueue as $count => $data){ + if(--$maxResendCnt) break; unset($this->resendQueue[$count]); $this->packetStats[1]++; $this->lag[] = $time - $data->sendtime; @@ -3296,6 +3302,7 @@ class Player{ break; case RakNetInfo::ACK: + //if(mt_rand(0, 99) > 50) break; foreach($packet->packets as $count){ if(isset($this->packetAlwaysRecoverQueue[$count])){ $this->lag[] = $time - $this->packetAlwaysRecoverQueue[$count]->sendtime; diff --git a/src/PocketMinecraftServer.php b/src/PocketMinecraftServer.php index 2a0afd75..39a8523c 100644 --- a/src/PocketMinecraftServer.php +++ b/src/PocketMinecraftServer.php @@ -3,11 +3,16 @@ class PocketMinecraftServer{ 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 */ public $api; + /** + * @var Player[] + */ + public $clients; + private $serverip, $evCnt, $handCnt, $events, $eventsID, $handlers, $serverType, $lastTick, $memoryStats, $async = [], $asyncID = 0; public $doTick, $levelData, $tiles, $entities, $schedule, $scheduleCnt, $whitelist, $spawn, $difficulty, $stop, $asyncThread; @@ -631,9 +636,6 @@ class PocketMinecraftServer{ foreach($this->clients as $client){ $client->handlePacketQueues(); - if($this->ticks % 40 == 0){ //2s - $client->sendPing(); - } } foreach($this->api->level->levels as $l){ diff --git a/src/entity/Entity.php b/src/entity/Entity.php index 975fb90c..36104762 100644 --- a/src/entity/Entity.php +++ b/src/entity/Entity.php @@ -999,7 +999,9 @@ class Entity extends Position $pk->yaw = $this->yaw; $pk->pitch = $this->pitch; $pk->bodyYaw = $this->yaw; - $this->server->api->player->broadcastPacket($players, $pk); + foreach($players as $player){ + if($player->hasEntity($this)) $player->entityQueueDataPacket(clone $pk); + } } } } @@ -1602,14 +1604,14 @@ class Entity extends Position $pk->eid = $this->eid; $pk->event = EntityEventPacket::ENTITY_DAMAGE; foreach($this->level->players as $p){ - $p->entityQueueDataPacket(clone $pk); + if($p->hasEntity($this)) $p->entityQueueDataPacket(clone $pk); } } if($this->player instanceof Player){ $pk = new SetHealthPacket(); $pk->health = $this->health; - $this->player->entityQueueDataPacket($pk); + if($this->player->hasEntity($this)) $this->player->entityQueueDataPacket($pk); } if($this->health <= 0 and $this->dead === false){ $this->makeDead($cause); @@ -1646,12 +1648,16 @@ class Entity extends Position $pk->z = -256; $pk->yaw = 0; $pk->pitch = 0; - $this->server->api->player->broadcastPacket($this->level->players, $pk); + foreach($this->level->players as $player){ + if($player->hasEntity($this)) $player->entityQueueDataPacket(clone $pk); + } }else{ $pk = new EntityEventPacket; $pk->eid = $this->eid; $pk->event = EntityEventPacket::ENTITY_DEAD; - $this->server->api->player->broadcastPacket($this->level->players, $pk); + foreach($this->level->players as $player){ + if($player->hasEntity($this)) $player->entityQueueDataPacket(clone $pk); + } } if($this->player instanceof Player){ diff --git a/src/entity/ai/tasks/TaskEatTileGoal.php b/src/entity/ai/tasks/TaskEatTileGoal.php index 5af5d21e..8bc3766e 100644 --- a/src/entity/ai/tasks/TaskEatTileGoal.php +++ b/src/entity/ai/tasks/TaskEatTileGoal.php @@ -5,7 +5,9 @@ class TaskEatTileGoal extends TaskBase public function onStart(EntityAI $ai) { $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) diff --git a/src/entity/object/Arrow.php b/src/entity/object/Arrow.php index 5915c4cf..4b26a8a0 100644 --- a/src/entity/object/Arrow.php +++ b/src/entity/object/Arrow.php @@ -47,16 +47,6 @@ class Arrow extends Entity{ $data["shotByPlayer"] = $this->shotByPlayer; 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 $f2 = sqrt($d * $d + $d1 * $d1 + $d2 * $d2); diff --git a/src/material/block/DoorBlock.php b/src/material/block/DoorBlock.php index dfdc7bce..a1634cde 100644 --- a/src/material/block/DoorBlock.php +++ b/src/material/block/DoorBlock.php @@ -208,7 +208,7 @@ class DoorBlock extends TransparentBlock{ $pk->z = $this->z; $pk->evid = 1003; $pk->data = 0; - ServerAPI::request()->api->player->broadcastPacket($players, $pk); + ServerAPI::request()->api->player->broadcastPacket($players, $pk); //TODO use block queue? return true; } return false; diff --git a/src/material/block/nonfull/FenceGateBlock.php b/src/material/block/nonfull/FenceGateBlock.php index 977f346c..74d8c59e 100644 --- a/src/material/block/nonfull/FenceGateBlock.php +++ b/src/material/block/nonfull/FenceGateBlock.php @@ -75,7 +75,7 @@ class FenceGateBlock extends TransparentBlock{ $pk->z = $this->z; $pk->evid = 1003; $pk->data = 0; - ServerAPI::request()->api->player->broadcastPacket($players, $pk); + ServerAPI::request()->api->player->broadcastPacket($players, $pk); //TODO use blok queue? return true; } } From 385f15f1bb5a8cdcb95754883d63065a86eb20db Mon Sep 17 00:00:00 2001 From: GameHerobrine Date: Mon, 30 Jun 2025 07:45:19 +0300 Subject: [PATCH 12/16] fixed sequenced packets, entity movement uses unrealible_sequenced --- src/Player.php | 34 +++++++++++++++---------- src/network/raknet/RakNetCodec.php | 3 +++ src/network/raknet/RakNetDataPacket.php | 1 + src/network/raknet/RakNetParser.php | 7 +++++ 4 files changed, 31 insertions(+), 14 deletions(-) diff --git a/src/Player.php b/src/Player.php index 63bfc393..198df046 100755 --- a/src/Player.php +++ b/src/Player.php @@ -90,7 +90,7 @@ class Player{ public $entityMovementQueue; public $entityMovementQueueLength = 0; - public $entityMovementQueueOrderIndex = 0; + public $entityMovementQueueSeqIndex = 0; /** * @var RakNetPacket @@ -122,7 +122,6 @@ class Player{ * @var boolean */ public $sendingInventoryRequired = false; - public $expectedSetSlotPackets = []; public $expectedSetSlotIndex = -1; public $lastExpectedSetSlotIndexReceived = -1; @@ -1556,9 +1555,7 @@ class Player{ } if(($resendCnt = count($this->resendQueue)) > 0){ - $maxResendCnt = $resendCnt > 25 ? 25 : $resendCnt; foreach($this->resendQueue as $count => $data){ - if(--$maxResendCnt) break; unset($this->resendQueue[$count]); $this->packetStats[1]++; $this->lag[] = $time - $data->sendtime; @@ -1654,8 +1651,8 @@ class Player{ } public function convertToLocalEIDPacket(RakNetDataPacket $pk){ if(!$pk->eidsToLocal($this)){ - ConsoleAPI::warn("Failed to convert eids to local in {$pk->pid()}! (Player: {$this->ip}:{$this->port}). Stacktrace: "); - foreach(explode("\n", (new Exception())->getTraceAsString()) as $s) ConsoleAPI::warn($s); + ConsoleAPI::debug("Failed to convert eids to local in {$pk->pid()}! (Player: {$this->ip}:{$this->port}). Stacktrace: "); + foreach(explode("\n", (new Exception())->getTraceAsString()) as $s) ConsoleAPI::debug($s); return false; } return true; @@ -1722,7 +1719,7 @@ class Player{ $headSent = false; $localeid = $this->global2localEID[$e->eid] ?? false; if($localeid === false){ - ConsoleAPI::warn("Attempting to convert global eid to local failed! (Global: {$e->eid}, Player: {$this->ip}:{$this->port}). Stacktrace: "); + ConsoleAPI::warn("Attempt to convert global eid to local failed! (Global: {$e->eid}, Player: {$this->ip}:{$this->port}). Stacktrace: "); foreach(explode("\n", (new Exception())->getTraceAsString()) as $s) ConsoleAPI::warn($s); return false; } @@ -1739,7 +1736,7 @@ class Player{ $motion->speedY = $e->speedY; $motion->speedZ = $e->speedZ; $motion->encode(); - $len += 1 + strlen($motion->buffer); + $len += 10 + strlen($motion->buffer); ++$packets; $motionSent = true; } @@ -1771,7 +1768,7 @@ class Player{ $move->encode(); } - $len += strlen($move->buffer) + 1; + $len += strlen($move->buffer) + 10; ++$packets; $moveSent = true; }else if($e->headYaw != $e->lastHeadYaw){ @@ -1779,7 +1776,7 @@ class Player{ $headyaw->eid = $localeid; $headyaw->yaw = $e->headYaw; $headyaw->encode(); - $len += strlen($headyaw->buffer) + 1; + $len += strlen($headyaw->buffer) + 10; ++$packets; $headSent = true; } @@ -1791,21 +1788,30 @@ class Player{ } if($motionSent){ $motion->messageIndex = 0; //force 0 cuz reliability 0 - $motion->reliability = 0; + $motion->reliability = 1; + $motion->orderIndex = $this->entityDataQueueOrderIndex; + $motion->orderChannel = self::ENTITY_ORDER_CHANNEL; + $motion->seqIndex = $this->entityMovementQueueSeqIndex++; $this->entityMovementQueue->data[] = $motion; } if($moveSent){ $move->messageIndex = 0; - $move->reliability = 0; + $move->reliability = 1; + $move->orderIndex = $this->entityDataQueueOrderIndex; + $move->orderChannel = self::ENTITY_ORDER_CHANNEL; + $move->seqIndex = $this->entityMovementQueueSeqIndex++; $this->entityMovementQueue->data[] = $move; } if($headSent){ $headyaw->messageIndex = 0; - $headyaw->reliability = 0; + $headyaw->reliability = 1; + $headyaw->orderIndex = $this->entityDataQueueOrderIndex; + $headyaw->orderChannel = self::ENTITY_ORDER_CHANNEL; + $headyaw->seqIndex = $this->entityMovementQueueSeqIndex++; $this->entityMovementQueue->data[] = $headyaw; } - $this->entityMovementQueueLength += 6*$packets + $len; + $this->entityMovementQueueLength += $len; $this->entityMovementPacketsPerSecond += $packets; } diff --git a/src/network/raknet/RakNetCodec.php b/src/network/raknet/RakNetCodec.php index bbd52589..b8e5b55b 100644 --- a/src/network/raknet/RakNetCodec.php +++ b/src/network/raknet/RakNetCodec.php @@ -106,6 +106,9 @@ class RakNetCodec{ or $pk->reliability === 7){ $packet->buffer .= Utils::writeLTriad($pk->messageIndex); } + if($pk->reliability == 1 || $pk->reliability == 4){ + $packet->buffer .= Utils::writeLTriad($pk->seqIndex); + } if($pk->reliability === 1 or $pk->reliability === 3 diff --git a/src/network/raknet/RakNetDataPacket.php b/src/network/raknet/RakNetDataPacket.php index 25fd2e93..8a45a3e5 100755 --- a/src/network/raknet/RakNetDataPacket.php +++ b/src/network/raknet/RakNetDataPacket.php @@ -11,6 +11,7 @@ abstract class RakNetDataPacket extends stdClass{ public $splitCount; public $splitID; public $splitIndex; + public $seqIndex; private $offset = 0; public abstract function encode(); diff --git a/src/network/raknet/RakNetParser.php b/src/network/raknet/RakNetParser.php index 900280a4..74bc3708 100644 --- a/src/network/raknet/RakNetParser.php +++ b/src/network/raknet/RakNetParser.php @@ -124,6 +124,12 @@ class RakNetParser{ }else{ $messageIndex = false; } + if($reliability == 1 || $reliability == 4){ + $offset += 3; + $seqIndex = Utils::readTriad(strrev(substr($buffer, $offset - 3, 3))); + }else{ + $seqIndex = false; + } if($reliability == 1 ||$reliability == 3 || $reliability == 4 || $reliability == 7){ $offset += 3; @@ -228,6 +234,7 @@ class RakNetParser{ $data->splitCount = $splitCount; $data->splitID = $splitID; $data->splitIndex = $splitIndex; + $data->seqIndex = $seqIndex; $data->localEids = true; $data->setBuffer($buf); } From dd6db76577cdc2953a673a186eed5fa8a0090252 Mon Sep 17 00:00:00 2001 From: GameHerobrine Date: Mon, 30 Jun 2025 15:06:58 +0300 Subject: [PATCH 13/16] big chat messages support --- src/Player.php | 41 +++++++++++++++++++++++++++++++++++++++-- 1 file changed, 39 insertions(+), 2 deletions(-) diff --git a/src/Player.php b/src/Player.php index 198df046..a3d16826 100755 --- a/src/Player.php +++ b/src/Player.php @@ -525,7 +525,43 @@ class Player{ $this->packetAlwaysRecoverQueue[$pk->seqNumber] = $pk; return [$pk->seqNumber]; } - + public function sendChatMessagePacket_big(RakNetDataPacket $pk){ + $sendtime = microtime(true); + $size = $this->MTU - 34; + if($size <= 0) return false; + $buffer = str_split($pk->buffer, $size); + $bigCnt = $this->bigCnt; + $this->bigCnt = ($this->bigCnt + 1) % 0x10000; + $cnts = []; + $bufCount = count($buffer); + + $orderIndex = $this->chatMessagesOrderIndex++; + foreach($buffer as $i => $buf){ + $cnts[] = $count = $this->counter[0]++; + + $pk = new UnknownPacket; + $pk->packetID = $pk->pid(); + $pk->reliability = 3; + + $pk->orderChannel = Player::CHATMESSAGE_ORDER_CHANNEL; + $pk->orderIndex = $orderIndex; + + $pk->hasSplit = true; + $pk->splitCount = $bufCount; + $pk->splitID = $bigCnt; + $pk->splitIndex = $i; + $pk->buffer = $buf; + $pk->messageIndex = $this->counter[3]++; + + $rk = new RakNetPacket(RakNetInfo::DATA_PACKET_0); + $rk->data[] = $pk; + $rk->seqNumber = $count; + $rk->sendtime = $sendtime; + $this->packetAlwaysRecoverQueue[$count] = $rk; + $this->send($rk); + } + return $cnts; + } public function blockQueueDataPacket_big(RakNetDataPacket $pk){ $sendtime = microtime(true); $size = $this->MTU - 34; @@ -1907,10 +1943,10 @@ class Player{ if(EventHandler::callEvent(new DataPacketSendEvent($this, $packet)) === BaseEvent::DENY) return false; if(isset(ProtocolInfo::EID_PACKETS[$packet->pid()])) if(!$this->convertToLocalEIDPacket($packet)) return false; - //TODO big chat messages support $packet->encode(); $len = strlen($packet->buffer) + 1; $MTU = $this->MTU - 24; + if($len > $MTU) return $this->sendChatMessagePacket_big($packet); if(($this->chatMessagesQueueLength + $len) >= $MTU) $this->sendChatBuffer(); @@ -2180,6 +2216,7 @@ class Player{ if($this->loggedIn === false){ break; } + switch($packet->status){ case 1: //Spawn!! if($this->spawned !== false){ From 3eea709f94888ed3bd6a56083bbf0ea4dba0fa83 Mon Sep 17 00:00:00 2001 From: GameHerobrine Date: Mon, 30 Jun 2025 15:47:41 +0300 Subject: [PATCH 14/16] removed some debug output --- src/Player.php | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/Player.php b/src/Player.php index a3d16826..52f279e8 100755 --- a/src/Player.php +++ b/src/Player.php @@ -2096,7 +2096,7 @@ class Player{ } $this->auth = true; - if(!$this->data->exists("inventory") or ($this->gamemode & 0x01) === 0x01){ + if(!$this->data->exists("inventory") || ($this->gamemode & 0x01) === 0x01){ if(($this->gamemode & 0x01) === 0x01){ $inv = []; if(($this->gamemode & 0x02) === 0x02){ @@ -2227,7 +2227,6 @@ class Player{ $pk->time = $this->level->getTime(); $pk->started = !$this->level->isTimeStopped(); $this->dataPacketAlwaysRecover($pk); - console($this->level->getTime()); $pos = new Position($this->entity->x, $this->entity->y, $this->entity->z, $this->level); $pData = $this->data->get("position"); From 31ae78674852af19043fc2da0c582193b5085cfe Mon Sep 17 00:00:00 2001 From: GameHerobrine Date: Tue, 1 Jul 2025 07:03:39 +0300 Subject: [PATCH 15/16] invisibility was rewritten --- src/Player.php | 124 ++++++++++++++++++++++++++++-------------- src/entity/Entity.php | 28 ++++++---- 2 files changed, 101 insertions(+), 51 deletions(-) diff --git a/src/Player.php b/src/Player.php index 52f279e8..48c36c97 100755 --- a/src/Player.php +++ b/src/Player.php @@ -147,6 +147,8 @@ class Player{ */ public $lastLocalEID = 0; + public $invisibleFor = []; + /** * @param integer $clientID * @param string $ip @@ -324,26 +326,8 @@ class Player{ foreach($this->level->entityList as $e){ if($e->eid !== $this->entity->eid){ if($e->isPlayer()){ - $pk = new MovePlayerPacket(); - $pk->eid = $this->entity->eid; - $pk->x = -256; - $pk->y = 128; - $pk->z = -256; - $pk->yaw = 0; - $pk->pitch = 0; - $pk->bodyYaw = 0; - $e->player->entityQueueDataPacket($pk); - - $pk = new MovePlayerPacket(); - $pk->eid = $e->eid; - $pk->x = -256; - $pk->y = 128; - $pk->z = -256; - $pk->yaw = 0; - $pk->pitch = 0; - $pk->bodyYaw = 0; - $this->entityQueueDataPacket($pk); - + $this->setInvisibleFor($e->player, true); + $e->player->setInvisibleFor($this, true); }else{ $pk = new RemoveEntityPacket(); $pk->eid = $e->eid; @@ -377,14 +361,8 @@ class Player{ $terrain = true; foreach($this->level->players as $player){ if($player !== $this and $player->entity instanceof Entity){ - $pk = new MoveEntityPacket_PosRot; - $pk->eid = $player->entity->eid; - $pk->x = $player->entity->x; - $pk->y = $player->entity->y; - $pk->z = $player->entity->z; - $pk->yaw = $player->entity->yaw; - $pk->pitch = $player->entity->pitch; - $this->entityQueueDataPacket($pk); + $player->setInvisibleFor($this, false); + $this->setInvisibleFor($player, false); $pk = new PlayerEquipmentPacket; $pk->eid = $this->eid; @@ -1049,9 +1027,19 @@ class Player{ } return true; } + + public function invisibilityHandler(&$data, $event){ + $target = $data["target"]; + if($target == $this){ + $for = $data["for"]; + if($target->level != $for->level || $target->gamemode == SPECTATOR) { + $data["status"] = true; + } + } + } /** - * @param mixed $data + * @param mixed &$data * @param string $event */ public function eventHandler($data, $event){ @@ -1282,16 +1270,54 @@ class Player{ } } - public function makeInvisibleForOnePlayer(Player $player){ - //TODO rewrite how invisibility is handled - $pk = new RemoveEntityPacket; - $pk->eid = $this->entity->eid; - $player->entityQueueDataPacket($pk); + + public function isInvisibleFor(Player $player){ + return isset($this->invisibleFor[$player->CID]); } + + public function setInvisibleFor(Player $player, $b, $send=true){ + $data = [ + "target" => $this, + "for" => $player, + "status" => $b + ]; + + $this->server->handle("player.invisible", $data); + $b = $data["status"]; + + if($b){ + $this->invisibleFor[$player->CID] = $b; + if($send){ + $pk = new MovePlayerPacket(); + $pk->x = -256; + $pk->y = 128; + $pk->z = -256; + $pk->eid = $this->eid; + $pk->yaw = 0; + $pk->pitch = 0; + $pk->headYaw = 0; + $player->entityQueueDataPacket($pk); + } + }else{ + unset($this->invisibleFor[$player->CID]); + if($send){ + $pk = new MovePlayerPacket(); + $pk->eid = $this->entity->eid; + $pk->x = $this->entity->x; + $pk->y = $this->entity->y; + $pk->z = $this->entity->z; + $pk->yaw = $this->entity->yaw; + $pk->pitch = $this->entity->pitch; + $pk->bodyYaw = $this->entity->headYaw; + $player->entityQueueDataPacket($pk); + } + } + } + public function makeInvisibleForAllPlayers(){ - $pk = new RemoveEntityPacket; - $pk->eid = $this->entity->eid; - $this->server->api->player->broadcastPacket($this->server->api->player->getAll($this->level), $pk); + foreach($this->server->api->player->getA as $player){ + if($player->CID != $this->CID) $this->setInvisibleFor($player, true); + } } public function getGamemode(){ switch($this->gamemode){ @@ -1385,10 +1411,14 @@ class Player{ } if($this->gamemode === SPECTATOR){ - $this->makeInvisibleForAllPlayers(); + foreach($this->server->api->player->getAll() as $player){ + if($player->CID != $this->CID) $this->setInvisibleFor($player, true); + } } if($this->gamemode === CREATIVE){ - $this->server->api->player->spawnToAllPlayers($this); + foreach($this->server->api->player->getAll() as $player){ + if($player->CID != $this->CID) $this->setInvisibleFor($player, false); + } } $this->inventory = $inv; @@ -1881,6 +1911,11 @@ class Player{ if($msg === true and $this->username != "" and $this->spawned !== false){ $this->server->api->chat->broadcast($this->username . " left the game: " . $reason); } + + foreach($this->server->api->player->getAll() as $player){ + $player->setInvisibleFor($this, false); + } + $this->spawned = false; console("[INFO] " . FORMAT_AQUA . $this->username . FORMAT_RESET . "[/" . $this->ip . ":" . $this->port . "] logged out due to " . $reason); $this->windows = []; @@ -2206,6 +2241,7 @@ class Player{ $this->evid[] = $this->server->event("player.pickup", [$this, "eventHandler"]); $this->evid[] = $this->server->event("tile.container.slot", [$this, "eventHandler"]); $this->evid[] = $this->server->event("tile.update", [$this, "eventHandler"]); + $this->server->addHandler("player.invisible", [$this, "invisibilityHandler"]); $this->lastMeasure = microtime(true); $this->server->schedule(50, [$this, "measureLag"], [], true); @@ -2706,7 +2742,7 @@ class Player{ $pk->pitch = $this->entity->pitch; $pk->bodyYaw = $this->entity->headYaw; foreach($this->entity->level->players as $player){ - if($player->entity->eid != $this->entity->eid){ + if($player->entity->eid != $this->entity->eid && !$this->isInvisibleFor($player)){ $player->entityQueueDataPacket(clone $pk); } } @@ -3397,6 +3433,14 @@ class Player{ } + /** + * @deprecated use Player::setInvisibleFor + * @param Player $player + */ + public function makeInvisibleForOnePlayer(Player $player){ + $this->setInvisibleFor($player, true); + } + /** * @deprecated craft system changed * @param array $craft diff --git a/src/entity/Entity.php b/src/entity/Entity.php index 36104762..3121b487 100644 --- a/src/entity/Entity.php +++ b/src/entity/Entity.php @@ -998,9 +998,9 @@ class Entity extends Position $pk->z = $this->z; $pk->yaw = $this->yaw; $pk->pitch = $this->pitch; - $pk->bodyYaw = $this->yaw; + $pk->bodyYaw = $this->headYaw; foreach($players as $player){ - if($player->hasEntity($this)) $player->entityQueueDataPacket(clone $pk); + if($player->hasEntity($this) && !$this->player->isInvisibleFor($player)) $player->entityQueueDataPacket(clone $pk); } } } @@ -1149,21 +1149,27 @@ class Entity extends Position if($this->player->connected !== true or $this->player->spawned === false){ return false; } - if($this->player->gamemode === SPECTATOR){ - break; - } $player->addEntity($this); - + if($this->level != $player->entity->level || $this->player->gamemode === SPECTATOR) $this->player->setInvisibleFor($player, true, send:false); $pk = new AddPlayerPacket(); $pk->clientID = 0; // $this->player->clientID; $pk->username = $this->player->username; $pk->eid = $this->eid; - $pk->x = $this->x; - $pk->y = $this->y; - $pk->z = $this->z; - $pk->yaw = 0; - $pk->pitch = 0; + if($this->player->isInvisibleFor($player)){ + $pk->x = -256; + $pk->y = 128; + $pk->z = -256; + $pk->yaw = 0; + $pk->pitch = 0; + }else{ + $pk->x = $this->x; + $pk->y = $this->y; + $pk->z = $this->z; + $pk->yaw = $this->yaw; + $pk->pitch = $this->pitch; + } + $pk->itemID = 0; $pk->itemAuxValue = 0; $pk->metadata = $this->getMetadata(); From 00c03d8bf05b7670ea9db55d79024685718ae26f Mon Sep 17 00:00:00 2001 From: GameHerobrine Date: Tue, 1 Jul 2025 09:47:04 +0300 Subject: [PATCH 16/16] readded limit to resendQueue, MovePlayerPacket will be sent after AddPlayerPacket to fix AddPlayerPacket bug --- src/Player.php | 2 ++ src/entity/Entity.php | 28 +++++++++++++++++----------- 2 files changed, 19 insertions(+), 11 deletions(-) diff --git a/src/Player.php b/src/Player.php index 48c36c97..9f71cabe 100755 --- a/src/Player.php +++ b/src/Player.php @@ -1621,7 +1621,9 @@ class Player{ } if(($resendCnt = count($this->resendQueue)) > 0){ + $limit = 25; foreach($this->resendQueue as $count => $data){ + if(!--$limit) break; unset($this->resendQueue[$count]); $this->packetStats[1]++; $this->lag[] = $time - $data->sendtime; diff --git a/src/entity/Entity.php b/src/entity/Entity.php index 3121b487..04575501 100644 --- a/src/entity/Entity.php +++ b/src/entity/Entity.php @@ -1153,27 +1153,33 @@ class Entity extends Position $player->addEntity($this); if($this->level != $player->entity->level || $this->player->gamemode === SPECTATOR) $this->player->setInvisibleFor($player, true, send:false); $pk = new AddPlayerPacket(); + $pkm = new MovePlayerPacket(); $pk->clientID = 0; // $this->player->clientID; $pk->username = $this->player->username; - $pk->eid = $this->eid; + $pkm->eid = $pk->eid = $this->eid; + if($this->player->isInvisibleFor($player)){ - $pk->x = -256; - $pk->y = 128; - $pk->z = -256; - $pk->yaw = 0; - $pk->pitch = 0; + $pkm->x = $pk->x = -256; + $pkm->y = $pk->y = 128; + $pkm->z = $pk->z = -256; + $pkm->yaw = $pk->yaw = 0; + $pkm->pitch = $pk->pitch = 0; + $pkm->bodyYaw = 0; }else{ - $pk->x = $this->x; - $pk->y = $this->y; - $pk->z = $this->z; - $pk->yaw = $this->yaw; - $pk->pitch = $this->pitch; + $pkm->x = $pk->x = $this->x; + $pkm->y = $pk->y = $this->y; + $pkm->z = $pk->z = $this->z; + $pkm->yaw = $pk->yaw = $this->yaw; + $pkm->pitch = $pk->pitch = $this->pitch; + $pkm->bodyYaw = $this->headYaw; } $pk->itemID = 0; $pk->itemAuxValue = 0; $pk->metadata = $this->getMetadata(); $player->entityQueueDataPacket($pk); + //AddPlayerPacket doesnt read yaw correctly in vanilla(uses PacketUtil::Rot_degreesToChar instead of PacketUtil::Rot_charToDegrees) + $player->entityQueueDataPacket($pkm); $pk = new PlayerEquipmentPacket(); $pk->eid = $this->eid;