83 protected const DEFAULT_BREATH_TICKS = 300;
96 private const TAG_LEGACY_HEALTH =
"HealF";
97 private const TAG_HEALTH =
"Health";
98 private const TAG_BREATH_TICKS =
"Air";
99 private const TAG_ACTIVE_EFFECTS =
"ActiveEffects";
100 private const TAG_EFFECT_ID =
"Id";
101 private const TAG_EFFECT_DURATION =
"Duration";
102 private const TAG_EFFECT_AMPLIFIER =
"Amplifier";
103 private const TAG_EFFECT_SHOW_PARTICLES =
"ShowParticles";
104 private const TAG_EFFECT_AMBIENT =
"Ambient";
106 protected int $attackTime = 0;
108 public int $deadTicks = 0;
109 protected int $maxDeadTicks = 25;
111 protected float $jumpVelocity = 0.42;
117 protected bool $breathing =
true;
118 protected int $breathTicks = self::DEFAULT_BREATH_TICKS;
119 protected int $maxBreathTicks = self::DEFAULT_BREATH_TICKS;
123 protected Attribute $knockbackResistanceAttr;
126 protected bool $sprinting =
false;
127 protected bool $sneaking =
false;
128 protected bool $gliding =
false;
129 protected bool $swimming =
false;
135 abstract public function getName() : string;
141 protected function initEntity(
CompoundTag $nbt) : void{
142 parent::initEntity($nbt);
145 $this->effectManager->getEffectAddHooks()->add(
function() :
void{ $this->networkPropertiesDirty =
true; });
146 $this->effectManager->getEffectRemoveHooks()->add(
function() :
void{ $this->networkPropertiesDirty =
true; });
148 $this->armorInventory =
new ArmorInventory($this);
150 $this->armorInventory->getListeners()->add(CallbackInventoryListener::onAnyChange(fn() => NetworkBroadcastUtils::broadcastEntityEvent(
152 fn(EntityEventBroadcaster $broadcaster, array $recipients) => $broadcaster->onMobArmorChange($recipients, $this)
155 $health = $this->getMaxHealth();
157 if(($healFTag = $nbt->
getTag(self::TAG_LEGACY_HEALTH)) instanceof FloatTag){
158 $health = $healFTag->getValue();
159 }elseif(($healthTag = $nbt->
getTag(self::TAG_HEALTH)) instanceof ShortTag){
160 $health = $healthTag->getValue();
161 }elseif($healthTag instanceof FloatTag){
162 $health = $healthTag->getValue();
165 $this->setHealth($health);
167 $this->setAirSupplyTicks($nbt->getShort(self::TAG_BREATH_TICKS, self::DEFAULT_BREATH_TICKS));
170 $activeEffectsTag = $nbt->
getListTag(self::TAG_ACTIVE_EFFECTS);
171 if($activeEffectsTag !==
null){
172 foreach($activeEffectsTag as $e){
173 $effect = EffectIdMap::getInstance()->fromId($e->getByte(self::TAG_EFFECT_ID));
174 if($effect ===
null){
178 $this->effectManager->add(
new EffectInstance(
180 $e->getInt(self::TAG_EFFECT_DURATION),
181 Binary::unsignByte($e->getByte(self::TAG_EFFECT_AMPLIFIER)),
182 $e->getByte(self::TAG_EFFECT_SHOW_PARTICLES, 1) !== 0,
183 $e->getByte(self::TAG_EFFECT_AMBIENT, 0) !== 0
189 protected function addAttributes() : void{
190 $this->attributeMap->add($this->healthAttr = AttributeFactory::getInstance()->mustGet(Attribute::HEALTH));
191 $this->attributeMap->add(AttributeFactory::getInstance()->mustGet(Attribute::FOLLOW_RANGE));
192 $this->attributeMap->add($this->knockbackResistanceAttr = AttributeFactory::getInstance()->mustGet(Attribute::KNOCKBACK_RESISTANCE));
193 $this->attributeMap->add($this->moveSpeedAttr = AttributeFactory::getInstance()->mustGet(Attribute::MOVEMENT_SPEED));
194 $this->attributeMap->add(AttributeFactory::getInstance()->mustGet(Attribute::ATTACK_DAMAGE));
195 $this->attributeMap->add($this->absorptionAttr = AttributeFactory::getInstance()->mustGet(Attribute::ABSORPTION));
202 return $this->nameTag !==
"" ? $this->nameTag : $this->getName();
206 $wasAlive = $this->isAlive();
207 parent::setHealth($amount);
208 $this->healthAttr->setValue(ceil($this->getHealth()),
true);
209 if($this->isAlive() && !$wasAlive){
214 public function getMaxHealth() : int{
215 return (int) $this->healthAttr->getMaxValue();
218 public function setMaxHealth(
int $amount) : void{
219 $this->healthAttr->setMaxValue($amount)->setDefaultValue($amount);
222 public function getAbsorption() : float{
223 return $this->absorptionAttr->getValue();
226 public function setAbsorption(
float $absorption) : void{
227 $this->absorptionAttr->setValue($absorption);
230 public function isSneaking() : bool{
231 return $this->sneaking;
234 public function setSneaking(
bool $value =
true) : void{
235 $this->sneaking = $value;
236 $this->networkPropertiesDirty =
true;
237 $this->recalculateSize();
240 public function isSprinting() : bool{
241 return $this->sprinting;
244 public function setSprinting(
bool $value =
true) : void{
245 if($value !== $this->isSprinting()){
246 $this->sprinting = $value;
247 $this->networkPropertiesDirty =
true;
248 $moveSpeed = $this->getMovementSpeed();
249 $this->setMovementSpeed($value ? ($moveSpeed * 1.3) : ($moveSpeed / 1.3));
250 $this->moveSpeedAttr->markSynchronized(
false);
254 public function isGliding() : bool{
255 return $this->gliding;
258 public function setGliding(
bool $value =
true) : void{
259 $this->gliding = $value;
260 $this->networkPropertiesDirty =
true;
261 $this->recalculateSize();
264 public function isSwimming() : bool{
265 return $this->swimming;
268 public function setSwimming(
bool $value =
true) : void{
269 $this->swimming = $value;
270 $this->networkPropertiesDirty =
true;
271 $this->recalculateSize();
274 private function recalculateSize() : void{
275 $size = $this->getInitialSizeInfo();
276 if($this->isSwimming() || $this->isGliding()){
277 $width = $size->getWidth();
278 $this->setSize((
new EntitySizeInfo($width, $width, $width * 0.9))->scale($this->getScale()));
279 }elseif($this->isSneaking()){
280 $this->setSize((
new EntitySizeInfo(3 / 4 * $size->getHeight(), $size->getWidth(), 3 / 4 * $size->getEyeHeight()))->scale($this->getScale()));
282 $this->setSize($size->scale($this->getScale()));
286 public function getMovementSpeed() : float{
287 return $this->moveSpeedAttr->getValue();
290 public function setMovementSpeed(
float $v,
bool $fit =
false) : void{
291 $this->moveSpeedAttr->setValue($v, $fit);
294 public function saveNBT() : CompoundTag{
295 $nbt = parent::saveNBT();
296 $nbt->
setFloat(self::TAG_HEALTH, $this->getHealth());
298 $nbt->
setShort(self::TAG_BREATH_TICKS, $this->getAirSupplyTicks());
300 if(count($this->effectManager->all()) > 0){
302 foreach($this->effectManager->all() as $effect){
303 $effects[] = CompoundTag::create()
304 ->setByte(self::TAG_EFFECT_ID, EffectIdMap::getInstance()->toId($effect->getType()))
305 ->setByte(self::TAG_EFFECT_AMPLIFIER, Binary::signByte($effect->getAmplifier()))
306 ->setInt(self::TAG_EFFECT_DURATION, $effect->getDuration())
307 ->setByte(self::TAG_EFFECT_AMBIENT, $effect->isAmbient() ? 1 : 0)
308 ->setByte(self::TAG_EFFECT_SHOW_PARTICLES, $effect->isVisible() ? 1 : 0);
311 $nbt->
setTag(self::TAG_ACTIVE_EFFECTS,
new ListTag($effects));
318 return $this->effectManager;
326 $this->applyConsumptionResults($consumable);
335 foreach($consumable->getAdditionalEffects() as $effect){
336 $this->effectManager->add($effect);
342 $consumable->onConsume($this);
349 return $this->jumpVelocity + ((($jumpBoost = $this->effectManager->get(
VanillaEffects::JUMP_BOOST())) !== null ? $jumpBoost->getEffectLevel() : 0) / 10);
357 $this->motion = $this->motion->withComponents(
null, $this->getJumpVelocity(),
null);
361 protected function calculateFallDamage(
float $fallDistance) : float{
362 return ceil($fallDistance - 3 - (($jumpBoost = $this->effectManager->get(VanillaEffects::JUMP_BOOST())) !== null ? $jumpBoost->getEffectLevel() : 0));
366 $fallBlockPos = $this->location->floor();
367 $fallBlock = $this->getWorld()->getBlock($fallBlockPos);
368 if(count($fallBlock->getCollisionBoxes()) === 0){
369 $fallBlockPos = $fallBlockPos->down();
370 $fallBlock = $this->getWorld()->getBlock($fallBlockPos);
372 $newVerticalVelocity = $fallBlock->onEntityLand($this);
374 $damage = $this->calculateFallDamage($this->fallDistance);
379 $this->broadcastSound($damage > 4 ?
383 }elseif($fallBlock->getTypeId() !== BlockTypeIds::AIR){
384 $this->broadcastSound(
new EntityLandSound($this, $fallBlock));
386 return $newVerticalVelocity;
396 foreach($this->armorInventory->getContents() as $item){
397 $total += $item->getDefensePoints();
408 foreach($this->armorInventory->getContents() as $item){
409 $result = max($result, $item->getEnchantmentLevel($enchantment));
415 public function getArmorInventory() : ArmorInventory{
416 return $this->armorInventory;
419 public function setOnFire(
int $seconds) : void{
420 parent::setOnFire($seconds - (int) min($seconds, $seconds * $this->getHighestArmorEnchantmentLevel(VanillaEnchantments::FIRE_PROTECTION()) * 0.15));
428 if($this->lastDamageCause !== null && $this->attackTime > 0){
429 if($this->lastDamageCause->getBaseDamage() >= $source->
getBaseDamage()){
432 $source->setModifier(-$this->lastDamageCause->getBaseDamage(), EntityDamageEvent::MODIFIER_PREVIOUS_DAMAGE_COOLDOWN);
434 if($source->canBeReducedByArmor()){
436 $source->setModifier(-$source->getFinalDamage() * $this->getArmorPoints() * 0.04, EntityDamageEvent::MODIFIER_ARMOR);
439 $cause = $source->getCause();
440 if(($resistance = $this->effectManager->get(VanillaEffects::RESISTANCE())) !==
null && $cause !== EntityDamageEvent::CAUSE_VOID && $cause !== EntityDamageEvent::CAUSE_SUICIDE){
441 $source->setModifier(-$source->getFinalDamage() * min(1, 0.2 * $resistance->getEffectLevel()), EntityDamageEvent::MODIFIER_RESISTANCE);
445 foreach($this->armorInventory->getContents() as $item){
446 if($item instanceof Armor){
447 $totalEpf += $item->getEnchantmentProtectionFactor($source);
450 $source->setModifier(-$source->getFinalDamage() * min(ceil(min($totalEpf, 25) * (mt_rand(50, 100) / 100)), 20) * 0.04, EntityDamageEvent::MODIFIER_ARMOR_ENCHANTMENTS);
452 $source->setModifier(-min($this->getAbsorption(), $source->getFinalDamage()), EntityDamageEvent::MODIFIER_ABSORPTION);
454 if($cause === EntityDamageEvent::CAUSE_FALLING_BLOCK && $this->armorInventory->getHelmet() instanceof Armor){
455 $source->setModifier(-($source->getFinalDamage() / 4), EntityDamageEvent::MODIFIER_ARMOR_HELMET);
465 $this->setAbsorption(max(0, $this->getAbsorption() + $source->getModifier(
EntityDamageEvent::MODIFIER_ABSORPTION)));
467 $this->damageArmor($source->getBaseDamage());
472 foreach($this->armorInventory->getContents() as $k => $item){
473 if($item instanceof Armor && ($thornsLevel = $item->getEnchantmentLevel(VanillaEnchantments::THORNS())) > 0){
474 if(mt_rand(0, 99) < $thornsLevel * 15){
475 $this->damageItem($item, 3);
476 $damage += ($thornsLevel > 10 ? $thornsLevel - 10 : 1 + mt_rand(0, 3));
478 $this->damageItem($item, 1);
481 $this->armorInventory->setItem($k, $item);
486 $attacker->attack(new EntityDamageByEntityEvent($this, $attacker, EntityDamageEvent::CAUSE_MAGIC, $damage));
489 if($source->getModifier(EntityDamageEvent::MODIFIER_ARMOR_HELMET) < 0){
490 $helmet = $this->armorInventory->getHelmet();
491 if($helmet instanceof Armor){
492 $finalDamage = $source->getFinalDamage();
493 $this->damageItem($helmet, (int) round($finalDamage * 4 + lcg_value() * $finalDamage * 2));
494 $this->armorInventory->setHelmet($helmet);
505 $durabilityRemoved = (int) max(floor($damage / 4), 1);
507 $armor = $this->armorInventory->getContents();
508 foreach($armor as $slotId => $item){
509 if($item instanceof
Armor){
510 $oldItem = clone $item;
511 $this->damageItem($item, $durabilityRemoved);
512 if(!$item->equalsExact($oldItem)){
513 $this->armorInventory->setItem($slotId, $item);
519 private function damageItem(Durable $item,
int $durabilityRemoved) : void{
520 $item->applyDamage($durabilityRemoved);
521 if($item->isBroken()){
522 $this->broadcastSound(new ItemBreakSound());
526 public function attack(EntityDamageEvent $source) : void{
527 if($this->noDamageTicks > 0 && $source->getCause() !== EntityDamageEvent::CAUSE_SUICIDE){
531 if($this->effectManager->has(VanillaEffects::FIRE_RESISTANCE()) && (
532 $source->getCause() === EntityDamageEvent::CAUSE_FIRE
533 || $source->getCause() === EntityDamageEvent::CAUSE_FIRE_TICK
534 || $source->getCause() === EntityDamageEvent::CAUSE_LAVA
540 if($source->getCause() !== EntityDamageEvent::CAUSE_SUICIDE){
541 $this->applyDamageModifiers($source);
544 if($source instanceof EntityDamageByEntityEvent && (
545 $source->getCause() === EntityDamageEvent::CAUSE_BLOCK_EXPLOSION ||
546 $source->getCause() === EntityDamageEvent::CAUSE_ENTITY_EXPLOSION)
550 $base = $source->getKnockBack();
551 $source->setKnockBack($base - min($base, $base * $this->getHighestArmorEnchantmentLevel(VanillaEnchantments::BLAST_PROTECTION()) * 0.15));
554 parent::attack($source);
556 if($source->isCancelled()){
560 if($this->attackTime <= 0){
563 $this->attackTime = $source->getAttackCooldown();
565 if($source instanceof EntityDamageByChildEntityEvent){
566 $e = $source->getChild();
568 $motion = $e->getMotion();
569 $this->knockBack($motion->x, $motion->z, $source->getKnockBack(), $source->getVerticalKnockBackLimit());
571 }elseif($source instanceof EntityDamageByEntityEvent){
572 $e = $source->getDamager();
574 $deltaX = $this->location->x - $e->location->x;
575 $deltaZ = $this->location->z - $e->location->z;
576 $this->knockBack($deltaX, $deltaZ, $source->getKnockBack(), $source->getVerticalKnockBackLimit());
580 if($this->isAlive()){
581 $this->doHitAnimation();
585 if($this->isAlive()){
586 $this->applyPostDamageEffects($source);
590 protected function doHitAnimation() : void{
591 $this->broadcastAnimation(new HurtAnimation($this));
594 public function knockBack(
float $x,
float $z,
float $force = self::DEFAULT_KNOCKBACK_FORCE, ?
float $verticalLimit = self::DEFAULT_KNOCKBACK_VERTICAL_LIMIT) : void{
595 $f = sqrt($x * $x + $z * $z);
599 if(mt_rand() / mt_getrandmax() > $this->knockbackResistanceAttr->getValue()){
602 $motionX = $this->motion->x / 2;
603 $motionY = $this->motion->y / 2;
604 $motionZ = $this->motion->z / 2;
605 $motionX += $x * $f * $force;
607 $motionZ += $z * $f * $force;
609 $verticalLimit ??= $force;
610 if($motionY > $verticalLimit){
611 $motionY = $verticalLimit;
614 $this->setMotion(
new Vector3($motionX, $motionY, $motionZ));
619 $ev = new
EntityDeathEvent($this, $this->getDrops(), $this->getXpDropAmount());
621 foreach($ev->getDrops() as $item){
622 $this->getWorld()->dropItem($this->location, $item);
626 $this->getWorld()->dropExperience($this->location, $ev->getXpDropAmount());
628 $this->startDeathAnimation();
632 if($this->deadTicks < $this->maxDeadTicks){
633 $this->deadTicks += $tickDiff;
634 if($this->deadTicks >= $this->maxDeadTicks){
635 $this->endDeathAnimation();
639 return $this->deadTicks >= $this->maxDeadTicks;
642 protected function startDeathAnimation() : void{
643 $this->broadcastAnimation(new DeathAnimation($this));
646 protected function endDeathAnimation() : void{
647 $this->despawnFromAll();
650 protected function entityBaseTick(
int $tickDiff = 1) : bool{
651 Timings::$livingEntityBaseTick->startTiming();
653 $hasUpdate = parent::entityBaseTick($tickDiff);
655 if($this->isAlive()){
656 if($this->effectManager->tick($tickDiff)){
660 if($this->isInsideOfSolid()){
662 $ev =
new EntityDamageEvent($this, EntityDamageEvent::CAUSE_SUFFOCATION, 1);
666 if($this->doAirSupplyTick($tickDiff)){
670 foreach($this->armorInventory->getContents() as $index => $item){
671 $oldItem = clone $item;
672 if($item->onTickWorn($this)){
674 if(!$item->equalsExact($oldItem)){
675 $this->armorInventory->setItem($index, $item);
681 if($this->attackTime > 0){
682 $this->attackTime -= $tickDiff;
685 Timings::$livingEntityBaseTick->stopTiming();
694 $ticks = $this->getAirSupplyTicks();
696 if(!$this->canBreathe()){
697 $this->setBreathing(
false);
699 if(($respirationLevel = $this->armorInventory->getHelmet()->getEnchantmentLevel(VanillaEnchantments::RESPIRATION())) <= 0 ||
700 lcg_value() <= (1 / ($respirationLevel + 1))
705 $this->onAirExpired();
708 }elseif(!$this->isBreathing()){
709 if($ticks < ($max = $this->getMaxAirSupplyTicks())){
710 $ticks += $tickDiff * 5;
714 $this->setBreathing(
true);
718 if($ticks !== $oldTicks){
719 $this->setAirSupplyTicks($ticks);
722 return $ticks !== $oldTicks;
729 return $this->effectManager->has(
VanillaEffects::WATER_BREATHING()) || $this->effectManager->has(
VanillaEffects::CONDUIT_POWER()) || !$this->isUnderwater();
736 return $this->breathing;
744 $this->breathing = $value;
745 $this->networkPropertiesDirty =
true;
753 return $this->breathTicks;
760 $this->breathTicks = $ticks;
761 $this->networkPropertiesDirty =
true;
768 return $this->maxBreathTicks;
775 $this->maxBreathTicks = $ticks;
776 $this->networkPropertiesDirty =
true;
808 public function getLineOfSight(
int $maxDistance,
int $maxLength = 0, array $transparent = []) : array{
809 if($maxDistance > 120){
813 if(count($transparent) === 0){
820 foreach(VoxelRayTrace::inDirection($this->location->add(0, $this->size->getEyeHeight(), 0), $this->getDirectionVector(), $maxDistance) as $vector3){
821 $block = $this->getWorld()->getBlockAt($vector3->x, $vector3->y, $vector3->z);
822 $blocks[$nextIndex++] = $block;
824 if($maxLength !== 0 && count($blocks) > $maxLength){
825 array_shift($blocks);
829 $id = $block->getTypeId();
831 if($transparent ===
null){
832 if($id !== BlockTypeIds::AIR){
836 if(!isset($transparent[$id])){
850 $line = $this->getLineOfSight($maxDistance, 1, $transparent);
851 if(count($line) > 0){
852 return array_shift($line);
863 $horizontal = sqrt(($target->x - $this->location->x) ** 2 + ($target->z - $this->location->z) ** 2);
864 $vertical = $target->y - ($this->location->y + $this->getEyeHeight());
865 $pitch = -atan2($vertical, $horizontal) / M_PI * 180;
867 $xDist = $target->x - $this->location->x;
868 $zDist = $target->z - $this->location->z;
870 $yaw = atan2($zDist, $xDist) / M_PI * 180 - 90;
875 $this->setRotation($yaw, $pitch);
879 parent::sendSpawnPacket($player);
881 $networkSession = $player->getNetworkSession();
882 $networkSession->getEntityEventBroadcaster()->onMobArmorChange([$networkSession], $this);
886 parent::syncNetworkData($properties);
888 $visibleEffects = [];
889 foreach ($this->effectManager->all() as $effect) {
890 if (!$effect->isVisible() || !$effect->getType()->hasBubbles()) {
893 $visibleEffects[EffectIdMap::getInstance()->toId($effect->getType())] = $effect->isAmbient();
897 ksort($visibleEffects, SORT_NUMERIC);
900 $packedEffectsCount = 0;
901 foreach ($visibleEffects as $effectId => $isAmbient) {
902 $effectsData = ($effectsData << 7) |
903 (($effectId & 0x3f) << 1) |
904 ($isAmbient ? 1 : 0);
906 if (++$packedEffectsCount >= 8) {
910 $properties->setLong(EntityMetadataProperties::VISIBLE_MOB_EFFECTS, $effectsData);
912 $properties->setShort(EntityMetadataProperties::AIR, $this->breathTicks);
913 $properties->setShort(EntityMetadataProperties::MAX_AIR, $this->maxBreathTicks);
915 $properties->setGenericFlag(EntityMetadataFlags::BREATHING, $this->breathing);
916 $properties->setGenericFlag(EntityMetadataFlags::SNEAKING, $this->sneaking);
917 $properties->setGenericFlag(EntityMetadataFlags::SPRINTING, $this->sprinting);
918 $properties->setGenericFlag(EntityMetadataFlags::GLIDING, $this->gliding);
919 $properties->setGenericFlag(EntityMetadataFlags::SWIMMING, $this->swimming);
923 $this->armorInventory->removeAllViewers();
924 $this->effectManager->getEffectAddHooks()->clear();
925 $this->effectManager->getEffectRemoveHooks()->clear();
931 $this->armorInventory,
934 parent::destroyCycles();