PocketMine-MP 5.30.2 git-98f04176111e5ecab5e8814ffc69d992bfb64939
Loading...
Searching...
No Matches
InGamePacketHandler.php
1<?php
2
3/*
4 *
5 * ____ _ _ __ __ _ __ __ ____
6 * | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
7 * | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
8 * | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
9 * |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
10 *
11 * This program is free software: you can redistribute it and/or modify
12 * it under the terms of the GNU Lesser General Public License as published by
13 * the Free Software Foundation, either version 3 of the License, or
14 * (at your option) any later version.
15 *
16 * @author PocketMine Team
17 * @link http://www.pocketmine.net/
18 *
19 *
20 */
21
22declare(strict_types=1);
23
24namespace pocketmine\network\mcpe\handler;
25
108use function array_push;
109use function count;
110use function fmod;
111use function get_debug_type;
112use function implode;
113use function in_array;
114use function is_infinite;
115use function is_nan;
116use function json_decode;
117use function max;
118use function mb_strlen;
119use function microtime;
120use function sprintf;
121use function str_starts_with;
122use function strlen;
123use const JSON_THROW_ON_ERROR;
124
129 private const MAX_FORM_RESPONSE_DEPTH = 2; //modal/simple will be 1, custom forms 2 - they will never contain anything other than string|int|float|bool|null
130
131 protected float $lastRightClickTime = 0.0;
132 protected ?UseItemTransactionData $lastRightClickData = null;
133
134 protected ?Vector3 $lastPlayerAuthInputPosition = null;
135 protected ?float $lastPlayerAuthInputYaw = null;
136 protected ?float $lastPlayerAuthInputPitch = null;
137 protected ?BitSet $lastPlayerAuthInputFlags = null;
138
139 protected ?BlockPosition $lastBlockAttacked = null;
140
141 public bool $forceMoveSync = false;
142
143 protected ?string $lastRequestedFullSkinId = null;
144
145 public function __construct(
146 private Player $player,
147 private NetworkSession $session,
148 private InventoryManager $inventoryManager
149 ){}
150
151 public function handleText(TextPacket $packet) : bool{
152 if($packet->type === TextPacket::TYPE_CHAT){
153 return $this->player->chat($packet->message);
154 }
155
156 return false;
157 }
158
159 public function handleMovePlayer(MovePlayerPacket $packet) : bool{
160 //The client sends this every time it lands on the ground, even when using PlayerAuthInputPacket.
161 //Silence the debug spam that this causes.
162 return true;
163 }
164
165 private function resolveOnOffInputFlags(BitSet $inputFlags, int $startFlag, int $stopFlag) : ?bool{
166 $enabled = $inputFlags->get($startFlag);
167 $disabled = $inputFlags->get($stopFlag);
168 if($enabled !== $disabled){
169 return $enabled;
170 }
171 //neither flag was set, or both were set
172 return null;
173 }
174
175 public function handlePlayerAuthInput(PlayerAuthInputPacket $packet) : bool{
176 $rawPos = $packet->getPosition();
177 $rawYaw = $packet->getYaw();
178 $rawPitch = $packet->getPitch();
179 foreach([$rawPos->x, $rawPos->y, $rawPos->z, $rawYaw, $packet->getHeadYaw(), $rawPitch] as $float){
180 if(is_infinite($float) || is_nan($float)){
181 $this->session->getLogger()->debug("Invalid movement received, contains NAN/INF components");
182 return false;
183 }
184 }
185
186 if($rawYaw !== $this->lastPlayerAuthInputYaw || $rawPitch !== $this->lastPlayerAuthInputPitch){
187 $this->lastPlayerAuthInputYaw = $rawYaw;
188 $this->lastPlayerAuthInputPitch = $rawPitch;
189
190 $yaw = fmod($rawYaw, 360);
191 $pitch = fmod($rawPitch, 360);
192 if($yaw < 0){
193 $yaw += 360;
194 }
195
196 $this->player->setRotation($yaw, $pitch);
197 }
198
199 $hasMoved = $this->lastPlayerAuthInputPosition === null || !$this->lastPlayerAuthInputPosition->equals($rawPos);
200 $newPos = $rawPos->subtract(0, 1.62, 0)->round(4);
201
202 if($this->forceMoveSync && $hasMoved){
203 $curPos = $this->player->getLocation();
204
205 if($newPos->distanceSquared($curPos) > 1){ //Tolerate up to 1 block to avoid problems with client-sided physics when spawning in blocks
206 $this->session->getLogger()->debug("Got outdated pre-teleport movement, received " . $newPos . ", expected " . $curPos);
207 //Still getting movements from before teleport, ignore them
208 return true;
209 }
210
211 // Once we get a movement within a reasonable distance, treat it as a teleport ACK and remove position lock
212 $this->forceMoveSync = false;
213 }
214
215 $inputFlags = $packet->getInputFlags();
216 if($this->lastPlayerAuthInputFlags === null || !$inputFlags->equals($this->lastPlayerAuthInputFlags)){
217 $this->lastPlayerAuthInputFlags = $inputFlags;
218
219 $sneaking = $inputFlags->get(PlayerAuthInputFlags::SNEAKING);
220 if($this->player->isSneaking() === $sneaking){
221 $sneaking = null;
222 }
223 $sprinting = $this->resolveOnOffInputFlags($inputFlags, PlayerAuthInputFlags::START_SPRINTING, PlayerAuthInputFlags::STOP_SPRINTING);
224 $swimming = $this->resolveOnOffInputFlags($inputFlags, PlayerAuthInputFlags::START_SWIMMING, PlayerAuthInputFlags::STOP_SWIMMING);
225 $gliding = $this->resolveOnOffInputFlags($inputFlags, PlayerAuthInputFlags::START_GLIDING, PlayerAuthInputFlags::STOP_GLIDING);
226 $flying = $this->resolveOnOffInputFlags($inputFlags, PlayerAuthInputFlags::START_FLYING, PlayerAuthInputFlags::STOP_FLYING);
227 $mismatch =
228 ($sneaking !== null && !$this->player->toggleSneak($sneaking)) |
229 ($sprinting !== null && !$this->player->toggleSprint($sprinting)) |
230 ($swimming !== null && !$this->player->toggleSwim($swimming)) |
231 ($gliding !== null && !$this->player->toggleGlide($gliding)) |
232 ($flying !== null && !$this->player->toggleFlight($flying));
233 if((bool) $mismatch){
234 $this->player->sendData([$this->player]);
235 }
236
237 if($inputFlags->get(PlayerAuthInputFlags::START_JUMPING)){
238 $this->player->jump();
239 }
240 if($inputFlags->get(PlayerAuthInputFlags::MISSED_SWING)){
241 $this->player->missSwing();
242 }
243 }
244
245 if(!$this->forceMoveSync && $hasMoved){
246 $this->lastPlayerAuthInputPosition = $rawPos;
247 //TODO: this packet has WAYYYYY more useful information that we're not using
248 $this->player->handleMovement($newPos);
249 }
250
251 $packetHandled = true;
252
253 $useItemTransaction = $packet->getItemInteractionData();
254 if($useItemTransaction !== null){
255 if(count($useItemTransaction->getTransactionData()->getActions()) > 100){
256 throw new PacketHandlingException("Too many actions in item use transaction");
257 }
258
259 $this->inventoryManager->setCurrentItemStackRequestId($useItemTransaction->getRequestId());
260 $this->inventoryManager->addRawPredictedSlotChanges($useItemTransaction->getTransactionData()->getActions());
261 if(!$this->handleUseItemTransaction($useItemTransaction->getTransactionData())){
262 $packetHandled = false;
263 $this->session->getLogger()->debug("Unhandled transaction in PlayerAuthInputPacket (type " . $useItemTransaction->getTransactionData()->getActionType() . ")");
264 }else{
265 $this->inventoryManager->syncMismatchedPredictedSlotChanges();
266 }
267 $this->inventoryManager->setCurrentItemStackRequestId(null);
268 }
269
270 $itemStackRequest = $packet->getItemStackRequest();
271 $itemStackResponseBuilder = $itemStackRequest !== null ? $this->handleSingleItemStackRequest($itemStackRequest) : null;
272
273 //itemstack request or transaction may set predictions for the outcome of these actions, so these need to be
274 //processed last
275 $blockActions = $packet->getBlockActions();
276 if($blockActions !== null){
277 if(count($blockActions) > 100){
278 throw new PacketHandlingException("Too many block actions in PlayerAuthInputPacket");
279 }
280 foreach(Utils::promoteKeys($blockActions) as $k => $blockAction){
281 $actionHandled = false;
282 if($blockAction instanceof PlayerBlockActionStopBreak){
283 $actionHandled = $this->handlePlayerActionFromData($blockAction->getActionType(), new BlockPosition(0, 0, 0), Facing::DOWN);
284 }elseif($blockAction instanceof PlayerBlockActionWithBlockInfo){
285 $actionHandled = $this->handlePlayerActionFromData($blockAction->getActionType(), $blockAction->getBlockPosition(), $blockAction->getFace());
286 }
287
288 if(!$actionHandled){
289 $packetHandled = false;
290 $this->session->getLogger()->debug("Unhandled player block action at offset $k in PlayerAuthInputPacket");
291 }
292 }
293 }
294
295 if($itemStackRequest !== null){
296 $itemStackResponse = $itemStackResponseBuilder?->build() ?? new ItemStackResponse(ItemStackResponse::RESULT_ERROR, $itemStackRequest->getRequestId());
297 $this->session->sendDataPacket(ItemStackResponsePacket::create([$itemStackResponse]));
298 }
299
300 return $packetHandled;
301 }
302
303 public function handleActorEvent(ActorEventPacket $packet) : bool{
304 if($packet->actorRuntimeId !== $this->player->getId()){
305 //TODO HACK: EATING_ITEM is sent back to the server when the server sends it for other players (1.14 bug, maybe earlier)
306 return $packet->actorRuntimeId === ActorEvent::EATING_ITEM;
307 }
308
309 switch($packet->eventId){
310 case ActorEvent::EATING_ITEM: //TODO: ignore this and handle it server-side
311 $item = $this->player->getInventory()->getItemInHand();
312 if($item->isNull()){
313 return false;
314 }
315 $this->player->broadcastAnimation(new ConsumingItemAnimation($this->player, $this->player->getInventory()->getItemInHand()));
316 break;
317 default:
318 return false;
319 }
320
321 return true;
322 }
323
324 public function handleInventoryTransaction(InventoryTransactionPacket $packet) : bool{
325 $result = true;
326
327 if(count($packet->trData->getActions()) > 50){
328 throw new PacketHandlingException("Too many actions in inventory transaction");
329 }
330 if(count($packet->requestChangedSlots) > 10){
331 throw new PacketHandlingException("Too many slot sync requests in inventory transaction");
332 }
333
334 $this->inventoryManager->setCurrentItemStackRequestId($packet->requestId);
335 $this->inventoryManager->addRawPredictedSlotChanges($packet->trData->getActions());
336
337 if($packet->trData instanceof NormalTransactionData){
338 $result = $this->handleNormalTransaction($packet->trData, $packet->requestId);
339 }elseif($packet->trData instanceof MismatchTransactionData){
340 $this->session->getLogger()->debug("Mismatch transaction received");
341 $this->inventoryManager->requestSyncAll();
342 $result = true;
343 }elseif($packet->trData instanceof UseItemTransactionData){
344 $result = $this->handleUseItemTransaction($packet->trData);
345 }elseif($packet->trData instanceof UseItemOnEntityTransactionData){
346 $result = $this->handleUseItemOnEntityTransaction($packet->trData);
347 }elseif($packet->trData instanceof ReleaseItemTransactionData){
348 $result = $this->handleReleaseItemTransaction($packet->trData);
349 }
350
351 $this->inventoryManager->syncMismatchedPredictedSlotChanges();
352
353 //requestChangedSlots asks the server to always send out the contents of the specified slots, even if they
354 //haven't changed. Handling these is necessary to ensure the client inventory stays in sync if the server
355 //rejects the transaction. The most common example of this is equipping armor by right-click, which doesn't send
356 //a legacy prediction action for the destination armor slot.
357 foreach($packet->requestChangedSlots as $containerInfo){
358 foreach($containerInfo->getChangedSlotIndexes() as $netSlot){
359 [$windowId, $slot] = ItemStackContainerIdTranslator::translate($containerInfo->getContainerId(), $this->inventoryManager->getCurrentWindowId(), $netSlot);
360 $inventoryAndSlot = $this->inventoryManager->locateWindowAndSlot($windowId, $slot);
361 if($inventoryAndSlot !== null){ //trigger the normal slot sync logic
362 $this->inventoryManager->onSlotChange($inventoryAndSlot[0], $inventoryAndSlot[1]);
363 }
364 }
365 }
366
367 $this->inventoryManager->setCurrentItemStackRequestId(null);
368 return $result;
369 }
370
371 private function executeInventoryTransaction(InventoryTransaction $transaction, int $requestId) : bool{
372 $this->player->setUsingItem(false);
373
374 $this->inventoryManager->setCurrentItemStackRequestId($requestId);
375 $this->inventoryManager->addTransactionPredictedSlotChanges($transaction);
376 try{
377 $transaction->execute();
379 $this->inventoryManager->requestSyncAll();
380 $logger = $this->session->getLogger();
381 $logger->debug("Invalid inventory transaction $requestId: " . $e->getMessage());
382
383 return false;
385 $this->session->getLogger()->debug("Inventory transaction $requestId cancelled by a plugin");
386
387 return false;
388 }finally{
389 $this->inventoryManager->syncMismatchedPredictedSlotChanges();
390 $this->inventoryManager->setCurrentItemStackRequestId(null);
391 }
392
393 return true;
394 }
395
396 private function handleNormalTransaction(NormalTransactionData $data, int $itemStackRequestId) : bool{
397 //When the ItemStackRequest system is used, this transaction type is used for dropping items by pressing Q.
398 //I don't know why they don't just use ItemStackRequest for that too, which already supports dropping items by
399 //clicking them outside an open inventory menu, but for now it is what it is.
400 //Fortunately, this means we can be much stricter about the validation criteria.
401
402 $actionCount = count($data->getActions());
403 if($actionCount > 2){
404 if($actionCount > 5){
405 throw new PacketHandlingException("Too many actions ($actionCount) in normal inventory transaction");
406 }
407
408 //Due to a bug in the game, this transaction type is still sent when a player edits a book. We don't need
409 //these transactions for editing books, since we have BookEditPacket, so we can just ignore them.
410 $this->session->getLogger()->debug("Ignoring normal inventory transaction with $actionCount actions (drop-item should have exactly 2 actions)");
411 return false;
412 }
413
414 $sourceSlot = null;
415 $clientItemStack = null;
416 $droppedCount = null;
417
418 foreach($data->getActions() as $networkInventoryAction){
419 if($networkInventoryAction->sourceType === NetworkInventoryAction::SOURCE_WORLD && $networkInventoryAction->inventorySlot === NetworkInventoryAction::ACTION_MAGIC_SLOT_DROP_ITEM){
420 $droppedCount = $networkInventoryAction->newItem->getItemStack()->getCount();
421 if($droppedCount <= 0){
422 throw new PacketHandlingException("Expected positive count for dropped item");
423 }
424 }elseif($networkInventoryAction->sourceType === NetworkInventoryAction::SOURCE_CONTAINER && $networkInventoryAction->windowId === ContainerIds::INVENTORY){
425 //mobile players can drop an item from a non-selected hotbar slot
426 $sourceSlot = $networkInventoryAction->inventorySlot;
427 $clientItemStack = $networkInventoryAction->oldItem->getItemStack();
428 }else{
429 $this->session->getLogger()->debug("Unexpected inventory action type $networkInventoryAction->sourceType in drop item transaction");
430 return false;
431 }
432 }
433 if($sourceSlot === null || $clientItemStack === null || $droppedCount === null){
434 $this->session->getLogger()->debug("Missing information in drop item transaction, need source slot, client item stack and dropped count");
435 return false;
436 }
437
438 $inventory = $this->player->getInventory();
439
440 if(!$inventory->slotExists($sourceSlot)){
441 return false; //TODO: size desync??
442 }
443
444 $sourceSlotItem = $inventory->getItem($sourceSlot);
445 if($sourceSlotItem->getCount() < $droppedCount){
446 return false;
447 }
448 $serverItemStack = $this->session->getTypeConverter()->coreItemStackToNet($sourceSlotItem);
449 //Sadly we don't have itemstack IDs here, so we have to compare the basic item properties to ensure that we're
450 //dropping the item the client expects (inventory might be out of sync with the client).
451 if(
452 $serverItemStack->getId() !== $clientItemStack->getId() ||
453 $serverItemStack->getMeta() !== $clientItemStack->getMeta() ||
454 $serverItemStack->getCount() !== $clientItemStack->getCount() ||
455 $serverItemStack->getBlockRuntimeId() !== $clientItemStack->getBlockRuntimeId()
456 //Raw extraData may not match because of TAG_Compound key ordering differences, and decoding it to compare
457 //is costly. Assume that we're in sync if id+meta+count+runtimeId match.
458 //NB: Make sure $clientItemStack isn't used to create the dropped item, as that would allow the client
459 //to change the item NBT since we're not validating it.
460 ){
461 return false;
462 }
463
464 //this modifies $sourceSlotItem
465 $droppedItem = $sourceSlotItem->pop($droppedCount);
466
467 $builder = new TransactionBuilder();
468 $builder->getInventory($inventory)->setItem($sourceSlot, $sourceSlotItem);
469 $builder->addAction(new DropItemAction($droppedItem));
470
471 $transaction = new InventoryTransaction($this->player, $builder->generateActions());
472 return $this->executeInventoryTransaction($transaction, $itemStackRequestId);
473 }
474
475 private function handleUseItemTransaction(UseItemTransactionData $data) : bool{
476 $this->player->selectHotbarSlot($data->getHotbarSlot());
477
478 switch($data->getActionType()){
479 case UseItemTransactionData::ACTION_CLICK_BLOCK:
480 //TODO: start hack for client spam bug
481 $clickPos = $data->getClickPosition();
482 $spamBug = ($this->lastRightClickData !== null &&
483 microtime(true) - $this->lastRightClickTime < 0.1 && //100ms
484 $this->lastRightClickData->getPlayerPosition()->distanceSquared($data->getPlayerPosition()) < 0.00001 &&
485 $this->lastRightClickData->getBlockPosition()->equals($data->getBlockPosition()) &&
486 $this->lastRightClickData->getClickPosition()->distanceSquared($clickPos) < 0.00001 //signature spam bug has 0 distance, but allow some error
487 );
488 //get rid of continued spam if the player clicks and holds right-click
489 $this->lastRightClickData = $data;
490 $this->lastRightClickTime = microtime(true);
491 if($spamBug){
492 return true;
493 }
494 //TODO: end hack for client spam bug
495
496 self::validateFacing($data->getFace());
497
498 $blockPos = $data->getBlockPosition();
499 $vBlockPos = new Vector3($blockPos->getX(), $blockPos->getY(), $blockPos->getZ());
500 $this->player->interactBlock($vBlockPos, $data->getFace(), $clickPos);
501 //always sync this in case plugins caused a different result than the client expected
502 //we *could* try to enhance detection of plugin-altered behaviour, but this would require propagating
503 //more information up the stack. For now I think this is good enough.
504 //if only the client would tell us what blocks it thinks changed...
505 $this->syncBlocksNearby($vBlockPos, $data->getFace());
506 return true;
507 case UseItemTransactionData::ACTION_CLICK_AIR:
508 if($this->player->isUsingItem()){
509 if(!$this->player->consumeHeldItem()){
510 $hungerAttr = $this->player->getAttributeMap()->get(Attribute::HUNGER) ?? throw new AssumptionFailedError();
511 $hungerAttr->markSynchronized(false);
512 }
513 return true;
514 }
515 $this->player->useHeldItem();
516 return true;
517 }
518
519 return false;
520 }
521
525 private static function validateFacing(int $facing) : void{
526 if(!in_array($facing, Facing::ALL, true)){
527 throw new PacketHandlingException("Invalid facing value $facing");
528 }
529 }
530
534 private function syncBlocksNearby(Vector3 $blockPos, ?int $face) : void{
535 if($blockPos->distanceSquared($this->player->getLocation()) < 10000){
536 $blocks = $blockPos->sidesArray();
537 if($face !== null){
538 $sidePos = $blockPos->getSide($face);
539
541 array_push($blocks, ...$sidePos->sidesArray()); //getAllSides() on each of these will include $blockPos and $sidePos because they are next to each other
542 }else{
543 $blocks[] = $blockPos;
544 }
545 foreach($this->player->getWorld()->createBlockUpdatePackets($blocks) as $packet){
546 $this->session->sendDataPacket($packet);
547 }
548 }
549 }
550
551 private function handleUseItemOnEntityTransaction(UseItemOnEntityTransactionData $data) : bool{
552 $target = $this->player->getWorld()->getEntity($data->getActorRuntimeId());
553 if($target === null){
554 return false;
555 }
556
557 $this->player->selectHotbarSlot($data->getHotbarSlot());
558
559 switch($data->getActionType()){
560 case UseItemOnEntityTransactionData::ACTION_INTERACT:
561 $this->player->interactEntity($target, $data->getClickPosition());
562 return true;
563 case UseItemOnEntityTransactionData::ACTION_ATTACK:
564 $this->player->attackEntity($target);
565 return true;
566 }
567
568 return false;
569 }
570
571 private function handleReleaseItemTransaction(ReleaseItemTransactionData $data) : bool{
572 $this->player->selectHotbarSlot($data->getHotbarSlot());
573
574 if($data->getActionType() === ReleaseItemTransactionData::ACTION_RELEASE){
575 $this->player->releaseHeldItem();
576 return true;
577 }
578
579 return false;
580 }
581
582 private function handleSingleItemStackRequest(ItemStackRequest $request) : ?ItemStackResponseBuilder{
583 if(count($request->getActions()) > 60){
584 //recipe book auto crafting can affect all slots of the inventory when consuming inputs or producing outputs
585 //this means there could be as many as 50 CraftingConsumeInput actions or Place (taking the result) actions
586 //in a single request (there are certain ways items can be arranged which will result in the same stack
587 //being taken from multiple times, but this is behaviour with a calculable limit)
588 //this means there SHOULD be AT MOST 53 actions in a single request, but 60 is a nice round number.
589 //n64Stacks = ?
590 //n1Stacks = 45 - n64Stacks
591 //nItemsRequiredFor1Craft = 9
592 //nResults = floor((n1Stacks + (n64Stacks * 64)) / nItemsRequiredFor1Craft)
593 //nTakeActionsTotal = floor(64 / nResults) + max(1, 64 % nResults) + ((nResults * nItemsRequiredFor1Craft) - (n64Stacks * 64))
594 throw new PacketHandlingException("Too many actions in ItemStackRequest");
595 }
596 $executor = new ItemStackRequestExecutor($this->player, $this->inventoryManager, $request);
597 try{
598 $transaction = $executor->generateInventoryTransaction();
599 if($transaction !== null){
600 $result = $this->executeInventoryTransaction($transaction, $request->getRequestId());
601 }else{
602 $result = true; //predictions only, just send responses
603 }
605 $result = false;
606 $this->session->getLogger()->debug("ItemStackRequest #" . $request->getRequestId() . " failed: " . $e->getMessage());
607 $this->session->getLogger()->debug(implode("\n", Utils::printableExceptionInfo($e)));
608 $this->inventoryManager->requestSyncAll();
609 }
610
611 return $result ? $executor->getItemStackResponseBuilder() : null;
612 }
613
614 public function handleItemStackRequest(ItemStackRequestPacket $packet) : bool{
615 $responses = [];
616 if(count($packet->getRequests()) > 80){
617 //TODO: we can probably lower this limit, but this will do for now
618 throw new PacketHandlingException("Too many requests in ItemStackRequestPacket");
619 }
620 foreach($packet->getRequests() as $request){
621 $responses[] = $this->handleSingleItemStackRequest($request)?->build() ?? new ItemStackResponse(ItemStackResponse::RESULT_ERROR, $request->getRequestId());
622 }
623
624 $this->session->sendDataPacket(ItemStackResponsePacket::create($responses));
625
626 return true;
627 }
628
629 public function handleMobEquipment(MobEquipmentPacket $packet) : bool{
630 if($packet->windowId === ContainerIds::OFFHAND){
631 return true; //this happens when we put an item into the offhand
632 }
633 if($packet->windowId === ContainerIds::INVENTORY){
634 $this->inventoryManager->onClientSelectHotbarSlot($packet->hotbarSlot);
635 if(!$this->player->selectHotbarSlot($packet->hotbarSlot)){
636 $this->inventoryManager->syncSelectedHotbarSlot();
637 }
638 return true;
639 }
640 return false;
641 }
642
643 public function handleMobArmorEquipment(MobArmorEquipmentPacket $packet) : bool{
644 return true; //Not used
645 }
646
647 public function handleInteract(InteractPacket $packet) : bool{
648 if($packet->action === InteractPacket::ACTION_MOUSEOVER){
649 //TODO HACK: silence useless spam (MCPE 1.8)
650 //due to some messy Mojang hacks, it sends this when changing the held item now, which causes us to think
651 //the inventory was closed when it wasn't.
652 //this is also sent whenever entity metadata updates, which can get really spammy.
653 //TODO: implement handling for this where it matters
654 return true;
655 }
656 $target = $this->player->getWorld()->getEntity($packet->targetActorRuntimeId);
657 if($target === null){
658 return false;
659 }
660 if($packet->action === InteractPacket::ACTION_OPEN_INVENTORY && $target === $this->player){
661 $this->inventoryManager->onClientOpenMainInventory();
662 return true;
663 }
664 return false; //TODO
665 }
666
667 public function handleBlockPickRequest(BlockPickRequestPacket $packet) : bool{
668 return $this->player->pickBlock(new Vector3($packet->blockPosition->getX(), $packet->blockPosition->getY(), $packet->blockPosition->getZ()), $packet->addUserData);
669 }
670
671 public function handleActorPickRequest(ActorPickRequestPacket $packet) : bool{
672 return $this->player->pickEntity($packet->actorUniqueId);
673 }
674
675 public function handlePlayerAction(PlayerActionPacket $packet) : bool{
676 return $this->handlePlayerActionFromData($packet->action, $packet->blockPosition, $packet->face);
677 }
678
679 private function handlePlayerActionFromData(int $action, BlockPosition $blockPosition, int $face) : bool{
680 $pos = new Vector3($blockPosition->getX(), $blockPosition->getY(), $blockPosition->getZ());
681
682 switch($action){
683 case PlayerAction::START_BREAK:
684 case PlayerAction::CONTINUE_DESTROY_BLOCK: //destroy the next block while holding down left click
685 self::validateFacing($face);
686 if($this->lastBlockAttacked !== null && $blockPosition->equals($this->lastBlockAttacked)){
687 //the client will send CONTINUE_DESTROY_BLOCK for the currently targeted block directly before it
688 //sends PREDICT_DESTROY_BLOCK, but also when it starts to break the block
689 //this seems like a bug in the client and would cause spurious left-click events if we allowed it to
690 //be delivered to the player
691 $this->session->getLogger()->debug("Ignoring PlayerAction $action on $pos because we were already destroying this block");
692 break;
693 }
694 if(!$this->player->attackBlock($pos, $face)){
695 $this->syncBlocksNearby($pos, $face);
696 }
697 $this->lastBlockAttacked = $blockPosition;
698
699 break;
700
701 case PlayerAction::ABORT_BREAK:
702 case PlayerAction::STOP_BREAK:
703 $this->player->stopBreakBlock($pos);
704 $this->lastBlockAttacked = null;
705 break;
706 case PlayerAction::START_SLEEPING:
707 //unused
708 break;
709 case PlayerAction::STOP_SLEEPING:
710 $this->player->stopSleep();
711 break;
712 case PlayerAction::CRACK_BREAK:
713 self::validateFacing($face);
714 $this->player->continueBreakBlock($pos, $face);
715 $this->lastBlockAttacked = $blockPosition;
716 break;
717 case PlayerAction::INTERACT_BLOCK: //TODO: ignored (for now)
718 break;
719 case PlayerAction::CREATIVE_PLAYER_DESTROY_BLOCK:
720 //TODO: do we need to handle this?
721 case PlayerAction::PREDICT_DESTROY_BLOCK:
722 if(!$this->player->breakBlock($pos)){
723 $this->syncBlocksNearby($pos, $face);
724 }
725 $this->lastBlockAttacked = null;
726 break;
727 case PlayerAction::START_ITEM_USE_ON:
728 case PlayerAction::STOP_ITEM_USE_ON:
729 //TODO: this has no obvious use and seems only used for analytics in vanilla - ignore it
730 break;
731 default:
732 $this->session->getLogger()->debug("Unhandled/unknown player action type " . $action);
733 return false;
734 }
735
736 $this->player->setUsingItem(false);
737
738 return true;
739 }
740
741 public function handleSetActorMotion(SetActorMotionPacket $packet) : bool{
742 return true; //Not used: This packet is (erroneously) sent to the server when the client is riding a vehicle.
743 }
744
745 public function handleAnimate(AnimatePacket $packet) : bool{
746 return true; //Not used
747 }
748
749 public function handleContainerClose(ContainerClosePacket $packet) : bool{
750 $this->inventoryManager->onClientRemoveWindow($packet->windowId);
751 return true;
752 }
753
754 public function handlePlayerHotbar(PlayerHotbarPacket $packet) : bool{
755 return true; //this packet is useless
756 }
757
758 public function handleBlockActorData(BlockActorDataPacket $packet) : bool{
759 $pos = new Vector3($packet->blockPosition->getX(), $packet->blockPosition->getY(), $packet->blockPosition->getZ());
760 if($pos->distanceSquared($this->player->getLocation()) > 10000){
761 return false;
762 }
763
764 $block = $this->player->getLocation()->getWorld()->getBlock($pos);
765 $nbt = $packet->nbt->getRoot();
766 if(!($nbt instanceof CompoundTag)) throw new AssumptionFailedError("PHPStan should ensure this is a CompoundTag"); //for phpstorm's benefit
767
768 if($block instanceof BaseSign){
769 $frontTextTag = $nbt->getTag(Sign::TAG_FRONT_TEXT);
770 if(!$frontTextTag instanceof CompoundTag){
771 throw new PacketHandlingException("Invalid tag type " . get_debug_type($frontTextTag) . " for tag \"" . Sign::TAG_FRONT_TEXT . "\" in sign update data");
772 }
773 $textBlobTag = $frontTextTag->getTag(Sign::TAG_TEXT_BLOB);
774 if(!$textBlobTag instanceof StringTag){
775 throw new PacketHandlingException("Invalid tag type " . get_debug_type($textBlobTag) . " for tag \"" . Sign::TAG_TEXT_BLOB . "\" in sign update data");
776 }
777
778 try{
779 $text = SignText::fromBlob($textBlobTag->getValue());
780 }catch(\InvalidArgumentException $e){
781 throw PacketHandlingException::wrap($e, "Invalid sign text update");
782 }
783
784 try{
785 if(!$block->updateText($this->player, $text)){
786 foreach($this->player->getWorld()->createBlockUpdatePackets([$pos]) as $updatePacket){
787 $this->session->sendDataPacket($updatePacket);
788 }
789 }
790 }catch(\UnexpectedValueException $e){
791 throw PacketHandlingException::wrap($e);
792 }
793
794 return true;
795 }
796
797 return false;
798 }
799
800 public function handleSetPlayerGameType(SetPlayerGameTypePacket $packet) : bool{
801 $gameMode = $this->session->getTypeConverter()->protocolGameModeToCore($packet->gamemode);
802 if($gameMode !== $this->player->getGamemode()){
803 //Set this back to default. TODO: handle this properly
804 $this->session->syncGameMode($this->player->getGamemode(), true);
805 }
806 return true;
807 }
808
809 public function handleSpawnExperienceOrb(SpawnExperienceOrbPacket $packet) : bool{
810 return false; //TODO
811 }
812
813 public function handleMapInfoRequest(MapInfoRequestPacket $packet) : bool{
814 return false; //TODO
815 }
816
817 public function handleRequestChunkRadius(RequestChunkRadiusPacket $packet) : bool{
818 $this->player->setViewDistance($packet->radius);
819
820 return true;
821 }
822
823 public function handleBossEvent(BossEventPacket $packet) : bool{
824 return false; //TODO
825 }
826
827 public function handleShowCredits(ShowCreditsPacket $packet) : bool{
828 return false; //TODO: handle resume
829 }
830
831 public function handleCommandRequest(CommandRequestPacket $packet) : bool{
832 if(str_starts_with($packet->command, '/')){
833 $this->player->chat($packet->command);
834 return true;
835 }
836 return false;
837 }
838
839 public function handleCommandBlockUpdate(CommandBlockUpdatePacket $packet) : bool{
840 return false; //TODO
841 }
842
843 public function handlePlayerSkin(PlayerSkinPacket $packet) : bool{
844 if($packet->skin->getFullSkinId() === $this->lastRequestedFullSkinId){
845 //TODO: HACK! In 1.19.60, the client sends its skin back to us if we sent it a skin different from the one
846 //it's using. We need to prevent this from causing a feedback loop.
847 $this->session->getLogger()->debug("Refused duplicate skin change request");
848 return true;
849 }
850 $this->lastRequestedFullSkinId = $packet->skin->getFullSkinId();
851
852 $this->session->getLogger()->debug("Processing skin change request");
853 try{
854 $skin = $this->session->getTypeConverter()->getSkinAdapter()->fromSkinData($packet->skin);
855 }catch(InvalidSkinException $e){
856 throw PacketHandlingException::wrap($e, "Invalid skin in PlayerSkinPacket");
857 }
858 return $this->player->changeSkin($skin, $packet->newSkinName, $packet->oldSkinName);
859 }
860
861 public function handleSubClientLogin(SubClientLoginPacket $packet) : bool{
862 return false; //TODO
863 }
864
868 private function checkBookText(string $string, string $fieldName, int $softLimit, int $hardLimit, bool &$cancel) : string{
869 if(strlen($string) > $hardLimit){
870 throw new PacketHandlingException(sprintf("Book %s must be at most %d bytes, but have %d bytes", $fieldName, $hardLimit, strlen($string)));
871 }
872
873 $result = TextFormat::clean($string, false);
874 //strlen() is O(1), mb_strlen() is O(n)
875 if(strlen($result) > $softLimit * 4 || mb_strlen($result, 'UTF-8') > $softLimit){
876 $cancel = true;
877 $this->session->getLogger()->debug("Cancelled book edit due to $fieldName exceeded soft limit of $softLimit chars");
878 }
879
880 return $result;
881 }
882
883 public function handleBookEdit(BookEditPacket $packet) : bool{
884 $inventory = $this->player->getInventory();
885 if(!$inventory->slotExists($packet->inventorySlot)){
886 return false;
887 }
888 //TODO: break this up into book API things
889 $oldBook = $inventory->getItem($packet->inventorySlot);
890 if(!($oldBook instanceof WritableBook)){
891 return false;
892 }
893
894 $newBook = clone $oldBook;
895 $modifiedPages = [];
896 $cancel = false;
897 switch($packet->type){
898 case BookEditPacket::TYPE_REPLACE_PAGE:
899 $text = self::checkBookText($packet->text, "page text", 256, WritableBookPage::PAGE_LENGTH_HARD_LIMIT_BYTES, $cancel);
900 $newBook->setPageText($packet->pageNumber, $text);
901 $modifiedPages[] = $packet->pageNumber;
902 break;
903 case BookEditPacket::TYPE_ADD_PAGE:
904 if(!$newBook->pageExists($packet->pageNumber)){
905 //this may only come before a page which already exists
906 //TODO: the client can send insert-before actions on trailing client-side pages which cause odd behaviour on the server
907 return false;
908 }
909 $text = self::checkBookText($packet->text, "page text", 256, WritableBookPage::PAGE_LENGTH_HARD_LIMIT_BYTES, $cancel);
910 $newBook->insertPage($packet->pageNumber, $text);
911 $modifiedPages[] = $packet->pageNumber;
912 break;
913 case BookEditPacket::TYPE_DELETE_PAGE:
914 if(!$newBook->pageExists($packet->pageNumber)){
915 return false;
916 }
917 $newBook->deletePage($packet->pageNumber);
918 $modifiedPages[] = $packet->pageNumber;
919 break;
920 case BookEditPacket::TYPE_SWAP_PAGES:
921 if(!$newBook->pageExists($packet->pageNumber) || !$newBook->pageExists($packet->secondaryPageNumber)){
922 //the client will create pages on its own without telling us until it tries to switch them
923 $newBook->addPage(max($packet->pageNumber, $packet->secondaryPageNumber));
924 }
925 $newBook->swapPages($packet->pageNumber, $packet->secondaryPageNumber);
926 $modifiedPages = [$packet->pageNumber, $packet->secondaryPageNumber];
927 break;
928 case BookEditPacket::TYPE_SIGN_BOOK:
929 $title = self::checkBookText($packet->title, "title", 16, Limits::INT16_MAX, $cancel);
930 //this one doesn't have a limit in vanilla, so we have to improvise
931 $author = self::checkBookText($packet->author, "author", 256, Limits::INT16_MAX, $cancel);
932
933 $newBook = VanillaItems::WRITTEN_BOOK()
934 ->setPages($oldBook->getPages())
935 ->setAuthor($author)
936 ->setTitle($title)
937 ->setGeneration(WrittenBook::GENERATION_ORIGINAL);
938 break;
939 default:
940 return false;
941 }
942
943 //for redundancy, in case of protocol changes, we don't want to pass these directly
944 $action = match($packet->type){
945 BookEditPacket::TYPE_REPLACE_PAGE => PlayerEditBookEvent::ACTION_REPLACE_PAGE,
946 BookEditPacket::TYPE_ADD_PAGE => PlayerEditBookEvent::ACTION_ADD_PAGE,
947 BookEditPacket::TYPE_DELETE_PAGE => PlayerEditBookEvent::ACTION_DELETE_PAGE,
948 BookEditPacket::TYPE_SWAP_PAGES => PlayerEditBookEvent::ACTION_SWAP_PAGES,
949 BookEditPacket::TYPE_SIGN_BOOK => PlayerEditBookEvent::ACTION_SIGN_BOOK,
950 default => throw new AssumptionFailedError("We already filtered unknown types in the switch above")
951 };
952
953 /*
954 * Plugins may have created books with more than 50 pages; we allow plugins to do this, but not players.
955 * Don't allow the page count to grow past 50, but allow deleting, swapping or altering text of existing pages.
956 */
957 $oldPageCount = count($oldBook->getPages());
958 $newPageCount = count($newBook->getPages());
959 if(($newPageCount > $oldPageCount && $newPageCount > 50)){
960 $this->session->getLogger()->debug("Cancelled book edit due to adding too many pages (new page count would be $newPageCount)");
961 $cancel = true;
962 }
963
964 $event = new PlayerEditBookEvent($this->player, $oldBook, $newBook, $action, $modifiedPages);
965 if($cancel){
966 $event->cancel();
967 }
968
969 $event->call();
970 if($event->isCancelled()){
971 return true;
972 }
973
974 $this->player->getInventory()->setItem($packet->inventorySlot, $event->getNewBook());
975
976 return true;
977 }
978
979 public function handleModalFormResponse(ModalFormResponsePacket $packet) : bool{
980 if($packet->cancelReason !== null){
981 //TODO: make APIs for this to allow plugins to use this information
982 return $this->player->onFormSubmit($packet->formId, null);
983 }elseif($packet->formData !== null){
984 try{
985 $responseData = json_decode($packet->formData, true, self::MAX_FORM_RESPONSE_DEPTH, JSON_THROW_ON_ERROR);
986 }catch(\JsonException $e){
987 throw PacketHandlingException::wrap($e, "Failed to decode form response data");
988 }
989 return $this->player->onFormSubmit($packet->formId, $responseData);
990 }else{
991 throw new PacketHandlingException("Expected either formData or cancelReason to be set in ModalFormResponsePacket");
992 }
993 }
994
995 public function handleServerSettingsRequest(ServerSettingsRequestPacket $packet) : bool{
996 return false; //TODO: GUI stuff
997 }
998
999 public function handleLabTable(LabTablePacket $packet) : bool{
1000 return false; //TODO
1001 }
1002
1003 public function handleLecternUpdate(LecternUpdatePacket $packet) : bool{
1004 $pos = $packet->blockPosition;
1005 $chunkX = $pos->getX() >> Chunk::COORD_BIT_SIZE;
1006 $chunkZ = $pos->getZ() >> Chunk::COORD_BIT_SIZE;
1007 $world = $this->player->getWorld();
1008 if(!$world->isChunkLoaded($chunkX, $chunkZ) || $world->isChunkLocked($chunkX, $chunkZ)){
1009 return false;
1010 }
1011
1012 $lectern = $world->getBlockAt($pos->getX(), $pos->getY(), $pos->getZ());
1013 if($lectern instanceof Lectern && $this->player->canInteract($lectern->getPosition(), 15)){
1014 if(!$lectern->onPageTurn($packet->page)){
1015 $this->syncBlocksNearby($lectern->getPosition(), null);
1016 }
1017 return true;
1018 }
1019
1020 return false;
1021 }
1022
1023 public function handleNetworkStackLatency(NetworkStackLatencyPacket $packet) : bool{
1024 return true; //TODO: implement this properly - this is here to silence debug spam from MCPE dev builds
1025 }
1026
1027 public function handleLevelSoundEvent(LevelSoundEventPacket $packet) : bool{
1028 /*
1029 * We don't handle this - all sounds are handled by the server now.
1030 * However, some plugins find this useful to detect events like left-click-air, which doesn't have any other
1031 * action bound to it.
1032 * In addition, we use this handler to silence debug noise, since this packet is frequently sent by the client.
1033 */
1034 return true;
1035 }
1036
1037 public function handleEmote(EmotePacket $packet) : bool{
1038 $this->player->emote($packet->getEmoteId());
1039 return true;
1040 }
1041}
sidesArray(bool $keys=false, int $step=1)
Definition Vector3.php:187
getSide(int $side, int $step=1)
Definition Vector3.php:120
static translate(int $containerInterfaceId, int $currentWindowId, int $slotId)