PocketMine-MP 5.35.1 git-e32e836dad793a3a3c8ddd8927c00e112b1e576a
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();
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
184 $activeEffectsTag = $nbt->getListTag(self::TAG_ACTIVE_EFFECTS, CompoundTag::class);
185 if($activeEffectsTag !== null){
186 foreach($activeEffectsTag as $e){
187 $effect = EffectIdMap::getInstance()->fromId($e->getByte(self::TAG_EFFECT_ID));
188 if($effect === null){
189 continue;
190 }
191
192 $this->effectManager->add(new EffectInstance(
193 $effect,
194 $e->getInt(self::TAG_EFFECT_DURATION),
195 Binary::unsignByte($e->getByte(self::TAG_EFFECT_AMPLIFIER)),
196 $e->getByte(self::TAG_EFFECT_SHOW_PARTICLES, 1) !== 0,
197 $e->getByte(self::TAG_EFFECT_AMBIENT, 0) !== 0
198 ));
199 }
200 }
201 }
202
203 protected function addAttributes() : void{
204 $this->attributeMap->add($this->healthAttr = AttributeFactory::getInstance()->mustGet(Attribute::HEALTH));
205 $this->attributeMap->add(AttributeFactory::getInstance()->mustGet(Attribute::FOLLOW_RANGE));
206 $this->attributeMap->add($this->knockbackResistanceAttr = AttributeFactory::getInstance()->mustGet(Attribute::KNOCKBACK_RESISTANCE));
207 $this->attributeMap->add($this->moveSpeedAttr = AttributeFactory::getInstance()->mustGet(Attribute::MOVEMENT_SPEED));
208 $this->attributeMap->add(AttributeFactory::getInstance()->mustGet(Attribute::ATTACK_DAMAGE));
209 $this->attributeMap->add($this->absorptionAttr = AttributeFactory::getInstance()->mustGet(Attribute::ABSORPTION));
210 }
211
215 public function getDisplayName() : string{
216 return $this->nameTag !== "" ? $this->nameTag : $this->getName();
217 }
218
219 public function setHealth(float $amount) : void{
220 $wasAlive = $this->isAlive();
221 parent::setHealth($amount);
222 $this->healthAttr->setValue(ceil($this->getHealth()), true);
223 if($this->isAlive() && !$wasAlive){
224 $this->broadcastAnimation(new RespawnAnimation($this));
225 }
226 }
227
228 public function getMaxHealth() : int{
229 return (int) $this->healthAttr->getMaxValue();
230 }
231
232 public function setMaxHealth(int $amount) : void{
233 $this->healthAttr->setMaxValue($amount)->setDefaultValue($amount);
234 }
235
236 public function getAbsorption() : float{
237 return $this->absorptionAttr->getValue();
238 }
239
240 public function setAbsorption(float $absorption) : void{
241 $this->absorptionAttr->setValue($absorption);
242 }
243
244 public function getSneakOffset() : float{
245 return 0.0;
246 }
247
248 public function isSneaking() : bool{
249 return $this->sneaking;
250 }
251
252 public function setSneaking(bool $value = true) : void{
253 $this->sneaking = $value;
254 $this->networkPropertiesDirty = true;
255 $this->recalculateSize();
256 }
257
258 public function isSprinting() : bool{
259 return $this->sprinting;
260 }
261
262 public function setSprinting(bool $value = true) : void{
263 if($value !== $this->isSprinting()){
264 $this->sprinting = $value;
265 $this->networkPropertiesDirty = true;
266 $moveSpeed = $this->getMovementSpeed();
267 $this->setMovementSpeed($value ? ($moveSpeed * 1.3) : ($moveSpeed / 1.3));
268 $this->moveSpeedAttr->markSynchronized(false); //TODO: reevaluate this hack
269 }
270 }
271
272 public function isGliding() : bool{
273 return $this->gliding;
274 }
275
276 public function setGliding(bool $value = true) : void{
277 $this->gliding = $value;
278 $this->networkPropertiesDirty = true;
279 $this->recalculateSize();
280 }
281
282 public function isSwimming() : bool{
283 return $this->swimming;
284 }
285
286 public function setSwimming(bool $value = true) : void{
287 $this->swimming = $value;
288 $this->networkPropertiesDirty = true;
289 $this->recalculateSize();
290 }
291
292 private function recalculateSize() : void{
293 $size = $this->getInitialSizeInfo();
294 if($this->isSwimming() || $this->isGliding()){
295 $width = $size->getWidth();
296 $this->setSize((new EntitySizeInfo($width, $width, $width * 0.9))->scale($this->getScale()));
297 }elseif($this->isSneaking()){
298 $this->setSize((new EntitySizeInfo($size->getHeight() - $this->getSneakOffset(), $size->getWidth(), $size->getEyeHeight() - $this->getSneakOffset()))->scale($this->getScale()));
299 }else{
300 $this->setSize($size->scale($this->getScale()));
301 }
302 }
303
304 public function getMovementSpeed() : float{
305 return $this->moveSpeedAttr->getValue();
306 }
307
308 public function setMovementSpeed(float $v, bool $fit = false) : void{
309 $this->moveSpeedAttr->setValue($v, $fit);
310 }
311
312 public function saveNBT() : CompoundTag{
313 $nbt = parent::saveNBT();
314 $nbt->setFloat(self::TAG_HEALTH, $this->getHealth());
315
316 $nbt->setShort(self::TAG_BREATH_TICKS, $this->getAirSupplyTicks());
317
318 if(count($this->effectManager->all()) > 0){
319 $effects = [];
320 foreach($this->effectManager->all() as $effect){
321 $effects[] = CompoundTag::create()
322 ->setByte(self::TAG_EFFECT_ID, EffectIdMap::getInstance()->toId($effect->getType()))
323 ->setByte(self::TAG_EFFECT_AMPLIFIER, Binary::signByte($effect->getAmplifier()))
324 ->setInt(self::TAG_EFFECT_DURATION, $effect->getDuration())
325 ->setByte(self::TAG_EFFECT_AMBIENT, $effect->isAmbient() ? 1 : 0)
326 ->setByte(self::TAG_EFFECT_SHOW_PARTICLES, $effect->isVisible() ? 1 : 0);
327 }
328
329 $nbt->setTag(self::TAG_ACTIVE_EFFECTS, new ListTag($effects));
330 }
331
332 return $nbt;
333 }
334
335 public function getEffects() : EffectManager{
336 return $this->effectManager;
337 }
338
343 public function consumeObject(Consumable $consumable) : bool{
344 $this->applyConsumptionResults($consumable);
345 return true;
346 }
347
352 protected function applyConsumptionResults(Consumable $consumable) : void{
353 foreach($consumable->getAdditionalEffects() as $effect){
354 $this->effectManager->add($effect);
355 }
356 if($consumable instanceof FoodSource){
357 $this->broadcastSound(new BurpSound());
358 }
359
360 $consumable->onConsume($this);
361 }
362
366 public function getJumpVelocity() : float{
367 return $this->jumpVelocity + ((($jumpBoost = $this->effectManager->get(VanillaEffects::JUMP_BOOST())) !== null ? $jumpBoost->getEffectLevel() : 0) / 10);
368 }
369
373 public function jump() : void{
374 if($this->onGround){
375 $this->motion = $this->motion->withComponents(null, $this->getJumpVelocity(), null); //Y motion should already be 0 if we're jumping from the ground.
376 }
377 }
378
379 protected function calculateFallDamage(float $fallDistance) : float{
380 return ceil($fallDistance - 3 - (($jumpBoost = $this->effectManager->get(VanillaEffects::JUMP_BOOST())) !== null ? $jumpBoost->getEffectLevel() : 0));
381 }
382
383 protected function onHitGround() : ?float{
384 $fallBlockPos = $this->location->floor();
385 $fallBlock = $this->getWorld()->getBlock($fallBlockPos);
386 if(count($fallBlock->getCollisionBoxes()) === 0){
387 $fallBlockPos = $fallBlockPos->down();
388 $fallBlock = $this->getWorld()->getBlock($fallBlockPos);
389 }
390 $newVerticalVelocity = $fallBlock->onEntityLand($this);
391
392 $damage = $this->calculateFallDamage($this->fallDistance);
393 if($damage > 0){
394 $ev = new EntityDamageEvent($this, EntityDamageEvent::CAUSE_FALL, $damage);
395 $this->attack($ev);
396
397 $this->broadcastSound($damage > 4 ?
398 new EntityLongFallSound($this) :
399 new EntityShortFallSound($this)
400 );
401 }elseif($fallBlock->getTypeId() !== BlockTypeIds::AIR){
402 $this->broadcastSound(new EntityLandSound($this, $fallBlock));
403 }
404 return $newVerticalVelocity;
405 }
406
412 public function getArmorPoints() : int{
413 $total = 0;
414 foreach($this->armorInventory->getContents() as $item){
415 $total += $item->getDefensePoints();
416 }
417
418 return $total;
419 }
420
424 public function getHighestArmorEnchantmentLevel(Enchantment $enchantment) : int{
425 $result = 0;
426 foreach($this->armorInventory->getContents() as $item){
427 $result = max($result, $item->getEnchantmentLevel($enchantment));
428 }
429
430 return $result;
431 }
432
433 public function getArmorInventory() : ArmorInventory{
434 return $this->armorInventory;
435 }
436
437 public function setOnFire(int $seconds) : void{
438 parent::setOnFire($seconds - (int) min($seconds, $seconds * $this->getHighestArmorEnchantmentLevel(VanillaEnchantments::FIRE_PROTECTION()) * 0.15));
439 }
440
445 public function applyDamageModifiers(EntityDamageEvent $source) : void{
446 if($this->lastDamageCause !== null && $this->attackTime > 0){
447 if($this->lastDamageCause->getBaseDamage() >= $source->getBaseDamage()){
448 $source->cancel();
449 }
450 $source->setModifier(-$this->lastDamageCause->getBaseDamage(), EntityDamageEvent::MODIFIER_PREVIOUS_DAMAGE_COOLDOWN);
451 }
452 if($source->canBeReducedByArmor()){
453 //MCPE uses the same system as PC did pre-1.9
454 $source->setModifier(-$source->getFinalDamage() * $this->getArmorPoints() * 0.04, EntityDamageEvent::MODIFIER_ARMOR);
455 }
456
457 $cause = $source->getCause();
458 if(($resistance = $this->effectManager->get(VanillaEffects::RESISTANCE())) !== null && $cause !== EntityDamageEvent::CAUSE_VOID && $cause !== EntityDamageEvent::CAUSE_SUICIDE){
459 $source->setModifier(-$source->getFinalDamage() * min(1, 0.2 * $resistance->getEffectLevel()), EntityDamageEvent::MODIFIER_RESISTANCE);
460 }
461
462 $totalEpf = 0;
463 foreach($this->armorInventory->getContents() as $item){
464 if($item instanceof Armor){
465 $totalEpf += $item->getEnchantmentProtectionFactor($source);
466 }
467 }
468 $source->setModifier(-$source->getFinalDamage() * min(ceil(min($totalEpf, 25) * (mt_rand(50, 100) / 100)), 20) * 0.04, EntityDamageEvent::MODIFIER_ARMOR_ENCHANTMENTS);
469
470 $source->setModifier(-min($this->getAbsorption(), $source->getFinalDamage()), EntityDamageEvent::MODIFIER_ABSORPTION);
471
472 if($cause === EntityDamageEvent::CAUSE_FALLING_BLOCK && $this->armorInventory->getHelmet() instanceof Armor){
473 $source->setModifier(-($source->getFinalDamage() / 4), EntityDamageEvent::MODIFIER_ARMOR_HELMET);
474 }
475 }
476
482 protected function applyPostDamageEffects(EntityDamageEvent $source) : void{
483 $this->setAbsorption(max(0, $this->getAbsorption() + $source->getModifier(EntityDamageEvent::MODIFIER_ABSORPTION)));
484 if($source->canBeReducedByArmor()){
485 $this->damageArmor($source->getBaseDamage());
486 }
487
488 if($source instanceof EntityDamageByEntityEvent && ($attacker = $source->getDamager()) !== null){
489 $damage = 0;
490 foreach($this->armorInventory->getContents() as $k => $item){
491 if($item instanceof Armor && ($thornsLevel = $item->getEnchantmentLevel(VanillaEnchantments::THORNS())) > 0){
492 if(mt_rand(0, 99) < $thornsLevel * 15){
493 $this->damageItem($item, 3);
494 $damage += ($thornsLevel > 10 ? $thornsLevel - 10 : 1 + mt_rand(0, 3));
495 }else{
496 $this->damageItem($item, 1); //thorns causes an extra +1 durability loss even if it didn't activate
497 }
498
499 $this->armorInventory->setItem($k, $item);
500 }
501 }
502
503 if($damage > 0){
504 $attacker->attack(new EntityDamageByEntityEvent($this, $attacker, EntityDamageEvent::CAUSE_MAGIC, $damage));
505 }
506
507 if($source->getModifier(EntityDamageEvent::MODIFIER_ARMOR_HELMET) < 0){
508 $helmet = $this->armorInventory->getHelmet();
509 if($helmet instanceof Armor){
510 $finalDamage = $source->getFinalDamage();
511 $this->damageItem($helmet, (int) round($finalDamage * 4 + Utils::getRandomFloat() * $finalDamage * 2));
512 $this->armorInventory->setHelmet($helmet);
513 }
514 }
515 }
516 }
517
522 public function damageArmor(float $damage) : void{
523 $durabilityRemoved = (int) max(floor($damage / 4), 1);
524
525 $armor = $this->armorInventory->getContents();
526 foreach($armor as $slotId => $item){
527 if($item instanceof Armor){
528 $oldItem = clone $item;
529 $this->damageItem($item, $durabilityRemoved);
530 if(!$item->equalsExact($oldItem)){
531 $this->armorInventory->setItem($slotId, $item);
532 }
533 }
534 }
535 }
536
537 private function damageItem(Durable $item, int $durabilityRemoved) : void{
538 $item->applyDamage($durabilityRemoved);
539 if($item->isBroken()){
540 $this->broadcastSound(new ItemBreakSound());
541 }
542 }
543
544 public function attack(EntityDamageEvent $source) : void{
545 if($this->noDamageTicks > 0 && $source->getCause() !== EntityDamageEvent::CAUSE_SUICIDE){
546 $source->cancel();
547 }
548
549 if($this->effectManager->has(VanillaEffects::FIRE_RESISTANCE()) && (
550 $source->getCause() === EntityDamageEvent::CAUSE_FIRE
551 || $source->getCause() === EntityDamageEvent::CAUSE_FIRE_TICK
552 || $source->getCause() === EntityDamageEvent::CAUSE_LAVA
553 )
554 ){
555 $source->cancel();
556 }
557
558 if($source->getCause() !== EntityDamageEvent::CAUSE_SUICIDE){
559 $this->applyDamageModifiers($source);
560 }
561
562 if($source instanceof EntityDamageByEntityEvent && (
563 $source->getCause() === EntityDamageEvent::CAUSE_BLOCK_EXPLOSION ||
564 $source->getCause() === EntityDamageEvent::CAUSE_ENTITY_EXPLOSION)
565 ){
566 //TODO: knockback should not just apply for entity damage sources
567 //this doesn't matter for TNT right now because the PrimedTNT entity is considered the source, not the block.
568 $base = $source->getKnockBack();
569 $source->setKnockBack($base - min($base, $base * $this->getHighestArmorEnchantmentLevel(VanillaEnchantments::BLAST_PROTECTION()) * 0.15));
570 }
571
572 parent::attack($source);
573
574 if($source->isCancelled()){
575 return;
576 }
577
578 if($this->attackTime <= 0){
579 //this logic only applies if the entity was cold attacked
580
581 $this->attackTime = $source->getAttackCooldown();
582
583 if($source instanceof EntityDamageByChildEntityEvent){
584 $e = $source->getChild();
585 if($e !== null){
586 $motion = $e->getMotion();
587 $this->knockBack($motion->x, $motion->z, $source->getKnockBack(), $source->getVerticalKnockBackLimit());
588 }
589 }elseif($source instanceof EntityDamageByEntityEvent){
590 $e = $source->getDamager();
591 if($e !== null){
592 $deltaX = $this->location->x - $e->location->x;
593 $deltaZ = $this->location->z - $e->location->z;
594 $this->knockBack($deltaX, $deltaZ, $source->getKnockBack(), $source->getVerticalKnockBackLimit());
595 }
596 }
597
598 if($this->isAlive()){
599 $this->doHitAnimation();
600 }
601 }
602
603 if($this->isAlive()){
604 $this->applyPostDamageEffects($source);
605 }
606 }
607
608 protected function doHitAnimation() : void{
609 $this->broadcastAnimation(new HurtAnimation($this));
610 }
611
612 public function knockBack(float $x, float $z, float $force = self::DEFAULT_KNOCKBACK_FORCE, ?float $verticalLimit = self::DEFAULT_KNOCKBACK_VERTICAL_LIMIT) : void{
613 $f = sqrt($x * $x + $z * $z);
614 if($f <= 0){
615 return;
616 }
617 if(mt_rand() / mt_getrandmax() > $this->knockbackResistanceAttr->getValue()){
618 $f = 1 / $f;
619
620 $motionX = $this->motion->x / 2;
621 $motionY = $this->motion->y / 2;
622 $motionZ = $this->motion->z / 2;
623 $motionX += $x * $f * $force;
624 $motionY += $force;
625 $motionZ += $z * $f * $force;
626
627 $verticalLimit ??= $force;
628 if($motionY > $verticalLimit){
629 $motionY = $verticalLimit;
630 }
631
632 $this->setMotion(new Vector3($motionX, $motionY, $motionZ));
633 }
634 }
635
636 protected function onDeath() : void{
637 $ev = new EntityDeathEvent($this, $this->getDrops(), $this->getXpDropAmount());
638 $ev->call();
639 foreach($ev->getDrops() as $item){
640 $this->getWorld()->dropItem($this->location, $item);
641 }
642
643 //TODO: check death conditions (must have been damaged by player < 5 seconds from death)
644 $this->getWorld()->dropExperience($this->location, $ev->getXpDropAmount());
645
646 $this->startDeathAnimation();
647 }
648
649 protected function onDeathUpdate(int $tickDiff) : bool{
650 if($this->deadTicks < $this->maxDeadTicks){
651 $this->deadTicks += $tickDiff;
652 if($this->deadTicks >= $this->maxDeadTicks){
653 $this->endDeathAnimation();
654 }
655 }
656
657 return $this->deadTicks >= $this->maxDeadTicks;
658 }
659
660 protected function startDeathAnimation() : void{
661 $this->broadcastAnimation(new DeathAnimation($this));
662 }
663
664 protected function endDeathAnimation() : void{
665 $this->despawnFromAll();
666 }
667
668 protected function entityBaseTick(int $tickDiff = 1) : bool{
669 Timings::$livingEntityBaseTick->startTiming();
670
671 $hasUpdate = parent::entityBaseTick($tickDiff);
672
673 if($this->isAlive()){
674 if($this->effectManager->tick($tickDiff)){
675 $hasUpdate = true;
676 }
677
678 if($this->isInsideOfSolid()){
679 $hasUpdate = true;
680 $ev = new EntityDamageEvent($this, EntityDamageEvent::CAUSE_SUFFOCATION, 1);
681 $this->attack($ev);
682 }
683
684 if($this->doAirSupplyTick($tickDiff)){
685 $hasUpdate = true;
686 }
687
688 foreach($this->armorInventory->getContents() as $index => $item){
689 $oldItem = clone $item;
690 if($item->onTickWorn($this)){
691 $hasUpdate = true;
692 if(!$item->equalsExact($oldItem)){
693 $this->armorInventory->setItem($index, $item);
694 }
695 }
696 }
697 }
698
699 if($this->attackTime > 0){
700 $this->attackTime -= $tickDiff;
701 }
702
703 Timings::$livingEntityBaseTick->stopTiming();
704
705 return $hasUpdate;
706 }
707
708 protected function move(float $dx, float $dy, float $dz) : void{
709 $oldX = $this->location->x;
710 $oldZ = $this->location->z;
711
712 parent::move($dx, $dy, $dz);
713
714 $frostWalkerLevel = $this->getFrostWalkerLevel();
715 if($frostWalkerLevel > 0 && (abs($this->location->x - $oldX) > self::MOTION_THRESHOLD || abs($this->location->z - $oldZ) > self::MOTION_THRESHOLD)){
716 $this->applyFrostWalker($frostWalkerLevel);
717 }
718 }
719
720 protected function applyFrostWalker(int $level) : void{
721 $radius = $level + 2;
722 $world = $this->getWorld();
723
724 $baseX = $this->location->getFloorX();
725 $y = $this->location->getFloorY() - 1;
726 $baseZ = $this->location->getFloorZ();
727
728 $liquid = VanillaBlocks::WATER();
729 $targetBlock = VanillaBlocks::FROSTED_ICE();
730 if(EntityFrostWalkerEvent::hasHandlers()){
731 $ev = new EntityFrostWalkerEvent($this, $radius, $liquid, $targetBlock);
732 $ev->call();
733 if($ev->isCancelled()){
734 return;
735 }
736 $radius = $ev->getRadius();
737 $liquid = $ev->getLiquid();
738 $targetBlock = $ev->getTargetBlock();
739 }
740
741 for($x = $baseX - $radius; $x <= $baseX + $radius; $x++){
742 for($z = $baseZ - $radius; $z <= $baseZ + $radius; $z++){
743 $block = $world->getBlockAt($x, $y, $z);
744 if(
745 !$block->isSameState($liquid) ||
746 $world->getBlockAt($x, $y + 1, $z)->getTypeId() !== BlockTypeIds::AIR ||
747 count($world->getNearbyEntities(AxisAlignedBB::one()->offsetCopy($x, $y, $z))) !== 0
748 ){
749 continue;
750 }
751 $world->setBlockAt($x, $y, $z, $targetBlock);
752 }
753 }
754 }
755
756 public function getFrostWalkerLevel() : int{
757 return $this->frostWalkerLevel ??= $this->armorInventory->getBoots()->getEnchantmentLevel(VanillaEnchantments::FROST_WALKER());
758 }
759
763 protected function doAirSupplyTick(int $tickDiff) : bool{
764 $ticks = $this->getAirSupplyTicks();
765 $oldTicks = $ticks;
766 if(!$this->canBreathe()){
767 $this->setBreathing(false);
768
769 if(($respirationLevel = $this->armorInventory->getHelmet()->getEnchantmentLevel(VanillaEnchantments::RESPIRATION())) <= 0 ||
770 Utils::getRandomFloat() <= (1 / ($respirationLevel + 1))
771 ){
772 $ticks -= $tickDiff;
773 if($ticks <= -20){
774 $ticks = 0;
775 $this->onAirExpired();
776 }
777 }
778 }elseif(!$this->isBreathing()){
779 if($ticks < ($max = $this->getMaxAirSupplyTicks())){
780 $ticks += $tickDiff * 5;
781 }
782 if($ticks >= $max){
783 $ticks = $max;
784 $this->setBreathing(true);
785 }
786 }
787
788 if($ticks !== $oldTicks){
789 $this->setAirSupplyTicks($ticks);
790 }
791
792 return $ticks !== $oldTicks;
793 }
794
798 public function canBreathe() : bool{
799 return $this->effectManager->has(VanillaEffects::WATER_BREATHING()) || $this->effectManager->has(VanillaEffects::CONDUIT_POWER()) || !$this->isUnderwater();
800 }
801
805 public function isBreathing() : bool{
806 return $this->breathing;
807 }
808
813 public function setBreathing(bool $value = true) : void{
814 $this->breathing = $value;
815 $this->networkPropertiesDirty = true;
816 }
817
822 public function getAirSupplyTicks() : int{
823 return $this->breathTicks;
824 }
825
829 public function setAirSupplyTicks(int $ticks) : void{
830 $this->breathTicks = $ticks;
831 $this->networkPropertiesDirty = true;
832 }
833
837 public function getMaxAirSupplyTicks() : int{
838 return $this->maxBreathTicks;
839 }
840
844 public function setMaxAirSupplyTicks(int $ticks) : void{
845 $this->maxBreathTicks = $ticks;
846 $this->networkPropertiesDirty = true;
847 }
848
853 public function onAirExpired() : void{
854 $ev = new EntityDamageEvent($this, EntityDamageEvent::CAUSE_DROWNING, 2);
855 $this->attack($ev);
856 }
857
861 public function getDrops() : array{
862 return [];
863 }
864
868 public function getXpDropAmount() : int{
869 return 0;
870 }
871
878 public function getLineOfSight(int $maxDistance, int $maxLength = 0, array $transparent = []) : array{
879 if($maxDistance > 120){
880 $maxDistance = 120;
881 }
882
883 if(count($transparent) === 0){
884 $transparent = null;
885 }
886
887 $blocks = [];
888 $nextIndex = 0;
889
890 foreach(VoxelRayTrace::inDirection($this->location->add(0, $this->size->getEyeHeight(), 0), $this->getDirectionVector(), $maxDistance) as $vector3){
891 $block = $this->getWorld()->getBlockAt($vector3->x, $vector3->y, $vector3->z);
892 $blocks[$nextIndex++] = $block;
893
894 if($maxLength !== 0 && count($blocks) > $maxLength){
895 array_shift($blocks);
896 --$nextIndex;
897 }
898
899 $id = $block->getTypeId();
900
901 if($transparent === null){
902 if($id !== BlockTypeIds::AIR){
903 break;
904 }
905 }else{
906 if(!isset($transparent[$id])){
907 break;
908 }
909 }
910 }
911
912 return $blocks;
913 }
914
919 public function getTargetBlock(int $maxDistance, array $transparent = []) : ?Block{
920 $line = $this->getLineOfSight($maxDistance, 1, $transparent);
921 if(count($line) > 0){
922 return array_shift($line);
923 }
924
925 return null;
926 }
927
932 public function lookAt(Vector3 $target) : void{
933 $horizontal = sqrt(($target->x - $this->location->x) ** 2 + ($target->z - $this->location->z) ** 2);
934 $vertical = $target->y - ($this->location->y + $this->getEyeHeight());
935 $pitch = -atan2($vertical, $horizontal) / M_PI * 180; //negative is up, positive is down
936
937 $xDist = $target->x - $this->location->x;
938 $zDist = $target->z - $this->location->z;
939
940 $yaw = atan2($zDist, $xDist) / M_PI * 180 - 90;
941 if($yaw < 0){
942 $yaw += 360.0;
943 }
944
945 $this->setRotation($yaw, $pitch);
946 }
947
948 protected function sendSpawnPacket(Player $player) : void{
949 parent::sendSpawnPacket($player);
950
951 $networkSession = $player->getNetworkSession();
952 $networkSession->getEntityEventBroadcaster()->onMobArmorChange([$networkSession], $this);
953 }
954
955 protected function syncNetworkData(EntityMetadataCollection $properties) : void{
956 parent::syncNetworkData($properties);
957
958 $visibleEffects = [];
959 foreach ($this->effectManager->all() as $effect) {
960 if (!$effect->isVisible() || !$effect->getType()->hasBubbles()) {
961 continue;
962 }
963 $visibleEffects[EffectIdMap::getInstance()->toId($effect->getType())] = $effect->isAmbient();
964 }
965
966 //TODO: HACK! the client may not be able to identify effects if they are not sorted.
967 ksort($visibleEffects, SORT_NUMERIC);
968
969 $effectsData = 0;
970 $packedEffectsCount = 0;
971 foreach ($visibleEffects as $effectId => $isAmbient) {
972 $effectsData = ($effectsData << 7) |
973 (($effectId & 0x3f) << 1) | //Why not use 7 bits instead of only 6? mojang...
974 ($isAmbient ? 1 : 0);
975
976 if (++$packedEffectsCount >= 8) {
977 break;
978 }
979 }
980 $properties->setLong(EntityMetadataProperties::VISIBLE_MOB_EFFECTS, $effectsData);
981
982 $properties->setShort(EntityMetadataProperties::AIR, $this->breathTicks);
983 $properties->setShort(EntityMetadataProperties::MAX_AIR, $this->maxBreathTicks);
984
985 $properties->setGenericFlag(EntityMetadataFlags::BREATHING, $this->breathing);
986 $properties->setGenericFlag(EntityMetadataFlags::SNEAKING, $this->sneaking);
987 $properties->setGenericFlag(EntityMetadataFlags::SPRINTING, $this->sprinting);
988 $properties->setGenericFlag(EntityMetadataFlags::GLIDING, $this->gliding);
989 $properties->setGenericFlag(EntityMetadataFlags::SWIMMING, $this->swimming);
990 }
991
992 protected function onDispose() : void{
993 $this->armorInventory->removeAllWindows();
994 $this->effectManager->getEffectAddHooks()->clear();
995 $this->effectManager->getEffectRemoveHooks()->clear();
996 parent::onDispose();
997 }
998
999 protected function destroyCycles() : void{
1000 unset(
1001 $this->effectManager
1002 );
1003 parent::destroyCycles();
1004 }
1005}
applyPostDamageEffects(EntityDamageEvent $source)
Definition Living.php:482
sendSpawnPacket(Player $player)
Definition Living.php:948
setMaxAirSupplyTicks(int $ticks)
Definition Living.php:844
setBreathing(bool $value=true)
Definition Living.php:813
lookAt(Vector3 $target)
Definition Living.php:932
onDeathUpdate(int $tickDiff)
Definition Living.php:649
damageArmor(float $damage)
Definition Living.php:522
setHealth(float $amount)
Definition Living.php:219
getLineOfSight(int $maxDistance, int $maxLength=0, array $transparent=[])
Definition Living.php:878
const DEFAULT_KNOCKBACK_VERTICAL_LIMIT
Definition Living.php:99
applyDamageModifiers(EntityDamageEvent $source)
Definition Living.php:445
getTargetBlock(int $maxDistance, array $transparent=[])
Definition Living.php:919
consumeObject(Consumable $consumable)
Definition Living.php:343
applyConsumptionResults(Consumable $consumable)
Definition Living.php:352
setAirSupplyTicks(int $ticks)
Definition Living.php:829
doAirSupplyTick(int $tickDiff)
Definition Living.php:763
getHighestArmorEnchantmentLevel(Enchantment $enchantment)
Definition Living.php:424
setTag(string $name, Tag $tag)
getListTag(string $name, string $tagClass=Tag::class)
setFloat(string $name, float $value)
setShort(string $name, int $value)
getEnchantmentLevel(Enchantment $enchantment)