PocketMine-MP 5.35.1 git-05a71d8cc5185aa9e46ef5f9754bb862464c13e0
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
250 public function getSneakOffset() : float{
251 return 0.31;
252 }
253
257 protected function initHumanData(CompoundTag $nbt) : void{
258 //TODO: use of NIL UUID for namespace is a hack; we should provide a proper UUID for the namespace
259 $this->uuid = Uuid::uuid3(Uuid::NIL, ((string) $this->getId()) . $this->skin->getSkinData() . $this->getNameTag());
260 }
261
266 private static function populateInventoryFromListTag(Inventory $inventory, array $items) : void{
267 $listeners = $inventory->getListeners()->toArray();
268 $inventory->getListeners()->clear();
269
270 $inventory->setContents($items);
271
272 $inventory->getListeners()->add(...$listeners);
273 }
274
275 protected function initEntity(CompoundTag $nbt) : void{
276 parent::initEntity($nbt);
277
278 $this->hungerManager = new HungerManager($this);
279 $this->xpManager = new ExperienceManager($this);
280
281 $this->inventory = new PlayerInventory($this);
282 $syncHeldItem = fn() => NetworkBroadcastUtils::broadcastEntityEvent(
283 $this->getViewers(),
284 fn(EntityEventBroadcaster $broadcaster, array $recipients) => $broadcaster->onMobMainHandItemChange($recipients, $this)
285 );
286 $this->inventory->getListeners()->add(new CallbackInventoryListener(
287 function(Inventory $unused, int $slot, Item $unused2) use ($syncHeldItem) : void{
288 if($slot === $this->inventory->getHeldItemIndex()){
289 $syncHeldItem();
290 }
291 },
292 function(Inventory $unused, array $oldItems) use ($syncHeldItem) : void{
293 if(array_key_exists($this->inventory->getHeldItemIndex(), $oldItems)){
294 $syncHeldItem();
295 }
296 }
297 ));
298 $this->offHandInventory = new PlayerOffHandInventory($this);
299 $this->enderInventory = new PlayerEnderInventory($this);
300 $this->initHumanData($nbt);
301
302 $inventoryTag = $nbt->getListTag(self::TAG_INVENTORY, CompoundTag::class);
303 if($inventoryTag !== null){
304 $inventoryItems = [];
305 $armorInventoryItems = [];
306
307 foreach($inventoryTag as $i => $item){
308 $slot = $item->getByte(SavedItemStackData::TAG_SLOT);
309 if($slot >= 0 && $slot < 9){ //Hotbar
310 //Old hotbar saving stuff, ignore it
311 }elseif($slot >= 100 && $slot < 104){ //Armor
312 $armorInventoryItems[$slot - 100] = Item::nbtDeserialize($item);
313 }elseif($slot >= 9 && $slot < $this->inventory->getSize() + 9){
314 $inventoryItems[$slot - 9] = Item::nbtDeserialize($item);
315 }
316 }
317
318 self::populateInventoryFromListTag($this->inventory, $inventoryItems);
319 self::populateInventoryFromListTag($this->armorInventory, $armorInventoryItems);
320 }
321 $offHand = $nbt->getCompoundTag(self::TAG_OFF_HAND_ITEM);
322 if($offHand !== null){
323 $this->offHandInventory->setItem(0, Item::nbtDeserialize($offHand));
324 }
325 $this->offHandInventory->getListeners()->add(CallbackInventoryListener::onAnyChange(fn() => NetworkBroadcastUtils::broadcastEntityEvent(
326 $this->getViewers(),
327 fn(EntityEventBroadcaster $broadcaster, array $recipients) => $broadcaster->onMobOffHandItemChange($recipients, $this)
328 )));
329
330 $enderChestInventoryTag = $nbt->getListTag(self::TAG_ENDER_CHEST_INVENTORY, CompoundTag::class);
331 if($enderChestInventoryTag !== null){
332 $enderChestInventoryItems = [];
333
334 foreach($enderChestInventoryTag as $i => $item){
335 $enderChestInventoryItems[$item->getByte(SavedItemStackData::TAG_SLOT)] = Item::nbtDeserialize($item);
336 }
337 self::populateInventoryFromListTag($this->enderInventory, $enderChestInventoryItems);
338 }
339
340 $this->inventory->setHeldItemIndex($nbt->getInt(self::TAG_SELECTED_INVENTORY_SLOT, 0));
341 $this->inventory->getHeldItemIndexChangeListeners()->add(fn() => NetworkBroadcastUtils::broadcastEntityEvent(
342 $this->getViewers(),
343 fn(EntityEventBroadcaster $broadcaster, array $recipients) => $broadcaster->onMobMainHandItemChange($recipients, $this)
344 ));
345
346 $this->hungerManager->setFood((float) $nbt->getInt(self::TAG_FOOD_LEVEL, (int) $this->hungerManager->getFood()));
347 $this->hungerManager->setExhaustion($nbt->getFloat(self::TAG_FOOD_EXHAUSTION_LEVEL, $this->hungerManager->getExhaustion()));
348 $this->hungerManager->setSaturation($nbt->getFloat(self::TAG_FOOD_SATURATION_LEVEL, $this->hungerManager->getSaturation()));
349 $this->hungerManager->setFoodTickTimer($nbt->getInt(self::TAG_FOOD_TICK_TIMER, $this->hungerManager->getFoodTickTimer()));
350
351 $this->xpManager->setXpAndProgressNoEvent(
352 $nbt->getInt(self::TAG_XP_LEVEL, 0),
353 $nbt->getFloat(self::TAG_XP_PROGRESS, 0.0));
354 $this->xpManager->setLifetimeTotalXp($nbt->getInt(self::TAG_LIFETIME_XP_TOTAL, 0));
355
356 if(($xpSeedTag = $nbt->getTag(self::TAG_XP_SEED)) instanceof IntTag){
357 $this->xpSeed = $xpSeedTag->getValue();
358 }else{
359 $this->xpSeed = EnchantingHelper::generateSeed();
360 }
361 }
362
363 protected function entityBaseTick(int $tickDiff = 1) : bool{
364 $hasUpdate = parent::entityBaseTick($tickDiff);
365
366 $this->hungerManager->tick($tickDiff);
367 $this->xpManager->tick($tickDiff);
368
369 return $hasUpdate;
370 }
371
372 public function getName() : string{
373 return $this->getNameTag();
374 }
375
376 public function applyDamageModifiers(EntityDamageEvent $source) : void{
377 parent::applyDamageModifiers($source);
378
379 $type = $source->getCause();
380 if($type !== EntityDamageEvent::CAUSE_SUICIDE && $type !== EntityDamageEvent::CAUSE_VOID
381 && ($this->inventory->getItemInHand() instanceof Totem || $this->offHandInventory->getItem(0) instanceof Totem)){
382
383 $compensation = $this->getHealth() - $source->getFinalDamage() - 1;
384 if($compensation <= -1){
385 $source->setModifier($compensation, EntityDamageEvent::MODIFIER_TOTEM);
386 }
387 }
388 }
389
390 protected function applyPostDamageEffects(EntityDamageEvent $source) : void{
391 parent::applyPostDamageEffects($source);
392 $totemModifier = $source->getModifier(EntityDamageEvent::MODIFIER_TOTEM);
393 if($totemModifier < 0){ //Totem prevented death
394 $this->effectManager->clear();
395
396 $this->effectManager->add(new EffectInstance(VanillaEffects::REGENERATION(), 40 * 20, 1));
397 $this->effectManager->add(new EffectInstance(VanillaEffects::FIRE_RESISTANCE(), 40 * 20, 1));
398 $this->effectManager->add(new EffectInstance(VanillaEffects::ABSORPTION(), 5 * 20, 1));
399
400 $this->broadcastAnimation(new TotemUseAnimation($this));
401 $this->broadcastSound(new TotemUseSound());
402
403 $hand = $this->inventory->getItemInHand();
404 if($hand instanceof Totem){
405 $hand->pop(); //Plugins could alter max stack size
406 $this->inventory->setItemInHand($hand);
407 }elseif(($offHand = $this->offHandInventory->getItem(0)) instanceof Totem){
408 $offHand->pop();
409 $this->offHandInventory->setItem(0, $offHand);
410 }
411 }
412 }
413
414 public function getDrops() : array{
415 return array_filter(array_merge(
416 array_values($this->inventory->getContents()),
417 array_values($this->armorInventory->getContents()),
418 array_values($this->offHandInventory->getContents()),
419 ), function(Item $item) : bool{ return !$item->hasEnchantment(VanillaEnchantments::VANISHING()) && !$item->keepOnDeath(); });
420 }
421
422 public function saveNBT() : CompoundTag{
423 $nbt = parent::saveNBT();
424
425 $nbt->setInt(self::TAG_FOOD_LEVEL, (int) $this->hungerManager->getFood());
426 $nbt->setFloat(self::TAG_FOOD_EXHAUSTION_LEVEL, $this->hungerManager->getExhaustion());
427 $nbt->setFloat(self::TAG_FOOD_SATURATION_LEVEL, $this->hungerManager->getSaturation());
428 $nbt->setInt(self::TAG_FOOD_TICK_TIMER, $this->hungerManager->getFoodTickTimer());
429
430 $nbt->setInt(self::TAG_XP_LEVEL, $this->xpManager->getXpLevel());
431 $nbt->setFloat(self::TAG_XP_PROGRESS, $this->xpManager->getXpProgress());
432 $nbt->setInt(self::TAG_LIFETIME_XP_TOTAL, $this->xpManager->getLifetimeTotalXp());
433 $nbt->setInt(self::TAG_XP_SEED, $this->xpSeed);
434
435 $inventoryTag = new ListTag([], NBT::TAG_Compound);
436 $nbt->setTag(self::TAG_INVENTORY, $inventoryTag);
437
438 //Normal inventory
439 $slotCount = $this->inventory->getSize() + $this->inventory->getHotbarSize();
440 for($slot = $this->inventory->getHotbarSize(); $slot < $slotCount; ++$slot){
441 $item = $this->inventory->getItem($slot - 9);
442 if(!$item->isNull()){
443 $inventoryTag->push($item->nbtSerialize($slot));
444 }
445 }
446
447 //Armor
448 for($slot = 100; $slot < 104; ++$slot){
449 $item = $this->armorInventory->getItem($slot - 100);
450 if(!$item->isNull()){
451 $inventoryTag->push($item->nbtSerialize($slot));
452 }
453 }
454
455 $nbt->setInt(self::TAG_SELECTED_INVENTORY_SLOT, $this->inventory->getHeldItemIndex());
456
457 $offHandItem = $this->offHandInventory->getItem(0);
458 if(!$offHandItem->isNull()){
459 $nbt->setTag(self::TAG_OFF_HAND_ITEM, $offHandItem->nbtSerialize());
460 }
461
463 $items = [];
464
465 $slotCount = $this->enderInventory->getSize();
466 for($slot = 0; $slot < $slotCount; ++$slot){
467 $item = $this->enderInventory->getItem($slot);
468 if(!$item->isNull()){
469 $items[] = $item->nbtSerialize($slot);
470 }
471 }
472
473 $nbt->setTag(self::TAG_ENDER_CHEST_INVENTORY, new ListTag($items, NBT::TAG_Compound));
474
475 $nbt->setTag(self::TAG_SKIN, CompoundTag::create()
476 ->setString(self::TAG_SKIN_NAME, $this->skin->getSkinId())
477 ->setByteArray(self::TAG_SKIN_DATA, $this->skin->getSkinData())
478 ->setByteArray(self::TAG_SKIN_CAPE_DATA, $this->skin->getCapeData())
479 ->setString(self::TAG_SKIN_GEOMETRY_NAME, $this->skin->getGeometryName())
480 ->setByteArray(self::TAG_SKIN_GEOMETRY_DATA, $this->skin->getGeometryData())
481 );
482
483 return $nbt;
484 }
485
486 public function spawnTo(Player $player) : void{
487 if($player !== $this){
488 parent::spawnTo($player);
489 }
490 }
491
492 protected function sendSpawnPacket(Player $player) : void{
493 $networkSession = $player->getNetworkSession();
494 $typeConverter = $networkSession->getTypeConverter();
495 if(!($this instanceof Player)){
496 $networkSession->sendDataPacket(PlayerListPacket::add([PlayerListEntry::createAdditionEntry($this->uuid, $this->id, $this->getName(), $typeConverter->getSkinAdapter()->toSkinData($this->skin))]));
497 }
498
499 $networkSession->sendDataPacket(AddPlayerPacket::create(
500 $this->getUniqueId(),
501 $this->getName(),
502 $this->getId(),
503 "",
504 $this->location->asVector3(),
505 $this->getMotion(),
506 $this->location->pitch,
507 $this->location->yaw,
508 $this->location->yaw, //TODO: head yaw
509 ItemStackWrapper::legacy($typeConverter->coreItemStackToNet($this->getInventory()->getItemInHand())),
510 GameMode::SURVIVAL,
511 $this->getAllNetworkData(),
512 new PropertySyncData([], []),
513 UpdateAbilitiesPacket::create(new AbilitiesData(CommandPermissions::NORMAL, PlayerPermissions::VISITOR, $this->getId() /* TODO: this should be unique ID */, [
514 new AbilitiesLayer(
515 AbilitiesLayer::LAYER_BASE,
516 array_fill(0, AbilitiesLayer::NUMBER_OF_ABILITIES, false),
517 0.0,
518 0.0,
519 0.0
520 )
521 ])),
522 [], //TODO: entity links
523 "", //device ID (we intentionally don't send this - secvuln)
524 DeviceOS::UNKNOWN //we intentionally don't send this (secvuln)
525 ));
526
527 //TODO: Hack for MCPE 1.2.13: DATA_NAMETAG is useless in AddPlayerPacket, so it has to be sent separately
528 $this->sendData([$player], [EntityMetadataProperties::NAMETAG => new StringMetadataProperty($this->getNameTag())]);
529
530 $entityEventBroadcaster = $networkSession->getEntityEventBroadcaster();
531 $entityEventBroadcaster->onMobArmorChange([$networkSession], $this);
532 $entityEventBroadcaster->onMobOffHandItemChange([$networkSession], $this);
533
534 if(!($this instanceof Player)){
535 $networkSession->sendDataPacket(PlayerListPacket::remove([PlayerListEntry::createRemovalEntry($this->uuid)]));
536 }
537 }
538
539 public function getOffsetPosition(Vector3 $vector3) : Vector3{
540 return $vector3->add(0, 1.621, 0); //TODO: +0.001 hack for MCPE falling underground
541 }
542
543 protected function onDispose() : void{
544 $this->inventory->removeAllViewers();
545 $this->inventory->getHeldItemIndexChangeListeners()->clear();
546 $this->offHandInventory->removeAllViewers();
547 $this->enderInventory->removeAllViewers();
548 parent::onDispose();
549 }
550
551 protected function destroyCycles() : void{
552 unset(
553 $this->inventory,
554 $this->offHandInventory,
555 $this->enderInventory,
556 $this->hungerManager,
557 $this->xpManager
558 );
559 parent::destroyCycles();
560 }
561}
applyPostDamageEffects(EntityDamageEvent $source)
Definition Human.php:390
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:492
initHumanData(CompoundTag $nbt)
Definition Human.php:257
setSkin(Skin $skin)
Definition Human.php:157
applyDamageModifiers(EntityDamageEvent $source)
Definition Human.php:376
consumeObject(Consumable $consumable)
Definition Human.php:201
setInt(string $name, int $value)
setTag(string $name, Tag $tag)
getListTag(string $name, string $tagClass=Tag::class)
setFloat(string $name, float $value)
onMobMainHandItemChange(array $recipients, Human $mob)