PocketMine-MP 5.17.1 git-df4ada81e5d74a14046f27cf44a37dcee69d657e
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
66use function array_shift;
67use function atan2;
68use function ceil;
69use function count;
70use function floor;
71use function lcg_value;
72use function max;
73use function min;
74use function mt_getrandmax;
75use function mt_rand;
76use function round;
77use function sqrt;
78use const M_PI;
79
80abstract class Living extends Entity{
81 protected const DEFAULT_BREATH_TICKS = 300;
82
87 public const DEFAULT_KNOCKBACK_FORCE = 0.4;
93
94 private const TAG_LEGACY_HEALTH = "HealF"; //TAG_Float
95 private const TAG_HEALTH = "Health"; //TAG_Float
96 private const TAG_BREATH_TICKS = "Air"; //TAG_Short
97 private const TAG_ACTIVE_EFFECTS = "ActiveEffects"; //TAG_List<TAG_Compound>
98 private const TAG_EFFECT_ID = "Id"; //TAG_Byte
99 private const TAG_EFFECT_DURATION = "Duration"; //TAG_Int
100 private const TAG_EFFECT_AMPLIFIER = "Amplifier"; //TAG_Byte
101 private const TAG_EFFECT_SHOW_PARTICLES = "ShowParticles"; //TAG_Byte
102 private const TAG_EFFECT_AMBIENT = "Ambient"; //TAG_Byte
103
104 protected int $attackTime = 0;
105
106 public int $deadTicks = 0;
107 protected int $maxDeadTicks = 25;
108
109 protected float $jumpVelocity = 0.42;
110
111 protected EffectManager $effectManager;
112
113 protected ArmorInventory $armorInventory;
114
115 protected bool $breathing = true;
116 protected int $breathTicks = self::DEFAULT_BREATH_TICKS;
117 protected int $maxBreathTicks = self::DEFAULT_BREATH_TICKS;
118
119 protected Attribute $healthAttr;
120 protected Attribute $absorptionAttr;
121 protected Attribute $knockbackResistanceAttr;
122 protected Attribute $moveSpeedAttr;
123
124 protected bool $sprinting = false;
125 protected bool $sneaking = false;
126 protected bool $gliding = false;
127 protected bool $swimming = false;
128
129 protected function getInitialDragMultiplier() : float{ return 0.02; }
130
131 protected function getInitialGravity() : float{ return 0.08; }
132
133 abstract public function getName() : string;
134
135 public function canBeRenamed() : bool{
136 return true;
137 }
138
139 protected function initEntity(CompoundTag $nbt) : void{
140 parent::initEntity($nbt);
141
142 $this->effectManager = new EffectManager($this);
143 $this->effectManager->getEffectAddHooks()->add(function() : void{ $this->networkPropertiesDirty = true; });
144 $this->effectManager->getEffectRemoveHooks()->add(function() : void{ $this->networkPropertiesDirty = true; });
145
146 $this->armorInventory = new ArmorInventory($this);
147 //TODO: load/save armor inventory contents
148 $this->armorInventory->getListeners()->add(CallbackInventoryListener::onAnyChange(fn() => NetworkBroadcastUtils::broadcastEntityEvent(
149 $this->getViewers(),
150 fn(EntityEventBroadcaster $broadcaster, array $recipients) => $broadcaster->onMobArmorChange($recipients, $this)
151 )));
152
153 $health = $this->getMaxHealth();
154
155 if(($healFTag = $nbt->getTag(self::TAG_LEGACY_HEALTH)) instanceof FloatTag){
156 $health = $healFTag->getValue();
157 }elseif(($healthTag = $nbt->getTag(self::TAG_HEALTH)) instanceof ShortTag){
158 $health = $healthTag->getValue(); //Older versions of PocketMine-MP incorrectly saved this as a short instead of a float
159 }elseif($healthTag instanceof FloatTag){
160 $health = $healthTag->getValue();
161 }
162
163 $this->setHealth($health);
164
165 $this->setAirSupplyTicks($nbt->getShort(self::TAG_BREATH_TICKS, self::DEFAULT_BREATH_TICKS));
166
168 $activeEffectsTag = $nbt->getListTag(self::TAG_ACTIVE_EFFECTS);
169 if($activeEffectsTag !== null){
170 foreach($activeEffectsTag as $e){
171 $effect = EffectIdMap::getInstance()->fromId($e->getByte(self::TAG_EFFECT_ID));
172 if($effect === null){
173 continue;
174 }
175
176 $this->effectManager->add(new EffectInstance(
177 $effect,
178 $e->getInt(self::TAG_EFFECT_DURATION),
179 Binary::unsignByte($e->getByte(self::TAG_EFFECT_AMPLIFIER)),
180 $e->getByte(self::TAG_EFFECT_SHOW_PARTICLES, 1) !== 0,
181 $e->getByte(self::TAG_EFFECT_AMBIENT, 0) !== 0
182 ));
183 }
184 }
185 }
186
187 protected function addAttributes() : void{
188 $this->attributeMap->add($this->healthAttr = AttributeFactory::getInstance()->mustGet(Attribute::HEALTH));
189 $this->attributeMap->add(AttributeFactory::getInstance()->mustGet(Attribute::FOLLOW_RANGE));
190 $this->attributeMap->add($this->knockbackResistanceAttr = AttributeFactory::getInstance()->mustGet(Attribute::KNOCKBACK_RESISTANCE));
191 $this->attributeMap->add($this->moveSpeedAttr = AttributeFactory::getInstance()->mustGet(Attribute::MOVEMENT_SPEED));
192 $this->attributeMap->add(AttributeFactory::getInstance()->mustGet(Attribute::ATTACK_DAMAGE));
193 $this->attributeMap->add($this->absorptionAttr = AttributeFactory::getInstance()->mustGet(Attribute::ABSORPTION));
194 }
195
199 public function getDisplayName() : string{
200 return $this->nameTag !== "" ? $this->nameTag : $this->getName();
201 }
202
203 public function setHealth(float $amount) : void{
204 $wasAlive = $this->isAlive();
205 parent::setHealth($amount);
206 $this->healthAttr->setValue(ceil($this->getHealth()), true);
207 if($this->isAlive() && !$wasAlive){
208 $this->broadcastAnimation(new RespawnAnimation($this));
209 }
210 }
211
212 public function getMaxHealth() : int{
213 return (int) $this->healthAttr->getMaxValue();
214 }
215
216 public function setMaxHealth(int $amount) : void{
217 $this->healthAttr->setMaxValue($amount)->setDefaultValue($amount);
218 }
219
220 public function getAbsorption() : float{
221 return $this->absorptionAttr->getValue();
222 }
223
224 public function setAbsorption(float $absorption) : void{
225 $this->absorptionAttr->setValue($absorption);
226 }
227
228 public function isSneaking() : bool{
229 return $this->sneaking;
230 }
231
232 public function setSneaking(bool $value = true) : void{
233 $this->sneaking = $value;
234 $this->networkPropertiesDirty = true;
235 $this->recalculateSize();
236 }
237
238 public function isSprinting() : bool{
239 return $this->sprinting;
240 }
241
242 public function setSprinting(bool $value = true) : void{
243 if($value !== $this->isSprinting()){
244 $this->sprinting = $value;
245 $this->networkPropertiesDirty = true;
246 $moveSpeed = $this->getMovementSpeed();
247 $this->setMovementSpeed($value ? ($moveSpeed * 1.3) : ($moveSpeed / 1.3));
248 $this->moveSpeedAttr->markSynchronized(false); //TODO: reevaluate this hack
249 }
250 }
251
252 public function isGliding() : bool{
253 return $this->gliding;
254 }
255
256 public function setGliding(bool $value = true) : void{
257 $this->gliding = $value;
258 $this->networkPropertiesDirty = true;
259 $this->recalculateSize();
260 }
261
262 public function isSwimming() : bool{
263 return $this->swimming;
264 }
265
266 public function setSwimming(bool $value = true) : void{
267 $this->swimming = $value;
268 $this->networkPropertiesDirty = true;
269 $this->recalculateSize();
270 }
271
272 private function recalculateSize() : void{
273 $size = $this->getInitialSizeInfo();
274 if($this->isSwimming() || $this->isGliding()){
275 $width = $size->getWidth();
276 $this->setSize((new EntitySizeInfo($width, $width, $width * 0.9))->scale($this->getScale()));
277 }elseif($this->isSneaking()){
278 $this->setSize((new EntitySizeInfo(3 / 4 * $size->getHeight(), $size->getWidth(), 3 / 4 * $size->getEyeHeight()))->scale($this->getScale()));
279 }else{
280 $this->setSize($size->scale($this->getScale()));
281 }
282 }
283
284 public function getMovementSpeed() : float{
285 return $this->moveSpeedAttr->getValue();
286 }
287
288 public function setMovementSpeed(float $v, bool $fit = false) : void{
289 $this->moveSpeedAttr->setValue($v, $fit);
290 }
291
292 public function saveNBT() : CompoundTag{
293 $nbt = parent::saveNBT();
294 $nbt->setFloat(self::TAG_HEALTH, $this->getHealth());
295
296 $nbt->setShort(self::TAG_BREATH_TICKS, $this->getAirSupplyTicks());
297
298 if(count($this->effectManager->all()) > 0){
299 $effects = [];
300 foreach($this->effectManager->all() as $effect){
301 $effects[] = CompoundTag::create()
302 ->setByte(self::TAG_EFFECT_ID, EffectIdMap::getInstance()->toId($effect->getType()))
303 ->setByte(self::TAG_EFFECT_AMPLIFIER, Binary::signByte($effect->getAmplifier()))
304 ->setInt(self::TAG_EFFECT_DURATION, $effect->getDuration())
305 ->setByte(self::TAG_EFFECT_AMBIENT, $effect->isAmbient() ? 1 : 0)
306 ->setByte(self::TAG_EFFECT_SHOW_PARTICLES, $effect->isVisible() ? 1 : 0);
307 }
308
309 $nbt->setTag(self::TAG_ACTIVE_EFFECTS, new ListTag($effects));
310 }
311
312 return $nbt;
313 }
314
315 public function getEffects() : EffectManager{
316 return $this->effectManager;
317 }
318
323 public function consumeObject(Consumable $consumable) : bool{
324 $this->applyConsumptionResults($consumable);
325 return true;
326 }
327
332 protected function applyConsumptionResults(Consumable $consumable) : void{
333 foreach($consumable->getAdditionalEffects() as $effect){
334 $this->effectManager->add($effect);
335 }
336 if($consumable instanceof FoodSource){
337 $this->broadcastSound(new BurpSound());
338 }
339
340 $consumable->onConsume($this);
341 }
342
346 public function getJumpVelocity() : float{
347 return $this->jumpVelocity + ((($jumpBoost = $this->effectManager->get(VanillaEffects::JUMP_BOOST())) !== null ? $jumpBoost->getEffectLevel() : 0) / 10);
348 }
349
353 public function jump() : void{
354 if($this->onGround){
355 $this->motion = $this->motion->withComponents(null, $this->getJumpVelocity(), null); //Y motion should already be 0 if we're jumping from the ground.
356 }
357 }
358
359 protected function calculateFallDamage(float $fallDistance) : float{
360 return ceil($fallDistance - 3 - (($jumpBoost = $this->effectManager->get(VanillaEffects::JUMP_BOOST())) !== null ? $jumpBoost->getEffectLevel() : 0));
361 }
362
363 protected function onHitGround() : ?float{
364 $fallBlockPos = $this->location->floor();
365 $fallBlock = $this->getWorld()->getBlock($fallBlockPos);
366 if(count($fallBlock->getCollisionBoxes()) === 0){
367 $fallBlockPos = $fallBlockPos->down();
368 $fallBlock = $this->getWorld()->getBlock($fallBlockPos);
369 }
370 $newVerticalVelocity = $fallBlock->onEntityLand($this);
371
372 $damage = $this->calculateFallDamage($this->fallDistance);
373 if($damage > 0){
374 $ev = new EntityDamageEvent($this, EntityDamageEvent::CAUSE_FALL, $damage);
375 $this->attack($ev);
376
377 $this->broadcastSound($damage > 4 ?
378 new EntityLongFallSound($this) :
379 new EntityShortFallSound($this)
380 );
381 }elseif($fallBlock->getTypeId() !== BlockTypeIds::AIR){
382 $this->broadcastSound(new EntityLandSound($this, $fallBlock));
383 }
384 return $newVerticalVelocity;
385 }
386
392 public function getArmorPoints() : int{
393 $total = 0;
394 foreach($this->armorInventory->getContents() as $item){
395 $total += $item->getDefensePoints();
396 }
397
398 return $total;
399 }
400
404 public function getHighestArmorEnchantmentLevel(Enchantment $enchantment) : int{
405 $result = 0;
406 foreach($this->armorInventory->getContents() as $item){
407 $result = max($result, $item->getEnchantmentLevel($enchantment));
408 }
409
410 return $result;
411 }
412
413 public function getArmorInventory() : ArmorInventory{
414 return $this->armorInventory;
415 }
416
417 public function setOnFire(int $seconds) : void{
418 parent::setOnFire($seconds - (int) min($seconds, $seconds * $this->getHighestArmorEnchantmentLevel(VanillaEnchantments::FIRE_PROTECTION()) * 0.15));
419 }
420
425 public function applyDamageModifiers(EntityDamageEvent $source) : void{
426 if($this->lastDamageCause !== null && $this->attackTime > 0){
427 if($this->lastDamageCause->getBaseDamage() >= $source->getBaseDamage()){
428 $source->cancel();
429 }
430 $source->setModifier(-$this->lastDamageCause->getBaseDamage(), EntityDamageEvent::MODIFIER_PREVIOUS_DAMAGE_COOLDOWN);
431 }
432 if($source->canBeReducedByArmor()){
433 //MCPE uses the same system as PC did pre-1.9
434 $source->setModifier(-$source->getFinalDamage() * $this->getArmorPoints() * 0.04, EntityDamageEvent::MODIFIER_ARMOR);
435 }
436
437 $cause = $source->getCause();
438 if(($resistance = $this->effectManager->get(VanillaEffects::RESISTANCE())) !== null && $cause !== EntityDamageEvent::CAUSE_VOID && $cause !== EntityDamageEvent::CAUSE_SUICIDE){
439 $source->setModifier(-$source->getFinalDamage() * min(1, 0.2 * $resistance->getEffectLevel()), EntityDamageEvent::MODIFIER_RESISTANCE);
440 }
441
442 $totalEpf = 0;
443 foreach($this->armorInventory->getContents() as $item){
444 if($item instanceof Armor){
445 $totalEpf += $item->getEnchantmentProtectionFactor($source);
446 }
447 }
448 $source->setModifier(-$source->getFinalDamage() * min(ceil(min($totalEpf, 25) * (mt_rand(50, 100) / 100)), 20) * 0.04, EntityDamageEvent::MODIFIER_ARMOR_ENCHANTMENTS);
449
450 $source->setModifier(-min($this->getAbsorption(), $source->getFinalDamage()), EntityDamageEvent::MODIFIER_ABSORPTION);
451
452 if($cause === EntityDamageEvent::CAUSE_FALLING_BLOCK && $this->armorInventory->getHelmet() instanceof Armor){
453 $source->setModifier(-($source->getFinalDamage() / 4), EntityDamageEvent::MODIFIER_ARMOR_HELMET);
454 }
455 }
456
462 protected function applyPostDamageEffects(EntityDamageEvent $source) : void{
463 $this->setAbsorption(max(0, $this->getAbsorption() + $source->getModifier(EntityDamageEvent::MODIFIER_ABSORPTION)));
464 if($source->canBeReducedByArmor()){
465 $this->damageArmor($source->getBaseDamage());
466 }
467
468 if($source instanceof EntityDamageByEntityEvent && ($attacker = $source->getDamager()) !== null){
469 $damage = 0;
470 foreach($this->armorInventory->getContents() as $k => $item){
471 if($item instanceof Armor && ($thornsLevel = $item->getEnchantmentLevel(VanillaEnchantments::THORNS())) > 0){
472 if(mt_rand(0, 99) < $thornsLevel * 15){
473 $this->damageItem($item, 3);
474 $damage += ($thornsLevel > 10 ? $thornsLevel - 10 : 1 + mt_rand(0, 3));
475 }else{
476 $this->damageItem($item, 1); //thorns causes an extra +1 durability loss even if it didn't activate
477 }
478
479 $this->armorInventory->setItem($k, $item);
480 }
481 }
482
483 if($damage > 0){
484 $attacker->attack(new EntityDamageByEntityEvent($this, $attacker, EntityDamageEvent::CAUSE_MAGIC, $damage));
485 }
486
487 if($source->getModifier(EntityDamageEvent::MODIFIER_ARMOR_HELMET) < 0){
488 $helmet = $this->armorInventory->getHelmet();
489 if($helmet instanceof Armor){
490 $finalDamage = $source->getFinalDamage();
491 $this->damageItem($helmet, (int) round($finalDamage * 4 + lcg_value() * $finalDamage * 2));
492 $this->armorInventory->setHelmet($helmet);
493 }
494 }
495 }
496 }
497
502 public function damageArmor(float $damage) : void{
503 $durabilityRemoved = (int) max(floor($damage / 4), 1);
504
505 $armor = $this->armorInventory->getContents();
506 foreach($armor as $slotId => $item){
507 if($item instanceof Armor){
508 $oldItem = clone $item;
509 $this->damageItem($item, $durabilityRemoved);
510 if(!$item->equalsExact($oldItem)){
511 $this->armorInventory->setItem($slotId, $item);
512 }
513 }
514 }
515 }
516
517 private function damageItem(Durable $item, int $durabilityRemoved) : void{
518 $item->applyDamage($durabilityRemoved);
519 if($item->isBroken()){
520 $this->broadcastSound(new ItemBreakSound());
521 }
522 }
523
524 public function attack(EntityDamageEvent $source) : void{
525 if($this->noDamageTicks > 0 && $source->getCause() !== EntityDamageEvent::CAUSE_SUICIDE){
526 $source->cancel();
527 }
528
529 if($this->effectManager->has(VanillaEffects::FIRE_RESISTANCE()) && (
530 $source->getCause() === EntityDamageEvent::CAUSE_FIRE
531 || $source->getCause() === EntityDamageEvent::CAUSE_FIRE_TICK
532 || $source->getCause() === EntityDamageEvent::CAUSE_LAVA
533 )
534 ){
535 $source->cancel();
536 }
537
538 if($source->getCause() !== EntityDamageEvent::CAUSE_SUICIDE){
539 $this->applyDamageModifiers($source);
540 }
541
542 if($source instanceof EntityDamageByEntityEvent && (
543 $source->getCause() === EntityDamageEvent::CAUSE_BLOCK_EXPLOSION ||
544 $source->getCause() === EntityDamageEvent::CAUSE_ENTITY_EXPLOSION)
545 ){
546 //TODO: knockback should not just apply for entity damage sources
547 //this doesn't matter for TNT right now because the PrimedTNT entity is considered the source, not the block.
548 $base = $source->getKnockBack();
549 $source->setKnockBack($base - min($base, $base * $this->getHighestArmorEnchantmentLevel(VanillaEnchantments::BLAST_PROTECTION()) * 0.15));
550 }
551
552 parent::attack($source);
553
554 if($source->isCancelled()){
555 return;
556 }
557
558 if($this->attackTime <= 0){
559 //this logic only applies if the entity was cold attacked
560
561 $this->attackTime = $source->getAttackCooldown();
562
563 if($source instanceof EntityDamageByChildEntityEvent){
564 $e = $source->getChild();
565 if($e !== null){
566 $motion = $e->getMotion();
567 $this->knockBack($motion->x, $motion->z, $source->getKnockBack(), $source->getVerticalKnockBackLimit());
568 }
569 }elseif($source instanceof EntityDamageByEntityEvent){
570 $e = $source->getDamager();
571 if($e !== null){
572 $deltaX = $this->location->x - $e->location->x;
573 $deltaZ = $this->location->z - $e->location->z;
574 $this->knockBack($deltaX, $deltaZ, $source->getKnockBack(), $source->getVerticalKnockBackLimit());
575 }
576 }
577
578 if($this->isAlive()){
579 $this->doHitAnimation();
580 }
581 }
582
583 if($this->isAlive()){
584 $this->applyPostDamageEffects($source);
585 }
586 }
587
588 protected function doHitAnimation() : void{
589 $this->broadcastAnimation(new HurtAnimation($this));
590 }
591
592 public function knockBack(float $x, float $z, float $force = self::DEFAULT_KNOCKBACK_FORCE, ?float $verticalLimit = self::DEFAULT_KNOCKBACK_VERTICAL_LIMIT) : void{
593 $f = sqrt($x * $x + $z * $z);
594 if($f <= 0){
595 return;
596 }
597 if(mt_rand() / mt_getrandmax() > $this->knockbackResistanceAttr->getValue()){
598 $f = 1 / $f;
599
600 $motionX = $this->motion->x / 2;
601 $motionY = $this->motion->y / 2;
602 $motionZ = $this->motion->z / 2;
603 $motionX += $x * $f * $force;
604 $motionY += $force;
605 $motionZ += $z * $f * $force;
606
607 $verticalLimit ??= $force;
608 if($motionY > $verticalLimit){
609 $motionY = $verticalLimit;
610 }
611
612 $this->setMotion(new Vector3($motionX, $motionY, $motionZ));
613 }
614 }
615
616 protected function onDeath() : void{
617 $ev = new EntityDeathEvent($this, $this->getDrops(), $this->getXpDropAmount());
618 $ev->call();
619 foreach($ev->getDrops() as $item){
620 $this->getWorld()->dropItem($this->location, $item);
621 }
622
623 //TODO: check death conditions (must have been damaged by player < 5 seconds from death)
624 $this->getWorld()->dropExperience($this->location, $ev->getXpDropAmount());
625
626 $this->startDeathAnimation();
627 }
628
629 protected function onDeathUpdate(int $tickDiff) : bool{
630 if($this->deadTicks < $this->maxDeadTicks){
631 $this->deadTicks += $tickDiff;
632 if($this->deadTicks >= $this->maxDeadTicks){
633 $this->endDeathAnimation();
634 }
635 }
636
637 return $this->deadTicks >= $this->maxDeadTicks;
638 }
639
640 protected function startDeathAnimation() : void{
641 $this->broadcastAnimation(new DeathAnimation($this));
642 }
643
644 protected function endDeathAnimation() : void{
645 $this->despawnFromAll();
646 }
647
648 protected function entityBaseTick(int $tickDiff = 1) : bool{
649 Timings::$livingEntityBaseTick->startTiming();
650
651 $hasUpdate = parent::entityBaseTick($tickDiff);
652
653 if($this->isAlive()){
654 if($this->effectManager->tick($tickDiff)){
655 $hasUpdate = true;
656 }
657
658 if($this->isInsideOfSolid()){
659 $hasUpdate = true;
660 $ev = new EntityDamageEvent($this, EntityDamageEvent::CAUSE_SUFFOCATION, 1);
661 $this->attack($ev);
662 }
663
664 if($this->doAirSupplyTick($tickDiff)){
665 $hasUpdate = true;
666 }
667
668 foreach($this->armorInventory->getContents() as $index => $item){
669 $oldItem = clone $item;
670 if($item->onTickWorn($this)){
671 $hasUpdate = true;
672 if(!$item->equalsExact($oldItem)){
673 $this->armorInventory->setItem($index, $item);
674 }
675 }
676 }
677 }
678
679 if($this->attackTime > 0){
680 $this->attackTime -= $tickDiff;
681 }
682
683 Timings::$livingEntityBaseTick->stopTiming();
684
685 return $hasUpdate;
686 }
687
691 protected function doAirSupplyTick(int $tickDiff) : bool{
692 $ticks = $this->getAirSupplyTicks();
693 $oldTicks = $ticks;
694 if(!$this->canBreathe()){
695 $this->setBreathing(false);
696
697 if(($respirationLevel = $this->armorInventory->getHelmet()->getEnchantmentLevel(VanillaEnchantments::RESPIRATION())) <= 0 ||
698 lcg_value() <= (1 / ($respirationLevel + 1))
699 ){
700 $ticks -= $tickDiff;
701 if($ticks <= -20){
702 $ticks = 0;
703 $this->onAirExpired();
704 }
705 }
706 }elseif(!$this->isBreathing()){
707 if($ticks < ($max = $this->getMaxAirSupplyTicks())){
708 $ticks += $tickDiff * 5;
709 }
710 if($ticks >= $max){
711 $ticks = $max;
712 $this->setBreathing(true);
713 }
714 }
715
716 if($ticks !== $oldTicks){
717 $this->setAirSupplyTicks($ticks);
718 }
719
720 return $ticks !== $oldTicks;
721 }
722
726 public function canBreathe() : bool{
727 return $this->effectManager->has(VanillaEffects::WATER_BREATHING()) || $this->effectManager->has(VanillaEffects::CONDUIT_POWER()) || !$this->isUnderwater();
728 }
729
733 public function isBreathing() : bool{
734 return $this->breathing;
735 }
736
741 public function setBreathing(bool $value = true) : void{
742 $this->breathing = $value;
743 $this->networkPropertiesDirty = true;
744 }
745
750 public function getAirSupplyTicks() : int{
751 return $this->breathTicks;
752 }
753
757 public function setAirSupplyTicks(int $ticks) : void{
758 $this->breathTicks = $ticks;
759 $this->networkPropertiesDirty = true;
760 }
761
765 public function getMaxAirSupplyTicks() : int{
766 return $this->maxBreathTicks;
767 }
768
772 public function setMaxAirSupplyTicks(int $ticks) : void{
773 $this->maxBreathTicks = $ticks;
774 $this->networkPropertiesDirty = true;
775 }
776
781 public function onAirExpired() : void{
782 $ev = new EntityDamageEvent($this, EntityDamageEvent::CAUSE_DROWNING, 2);
783 $this->attack($ev);
784 }
785
789 public function getDrops() : array{
790 return [];
791 }
792
796 public function getXpDropAmount() : int{
797 return 0;
798 }
799
806 public function getLineOfSight(int $maxDistance, int $maxLength = 0, array $transparent = []) : array{
807 if($maxDistance > 120){
808 $maxDistance = 120;
809 }
810
811 if(count($transparent) === 0){
812 $transparent = null;
813 }
814
815 $blocks = [];
816 $nextIndex = 0;
817
818 foreach(VoxelRayTrace::inDirection($this->location->add(0, $this->size->getEyeHeight(), 0), $this->getDirectionVector(), $maxDistance) as $vector3){
819 $block = $this->getWorld()->getBlockAt($vector3->x, $vector3->y, $vector3->z);
820 $blocks[$nextIndex++] = $block;
821
822 if($maxLength !== 0 && count($blocks) > $maxLength){
823 array_shift($blocks);
824 --$nextIndex;
825 }
826
827 $id = $block->getTypeId();
828
829 if($transparent === null){
830 if($id !== BlockTypeIds::AIR){
831 break;
832 }
833 }else{
834 if(!isset($transparent[$id])){
835 break;
836 }
837 }
838 }
839
840 return $blocks;
841 }
842
847 public function getTargetBlock(int $maxDistance, array $transparent = []) : ?Block{
848 $line = $this->getLineOfSight($maxDistance, 1, $transparent);
849 if(count($line) > 0){
850 return array_shift($line);
851 }
852
853 return null;
854 }
855
860 public function lookAt(Vector3 $target) : void{
861 $horizontal = sqrt(($target->x - $this->location->x) ** 2 + ($target->z - $this->location->z) ** 2);
862 $vertical = $target->y - ($this->location->y + $this->getEyeHeight());
863 $pitch = -atan2($vertical, $horizontal) / M_PI * 180; //negative is up, positive is down
864
865 $xDist = $target->x - $this->location->x;
866 $zDist = $target->z - $this->location->z;
867
868 $yaw = atan2($zDist, $xDist) / M_PI * 180 - 90;
869 if($yaw < 0){
870 $yaw += 360.0;
871 }
872
873 $this->setRotation($yaw, $pitch);
874 }
875
876 protected function sendSpawnPacket(Player $player) : void{
877 parent::sendSpawnPacket($player);
878
879 $networkSession = $player->getNetworkSession();
880 $networkSession->getEntityEventBroadcaster()->onMobArmorChange([$networkSession], $this);
881 }
882
883 protected function syncNetworkData(EntityMetadataCollection $properties) : void{
884 parent::syncNetworkData($properties);
885
886 $properties->setByte(EntityMetadataProperties::POTION_AMBIENT, $this->effectManager->hasOnlyAmbientEffects() ? 1 : 0);
887 $properties->setInt(EntityMetadataProperties::POTION_COLOR, Binary::signInt($this->effectManager->getBubbleColor()->toARGB()));
888 $properties->setShort(EntityMetadataProperties::AIR, $this->breathTicks);
889 $properties->setShort(EntityMetadataProperties::MAX_AIR, $this->maxBreathTicks);
890
891 $properties->setGenericFlag(EntityMetadataFlags::BREATHING, $this->breathing);
892 $properties->setGenericFlag(EntityMetadataFlags::SNEAKING, $this->sneaking);
893 $properties->setGenericFlag(EntityMetadataFlags::SPRINTING, $this->sprinting);
894 $properties->setGenericFlag(EntityMetadataFlags::GLIDING, $this->gliding);
895 $properties->setGenericFlag(EntityMetadataFlags::SWIMMING, $this->swimming);
896 }
897
898 protected function onDispose() : void{
899 $this->armorInventory->removeAllViewers();
900 $this->effectManager->getEffectAddHooks()->clear();
901 $this->effectManager->getEffectRemoveHooks()->clear();
902 parent::onDispose();
903 }
904
905 protected function destroyCycles() : void{
906 unset(
907 $this->armorInventory,
908 $this->effectManager
909 );
910 parent::destroyCycles();
911 }
912}
applyPostDamageEffects(EntityDamageEvent $source)
Definition: Living.php:462
sendSpawnPacket(Player $player)
Definition: Living.php:876
setMaxAirSupplyTicks(int $ticks)
Definition: Living.php:772
setBreathing(bool $value=true)
Definition: Living.php:741
lookAt(Vector3 $target)
Definition: Living.php:860
const DEFAULT_KNOCKBACK_FORCE
Definition: Living.php:87
onDeathUpdate(int $tickDiff)
Definition: Living.php:629
damageArmor(float $damage)
Definition: Living.php:502
setHealth(float $amount)
Definition: Living.php:203
getLineOfSight(int $maxDistance, int $maxLength=0, array $transparent=[])
Definition: Living.php:806
const DEFAULT_KNOCKBACK_VERTICAL_LIMIT
Definition: Living.php:92
applyDamageModifiers(EntityDamageEvent $source)
Definition: Living.php:425
getTargetBlock(int $maxDistance, array $transparent=[])
Definition: Living.php:847
consumeObject(Consumable $consumable)
Definition: Living.php:323
applyConsumptionResults(Consumable $consumable)
Definition: Living.php:332
setAirSupplyTicks(int $ticks)
Definition: Living.php:757
doAirSupplyTick(int $tickDiff)
Definition: Living.php:691
getHighestArmorEnchantmentLevel(Enchantment $enchantment)
Definition: Living.php:404
setTag(string $name, Tag $tag)
setFloat(string $name, float $value)
setShort(string $name, int $value)