-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathPlayer.php
More file actions
2710 lines (2285 loc) · 84.6 KB
/
Player.php
File metadata and controls
2710 lines (2285 loc) · 84.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/*
*
* ____ _ _ __ __ _ __ __ ____
* | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
* | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
* | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
* |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* @author PocketMine Team
* @link http://www.pocketmine.net/
*
*
*/
declare(strict_types=1);
namespace pocketmine\player;
use pocketmine\block\BaseSign;
use pocketmine\block\Bed;
use pocketmine\block\BlockTypeTags;
use pocketmine\block\UnknownBlock;
use pocketmine\block\VanillaBlocks;
use pocketmine\command\CommandSender;
use pocketmine\crafting\CraftingGrid;
use pocketmine\data\java\GameModeIdMap;
use pocketmine\entity\animation\Animation;
use pocketmine\entity\animation\ArmSwingAnimation;
use pocketmine\entity\animation\CriticalHitAnimation;
use pocketmine\entity\Attribute;
use pocketmine\entity\effect\VanillaEffects;
use pocketmine\entity\Entity;
use pocketmine\entity\Human;
use pocketmine\entity\Living;
use pocketmine\entity\Location;
use pocketmine\entity\object\ItemEntity;
use pocketmine\entity\projectile\Arrow;
use pocketmine\entity\Skin;
use pocketmine\event\entity\EntityDamageByEntityEvent;
use pocketmine\event\entity\EntityDamageEvent;
use pocketmine\event\inventory\InventoryCloseEvent;
use pocketmine\event\inventory\InventoryOpenEvent;
use pocketmine\event\player\PlayerBedEnterEvent;
use pocketmine\event\player\PlayerBedLeaveEvent;
use pocketmine\event\player\PlayerBlockPickEvent;
use pocketmine\event\player\PlayerChangeSkinEvent;
use pocketmine\event\player\PlayerChatEvent;
use pocketmine\event\player\PlayerDeathEvent;
use pocketmine\event\player\PlayerDisplayNameChangeEvent;
use pocketmine\event\player\PlayerDropItemEvent;
use pocketmine\event\player\PlayerEmoteEvent;
use pocketmine\event\player\PlayerEntityInteractEvent;
use pocketmine\event\player\PlayerExhaustEvent;
use pocketmine\event\player\PlayerGameModeChangeEvent;
use pocketmine\event\player\PlayerInteractEvent;
use pocketmine\event\player\PlayerItemConsumeEvent;
use pocketmine\event\player\PlayerItemHeldEvent;
use pocketmine\event\player\PlayerItemUseEvent;
use pocketmine\event\player\PlayerJoinEvent;
use pocketmine\event\player\PlayerJumpEvent;
use pocketmine\event\player\PlayerKickEvent;
use pocketmine\event\player\PlayerMissSwingEvent;
use pocketmine\event\player\PlayerMoveEvent;
use pocketmine\event\player\PlayerPostChunkSendEvent;
use pocketmine\event\player\PlayerQuitEvent;
use pocketmine\event\player\PlayerRespawnEvent;
use pocketmine\event\player\PlayerToggleFlightEvent;
use pocketmine\event\player\PlayerToggleGlideEvent;
use pocketmine\event\player\PlayerToggleSneakEvent;
use pocketmine\event\player\PlayerToggleSprintEvent;
use pocketmine\event\player\PlayerToggleSwimEvent;
use pocketmine\event\player\PlayerTransferEvent;
use pocketmine\event\player\PlayerViewDistanceChangeEvent;
use pocketmine\form\Form;
use pocketmine\form\FormValidationException;
use pocketmine\inventory\CallbackInventoryListener;
use pocketmine\inventory\CreativeInventory;
use pocketmine\inventory\Inventory;
use pocketmine\inventory\PlayerCraftingInventory;
use pocketmine\inventory\PlayerCursorInventory;
use pocketmine\inventory\TemporaryInventory;
use pocketmine\inventory\transaction\action\DropItemAction;
use pocketmine\inventory\transaction\InventoryTransaction;
use pocketmine\inventory\transaction\TransactionBuilder;
use pocketmine\inventory\transaction\TransactionCancelledException;
use pocketmine\inventory\transaction\TransactionValidationException;
use pocketmine\item\ConsumableItem;
use pocketmine\item\Durable;
use pocketmine\item\enchantment\EnchantmentInstance;
use pocketmine\item\enchantment\MeleeWeaponEnchantment;
use pocketmine\item\Item;
use pocketmine\item\ItemUseResult;
use pocketmine\item\Releasable;
use pocketmine\lang\KnownTranslationFactory;
use pocketmine\lang\Language;
use pocketmine\lang\Translatable;
use pocketmine\math\Vector3;
use pocketmine\nbt\tag\CompoundTag;
use pocketmine\nbt\tag\IntTag;
use pocketmine\network\mcpe\NetworkSession;
use pocketmine\network\mcpe\protocol\AnimatePacket;
use pocketmine\network\mcpe\protocol\MovePlayerPacket;
use pocketmine\network\mcpe\protocol\SetActorMotionPacket;
use pocketmine\network\mcpe\protocol\types\BlockPosition;
use pocketmine\network\mcpe\protocol\types\entity\EntityMetadataCollection;
use pocketmine\network\mcpe\protocol\types\entity\EntityMetadataFlags;
use pocketmine\network\mcpe\protocol\types\entity\EntityMetadataProperties;
use pocketmine\network\mcpe\protocol\types\entity\PlayerMetadataFlags;
use pocketmine\permission\DefaultPermissionNames;
use pocketmine\permission\DefaultPermissions;
use pocketmine\permission\PermissibleBase;
use pocketmine\permission\PermissibleDelegateTrait;
use pocketmine\player\chat\StandardChatFormatter;
use pocketmine\Server;
use pocketmine\ServerProperties;
use pocketmine\timings\Timings;
use pocketmine\utils\AssumptionFailedError;
use pocketmine\utils\TextFormat;
use pocketmine\world\ChunkListener;
use pocketmine\world\ChunkListenerNoOpTrait;
use pocketmine\world\ChunkLoader;
use pocketmine\world\ChunkTicker;
use pocketmine\world\format\Chunk;
use pocketmine\world\Position;
use pocketmine\world\sound\EntityAttackNoDamageSound;
use pocketmine\world\sound\EntityAttackSound;
use pocketmine\world\sound\FireExtinguishSound;
use pocketmine\world\sound\ItemBreakSound;
use pocketmine\world\sound\Sound;
use pocketmine\world\World;
use pocketmine\YmlServerProperties;
use Ramsey\Uuid\UuidInterface;
use function abs;
use function array_filter;
use function array_shift;
use function assert;
use function count;
use function explode;
use function floor;
use function get_class;
use function is_int;
use function max;
use function mb_strlen;
use function microtime;
use function min;
use function preg_match;
use function spl_object_id;
use function sqrt;
use function str_starts_with;
use function strlen;
use function strtolower;
use function substr;
use function trim;
use const M_PI;
use const M_SQRT3;
use const PHP_INT_MAX;
/**
* Main class that handles networking, recovery, and packet sending to the server part
*/
class Player extends Human implements CommandSender, ChunkListener, IPlayer{
use PermissibleDelegateTrait;
private const MOVES_PER_TICK = 2;
private const MOVE_BACKLOG_SIZE = 100 * self::MOVES_PER_TICK; //100 ticks backlog (5 seconds)
/** Max length of a chat message (UTF-8 codepoints, not bytes) */
private const MAX_CHAT_CHAR_LENGTH = 512;
/**
* Max length of a chat message in bytes. This is a theoretical maximum (if every character was 4 bytes).
* Since mb_strlen() is O(n), it gets very slow with large messages. Checking byte length with strlen() is O(1) and
* is a useful heuristic to filter out oversized messages.
*/
private const MAX_CHAT_BYTE_LENGTH = self::MAX_CHAT_CHAR_LENGTH * 4;
private const MAX_REACH_DISTANCE_CREATIVE = 13;
private const MAX_REACH_DISTANCE_SURVIVAL = 7;
private const MAX_REACH_DISTANCE_ENTITY_INTERACTION = 8;
public const TAG_FIRST_PLAYED = "firstPlayed"; //TAG_Long
public const TAG_LAST_PLAYED = "lastPlayed"; //TAG_Long
private const TAG_GAME_MODE = "playerGameType"; //TAG_Int
private const TAG_SPAWN_WORLD = "SpawnLevel"; //TAG_String
private const TAG_SPAWN_X = "SpawnX"; //TAG_Int
private const TAG_SPAWN_Y = "SpawnY"; //TAG_Int
private const TAG_SPAWN_Z = "SpawnZ"; //TAG_Int
public const TAG_LEVEL = "Level"; //TAG_String
public const TAG_LAST_KNOWN_XUID = "LastKnownXUID"; //TAG_String
/**
* Validates the given username.
*/
public static function isValidUserName(?string $name) : bool{
if($name === null){
return false;
}
$lname = strtolower($name);
$len = strlen($name);
return $lname !== "rcon" && $lname !== "console" && $len >= 1 && $len <= 16 && preg_match("/[^A-Za-z0-9_ ]/", $name) === 0;
}
protected ?NetworkSession $networkSession;
public bool $spawned = false;
protected string $username;
protected string $displayName;
protected string $xuid = "";
protected bool $authenticated;
protected PlayerInfo $playerInfo;
protected ?Inventory $currentWindow = null;
/** @var Inventory[] */
protected array $permanentWindows = [];
protected PlayerCursorInventory $cursorInventory;
protected PlayerCraftingInventory $craftingGrid;
protected CreativeInventory $creativeInventory;
protected int $messageCounter = 2;
protected int $firstPlayed;
protected int $lastPlayed;
protected GameMode $gamemode;
/**
* @var UsedChunkStatus[] chunkHash => status
* @phpstan-var array<int, UsedChunkStatus>
*/
protected array $usedChunks = [];
/**
* @var true[]
* @phpstan-var array<int, true>
*/
private array $activeChunkGenerationRequests = [];
/**
* @var true[] chunkHash => dummy
* @phpstan-var array<int, true>
*/
protected array $loadQueue = [];
protected int $nextChunkOrderRun = 5;
/** @var true[] */
private array $tickingChunks = [];
protected int $viewDistance = -1;
protected int $spawnThreshold;
protected int $spawnChunkLoadCount = 0;
protected int $chunksPerTick;
protected ChunkSelector $chunkSelector;
protected ChunkLoader $chunkLoader;
protected ChunkTicker $chunkTicker;
/** @var bool[] map: raw UUID (string) => bool */
protected array $hiddenPlayers = [];
protected float $moveRateLimit = 10 * self::MOVES_PER_TICK;
protected ?float $lastMovementProcess = null;
protected int $inAirTicks = 0;
protected float $stepHeight = 0.6;
protected ?Vector3 $sleeping = null;
private ?Position $spawnPosition = null;
private bool $respawnLocked = false;
//TODO: Abilities
protected bool $autoJump = true;
protected bool $allowFlight = false;
protected bool $blockCollision = true;
protected bool $flying = false;
/** @phpstan-var positive-int|null */
protected ?int $lineHeight = null;
protected string $locale = "en_US";
protected int $startAction = -1;
/** @var int[] ID => ticks map */
protected array $usedItemsCooldown = [];
private int $lastEmoteTick = 0;
protected int $formIdCounter = 0;
/** @var Form[] */
protected array $forms = [];
protected \Logger $logger;
protected ?SurvivalBlockBreakHandler $blockBreakHandler = null;
public function __construct(Server $server, NetworkSession $session, PlayerInfo $playerInfo, bool $authenticated, Location $spawnLocation, ?CompoundTag $namedtag){
$username = TextFormat::clean($playerInfo->getUsername());
$this->logger = new \PrefixedLogger($server->getLogger(), "Player: $username");
$this->server = $server;
$this->networkSession = $session;
$this->playerInfo = $playerInfo;
$this->authenticated = $authenticated;
$this->username = $username;
$this->displayName = $this->username;
$this->locale = $this->playerInfo->getLocale();
$this->uuid = $this->playerInfo->getUuid();
$this->xuid = $this->playerInfo instanceof XboxLivePlayerInfo ? $this->playerInfo->getXuid() : "";
$this->creativeInventory = CreativeInventory::getInstance();
$rootPermissions = [DefaultPermissions::ROOT_USER => true];
if($this->server->isOp($this->username)){
$rootPermissions[DefaultPermissions::ROOT_OPERATOR] = true;
}
$this->perm = new PermissibleBase($rootPermissions);
$this->chunksPerTick = $this->server->getConfigGroup()->getPropertyInt(YmlServerProperties::CHUNK_SENDING_PER_TICK, 4);
$this->spawnThreshold = (int) (($this->server->getConfigGroup()->getPropertyInt(YmlServerProperties::CHUNK_SENDING_SPAWN_RADIUS, 4) ** 2) * M_PI);
$this->chunkSelector = new ChunkSelector();
$this->chunkLoader = new class implements ChunkLoader{};
$this->chunkTicker = new ChunkTicker();
$world = $spawnLocation->getWorld();
//load the spawn chunk so we can see the terrain
$xSpawnChunk = $spawnLocation->getFloorX() >> Chunk::COORD_BIT_SIZE;
$zSpawnChunk = $spawnLocation->getFloorZ() >> Chunk::COORD_BIT_SIZE;
$world->registerChunkLoader($this->chunkLoader, $xSpawnChunk, $zSpawnChunk, true);
$world->registerChunkListener($this, $xSpawnChunk, $zSpawnChunk);
$this->usedChunks[World::chunkHash($xSpawnChunk, $zSpawnChunk)] = UsedChunkStatus::NEEDED;
parent::__construct($spawnLocation, $this->playerInfo->getSkin(), $namedtag);
}
protected function initHumanData(CompoundTag $nbt) : void{
$this->setNameTag($this->username);
}
private function callDummyItemHeldEvent() : void{
$slot = $this->inventory->getHeldItemIndex();
$event = new PlayerItemHeldEvent($this, $this->inventory->getItem($slot), $slot);
$event->call();
//TODO: this event is actually cancellable, but cancelling it here has no meaningful result, so we
//just ignore it. We fire this only because the content of the held slot changed, not because the
//held slot index changed. We can't prevent that from here, and nor would it be sensible to.
}
protected function initEntity(CompoundTag $nbt) : void{
parent::initEntity($nbt);
$this->addDefaultWindows();
$this->inventory->getListeners()->add(new CallbackInventoryListener(
function(Inventory $unused, int $slot) : void{
if($slot === $this->inventory->getHeldItemIndex()){
$this->setUsingItem(false);
$this->callDummyItemHeldEvent();
}
},
function() : void{
$this->setUsingItem(false);
$this->callDummyItemHeldEvent();
}
));
$this->firstPlayed = $nbt->getLong(self::TAG_FIRST_PLAYED, $now = (int) (microtime(true) * 1000));
$this->lastPlayed = $nbt->getLong(self::TAG_LAST_PLAYED, $now);
if(!$this->server->getForceGamemode() && ($gameModeTag = $nbt->getTag(self::TAG_GAME_MODE)) instanceof IntTag){
$this->internalSetGameMode(GameModeIdMap::getInstance()->fromId($gameModeTag->getValue()) ?? GameMode::SURVIVAL); //TODO: bad hack here to avoid crashes on corrupted data
}else{
$this->internalSetGameMode($this->server->getGamemode());
}
$this->keepMovement = true;
$this->setNameTagVisible();
$this->setNameTagAlwaysVisible();
$this->setCanClimb();
if(($world = $this->server->getWorldManager()->getWorldByName($nbt->getString(self::TAG_SPAWN_WORLD, ""))) instanceof World){
$this->spawnPosition = new Position($nbt->getInt(self::TAG_SPAWN_X), $nbt->getInt(self::TAG_SPAWN_Y), $nbt->getInt(self::TAG_SPAWN_Z), $world);
}
}
public function getLeaveMessage() : Translatable|string{
if($this->spawned){
return KnownTranslationFactory::multiplayer_player_left($this->getDisplayName())->prefix(TextFormat::YELLOW);
}
return "";
}
public function isAuthenticated() : bool{
return $this->authenticated;
}
/**
* Returns an object containing information about the player, such as their username, skin, and misc extra
* client-specific data.
*/
public function getPlayerInfo() : PlayerInfo{ return $this->playerInfo; }
/**
* If the player is logged into Xbox Live, returns their Xbox user ID (XUID) as a string. Returns an empty string if
* the player is not logged into Xbox Live.
*/
public function getXuid() : string{
return $this->xuid;
}
/**
* Returns the player's UUID. This should be the preferred method to identify a player.
* It does not change if the player changes their username.
*
* All players will have a UUID, regardless of whether they are logged into Xbox Live or not. However, note that
* non-XBL players can fake their UUIDs.
*/
public function getUniqueId() : UuidInterface{
return parent::getUniqueId();
}
/**
* TODO: not sure this should be nullable
*/
public function getFirstPlayed() : ?int{
return $this->firstPlayed;
}
/**
* TODO: not sure this should be nullable
*/
public function getLastPlayed() : ?int{
return $this->lastPlayed;
}
public function hasPlayedBefore() : bool{
return $this->lastPlayed - $this->firstPlayed > 1; // microtime(true) - microtime(true) may have less than one millisecond difference
}
/**
* Sets whether the player is allowed to toggle flight mode.
*
* If set to false, the player will be locked in its current flight mode (flying/not flying), and attempts by the
* player to enter or exit flight mode will be prevented.
*
* Note: Setting this to false DOES NOT change whether the player is currently flying. Use
* {@link Player::setFlying()} for that purpose.
*/
public function setAllowFlight(bool $value) : void{
if($this->allowFlight !== $value){
$this->allowFlight = $value;
$this->getNetworkSession()->syncAbilities($this);
}
}
/**
* Returns whether the player is allowed to toggle its flight state.
*
* If false, the player is locked in its current flight mode (flying/not flying), and attempts by the player to
* enter or exit flight mode will be prevented.
*/
public function getAllowFlight() : bool{
return $this->allowFlight;
}
/**
* Sets whether the player's movement may be obstructed by blocks with collision boxes.
* If set to false, the player can move through any block unobstructed.
*
* Note: Enabling flight mode in conjunction with this is recommended. A non-flying player will simply fall through
* the ground into the void.
* @see Player::setFlying()
*/
public function setHasBlockCollision(bool $value) : void{
if($this->blockCollision !== $value){
$this->blockCollision = $value;
$this->getNetworkSession()->syncAbilities($this);
}
}
/**
* Returns whether blocks may obstruct the player's movement.
* If false, the player can move through any block unobstructed.
*/
public function hasBlockCollision() : bool{
return $this->blockCollision;
}
public function setFlying(bool $value) : void{
if($this->flying !== $value){
$this->flying = $value;
$this->resetFallDistance();
$this->getNetworkSession()->syncAbilities($this);
}
}
public function isFlying() : bool{
return $this->flying;
}
public function setAutoJump(bool $value) : void{
if($this->autoJump !== $value){
$this->autoJump = $value;
$this->getNetworkSession()->syncAdventureSettings();
}
}
public function hasAutoJump() : bool{
return $this->autoJump;
}
public function spawnTo(Player $player) : void{
if($this->isAlive() && $player->isAlive() && $player->canSee($this) && !$this->isSpectator()){
parent::spawnTo($player);
}
}
public function getServer() : Server{
return $this->server;
}
public function getScreenLineHeight() : int{
return $this->lineHeight ?? 7;
}
public function setScreenLineHeight(?int $height) : void{
if($height !== null && $height < 1){
throw new \InvalidArgumentException("Line height must be at least 1");
}
$this->lineHeight = $height;
}
public function canSee(Player $player) : bool{
return !isset($this->hiddenPlayers[$player->getUniqueId()->getBytes()]);
}
public function hidePlayer(Player $player) : void{
if($player === $this){
return;
}
$this->hiddenPlayers[$player->getUniqueId()->getBytes()] = true;
$player->despawnFrom($this);
}
public function showPlayer(Player $player) : void{
if($player === $this){
return;
}
unset($this->hiddenPlayers[$player->getUniqueId()->getBytes()]);
if($player->isOnline()){
$player->spawnTo($this);
}
}
public function canCollideWith(Entity $entity) : bool{
return false;
}
public function canBeCollidedWith() : bool{
return !$this->isSpectator() && parent::canBeCollidedWith();
}
public function resetFallDistance() : void{
parent::resetFallDistance();
$this->inAirTicks = 0;
}
public function getViewDistance() : int{
return $this->viewDistance;
}
public function setViewDistance(int $distance) : void{
$newViewDistance = $this->server->getAllowedViewDistance($distance);
if($newViewDistance !== $this->viewDistance){
$ev = new PlayerViewDistanceChangeEvent($this, $this->viewDistance, $newViewDistance);
$ev->call();
}
$this->viewDistance = $newViewDistance;
$this->spawnThreshold = (int) (min($this->viewDistance, $this->server->getConfigGroup()->getPropertyInt(YmlServerProperties::CHUNK_SENDING_SPAWN_RADIUS, 4)) ** 2 * M_PI);
$this->nextChunkOrderRun = 0;
$this->getNetworkSession()->syncViewAreaRadius($this->viewDistance);
$this->logger->debug("Setting view distance to " . $this->viewDistance . " (requested " . $distance . ")");
}
public function isOnline() : bool{
return $this->isConnected();
}
public function isConnected() : bool{
return $this->networkSession !== null && $this->networkSession->isConnected();
}
public function getNetworkSession() : NetworkSession{
if($this->networkSession === null){
throw new \LogicException("Player is not connected");
}
return $this->networkSession;
}
/**
* Gets the username
*/
public function getName() : string{
return $this->username;
}
/**
* Returns the "friendly" display name of this player to use in the chat.
*/
public function getDisplayName() : string{
return $this->displayName;
}
public function setDisplayName(string $name) : void{
$ev = new PlayerDisplayNameChangeEvent($this, $this->displayName, $name);
$ev->call();
$this->displayName = $ev->getNewName();
}
/**
* Returns the player's locale, e.g. en_US.
*/
public function getLocale() : string{
return $this->locale;
}
public function getLanguage() : Language{
return $this->server->getLanguage();
}
/**
* Called when a player changes their skin.
* Plugin developers should not use this, use setSkin() and sendSkin() instead.
*/
public function changeSkin(Skin $skin, string $newSkinName, string $oldSkinName) : bool{
$ev = new PlayerChangeSkinEvent($this, $this->getSkin(), $skin);
$ev->call();
if($ev->isCancelled()){
$this->sendSkin([$this]);
return true;
}
$this->setSkin($ev->getNewSkin());
$this->sendSkin($this->server->getOnlinePlayers());
return true;
}
/**
* {@inheritdoc}
*
* If null is given, will additionally send the skin to the player itself as well as its viewers.
*/
public function sendSkin(?array $targets = null) : void{
parent::sendSkin($targets ?? $this->server->getOnlinePlayers());
}
/**
* Returns whether the player is currently using an item (right-click and hold).
*/
public function isUsingItem() : bool{
return $this->startAction > -1;
}
public function setUsingItem(bool $value) : void{
$this->startAction = $value ? $this->server->getTick() : -1;
$this->networkPropertiesDirty = true;
}
/**
* Returns how long the player has been using their currently-held item for. Used for determining arrow shoot force
* for bows.
*/
public function getItemUseDuration() : int{
return $this->startAction === -1 ? -1 : ($this->server->getTick() - $this->startAction);
}
/**
* Returns the server tick on which the player's cooldown period expires for the given item.
*/
public function getItemCooldownExpiry(Item $item) : int{
$this->checkItemCooldowns();
return $this->usedItemsCooldown[$item->getStateId()] ?? 0;
}
/**
* Returns whether the player has a cooldown period left before it can use the given item again.
*/
public function hasItemCooldown(Item $item) : bool{
$this->checkItemCooldowns();
return isset($this->usedItemsCooldown[$item->getStateId()]);
}
/**
* Resets the player's cooldown time for the given item back to the maximum.
*/
public function resetItemCooldown(Item $item, ?int $ticks = null) : void{
$ticks = $ticks ?? $item->getCooldownTicks();
if($ticks > 0){
$this->usedItemsCooldown[$item->getStateId()] = $this->server->getTick() + $ticks;
}
}
protected function checkItemCooldowns() : void{
$serverTick = $this->server->getTick();
foreach($this->usedItemsCooldown as $itemId => $cooldownUntil){
if($cooldownUntil <= $serverTick){
unset($this->usedItemsCooldown[$itemId]);
}
}
}
protected function setPosition(Vector3 $pos) : bool{
$oldWorld = $this->location->isValid() ? $this->location->getWorld() : null;
if(parent::setPosition($pos)){
$newWorld = $this->getWorld();
if($oldWorld !== $newWorld){
if($oldWorld !== null){
foreach($this->usedChunks as $index => $status){
World::getXZ($index, $X, $Z);
$this->unloadChunk($X, $Z, $oldWorld);
}
}
$this->usedChunks = [];
$this->loadQueue = [];
$this->getNetworkSession()->onEnterWorld();
}
return true;
}
return false;
}
protected function unloadChunk(int $x, int $z, ?World $world = null) : void{
$world = $world ?? $this->getWorld();
$index = World::chunkHash($x, $z);
if(isset($this->usedChunks[$index])){
foreach($world->getChunkEntities($x, $z) as $entity){
if($entity !== $this){
$entity->despawnFrom($this);
}
}
$this->getNetworkSession()->stopUsingChunk($x, $z);
unset($this->usedChunks[$index]);
unset($this->activeChunkGenerationRequests[$index]);
}
$world->unregisterChunkLoader($this->chunkLoader, $x, $z);
$world->unregisterChunkListener($this, $x, $z);
unset($this->loadQueue[$index]);
$world->unregisterTickingChunk($this->chunkTicker, $x, $z);
unset($this->tickingChunks[$index]);
}
protected function spawnEntitiesOnAllChunks() : void{
foreach($this->usedChunks as $chunkHash => $status){
if($status === UsedChunkStatus::SENT){
World::getXZ($chunkHash, $chunkX, $chunkZ);
$this->spawnEntitiesOnChunk($chunkX, $chunkZ);
}
}
}
protected function spawnEntitiesOnChunk(int $chunkX, int $chunkZ) : void{
foreach($this->getWorld()->getChunkEntities($chunkX, $chunkZ) as $entity){
if($entity !== $this && !$entity->isFlaggedForDespawn()){
$entity->spawnTo($this);
}
}
}
/**
* Requests chunks from the world to be sent, up to a set limit every tick. This operates on the results of the most recent chunk
* order.
*/
protected function requestChunks() : void{
if(!$this->isConnected()){
return;
}
Timings::$playerChunkSend->startTiming();
$count = 0;
$world = $this->getWorld();
$limit = $this->chunksPerTick - count($this->activeChunkGenerationRequests);
foreach($this->loadQueue as $index => $distance){
if($count >= $limit){
break;
}
$X = null;
$Z = null;
World::getXZ($index, $X, $Z);
assert(is_int($X) && is_int($Z));
++$count;
$this->usedChunks[$index] = UsedChunkStatus::REQUESTED_GENERATION;
$this->activeChunkGenerationRequests[$index] = true;
unset($this->loadQueue[$index]);
$this->getWorld()->registerChunkLoader($this->chunkLoader, $X, $Z, true);
$this->getWorld()->registerChunkListener($this, $X, $Z);
if(isset($this->tickingChunks[$index])){
$this->getWorld()->registerTickingChunk($this->chunkTicker, $X, $Z);
}
$this->getWorld()->requestChunkPopulation($X, $Z, $this->chunkLoader)->onCompletion(
function() use ($X, $Z, $index, $world) : void{
if(!$this->isConnected() || !isset($this->usedChunks[$index]) || $world !== $this->getWorld()){
return;
}
if($this->usedChunks[$index] !== UsedChunkStatus::REQUESTED_GENERATION){
//We may have previously requested this, decided we didn't want it, and then decided we did want
//it again, all before the generation request got executed. In that case, the promise would have
//multiple callbacks for this player. In that case, only the first one matters.
return;
}
unset($this->activeChunkGenerationRequests[$index]);
$this->usedChunks[$index] = UsedChunkStatus::REQUESTED_SENDING;
$this->getNetworkSession()->startUsingChunk($X, $Z, function() use ($X, $Z, $index) : void{
$this->usedChunks[$index] = UsedChunkStatus::SENT;
if($this->spawnChunkLoadCount === -1){
$this->spawnEntitiesOnChunk($X, $Z);
}elseif($this->spawnChunkLoadCount++ === $this->spawnThreshold){
$this->spawnChunkLoadCount = -1;
$this->spawnEntitiesOnAllChunks();
$this->getNetworkSession()->notifyTerrainReady();
}
(new PlayerPostChunkSendEvent($this, $X, $Z))->call();
});
},
static function() : void{
//NOOP: we'll re-request this if it fails anyway
}
);
}
Timings::$playerChunkSend->stopTiming();
}
private function recheckBroadcastPermissions() : void{
foreach([
DefaultPermissionNames::BROADCAST_ADMIN => Server::BROADCAST_CHANNEL_ADMINISTRATIVE,
DefaultPermissionNames::BROADCAST_USER => Server::BROADCAST_CHANNEL_USERS
] as $permission => $channel){
if($this->hasPermission($permission)){
$this->server->subscribeToBroadcastChannel($channel, $this);
}else{
$this->server->unsubscribeFromBroadcastChannel($channel, $this);
}
}
}
/**
* Called by the network system when the pre-spawn sequence is completed (e.g. after sending spawn chunks).
* This fires join events and broadcasts join messages to other online players.
*/
public function doFirstSpawn() : void{
if($this->spawned){
return;
}
$this->spawned = true;
$this->recheckBroadcastPermissions();
$this->getPermissionRecalculationCallbacks()->add(function(array $changedPermissionsOldValues) : void{
if(isset($changedPermissionsOldValues[Server::BROADCAST_CHANNEL_ADMINISTRATIVE]) || isset($changedPermissionsOldValues[Server::BROADCAST_CHANNEL_USERS])){
$this->recheckBroadcastPermissions();
}
});
$ev = new PlayerJoinEvent($this,
KnownTranslationFactory::multiplayer_player_joined($this->getDisplayName())->prefix(TextFormat::YELLOW)
);
$ev->call();
if($ev->getJoinMessage() !== ""){
$this->server->broadcastMessage($ev->getJoinMessage());
}
$this->noDamageTicks = 60;
$this->spawnToAll();
if($this->getHealth() <= 0){
$this->logger->debug("Quit while dead, forcing respawn");
$this->actuallyRespawn();
}
}
/**
* @param true[] $oldTickingChunks
* @param true[] $newTickingChunks
*
* @phpstan-param array<int, true> $oldTickingChunks
* @phpstan-param array<int, true> $newTickingChunks
*/
private function updateTickingChunkRegistrations(array $oldTickingChunks, array $newTickingChunks) : void{
$world = $this->getWorld();
foreach($oldTickingChunks as $hash => $_){
if(!isset($newTickingChunks[$hash]) && !isset($this->loadQueue[$hash])){
//we are (probably) still using this chunk, but it's no longer within ticking range
World::getXZ($hash, $tickingChunkX, $tickingChunkZ);
$world->unregisterTickingChunk($this->chunkTicker, $tickingChunkX, $tickingChunkZ);
}
}
foreach($newTickingChunks as $hash => $_){
if(!isset($oldTickingChunks[$hash]) && !isset($this->loadQueue[$hash])){
//we were already using this chunk, but it is now within ticking range
World::getXZ($hash, $tickingChunkX, $tickingChunkZ);
$world->registerTickingChunk($this->chunkTicker, $tickingChunkX, $tickingChunkZ);
}
}
}
/**
* Calculates which new chunks this player needs to use, and which currently-used chunks it needs to stop using.
* This is based on factors including the player's current render radius and current position.
*/
protected function orderChunks() : void{
if(!$this->isConnected() || $this->viewDistance === -1){
return;
}
Timings::$playerChunkOrder->startTiming();
$newOrder = [];
$tickingChunks = [];
$unloadChunks = $this->usedChunks;
$world = $this->getWorld();
$tickingChunkRadius = $world->getChunkTickRadius();
foreach($this->chunkSelector->selectChunks(
$this->server->getAllowedViewDistance($this->viewDistance),
$this->location->getFloorX() >> Chunk::COORD_BIT_SIZE,
$this->location->getFloorZ() >> Chunk::COORD_BIT_SIZE
) as $radius => $hash){
if(!isset($this->usedChunks[$hash]) || $this->usedChunks[$hash] === UsedChunkStatus::NEEDED){
$newOrder[$hash] = true;
}
if($radius < $tickingChunkRadius){
$tickingChunks[$hash] = true;
}
unset($unloadChunks[$hash]);
}
foreach($unloadChunks as $index => $status){
World::getXZ($index, $X, $Z);
$this->unloadChunk($X, $Z);
}
$this->loadQueue = $newOrder;
$this->updateTickingChunkRegistrations($this->tickingChunks, $tickingChunks);
$this->tickingChunks = $tickingChunks;
if(count($this->loadQueue) > 0 || count($unloadChunks) > 0){
$this->getNetworkSession()->syncViewAreaCenterPoint($this->location, $this->viewDistance);
}
Timings::$playerChunkOrder->stopTiming();
}
/**
* Returns whether the player is using the chunk with the given coordinates, irrespective of whether the chunk has
* been sent yet.
*/
public function isUsingChunk(int $chunkX, int $chunkZ) : bool{
return isset($this->usedChunks[World::chunkHash($chunkX, $chunkZ)]);
}
/**
* @return UsedChunkStatus[] chunkHash => status
* @phpstan-return array<int, UsedChunkStatus>
*/
public function getUsedChunks() : array{
return $this->usedChunks;
}
/**
* Returns a usage status of the given chunk, or null if the player is not using the given chunk.
*/
public function getUsedChunkStatus(int $chunkX, int $chunkZ) : ?UsedChunkStatus{
return $this->usedChunks[World::chunkHash($chunkX, $chunkZ)] ?? null;