PocketMine-MP 5.23.3 git-f7687af337d001ddbcc47b8e773f014a33faa662
Loading...
Searching...
No Matches
Human.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\entity;
25
72use Ramsey\Uuid\Uuid;
73use Ramsey\Uuid\UuidInterface;
74use function array_fill;
75use function array_filter;
76use function array_key_exists;
77use function array_merge;
78use function array_values;
79use function min;
80
81class Human extends Living implements ProjectileSource, InventoryHolder{
82
83 private const TAG_INVENTORY = "Inventory"; //TAG_List<TAG_Compound>
84 private const TAG_OFF_HAND_ITEM = "OffHandItem"; //TAG_Compound
85 private const TAG_ENDER_CHEST_INVENTORY = "EnderChestInventory"; //TAG_List<TAG_Compound>
86 private const TAG_SELECTED_INVENTORY_SLOT = "SelectedInventorySlot"; //TAG_Int
87 private const TAG_FOOD_LEVEL = "foodLevel"; //TAG_Int
88 private const TAG_FOOD_EXHAUSTION_LEVEL = "foodExhaustionLevel"; //TAG_Float
89 private const TAG_FOOD_SATURATION_LEVEL = "foodSaturationLevel"; //TAG_Float
90 private const TAG_FOOD_TICK_TIMER = "foodTickTimer"; //TAG_Int
91 private const TAG_XP_LEVEL = "XpLevel"; //TAG_Int
92 private const TAG_XP_PROGRESS = "XpP"; //TAG_Float
93 private const TAG_LIFETIME_XP_TOTAL = "XpTotal"; //TAG_Int
94 private const TAG_XP_SEED = "XpSeed"; //TAG_Int
95 private const TAG_SKIN = "Skin"; //TAG_Compound
96 private const TAG_SKIN_NAME = "Name"; //TAG_String
97 private const TAG_SKIN_DATA = "Data"; //TAG_ByteArray
98 private const TAG_SKIN_CAPE_DATA = "CapeData"; //TAG_ByteArray
99 private const TAG_SKIN_GEOMETRY_NAME = "GeometryName"; //TAG_String
100 private const TAG_SKIN_GEOMETRY_DATA = "GeometryData"; //TAG_ByteArray
101
102 public static function getNetworkTypeId() : string{ return EntityIds::PLAYER; }
103
104 protected PlayerInventory $inventory;
105 protected PlayerOffHandInventory $offHandInventory;
106 protected PlayerEnderInventory $enderInventory;
107
108 protected UuidInterface $uuid;
109
110 protected Skin $skin;
111
112 protected HungerManager $hungerManager;
113 protected ExperienceManager $xpManager;
114
115 protected int $xpSeed;
116
117 public function __construct(Location $location, Skin $skin, ?CompoundTag $nbt = null){
118 $this->skin = $skin;
119 parent::__construct($location, $nbt);
120 }
121
122 protected function getInitialSizeInfo() : EntitySizeInfo{ return new EntitySizeInfo(1.8, 0.6, 1.62); }
123
128 public static function parseSkinNBT(CompoundTag $nbt) : Skin{
129 $skinTag = $nbt->getCompoundTag(self::TAG_SKIN);
130 if($skinTag === null){
131 throw new SavedDataLoadingException("Missing skin data");
132 }
133 return new Skin( //this throws if the skin is invalid
134 $skinTag->getString(self::TAG_SKIN_NAME),
135 ($skinDataTag = $skinTag->getTag(self::TAG_SKIN_DATA)) instanceof StringTag ? $skinDataTag->getValue() : $skinTag->getByteArray(self::TAG_SKIN_DATA), //old data (this used to be saved as a StringTag in older versions of PM)
136 $skinTag->getByteArray(self::TAG_SKIN_CAPE_DATA, ""),
137 $skinTag->getString(self::TAG_SKIN_GEOMETRY_NAME, ""),
138 $skinTag->getByteArray(self::TAG_SKIN_GEOMETRY_DATA, "")
139 );
140 }
141
142 public function getUniqueId() : UuidInterface{
143 return $this->uuid;
144 }
145
149 public function getSkin() : Skin{
150 return $this->skin;
151 }
152
157 public function setSkin(Skin $skin) : void{
158 $this->skin = $skin;
159 }
160
167 public function sendSkin(?array $targets = null) : void{
168 NetworkBroadcastUtils::broadcastPackets($targets ?? $this->hasSpawned, [
169 PlayerSkinPacket::create($this->getUniqueId(), "", "", TypeConverter::getInstance()->getSkinAdapter()->toSkinData($this->skin))
170 ]);
171 }
172
173 public function jump() : void{
174 parent::jump();
175 if($this->isSprinting()){
176 $this->hungerManager->exhaust(0.2, PlayerExhaustEvent::CAUSE_SPRINT_JUMPING);
177 }else{
178 $this->hungerManager->exhaust(0.05, PlayerExhaustEvent::CAUSE_JUMPING);
179 }
180 }
181
182 public function emote(string $emoteId) : void{
183 NetworkBroadcastUtils::broadcastEntityEvent(
184 $this->getViewers(),
185 fn(EntityEventBroadcaster $broadcaster, array $recipients) => $broadcaster->onEmote($recipients, $this, $emoteId)
186 );
187 }
188
189 public function getHungerManager() : HungerManager{
190 return $this->hungerManager;
191 }
192
197 public function canEat() : bool{
198 return $this->hungerManager->isHungry() || $this->getWorld()->getDifficulty() === World::DIFFICULTY_PEACEFUL;
199 }
200
201 public function consumeObject(Consumable $consumable) : bool{
202 if($consumable instanceof FoodSource && $consumable->requiresHunger() && !$this->canEat()){
203 return false;
204 }
205
206 return parent::consumeObject($consumable);
207 }
208
209 protected function applyConsumptionResults(Consumable $consumable) : void{
210 if($consumable instanceof FoodSource){
211 $this->hungerManager->addFood($consumable->getFoodRestore());
212 $this->hungerManager->addSaturation($consumable->getSaturationRestore());
213 }
214
215 parent::applyConsumptionResults($consumable);
216 }
217
218 public function getXpManager() : ExperienceManager{
219 return $this->xpManager;
220 }
221
222 public function getEnchantmentSeed() : int{
223 return $this->xpSeed;
224 }
225
226 public function setEnchantmentSeed(int $seed) : void{
227 $this->xpSeed = $seed;
228 }
229
230 public function regenerateEnchantmentSeed() : void{
231 $this->xpSeed = EnchantingHelper::generateSeed();
232 }
233
234 public function getXpDropAmount() : int{
235 //this causes some XP to be lost on death when above level 1 (by design), dropping at most enough points for
236 //about 7.5 levels of XP.
237 return min(100, 7 * $this->xpManager->getXpLevel());
238 }
239
240 public function getInventory() : PlayerInventory{
241 return $this->inventory;
242 }
243
244 public function getOffHandInventory() : PlayerOffHandInventory{ return $this->offHandInventory; }
245
246 public function getEnderInventory() : PlayerEnderInventory{
247 return $this->enderInventory;
248 }
249
253 protected function initHumanData(CompoundTag $nbt) : void{
254 //TODO: use of NIL UUID for namespace is a hack; we should provide a proper UUID for the namespace
255 $this->uuid = Uuid::uuid3(Uuid::NIL, ((string) $this->getId()) . $this->skin->getSkinData() . $this->getNameTag());
256 }
257
262 private static function populateInventoryFromListTag(Inventory $inventory, array $items) : void{
263 $listeners = $inventory->getListeners()->toArray();
264 $inventory->getListeners()->clear();
265
266 $inventory->setContents($items);
267
268 $inventory->getListeners()->add(...$listeners);
269 }
270
271 protected function initEntity(CompoundTag $nbt) : void{
272 parent::initEntity($nbt);
273
274 $this->hungerManager = new HungerManager($this);
275 $this->xpManager = new ExperienceManager($this);
276
277 $this->inventory = new PlayerInventory($this);
278 $syncHeldItem = fn() => NetworkBroadcastUtils::broadcastEntityEvent(
279 $this->getViewers(),
280 fn(EntityEventBroadcaster $broadcaster, array $recipients) => $broadcaster->onMobMainHandItemChange($recipients, $this)
281 );
282 $this->inventory->getListeners()->add(new CallbackInventoryListener(
283 function(Inventory $unused, int $slot, Item $unused2) use ($syncHeldItem) : void{
284 if($slot === $this->inventory->getHeldItemIndex()){
285 $syncHeldItem();
286 }
287 },
288 function(Inventory $unused, array $oldItems) use ($syncHeldItem) : void{
289 if(array_key_exists($this->inventory->getHeldItemIndex(), $oldItems)){
290 $syncHeldItem();
291 }
292 }
293 ));
294 $this->offHandInventory = new PlayerOffHandInventory($this);
295 $this->enderInventory = new PlayerEnderInventory($this);
296 $this->initHumanData($nbt);
297
298 $inventoryTag = $nbt->getListTag(self::TAG_INVENTORY);
299 if($inventoryTag !== null){
300 $inventoryItems = [];
301 $armorInventoryItems = [];
302
304 foreach($inventoryTag as $i => $item){
305 $slot = $item->getByte(SavedItemStackData::TAG_SLOT);
306 if($slot >= 0 && $slot < 9){ //Hotbar
307 //Old hotbar saving stuff, ignore it
308 }elseif($slot >= 100 && $slot < 104){ //Armor
309 $armorInventoryItems[$slot - 100] = Item::nbtDeserialize($item);
310 }elseif($slot >= 9 && $slot < $this->inventory->getSize() + 9){
311 $inventoryItems[$slot - 9] = Item::nbtDeserialize($item);
312 }
313 }
314
315 self::populateInventoryFromListTag($this->inventory, $inventoryItems);
316 self::populateInventoryFromListTag($this->armorInventory, $armorInventoryItems);
317 }
318 $offHand = $nbt->getCompoundTag(self::TAG_OFF_HAND_ITEM);
319 if($offHand !== null){
320 $this->offHandInventory->setItem(0, Item::nbtDeserialize($offHand));
321 }
322 $this->offHandInventory->getListeners()->add(CallbackInventoryListener::onAnyChange(fn() => NetworkBroadcastUtils::broadcastEntityEvent(
323 $this->getViewers(),
324 fn(EntityEventBroadcaster $broadcaster, array $recipients) => $broadcaster->onMobOffHandItemChange($recipients, $this)
325 )));
326
327 $enderChestInventoryTag = $nbt->getListTag(self::TAG_ENDER_CHEST_INVENTORY);
328 if($enderChestInventoryTag !== null){
329 $enderChestInventoryItems = [];
330
332 foreach($enderChestInventoryTag as $i => $item){
333 $enderChestInventoryItems[$item->getByte(SavedItemStackData::TAG_SLOT)] = Item::nbtDeserialize($item);
334 }
335 self::populateInventoryFromListTag($this->enderInventory, $enderChestInventoryItems);
336 }
337
338 $this->inventory->setHeldItemIndex($nbt->getInt(self::TAG_SELECTED_INVENTORY_SLOT, 0));
339 $this->inventory->getHeldItemIndexChangeListeners()->add(fn() => NetworkBroadcastUtils::broadcastEntityEvent(
340 $this->getViewers(),
341 fn(EntityEventBroadcaster $broadcaster, array $recipients) => $broadcaster->onMobMainHandItemChange($recipients, $this)
342 ));
343
344 $this->hungerManager->setFood((float) $nbt->getInt(self::TAG_FOOD_LEVEL, (int) $this->hungerManager->getFood()));
345 $this->hungerManager->setExhaustion($nbt->getFloat(self::TAG_FOOD_EXHAUSTION_LEVEL, $this->hungerManager->getExhaustion()));
346 $this->hungerManager->setSaturation($nbt->getFloat(self::TAG_FOOD_SATURATION_LEVEL, $this->hungerManager->getSaturation()));
347 $this->hungerManager->setFoodTickTimer($nbt->getInt(self::TAG_FOOD_TICK_TIMER, $this->hungerManager->getFoodTickTimer()));
348
349 $this->xpManager->setXpAndProgressNoEvent(
350 $nbt->getInt(self::TAG_XP_LEVEL, 0),
351 $nbt->getFloat(self::TAG_XP_PROGRESS, 0.0));
352 $this->xpManager->setLifetimeTotalXp($nbt->getInt(self::TAG_LIFETIME_XP_TOTAL, 0));
353
354 if(($xpSeedTag = $nbt->getTag(self::TAG_XP_SEED)) instanceof IntTag){
355 $this->xpSeed = $xpSeedTag->getValue();
356 }else{
357 $this->xpSeed = EnchantingHelper::generateSeed();
358 }
359 }
360
361 protected function entityBaseTick(int $tickDiff = 1) : bool{
362 $hasUpdate = parent::entityBaseTick($tickDiff);
363
364 $this->hungerManager->tick($tickDiff);
365 $this->xpManager->tick($tickDiff);
366
367 return $hasUpdate;
368 }
369
370 public function getName() : string{
371 return $this->getNameTag();
372 }
373
374 public function applyDamageModifiers(EntityDamageEvent $source) : void{
375 parent::applyDamageModifiers($source);
376
377 $type = $source->getCause();
378 if($type !== EntityDamageEvent::CAUSE_SUICIDE && $type !== EntityDamageEvent::CAUSE_VOID
379 && ($this->inventory->getItemInHand() instanceof Totem || $this->offHandInventory->getItem(0) instanceof Totem)){
380
381 $compensation = $this->getHealth() - $source->getFinalDamage() - 1;
382 if($compensation <= -1){
383 $source->setModifier($compensation, EntityDamageEvent::MODIFIER_TOTEM);
384 }
385 }
386 }
387
388 protected function applyPostDamageEffects(EntityDamageEvent $source) : void{
389 parent::applyPostDamageEffects($source);
390 $totemModifier = $source->getModifier(EntityDamageEvent::MODIFIER_TOTEM);
391 if($totemModifier < 0){ //Totem prevented death
392 $this->effectManager->clear();
393
394 $this->effectManager->add(new EffectInstance(VanillaEffects::REGENERATION(), 40 * 20, 1));
395 $this->effectManager->add(new EffectInstance(VanillaEffects::FIRE_RESISTANCE(), 40 * 20, 1));
396 $this->effectManager->add(new EffectInstance(VanillaEffects::ABSORPTION(), 5 * 20, 1));
397
398 $this->broadcastAnimation(new TotemUseAnimation($this));
399 $this->broadcastSound(new TotemUseSound());
400
401 $hand = $this->inventory->getItemInHand();
402 if($hand instanceof Totem){
403 $hand->pop(); //Plugins could alter max stack size
404 $this->inventory->setItemInHand($hand);
405 }elseif(($offHand = $this->offHandInventory->getItem(0)) instanceof Totem){
406 $offHand->pop();
407 $this->offHandInventory->setItem(0, $offHand);
408 }
409 }
410 }
411
412 public function getDrops() : array{
413 return array_filter(array_merge(
414 array_values($this->inventory->getContents()),
415 array_values($this->armorInventory->getContents()),
416 array_values($this->offHandInventory->getContents()),
417 ), function(Item $item) : bool{ return !$item->hasEnchantment(VanillaEnchantments::VANISHING()) && !$item->keepOnDeath(); });
418 }
419
420 public function saveNBT() : CompoundTag{
421 $nbt = parent::saveNBT();
422
423 $nbt->setInt(self::TAG_FOOD_LEVEL, (int) $this->hungerManager->getFood());
424 $nbt->setFloat(self::TAG_FOOD_EXHAUSTION_LEVEL, $this->hungerManager->getExhaustion());
425 $nbt->setFloat(self::TAG_FOOD_SATURATION_LEVEL, $this->hungerManager->getSaturation());
426 $nbt->setInt(self::TAG_FOOD_TICK_TIMER, $this->hungerManager->getFoodTickTimer());
427
428 $nbt->setInt(self::TAG_XP_LEVEL, $this->xpManager->getXpLevel());
429 $nbt->setFloat(self::TAG_XP_PROGRESS, $this->xpManager->getXpProgress());
430 $nbt->setInt(self::TAG_LIFETIME_XP_TOTAL, $this->xpManager->getLifetimeTotalXp());
431 $nbt->setInt(self::TAG_XP_SEED, $this->xpSeed);
432
433 $inventoryTag = new ListTag([], NBT::TAG_Compound);
434 $nbt->setTag(self::TAG_INVENTORY, $inventoryTag);
435
436 //Normal inventory
437 $slotCount = $this->inventory->getSize() + $this->inventory->getHotbarSize();
438 for($slot = $this->inventory->getHotbarSize(); $slot < $slotCount; ++$slot){
439 $item = $this->inventory->getItem($slot - 9);
440 if(!$item->isNull()){
441 $inventoryTag->push($item->nbtSerialize($slot));
442 }
443 }
444
445 //Armor
446 for($slot = 100; $slot < 104; ++$slot){
447 $item = $this->armorInventory->getItem($slot - 100);
448 if(!$item->isNull()){
449 $inventoryTag->push($item->nbtSerialize($slot));
450 }
451 }
452
453 $nbt->setInt(self::TAG_SELECTED_INVENTORY_SLOT, $this->inventory->getHeldItemIndex());
454
455 $offHandItem = $this->offHandInventory->getItem(0);
456 if(!$offHandItem->isNull()){
457 $nbt->setTag(self::TAG_OFF_HAND_ITEM, $offHandItem->nbtSerialize());
458 }
459
461 $items = [];
462
463 $slotCount = $this->enderInventory->getSize();
464 for($slot = 0; $slot < $slotCount; ++$slot){
465 $item = $this->enderInventory->getItem($slot);
466 if(!$item->isNull()){
467 $items[] = $item->nbtSerialize($slot);
468 }
469 }
470
471 $nbt->setTag(self::TAG_ENDER_CHEST_INVENTORY, new ListTag($items, NBT::TAG_Compound));
472
473 $nbt->setTag(self::TAG_SKIN, CompoundTag::create()
474 ->setString(self::TAG_SKIN_NAME, $this->skin->getSkinId())
475 ->setByteArray(self::TAG_SKIN_DATA, $this->skin->getSkinData())
476 ->setByteArray(self::TAG_SKIN_CAPE_DATA, $this->skin->getCapeData())
477 ->setString(self::TAG_SKIN_GEOMETRY_NAME, $this->skin->getGeometryName())
478 ->setByteArray(self::TAG_SKIN_GEOMETRY_DATA, $this->skin->getGeometryData())
479 );
480
481 return $nbt;
482 }
483
484 public function spawnTo(Player $player) : void{
485 if($player !== $this){
486 parent::spawnTo($player);
487 }
488 }
489
490 protected function sendSpawnPacket(Player $player) : void{
491 $networkSession = $player->getNetworkSession();
492 $typeConverter = $networkSession->getTypeConverter();
493 if(!($this instanceof Player)){
494 $networkSession->sendDataPacket(PlayerListPacket::add([PlayerListEntry::createAdditionEntry($this->uuid, $this->id, $this->getName(), $typeConverter->getSkinAdapter()->toSkinData($this->skin))]));
495 }
496
497 $networkSession->sendDataPacket(AddPlayerPacket::create(
498 $this->getUniqueId(),
499 $this->getName(),
500 $this->getId(),
501 "",
502 $this->location->asVector3(),
503 $this->getMotion(),
504 $this->location->pitch,
505 $this->location->yaw,
506 $this->location->yaw, //TODO: head yaw
507 ItemStackWrapper::legacy($typeConverter->coreItemStackToNet($this->getInventory()->getItemInHand())),
508 GameMode::SURVIVAL,
509 $this->getAllNetworkData(),
510 new PropertySyncData([], []),
511 UpdateAbilitiesPacket::create(new AbilitiesData(CommandPermissions::NORMAL, PlayerPermissions::VISITOR, $this->getId() /* TODO: this should be unique ID */, [
512 new AbilitiesLayer(
513 AbilitiesLayer::LAYER_BASE,
514 array_fill(0, AbilitiesLayer::NUMBER_OF_ABILITIES, false),
515 0.0,
516 0.0
517 )
518 ])),
519 [], //TODO: entity links
520 "", //device ID (we intentionally don't send this - secvuln)
521 DeviceOS::UNKNOWN //we intentionally don't send this (secvuln)
522 ));
523
524 //TODO: Hack for MCPE 1.2.13: DATA_NAMETAG is useless in AddPlayerPacket, so it has to be sent separately
525 $this->sendData([$player], [EntityMetadataProperties::NAMETAG => new StringMetadataProperty($this->getNameTag())]);
526
527 $entityEventBroadcaster = $networkSession->getEntityEventBroadcaster();
528 $entityEventBroadcaster->onMobArmorChange([$networkSession], $this);
529 $entityEventBroadcaster->onMobOffHandItemChange([$networkSession], $this);
530
531 if(!($this instanceof Player)){
532 $networkSession->sendDataPacket(PlayerListPacket::remove([PlayerListEntry::createRemovalEntry($this->uuid)]));
533 }
534 }
535
536 public function getOffsetPosition(Vector3 $vector3) : Vector3{
537 return $vector3->add(0, 1.621, 0); //TODO: +0.001 hack for MCPE falling underground
538 }
539
540 protected function onDispose() : void{
541 $this->inventory->removeAllViewers();
542 $this->inventory->getHeldItemIndexChangeListeners()->clear();
543 $this->offHandInventory->removeAllViewers();
544 $this->enderInventory->removeAllViewers();
545 parent::onDispose();
546 }
547
548 protected function destroyCycles() : void{
549 unset(
550 $this->inventory,
551 $this->offHandInventory,
552 $this->enderInventory,
553 $this->hungerManager,
554 $this->xpManager
555 );
556 parent::destroyCycles();
557 }
558}
applyPostDamageEffects(EntityDamageEvent $source)
Definition Human.php:388
applyConsumptionResults(Consumable $consumable)
Definition Human.php:209
static parseSkinNBT(CompoundTag $nbt)
Definition Human.php:128
sendSkin(?array $targets=null)
Definition Human.php:167
sendSpawnPacket(Player $player)
Definition Human.php:490
initHumanData(CompoundTag $nbt)
Definition Human.php:253
setSkin(Skin $skin)
Definition Human.php:157
applyDamageModifiers(EntityDamageEvent $source)
Definition Human.php:374
consumeObject(Consumable $consumable)
Definition Human.php:201
setInt(string $name, int $value)
setTag(string $name, Tag $tag)
setFloat(string $name, float $value)
onMobMainHandItemChange(array $recipients, Human $mob)