PocketMine-MP 5.28.3 git-d5a1007c80fcee27feb2251cf5dcf1ad5a59a85c
Loading...
Searching...
No Matches
Living.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
71use function abs;
72use function array_shift;
73use function atan2;
74use function ceil;
75use function count;
76use function floor;
77use function ksort;
78use function max;
79use function min;
80use function mt_getrandmax;
81use function mt_rand;
82use function round;
83use function sqrt;
84use const M_PI;
85use const SORT_NUMERIC;
86
87abstract class Living extends Entity{
88 protected const DEFAULT_BREATH_TICKS = 300;
89
94 public const DEFAULT_KNOCKBACK_FORCE = 0.4;
100
101 private const TAG_LEGACY_HEALTH = "HealF"; //TAG_Float
102 private const TAG_HEALTH = "Health"; //TAG_Float
103 private const TAG_BREATH_TICKS = "Air"; //TAG_Short
104 private const TAG_ACTIVE_EFFECTS = "ActiveEffects"; //TAG_List<TAG_Compound>
105 private const TAG_EFFECT_ID = "Id"; //TAG_Byte
106 private const TAG_EFFECT_DURATION = "Duration"; //TAG_Int
107 private const TAG_EFFECT_AMPLIFIER = "Amplifier"; //TAG_Byte
108 private const TAG_EFFECT_SHOW_PARTICLES = "ShowParticles"; //TAG_Byte
109 private const TAG_EFFECT_AMBIENT = "Ambient"; //TAG_Byte
110
111 protected int $attackTime = 0;
112
113 public int $deadTicks = 0;
114 protected int $maxDeadTicks = 25;
115
116 protected float $jumpVelocity = 0.42;
117
118 protected EffectManager $effectManager;
119
120 protected ArmorInventory $armorInventory;
121
122 protected bool $breathing = true;
123 protected int $breathTicks = self::DEFAULT_BREATH_TICKS;
124 protected int $maxBreathTicks = self::DEFAULT_BREATH_TICKS;
125
126 protected Attribute $healthAttr;
127 protected Attribute $absorptionAttr;
128 protected Attribute $knockbackResistanceAttr;
129 protected Attribute $moveSpeedAttr;
130
131 protected bool $sprinting = false;
132 protected bool $sneaking = false;
133 protected bool $gliding = false;
134 protected bool $swimming = false;
135
136 private ?int $frostWalkerLevel = null;
137
138 protected function getInitialDragMultiplier() : float{ return 0.02; }
139
140 protected function getInitialGravity() : float{ return 0.08; }
141
142 abstract public function getName() : string;
143
144 public function canBeRenamed() : bool{
145 return true;
146 }
147
148 protected function initEntity(CompoundTag $nbt) : void{
149 parent::initEntity($nbt);
150
151 $this->effectManager = new EffectManager($this);
152 $this->effectManager->getEffectAddHooks()->add(function() : void{ $this->networkPropertiesDirty = true; });
153 $this->effectManager->getEffectRemoveHooks()->add(function() : void{ $this->networkPropertiesDirty = true; });
154
155 $this->armorInventory = new ArmorInventory($this);
156 //TODO: load/save armor inventory contents
157 $this->armorInventory->getListeners()->add(CallbackInventoryListener::onAnyChange(fn() => NetworkBroadcastUtils::broadcastEntityEvent(
158 $this->getViewers(),
159 fn(EntityEventBroadcaster $broadcaster, array $recipients) => $broadcaster->onMobArmorChange($recipients, $this)
160 )));
161 $this->armorInventory->getListeners()->add(new CallbackInventoryListener(
162 onSlotChange: function(Inventory $inventory, int $slot) : void{
163 if($slot === ArmorInventory::SLOT_FEET){
164 $this->frostWalkerLevel = null;
165 }
166 },
167 onContentChange: function() : void{ $this->frostWalkerLevel = null; }
168 ));
169
170 $health = $this->getMaxHealth();
171
172 if(($healFTag = $nbt->getTag(self::TAG_LEGACY_HEALTH)) instanceof FloatTag){
173 $health = $healFTag->getValue();
174 }elseif(($healthTag = $nbt->getTag(self::TAG_HEALTH)) instanceof ShortTag){
175 $health = $healthTag->getValue(); //Older versions of PocketMine-MP incorrectly saved this as a short instead of a float
176 }elseif($healthTag instanceof FloatTag){
177 $health = $healthTag->getValue();
178 }
179
180 $this->setHealth($health);
181
182 $this->setAirSupplyTicks($nbt->getShort(self::TAG_BREATH_TICKS, self::DEFAULT_BREATH_TICKS));
183
185 $activeEffectsTag = $nbt->getListTag(self::TAG_ACTIVE_EFFECTS);
186 if($activeEffectsTag !== null){
187 foreach($activeEffectsTag as $e){
188 $effect = EffectIdMap::getInstance()->fromId($e->getByte(self::TAG_EFFECT_ID));
189 if($effect === null){
190 continue;
191 }
192
193 $this->effectManager->add(new EffectInstance(
194 $effect,
195 $e->getInt(self::TAG_EFFECT_DURATION),
196 Binary::unsignByte($e->getByte(self::TAG_EFFECT_AMPLIFIER)),
197 $e->getByte(self::TAG_EFFECT_SHOW_PARTICLES, 1) !== 0,
198 $e->getByte(self::TAG_EFFECT_AMBIENT, 0) !== 0
199 ));
200 }
201 }
202 }
203
204 protected function addAttributes() : void{
205 $this->attributeMap->add($this->healthAttr = AttributeFactory::getInstance()->mustGet(Attribute::HEALTH));
206 $this->attributeMap->add(AttributeFactory::getInstance()->mustGet(Attribute::FOLLOW_RANGE));
207 $this->attributeMap->add($this->knockbackResistanceAttr = AttributeFactory::getInstance()->mustGet(Attribute::KNOCKBACK_RESISTANCE));
208 $this->attributeMap->add($this->moveSpeedAttr = AttributeFactory::getInstance()->mustGet(Attribute::MOVEMENT_SPEED));
209 $this->attributeMap->add(AttributeFactory::getInstance()->mustGet(Attribute::ATTACK_DAMAGE));
210 $this->attributeMap->add($this->absorptionAttr = AttributeFactory::getInstance()->mustGet(Attribute::ABSORPTION));
211 }
212
216 public function getDisplayName() : string{
217 return $this->nameTag !== "" ? $this->nameTag : $this->getName();
218 }
219
220 public function setHealth(float $amount) : void{
221 $wasAlive = $this->isAlive();
222 parent::setHealth($amount);
223 $this->healthAttr->setValue(ceil($this->getHealth()), true);
224 if($this->isAlive() && !$wasAlive){
225 $this->broadcastAnimation(new RespawnAnimation($this));
226 }
227 }
228
229 public function getMaxHealth() : int{
230 return (int) $this->healthAttr->getMaxValue();
231 }
232
233 public function setMaxHealth(int $amount) : void{
234 $this->healthAttr->setMaxValue($amount)->setDefaultValue($amount);
235 }
236
237 public function getAbsorption() : float{
238 return $this->absorptionAttr->getValue();
239 }
240
241 public function setAbsorption(float $absorption) : void{
242 $this->absorptionAttr->setValue($absorption);
243 }
244
245 public function isSneaking() : bool{
246 return $this->sneaking;
247 }
248
249 public function setSneaking(bool $value = true) : void{
250 $this->sneaking = $value;
251 $this->networkPropertiesDirty = true;
252 $this->recalculateSize();
253 }
254
255 public function isSprinting() : bool{
256 return $this->sprinting;
257 }
258
259 public function setSprinting(bool $value = true) : void{
260 if($value !== $this->isSprinting()){
261 $this->sprinting = $value;
262 $this->networkPropertiesDirty = true;
263 $moveSpeed = $this->getMovementSpeed();
264 $this->setMovementSpeed($value ? ($moveSpeed * 1.3) : ($moveSpeed / 1.3));
265 $this->moveSpeedAttr->markSynchronized(false); //TODO: reevaluate this hack
266 }
267 }
268
269 public function isGliding() : bool{
270 return $this->gliding;
271 }
272
273 public function setGliding(bool $value = true) : void{
274 $this->gliding = $value;
275 $this->networkPropertiesDirty = true;
276 $this->recalculateSize();
277 }
278
279 public function isSwimming() : bool{
280 return $this->swimming;
281 }
282
283 public function setSwimming(bool $value = true) : void{
284 $this->swimming = $value;
285 $this->networkPropertiesDirty = true;
286 $this->recalculateSize();
287 }
288
289 private function recalculateSize() : void{
290 $size = $this->getInitialSizeInfo();
291 if($this->isSwimming() || $this->isGliding()){
292 $width = $size->getWidth();
293 $this->setSize((new EntitySizeInfo($width, $width, $width * 0.9))->scale($this->getScale()));
294 }elseif($this->isSneaking()){
295 $this->setSize((new EntitySizeInfo(3 / 4 * $size->getHeight(), $size->getWidth(), 3 / 4 * $size->getEyeHeight()))->scale($this->getScale()));
296 }else{
297 $this->setSize($size->scale($this->getScale()));
298 }
299 }
300
301 public function getMovementSpeed() : float{
302 return $this->moveSpeedAttr->getValue();
303 }
304
305 public function setMovementSpeed(float $v, bool $fit = false) : void{
306 $this->moveSpeedAttr->setValue($v, $fit);
307 }
308
309 public function saveNBT() : CompoundTag{
310 $nbt = parent::saveNBT();
311 $nbt->setFloat(self::TAG_HEALTH, $this->getHealth());
312
313 $nbt->setShort(self::TAG_BREATH_TICKS, $this->getAirSupplyTicks());
314
315 if(count($this->effectManager->all()) > 0){
316 $effects = [];
317 foreach($this->effectManager->all() as $effect){
318 $effects[] = CompoundTag::create()
319 ->setByte(self::TAG_EFFECT_ID, EffectIdMap::getInstance()->toId($effect->getType()))
320 ->setByte(self::TAG_EFFECT_AMPLIFIER, Binary::signByte($effect->getAmplifier()))
321 ->setInt(self::TAG_EFFECT_DURATION, $effect->getDuration())
322 ->setByte(self::TAG_EFFECT_AMBIENT, $effect->isAmbient() ? 1 : 0)
323 ->setByte(self::TAG_EFFECT_SHOW_PARTICLES, $effect->isVisible() ? 1 : 0);
324 }
325
326 $nbt->setTag(self::TAG_ACTIVE_EFFECTS, new ListTag($effects));
327 }
328
329 return $nbt;
330 }
331
332 public function getEffects() : EffectManager{
333 return $this->effectManager;
334 }
335
340 public function consumeObject(Consumable $consumable) : bool{
341 $this->applyConsumptionResults($consumable);
342 return true;
343 }
344
349 protected function applyConsumptionResults(Consumable $consumable) : void{
350 foreach($consumable->getAdditionalEffects() as $effect){
351 $this->effectManager->add($effect);
352 }
353 if($consumable instanceof FoodSource){
354 $this->broadcastSound(new BurpSound());
355 }
356
357 $consumable->onConsume($this);
358 }
359
363 public function getJumpVelocity() : float{
364 return $this->jumpVelocity + ((($jumpBoost = $this->effectManager->get(VanillaEffects::JUMP_BOOST())) !== null ? $jumpBoost->getEffectLevel() : 0) / 10);
365 }
366
370 public function jump() : void{
371 if($this->onGround){
372 $this->motion = $this->motion->withComponents(null, $this->getJumpVelocity(), null); //Y motion should already be 0 if we're jumping from the ground.
373 }
374 }
375
376 protected function calculateFallDamage(float $fallDistance) : float{
377 return ceil($fallDistance - 3 - (($jumpBoost = $this->effectManager->get(VanillaEffects::JUMP_BOOST())) !== null ? $jumpBoost->getEffectLevel() : 0));
378 }
379
380 protected function onHitGround() : ?float{
381 $fallBlockPos = $this->location->floor();
382 $fallBlock = $this->getWorld()->getBlock($fallBlockPos);
383 if(count($fallBlock->getCollisionBoxes()) === 0){
384 $fallBlockPos = $fallBlockPos->down();
385 $fallBlock = $this->getWorld()->getBlock($fallBlockPos);
386 }
387 $newVerticalVelocity = $fallBlock->onEntityLand($this);
388
389 $damage = $this->calculateFallDamage($this->fallDistance);
390 if($damage > 0){
391 $ev = new EntityDamageEvent($this, EntityDamageEvent::CAUSE_FALL, $damage);
392 $this->attack($ev);
393
394 $this->broadcastSound($damage > 4 ?
395 new EntityLongFallSound($this) :
396 new EntityShortFallSound($this)
397 );
398 }elseif($fallBlock->getTypeId() !== BlockTypeIds::AIR){
399 $this->broadcastSound(new EntityLandSound($this, $fallBlock));
400 }
401 return $newVerticalVelocity;
402 }
403
409 public function getArmorPoints() : int{
410 $total = 0;
411 foreach($this->armorInventory->getContents() as $item){
412 $total += $item->getDefensePoints();
413 }
414
415 return $total;
416 }
417
421 public function getHighestArmorEnchantmentLevel(Enchantment $enchantment) : int{
422 $result = 0;
423 foreach($this->armorInventory->getContents() as $item){
424 $result = max($result, $item->getEnchantmentLevel($enchantment));
425 }
426
427 return $result;
428 }
429
430 public function getArmorInventory() : ArmorInventory{
431 return $this->armorInventory;
432 }
433
434 public function setOnFire(int $seconds) : void{
435 parent::setOnFire($seconds - (int) min($seconds, $seconds * $this->getHighestArmorEnchantmentLevel(VanillaEnchantments::FIRE_PROTECTION()) * 0.15));
436 }
437
442 public function applyDamageModifiers(EntityDamageEvent $source) : void{
443 if($this->lastDamageCause !== null && $this->attackTime > 0){
444 if($this->lastDamageCause->getBaseDamage() >= $source->getBaseDamage()){
445 $source->cancel();
446 }
447 $source->setModifier(-$this->lastDamageCause->getBaseDamage(), EntityDamageEvent::MODIFIER_PREVIOUS_DAMAGE_COOLDOWN);
448 }
449 if($source->canBeReducedByArmor()){
450 //MCPE uses the same system as PC did pre-1.9
451 $source->setModifier(-$source->getFinalDamage() * $this->getArmorPoints() * 0.04, EntityDamageEvent::MODIFIER_ARMOR);
452 }
453
454 $cause = $source->getCause();
455 if(($resistance = $this->effectManager->get(VanillaEffects::RESISTANCE())) !== null && $cause !== EntityDamageEvent::CAUSE_VOID && $cause !== EntityDamageEvent::CAUSE_SUICIDE){
456 $source->setModifier(-$source->getFinalDamage() * min(1, 0.2 * $resistance->getEffectLevel()), EntityDamageEvent::MODIFIER_RESISTANCE);
457 }
458
459 $totalEpf = 0;
460 foreach($this->armorInventory->getContents() as $item){
461 if($item instanceof Armor){
462 $totalEpf += $item->getEnchantmentProtectionFactor($source);
463 }
464 }
465 $source->setModifier(-$source->getFinalDamage() * min(ceil(min($totalEpf, 25) * (mt_rand(50, 100) / 100)), 20) * 0.04, EntityDamageEvent::MODIFIER_ARMOR_ENCHANTMENTS);
466
467 $source->setModifier(-min($this->getAbsorption(), $source->getFinalDamage()), EntityDamageEvent::MODIFIER_ABSORPTION);
468
469 if($cause === EntityDamageEvent::CAUSE_FALLING_BLOCK && $this->armorInventory->getHelmet() instanceof Armor){
470 $source->setModifier(-($source->getFinalDamage() / 4), EntityDamageEvent::MODIFIER_ARMOR_HELMET);
471 }
472 }
473
479 protected function applyPostDamageEffects(EntityDamageEvent $source) : void{
480 $this->setAbsorption(max(0, $this->getAbsorption() + $source->getModifier(EntityDamageEvent::MODIFIER_ABSORPTION)));
481 if($source->canBeReducedByArmor()){
482 $this->damageArmor($source->getBaseDamage());
483 }
484
485 if($source instanceof EntityDamageByEntityEvent && ($attacker = $source->getDamager()) !== null){
486 $damage = 0;
487 foreach($this->armorInventory->getContents() as $k => $item){
488 if($item instanceof Armor && ($thornsLevel = $item->getEnchantmentLevel(VanillaEnchantments::THORNS())) > 0){
489 if(mt_rand(0, 99) < $thornsLevel * 15){
490 $this->damageItem($item, 3);
491 $damage += ($thornsLevel > 10 ? $thornsLevel - 10 : 1 + mt_rand(0, 3));
492 }else{
493 $this->damageItem($item, 1); //thorns causes an extra +1 durability loss even if it didn't activate
494 }
495
496 $this->armorInventory->setItem($k, $item);
497 }
498 }
499
500 if($damage > 0){
501 $attacker->attack(new EntityDamageByEntityEvent($this, $attacker, EntityDamageEvent::CAUSE_MAGIC, $damage));
502 }
503
504 if($source->getModifier(EntityDamageEvent::MODIFIER_ARMOR_HELMET) < 0){
505 $helmet = $this->armorInventory->getHelmet();
506 if($helmet instanceof Armor){
507 $finalDamage = $source->getFinalDamage();
508 $this->damageItem($helmet, (int) round($finalDamage * 4 + Utils::getRandomFloat() * $finalDamage * 2));
509 $this->armorInventory->setHelmet($helmet);
510 }
511 }
512 }
513 }
514
519 public function damageArmor(float $damage) : void{
520 $durabilityRemoved = (int) max(floor($damage / 4), 1);
521
522 $armor = $this->armorInventory->getContents();
523 foreach($armor as $slotId => $item){
524 if($item instanceof Armor){
525 $oldItem = clone $item;
526 $this->damageItem($item, $durabilityRemoved);
527 if(!$item->equalsExact($oldItem)){
528 $this->armorInventory->setItem($slotId, $item);
529 }
530 }
531 }
532 }
533
534 private function damageItem(Durable $item, int $durabilityRemoved) : void{
535 $item->applyDamage($durabilityRemoved);
536 if($item->isBroken()){
537 $this->broadcastSound(new ItemBreakSound());
538 }
539 }
540
541 public function attack(EntityDamageEvent $source) : void{
542 if($this->noDamageTicks > 0 && $source->getCause() !== EntityDamageEvent::CAUSE_SUICIDE){
543 $source->cancel();
544 }
545
546 if($this->effectManager->has(VanillaEffects::FIRE_RESISTANCE()) && (
547 $source->getCause() === EntityDamageEvent::CAUSE_FIRE
548 || $source->getCause() === EntityDamageEvent::CAUSE_FIRE_TICK
549 || $source->getCause() === EntityDamageEvent::CAUSE_LAVA
550 )
551 ){
552 $source->cancel();
553 }
554
555 if($source->getCause() !== EntityDamageEvent::CAUSE_SUICIDE){
556 $this->applyDamageModifiers($source);
557 }
558
559 if($source instanceof EntityDamageByEntityEvent && (
560 $source->getCause() === EntityDamageEvent::CAUSE_BLOCK_EXPLOSION ||
561 $source->getCause() === EntityDamageEvent::CAUSE_ENTITY_EXPLOSION)
562 ){
563 //TODO: knockback should not just apply for entity damage sources
564 //this doesn't matter for TNT right now because the PrimedTNT entity is considered the source, not the block.
565 $base = $source->getKnockBack();
566 $source->setKnockBack($base - min($base, $base * $this->getHighestArmorEnchantmentLevel(VanillaEnchantments::BLAST_PROTECTION()) * 0.15));
567 }
568
569 parent::attack($source);
570
571 if($source->isCancelled()){
572 return;
573 }
574
575 if($this->attackTime <= 0){
576 //this logic only applies if the entity was cold attacked
577
578 $this->attackTime = $source->getAttackCooldown();
579
580 if($source instanceof EntityDamageByChildEntityEvent){
581 $e = $source->getChild();
582 if($e !== null){
583 $motion = $e->getMotion();
584 $this->knockBack($motion->x, $motion->z, $source->getKnockBack(), $source->getVerticalKnockBackLimit());
585 }
586 }elseif($source instanceof EntityDamageByEntityEvent){
587 $e = $source->getDamager();
588 if($e !== null){
589 $deltaX = $this->location->x - $e->location->x;
590 $deltaZ = $this->location->z - $e->location->z;
591 $this->knockBack($deltaX, $deltaZ, $source->getKnockBack(), $source->getVerticalKnockBackLimit());
592 }
593 }
594
595 if($this->isAlive()){
596 $this->doHitAnimation();
597 }
598 }
599
600 if($this->isAlive()){
601 $this->applyPostDamageEffects($source);
602 }
603 }
604
605 protected function doHitAnimation() : void{
606 $this->broadcastAnimation(new HurtAnimation($this));
607 }
608
609 public function knockBack(float $x, float $z, float $force = self::DEFAULT_KNOCKBACK_FORCE, ?float $verticalLimit = self::DEFAULT_KNOCKBACK_VERTICAL_LIMIT) : void{
610 $f = sqrt($x * $x + $z * $z);
611 if($f <= 0){
612 return;
613 }
614 if(mt_rand() / mt_getrandmax() > $this->knockbackResistanceAttr->getValue()){
615 $f = 1 / $f;
616
617 $motionX = $this->motion->x / 2;
618 $motionY = $this->motion->y / 2;
619 $motionZ = $this->motion->z / 2;
620 $motionX += $x * $f * $force;
621 $motionY += $force;
622 $motionZ += $z * $f * $force;
623
624 $verticalLimit ??= $force;
625 if($motionY > $verticalLimit){
626 $motionY = $verticalLimit;
627 }
628
629 $this->setMotion(new Vector3($motionX, $motionY, $motionZ));
630 }
631 }
632
633 protected function onDeath() : void{
634 $ev = new EntityDeathEvent($this, $this->getDrops(), $this->getXpDropAmount());
635 $ev->call();
636 foreach($ev->getDrops() as $item){
637 $this->getWorld()->dropItem($this->location, $item);
638 }
639
640 //TODO: check death conditions (must have been damaged by player < 5 seconds from death)
641 $this->getWorld()->dropExperience($this->location, $ev->getXpDropAmount());
642
643 $this->startDeathAnimation();
644 }
645
646 protected function onDeathUpdate(int $tickDiff) : bool{
647 if($this->deadTicks < $this->maxDeadTicks){
648 $this->deadTicks += $tickDiff;
649 if($this->deadTicks >= $this->maxDeadTicks){
650 $this->endDeathAnimation();
651 }
652 }
653
654 return $this->deadTicks >= $this->maxDeadTicks;
655 }
656
657 protected function startDeathAnimation() : void{
658 $this->broadcastAnimation(new DeathAnimation($this));
659 }
660
661 protected function endDeathAnimation() : void{
662 $this->despawnFromAll();
663 }
664
665 protected function entityBaseTick(int $tickDiff = 1) : bool{
666 Timings::$livingEntityBaseTick->startTiming();
667
668 $hasUpdate = parent::entityBaseTick($tickDiff);
669
670 if($this->isAlive()){
671 if($this->effectManager->tick($tickDiff)){
672 $hasUpdate = true;
673 }
674
675 if($this->isInsideOfSolid()){
676 $hasUpdate = true;
677 $ev = new EntityDamageEvent($this, EntityDamageEvent::CAUSE_SUFFOCATION, 1);
678 $this->attack($ev);
679 }
680
681 if($this->doAirSupplyTick($tickDiff)){
682 $hasUpdate = true;
683 }
684
685 foreach($this->armorInventory->getContents() as $index => $item){
686 $oldItem = clone $item;
687 if($item->onTickWorn($this)){
688 $hasUpdate = true;
689 if(!$item->equalsExact($oldItem)){
690 $this->armorInventory->setItem($index, $item);
691 }
692 }
693 }
694 }
695
696 if($this->attackTime > 0){
697 $this->attackTime -= $tickDiff;
698 }
699
700 Timings::$livingEntityBaseTick->stopTiming();
701
702 return $hasUpdate;
703 }
704
705 protected function move(float $dx, float $dy, float $dz) : void{
706 $oldX = $this->location->x;
707 $oldZ = $this->location->z;
708
709 parent::move($dx, $dy, $dz);
710
711 $frostWalkerLevel = $this->getFrostWalkerLevel();
712 if($frostWalkerLevel > 0 && (abs($this->location->x - $oldX) > self::MOTION_THRESHOLD || abs($this->location->z - $oldZ) > self::MOTION_THRESHOLD)){
713 $this->applyFrostWalker($frostWalkerLevel);
714 }
715 }
716
717 protected function applyFrostWalker(int $level) : void{
718 $radius = $level + 2;
719 $world = $this->getWorld();
720
721 $baseX = $this->location->getFloorX();
722 $y = $this->location->getFloorY() - 1;
723 $baseZ = $this->location->getFloorZ();
724
725 $liquid = VanillaBlocks::WATER();
726 $targetBlock = VanillaBlocks::FROSTED_ICE();
727 if(EntityFrostWalkerEvent::hasHandlers()){
728 $ev = new EntityFrostWalkerEvent($this, $radius, $liquid, $targetBlock);
729 $ev->call();
730 if($ev->isCancelled()){
731 return;
732 }
733 $radius = $ev->getRadius();
734 $liquid = $ev->getLiquid();
735 $targetBlock = $ev->getTargetBlock();
736 }
737
738 for($x = $baseX - $radius; $x <= $baseX + $radius; $x++){
739 for($z = $baseZ - $radius; $z <= $baseZ + $radius; $z++){
740 $block = $world->getBlockAt($x, $y, $z);
741 if(
742 !$block->isSameState($liquid) ||
743 $world->getBlockAt($x, $y + 1, $z)->getTypeId() !== BlockTypeIds::AIR ||
744 count($world->getNearbyEntities(AxisAlignedBB::one()->offset($x, $y, $z))) !== 0
745 ){
746 continue;
747 }
748 $world->setBlockAt($x, $y, $z, $targetBlock);
749 }
750 }
751 }
752
753 public function getFrostWalkerLevel() : int{
754 return $this->frostWalkerLevel ??= $this->armorInventory->getBoots()->getEnchantmentLevel(VanillaEnchantments::FROST_WALKER());
755 }
756
760 protected function doAirSupplyTick(int $tickDiff) : bool{
761 $ticks = $this->getAirSupplyTicks();
762 $oldTicks = $ticks;
763 if(!$this->canBreathe()){
764 $this->setBreathing(false);
765
766 if(($respirationLevel = $this->armorInventory->getHelmet()->getEnchantmentLevel(VanillaEnchantments::RESPIRATION())) <= 0 ||
767 Utils::getRandomFloat() <= (1 / ($respirationLevel + 1))
768 ){
769 $ticks -= $tickDiff;
770 if($ticks <= -20){
771 $ticks = 0;
772 $this->onAirExpired();
773 }
774 }
775 }elseif(!$this->isBreathing()){
776 if($ticks < ($max = $this->getMaxAirSupplyTicks())){
777 $ticks += $tickDiff * 5;
778 }
779 if($ticks >= $max){
780 $ticks = $max;
781 $this->setBreathing(true);
782 }
783 }
784
785 if($ticks !== $oldTicks){
786 $this->setAirSupplyTicks($ticks);
787 }
788
789 return $ticks !== $oldTicks;
790 }
791
795 public function canBreathe() : bool{
796 return $this->effectManager->has(VanillaEffects::WATER_BREATHING()) || $this->effectManager->has(VanillaEffects::CONDUIT_POWER()) || !$this->isUnderwater();
797 }
798
802 public function isBreathing() : bool{
803 return $this->breathing;
804 }
805
810 public function setBreathing(bool $value = true) : void{
811 $this->breathing = $value;
812 $this->networkPropertiesDirty = true;
813 }
814
819 public function getAirSupplyTicks() : int{
820 return $this->breathTicks;
821 }
822
826 public function setAirSupplyTicks(int $ticks) : void{
827 $this->breathTicks = $ticks;
828 $this->networkPropertiesDirty = true;
829 }
830
834 public function getMaxAirSupplyTicks() : int{
835 return $this->maxBreathTicks;
836 }
837
841 public function setMaxAirSupplyTicks(int $ticks) : void{
842 $this->maxBreathTicks = $ticks;
843 $this->networkPropertiesDirty = true;
844 }
845
850 public function onAirExpired() : void{
851 $ev = new EntityDamageEvent($this, EntityDamageEvent::CAUSE_DROWNING, 2);
852 $this->attack($ev);
853 }
854
858 public function getDrops() : array{
859 return [];
860 }
861
865 public function getXpDropAmount() : int{
866 return 0;
867 }
868
875 public function getLineOfSight(int $maxDistance, int $maxLength = 0, array $transparent = []) : array{
876 if($maxDistance > 120){
877 $maxDistance = 120;
878 }
879
880 if(count($transparent) === 0){
881 $transparent = null;
882 }
883
884 $blocks = [];
885 $nextIndex = 0;
886
887 foreach(VoxelRayTrace::inDirection($this->location->add(0, $this->size->getEyeHeight(), 0), $this->getDirectionVector(), $maxDistance) as $vector3){
888 $block = $this->getWorld()->getBlockAt($vector3->x, $vector3->y, $vector3->z);
889 $blocks[$nextIndex++] = $block;
890
891 if($maxLength !== 0 && count($blocks) > $maxLength){
892 array_shift($blocks);
893 --$nextIndex;
894 }
895
896 $id = $block->getTypeId();
897
898 if($transparent === null){
899 if($id !== BlockTypeIds::AIR){
900 break;
901 }
902 }else{
903 if(!isset($transparent[$id])){
904 break;
905 }
906 }
907 }
908
909 return $blocks;
910 }
911
916 public function getTargetBlock(int $maxDistance, array $transparent = []) : ?Block{
917 $line = $this->getLineOfSight($maxDistance, 1, $transparent);
918 if(count($line) > 0){
919 return array_shift($line);
920 }
921
922 return null;
923 }
924
929 public function lookAt(Vector3 $target) : void{
930 $horizontal = sqrt(($target->x - $this->location->x) ** 2 + ($target->z - $this->location->z) ** 2);
931 $vertical = $target->y - ($this->location->y + $this->getEyeHeight());
932 $pitch = -atan2($vertical, $horizontal) / M_PI * 180; //negative is up, positive is down
933
934 $xDist = $target->x - $this->location->x;
935 $zDist = $target->z - $this->location->z;
936
937 $yaw = atan2($zDist, $xDist) / M_PI * 180 - 90;
938 if($yaw < 0){
939 $yaw += 360.0;
940 }
941
942 $this->setRotation($yaw, $pitch);
943 }
944
945 protected function sendSpawnPacket(Player $player) : void{
946 parent::sendSpawnPacket($player);
947
948 $networkSession = $player->getNetworkSession();
949 $networkSession->getEntityEventBroadcaster()->onMobArmorChange([$networkSession], $this);
950 }
951
952 protected function syncNetworkData(EntityMetadataCollection $properties) : void{
953 parent::syncNetworkData($properties);
954
955 $visibleEffects = [];
956 foreach ($this->effectManager->all() as $effect) {
957 if (!$effect->isVisible() || !$effect->getType()->hasBubbles()) {
958 continue;
959 }
960 $visibleEffects[EffectIdMap::getInstance()->toId($effect->getType())] = $effect->isAmbient();
961 }
962
963 //TODO: HACK! the client may not be able to identify effects if they are not sorted.
964 ksort($visibleEffects, SORT_NUMERIC);
965
966 $effectsData = 0;
967 $packedEffectsCount = 0;
968 foreach ($visibleEffects as $effectId => $isAmbient) {
969 $effectsData = ($effectsData << 7) |
970 (($effectId & 0x3f) << 1) | //Why not use 7 bits instead of only 6? mojang...
971 ($isAmbient ? 1 : 0);
972
973 if (++$packedEffectsCount >= 8) {
974 break;
975 }
976 }
977 $properties->setLong(EntityMetadataProperties::VISIBLE_MOB_EFFECTS, $effectsData);
978
979 $properties->setShort(EntityMetadataProperties::AIR, $this->breathTicks);
980 $properties->setShort(EntityMetadataProperties::MAX_AIR, $this->maxBreathTicks);
981
982 $properties->setGenericFlag(EntityMetadataFlags::BREATHING, $this->breathing);
983 $properties->setGenericFlag(EntityMetadataFlags::SNEAKING, $this->sneaking);
984 $properties->setGenericFlag(EntityMetadataFlags::SPRINTING, $this->sprinting);
985 $properties->setGenericFlag(EntityMetadataFlags::GLIDING, $this->gliding);
986 $properties->setGenericFlag(EntityMetadataFlags::SWIMMING, $this->swimming);
987 }
988
989 protected function onDispose() : void{
990 $this->armorInventory->removeAllViewers();
991 $this->effectManager->getEffectAddHooks()->clear();
992 $this->effectManager->getEffectRemoveHooks()->clear();
993 parent::onDispose();
994 }
995
996 protected function destroyCycles() : void{
997 unset(
998 $this->armorInventory,
999 $this->effectManager
1000 );
1001 parent::destroyCycles();
1002 }
1003}
applyPostDamageEffects(EntityDamageEvent $source)
Definition Living.php:479
sendSpawnPacket(Player $player)
Definition Living.php:945
setMaxAirSupplyTicks(int $ticks)
Definition Living.php:841
setBreathing(bool $value=true)
Definition Living.php:810
lookAt(Vector3 $target)
Definition Living.php:929
onDeathUpdate(int $tickDiff)
Definition Living.php:646
damageArmor(float $damage)
Definition Living.php:519
setHealth(float $amount)
Definition Living.php:220
getLineOfSight(int $maxDistance, int $maxLength=0, array $transparent=[])
Definition Living.php:875
const DEFAULT_KNOCKBACK_VERTICAL_LIMIT
Definition Living.php:99
applyDamageModifiers(EntityDamageEvent $source)
Definition Living.php:442
getTargetBlock(int $maxDistance, array $transparent=[])
Definition Living.php:916
consumeObject(Consumable $consumable)
Definition Living.php:340
applyConsumptionResults(Consumable $consumable)
Definition Living.php:349
setAirSupplyTicks(int $ticks)
Definition Living.php:826
doAirSupplyTick(int $tickDiff)
Definition Living.php:760
getHighestArmorEnchantmentLevel(Enchantment $enchantment)
Definition Living.php:421
setTag(string $name, Tag $tag)
setFloat(string $name, float $value)
setShort(string $name, int $value)
getEnchantmentLevel(Enchantment $enchantment)