87 public const MOTION_THRESHOLD = 0.00001;
88 protected const STEP_CLIP_MULTIPLIER = 0.4;
90 private const TAG_FIRE =
"Fire";
91 private const TAG_ON_GROUND =
"OnGround";
92 private const TAG_FALL_DISTANCE =
"FallDistance";
93 private const TAG_CUSTOM_NAME =
"CustomName";
94 private const TAG_CUSTOM_NAME_VISIBLE =
"CustomNameVisible";
95 public const TAG_POS =
"Pos";
96 public const TAG_MOTION =
"Motion";
97 public const TAG_ROTATION =
"Rotation";
99 private static int $entityCount = 1;
105 return self::$entityCount++;
112 protected array $hasSpawned = [];
121 protected ?array $blocksAround =
null;
127 protected bool $forceMovementUpdate =
false;
128 private bool $checkBlockIntersectionsNextTick =
true;
131 public bool $onGround =
false;
135 private float $health = 20.0;
136 private int $maxHealth = 20;
138 protected float $ySize = 0.0;
139 protected float $stepHeight = 0.0;
140 public bool $keepMovement =
false;
142 public float $fallDistance = 0.0;
143 public int $ticksLived = 0;
144 public int $lastUpdate;
145 protected int $fireTicks = 0;
147 private bool $savedWithChunk =
true;
149 public bool $isCollided =
false;
150 public bool $isCollidedHorizontally =
false;
151 public bool $isCollidedVertically =
false;
153 public int $noDamageTicks = 0;
154 protected bool $justCreated =
true;
158 protected float $gravity;
159 protected float $drag;
160 protected bool $gravityEnabled =
true;
164 protected bool $closed =
false;
165 private bool $closeInFlight =
false;
166 private bool $needsDespawn =
false;
170 protected bool $networkPropertiesDirty =
false;
172 protected string $nameTag =
"";
173 protected bool $nameTagVisible =
true;
174 protected bool $alwaysShowNameTag =
false;
175 protected string $scoreTag =
"";
176 protected float $scale = 1.0;
178 protected bool $canClimb =
false;
179 protected bool $canClimbWalls =
false;
180 protected bool $noClientPredictions =
false;
181 protected bool $invisible =
false;
182 protected bool $silent =
false;
184 protected ?
int $ownerId =
null;
185 protected ?
int $targetId =
null;
187 private bool $constructorCalled =
false;
190 if($this->constructorCalled){
191 throw new \LogicException(
"Attempted to call constructor for an Entity multiple times");
193 $this->constructorCalled =
true;
194 Utils::checkLocationNotInfOrNaN($location);
196 $this->timings = Timings::getEntityTimings($this);
198 $this->size = $this->getInitialSizeInfo();
199 $this->drag = $this->getInitialDragMultiplier();
200 $this->gravity = $this->getInitialGravity();
202 $this->
id = self::nextRuntimeId();
207 $this->boundingBox =
new AxisAlignedBB(0, 0, 0, 0, 0, 0);
208 $this->recalculateBoundingBox();
213 $this->motion = Vector3::zero();
216 $this->resetLastMovements();
218 $this->networkProperties =
new EntityMetadataCollection();
220 $this->attributeMap =
new AttributeMap();
221 $this->addAttributes();
223 $this->initEntity($nbt ??
new CompoundTag());
225 $this->getWorld()->addEntity($this);
227 $this->lastUpdate = $this->
server->getTick();
229 $this->scheduleUpdate();
232 abstract protected function getInitialSizeInfo() : EntitySizeInfo;
249 public function getNameTag() : string{
250 return $this->nameTag;
253 public function isNameTagVisible() : bool{
254 return $this->nameTagVisible;
257 public function isNameTagAlwaysVisible() : bool{
258 return $this->alwaysShowNameTag;
269 public function setNameTag(
string $name) : void{
270 $this->nameTag = $name;
271 $this->networkPropertiesDirty =
true;
274 public function setNameTagVisible(
bool $value =
true) : void{
275 $this->nameTagVisible = $value;
276 $this->networkPropertiesDirty =
true;
279 public function setNameTagAlwaysVisible(
bool $value =
true) : void{
280 $this->alwaysShowNameTag = $value;
281 $this->networkPropertiesDirty =
true;
284 public function getScoreTag() : ?string{
285 return $this->scoreTag;
288 public function setScoreTag(
string $score) : void{
289 $this->scoreTag = $score;
290 $this->networkPropertiesDirty =
true;
293 public function getScale() : float{
297 public function setScale(
float $value) : void{
299 throw new \InvalidArgumentException(
"Scale must be greater than 0");
301 $this->scale = $value;
302 $this->setSize($this->getInitialSizeInfo()->scale($value));
305 public function getBoundingBox() : AxisAlignedBB{
306 return $this->boundingBox;
309 protected function recalculateBoundingBox() : void{
310 $halfWidth = $this->size->getWidth() / 2;
312 $this->boundingBox =
new AxisAlignedBB(
313 $this->location->x - $halfWidth,
314 $this->location->y + $this->ySize,
315 $this->location->z - $halfWidth,
316 $this->location->x + $halfWidth,
317 $this->location->y + $this->size->getHeight() + $this->ySize,
318 $this->location->z + $halfWidth
322 public function getSize() : EntitySizeInfo{
326 protected function setSize(EntitySizeInfo $size) : void{
328 $this->recalculateBoundingBox();
329 $this->networkPropertiesDirty =
true;
337 return $this->noClientPredictions;
349 $this->noClientPredictions = $value;
350 $this->networkPropertiesDirty =
true;
353 public function isInvisible() : bool{
354 return $this->invisible;
357 public function setInvisible(
bool $value =
true) : void{
358 $this->invisible = $value;
359 $this->networkPropertiesDirty =
true;
362 public function isSilent() : bool{
363 return $this->silent;
366 public function setSilent(
bool $value =
true) : void{
367 $this->silent = $value;
368 $this->networkPropertiesDirty =
true;
375 return $this->canClimb;
382 $this->canClimb = $value;
383 $this->networkPropertiesDirty =
true;
390 return $this->canClimbWalls;
397 $this->canClimbWalls = $value;
398 $this->networkPropertiesDirty =
true;
405 return $this->ownerId;
412 return $this->ownerId !== null ? $this->
server->getWorldManager()->findEntity($this->ownerId) : null;
422 $this->ownerId =
null;
423 }elseif($owner->closed){
424 throw new \InvalidArgumentException(
"Supplied owning entity is garbage and cannot be used");
426 $this->ownerId = $owner->getId();
428 $this->networkPropertiesDirty =
true;
435 return $this->targetId;
443 return $this->targetId !== null ? $this->
server->getWorldManager()->findEntity($this->targetId) : null;
452 if($target === null){
453 $this->targetId =
null;
454 }elseif($target->closed){
455 throw new \InvalidArgumentException(
"Supplied target entity is garbage and cannot be used");
457 $this->targetId = $target->getId();
459 $this->networkPropertiesDirty =
true;
466 return $this->savedWithChunk;
474 $this->savedWithChunk = $value;
479 ->setTag(self::TAG_POS, new
ListTag([
484 ->setTag(self::TAG_MOTION, new
ListTag([
489 ->setTag(self::TAG_ROTATION, new
ListTag([
491 new
FloatTag($this->location->pitch)
494 if(!($this instanceof
Player)){
495 EntityFactory::getInstance()->injectSaveId(get_class($this), $nbt);
497 if($this->getNameTag() !==
""){
498 $nbt->setString(self::TAG_CUSTOM_NAME, $this->getNameTag());
499 $nbt->setByte(self::TAG_CUSTOM_NAME_VISIBLE, $this->isNameTagVisible() ? 1 : 0);
503 $nbt->
setFloat(self::TAG_FALL_DISTANCE, $this->fallDistance);
504 $nbt->setShort(self::TAG_FIRE, $this->fireTicks);
505 $nbt->setByte(self::TAG_ON_GROUND, $this->onGround ? 1 : 0);
507 $nbt->setLong(VersionInfo::TAG_WORLD_DATA_VERSION, VersionInfo::WORLD_DATA_VERSION);
512 protected function initEntity(CompoundTag $nbt) : void{
513 $this->fireTicks = $nbt->getShort(self::TAG_FIRE, 0);
515 $this->onGround = $nbt->getByte(self::TAG_ON_GROUND, 0) !== 0;
517 $this->fallDistance = $nbt->getFloat(self::TAG_FALL_DISTANCE, 0.0);
519 if(($customNameTag = $nbt->getTag(self::TAG_CUSTOM_NAME)) instanceof StringTag){
520 $this->setNameTag($customNameTag->getValue());
522 if(($customNameVisibleTag = $nbt->getTag(self::TAG_CUSTOM_NAME_VISIBLE)) instanceof StringTag){
524 $this->setNameTagVisible($customNameVisibleTag->getValue() !==
"");
526 $this->setNameTagVisible($nbt->getByte(self::TAG_CUSTOM_NAME_VISIBLE, 1) !== 0);
531 protected function addAttributes() : void{
535 public function attack(EntityDamageEvent $source) : void{
536 if($this->isFireProof() && (
537 $source->getCause() === EntityDamageEvent::CAUSE_FIRE ||
538 $source->getCause() === EntityDamageEvent::CAUSE_FIRE_TICK ||
539 $source->getCause() === EntityDamageEvent::CAUSE_LAVA
545 if($source->isCancelled()){
549 $this->setLastDamageCause($source);
551 $this->setHealth($this->getHealth() - $source->getFinalDamage());
554 public function heal(EntityRegainHealthEvent $source) : void{
556 if($source->isCancelled()){
560 $this->setHealth($this->getHealth() + $source->getAmount());
563 public function kill() : void{
564 if($this->isAlive()){
567 $this->scheduleUpdate();
581 protected function onDeathUpdate(int $tickDiff) : bool{
585 public function isAlive() : bool{
586 return $this->health > 0;
589 public function getHealth() : float{
590 return $this->health;
597 if($amount === $this->health){
602 if($this->isAlive()){
603 if(!$this->justCreated){
609 }elseif($amount <= $this->getMaxHealth() || $amount < $this->health){
610 $this->health = $amount;
612 $this->health = $this->getMaxHealth();
616 public function getMaxHealth() : int{
617 return $this->maxHealth;
620 public function setMaxHealth(
int $amount) : void{
621 $this->maxHealth = $amount;
624 public function setLastDamageCause(EntityDamageEvent $type) : void{
625 $this->lastDamageCause = $type;
628 public function getLastDamageCause() : ?EntityDamageEvent{
629 return $this->lastDamageCause;
632 public function getAttributeMap() : AttributeMap{
633 return $this->attributeMap;
636 public function getNetworkProperties() : EntityMetadataCollection{
637 return $this->networkProperties;
640 protected function entityBaseTick(
int $tickDiff = 1) : bool{
643 if($this->justCreated){
644 $this->justCreated =
false;
645 if(!$this->isAlive()){
650 $changedProperties = $this->getDirtyNetworkData();
651 if(count($changedProperties) > 0){
652 $this->sendData(
null, $changedProperties);
653 $this->networkProperties->clearDirtyProperties();
658 if($this->checkBlockIntersectionsNextTick){
659 $this->checkBlockIntersections();
661 $this->checkBlockIntersectionsNextTick =
true;
663 if($this->location->y <= World::Y_MIN - 16 && $this->isAlive()){
664 $ev =
new EntityDamageEvent($this, EntityDamageEvent::CAUSE_VOID, 10);
669 if($this->isOnFire() && $this->doOnFireTick($tickDiff)){
673 if($this->noDamageTicks > 0){
674 $this->noDamageTicks -= $tickDiff;
675 if($this->noDamageTicks < 0){
676 $this->noDamageTicks = 0;
680 $this->ticksLived += $tickDiff;
685 public function isOnFire() : bool{
686 return $this->fireTicks > 0;
689 public function setOnFire(
int $seconds) : void{
690 $ticks = $seconds * 20;
691 if($ticks > $this->getFireTicks()){
692 $this->setFireTicks($ticks);
694 $this->networkPropertiesDirty =
true;
697 public function getFireTicks() : int{
698 return $this->fireTicks;
706 throw new \InvalidArgumentException(
"Fire ticks cannot be negative");
713 $fireTicks = min($fireTicks, Limits::INT16_MAX);
715 if(!$this->isFireProof()){
716 $this->fireTicks = $fireTicks;
717 $this->networkPropertiesDirty =
true;
721 public function extinguish() : void{
722 $this->fireTicks = 0;
723 $this->networkPropertiesDirty =
true;
726 public function isFireProof() : bool{
730 protected function doOnFireTick(
int $tickDiff = 1) : bool{
731 if($this->isFireProof() && $this->isOnFire()){
736 $this->fireTicks -= $tickDiff;
738 if(($this->fireTicks % 20 === 0) || $tickDiff > 20){
739 $this->dealFireDamage();
742 if(!$this->isOnFire()){
759 public function canCollideWith(
Entity $entity) : bool{
760 return !$this->justCreated && $entity !== $this;
763 public function canBeCollidedWith() : bool{
764 return $this->isAlive();
767 protected function updateMovement(
bool $teleport =
false) : void{
768 $diffPosition = $this->location->distanceSquared($this->lastLocation);
769 $diffRotation = ($this->location->yaw - $this->lastLocation->yaw) ** 2 + ($this->location->pitch - $this->lastLocation->pitch) ** 2;
771 $diffMotion = $this->motion->subtractVector($this->lastMotion)->lengthSquared();
773 $still = $this->motion->lengthSquared() === 0.0;
774 $wasStill = $this->lastMotion->lengthSquared() === 0.0;
775 if($wasStill !== $still){
777 $this->setNoClientPredictions($still);
780 if($teleport || $diffPosition > 0.0001 || $diffRotation > 1.0 || (!$wasStill && $still)){
781 $this->lastLocation = $this->location->asLocation();
783 $this->broadcastMovement($teleport);
786 if($diffMotion > 0.0025 || $wasStill !== $still){
787 $this->lastMotion = clone $this->motion;
789 $this->broadcastMotion();
793 public function getOffsetPosition(Vector3 $vector3) : Vector3{
797 protected function broadcastMovement(
bool $teleport =
false) : void{
798 NetworkBroadcastUtils::broadcastPackets($this->hasSpawned, [MoveActorAbsolutePacket::create(
800 $this->getOffsetPosition($this->location),
801 $this->location->pitch,
802 $this->location->yaw,
803 $this->location->yaw,
810 ($this->onGround ? MoveActorAbsolutePacket::FLAG_GROUND : 0)
815 protected function broadcastMotion() : void{
816 NetworkBroadcastUtils::broadcastPackets($this->hasSpawned, [SetActorMotionPacket::create($this->
id, $this->getMotion(), tick: 0)]);
819 public function getGravity() : float{
820 return $this->gravity;
823 public function setGravity(
float $gravity) : void{
824 Utils::checkFloatNotInfOrNaN(
"gravity", $gravity);
825 $this->gravity = $gravity;
828 public function hasGravity() : bool{
829 return $this->gravityEnabled;
832 public function setHasGravity(
bool $v =
true) : void{
833 $this->gravityEnabled = $v;
836 protected function applyDragBeforeGravity() : bool{
840 protected function tryChangeMovement() : void{
841 $friction = 1 - $this->drag;
843 $mY = $this->motion->y;
845 if($this->applyDragBeforeGravity()){
849 if($this->gravityEnabled){
850 $mY -= $this->gravity;
853 if(!$this->applyDragBeforeGravity()){
858 $friction *= $this->getWorld()->getBlockAt((
int) floor($this->location->x), (
int) floor($this->location->y - 1), (
int) floor($this->location->z))->getFrictionFactor();
861 $this->motion =
new Vector3($this->motion->x * $friction, $mY, $this->motion->z * $friction);
864 protected function checkObstruction(
float $x,
float $y,
float $z) : bool{
865 $world = $this->getWorld();
866 if(count($world->getBlockCollisionBoxes($this->boundingBox)) === 0){
870 $floorX = (
int) floor($x);
871 $floorY = (int) floor($y);
872 $floorZ = (int) floor($z);
874 $diffX = $x - $floorX;
875 $diffY = $y - $floorY;
876 $diffZ = $z - $floorZ;
878 if($world->getBlockAt($floorX, $floorY, $floorZ)->isSolid()){
879 $westNonSolid = !$world->getBlockAt($floorX - 1, $floorY, $floorZ)->isSolid();
880 $eastNonSolid = !$world->getBlockAt($floorX + 1, $floorY, $floorZ)->isSolid();
881 $downNonSolid = !$world->getBlockAt($floorX, $floorY - 1, $floorZ)->isSolid();
882 $upNonSolid = !$world->getBlockAt($floorX, $floorY + 1, $floorZ)->isSolid();
883 $northNonSolid = !$world->getBlockAt($floorX, $floorY, $floorZ - 1)->isSolid();
884 $southNonSolid = !$world->getBlockAt($floorX, $floorY, $floorZ + 1)->isSolid();
891 $direction = Facing::WEST;
894 if($eastNonSolid && 1 - $diffX < $limit){
896 $direction = Facing::EAST;
899 if($downNonSolid && $diffY < $limit){
901 $direction = Facing::DOWN;
904 if($upNonSolid && 1 - $diffY < $limit){
906 $direction = Facing::UP;
909 if($northNonSolid && $diffZ < $limit){
911 $direction = Facing::NORTH;
914 if($southNonSolid && 1 - $diffZ < $limit){
915 $direction = Facing::SOUTH;
918 if($direction === -1){
922 $force = Utils::getRandomFloat() * 0.2 + 0.1;
924 $this->motion = match($direction){
925 Facing::WEST => $this->motion->withComponents(-$force,
null,
null),
926 Facing::EAST => $this->motion->withComponents($force,
null,
null),
927 Facing::DOWN => $this->motion->withComponents(
null, -$force,
null),
928 Facing::UP => $this->motion->withComponents(
null, $force,
null),
929 Facing::NORTH => $this->motion->withComponents(
null,
null, -$force),
930 Facing::SOUTH => $this->motion->withComponents(
null,
null, $force),
938 public function getHorizontalFacing() : int{
939 $angle = fmod($this->location->yaw, 360);
944 if((0 <= $angle && $angle < 45) || (315 <= $angle && $angle < 360)){
945 return Facing::SOUTH;
947 if(45 <= $angle && $angle < 135){
950 if(135 <= $angle && $angle < 225){
951 return Facing::NORTH;
957 public function getDirectionVector() : Vector3{
958 $y = -sin(deg2rad($this->location->pitch));
959 $xz = cos(deg2rad($this->location->pitch));
960 $x = -$xz * sin(deg2rad($this->location->yaw));
961 $z = $xz * cos(deg2rad($this->location->yaw));
963 return (
new Vector3($x, $y, $z))->normalize();
966 public function getDirectionPlane() : Vector2{
967 return (new Vector2(-cos(deg2rad($this->location->yaw) - M_PI_2), -sin(deg2rad($this->location->yaw) - M_PI_2)))->normalize();
978 public function onUpdate(
int $currentTick) : bool{
983 $tickDiff = $currentTick - $this->lastUpdate;
985 if(!$this->justCreated){
986 $this->
server->getLogger()->debug(
"Expected tick difference of at least 1, got $tickDiff for " . get_class($this));
992 $this->lastUpdate = $currentTick;
994 if($this->justCreated){
995 $this->onFirstUpdate($currentTick);
998 if(!$this->isAlive()){
999 if($this->onDeathUpdate($tickDiff)){
1000 $this->flagForDespawn();
1006 $this->timings->startTiming();
1008 if($this->hasMovementUpdate()){
1009 $this->tryChangeMovement();
1011 $this->motion = $this->motion->withComponents(
1012 abs($this->motion->x) <= self::MOTION_THRESHOLD ? 0 :
null,
1013 abs($this->motion->y) <= self::MOTION_THRESHOLD ? 0 :
null,
1014 abs($this->motion->z) <= self::MOTION_THRESHOLD ? 0 :
null
1017 if(floatval($this->motion->x) !== 0.0 || floatval($this->motion->y) !== 0.0 || floatval($this->motion->z) !== 0.0){
1018 $this->move($this->motion->x, $this->motion->y, $this->motion->z);
1021 $this->forceMovementUpdate =
false;
1024 $this->updateMovement();
1026 Timings::$entityBaseTick->startTiming();
1027 $hasUpdate = $this->entityBaseTick($tickDiff);
1028 Timings::$entityBaseTick->stopTiming();
1030 $this->timings->stopTiming();
1032 return ($hasUpdate || $this->hasMovementUpdate());
1035 final public function scheduleUpdate() : void{
1037 throw new \LogicException(
"Cannot schedule update on garbage entity " . get_class($this));
1039 $this->getWorld()->updateEntities[$this->id] = $this;
1042 public function onNearbyBlockChange() : void{
1043 $this->setForceMovementUpdate();
1044 $this->scheduleUpdate();
1052 $this->scheduleUpdate();
1060 $this->forceMovementUpdate = $value;
1062 $this->blocksAround =
null;
1070 $this->forceMovementUpdate ||
1071 floatval($this->motion->x) !== 0.0 ||
1072 floatval($this->motion->y) !== 0.0 ||
1073 floatval($this->motion->z) !== 0.0 ||
1078 public function getFallDistance() : float{ return $this->fallDistance; }
1080 public function setFallDistance(
float $fallDistance) : void{
1081 $this->fallDistance = $fallDistance;
1084 public function resetFallDistance() : void{
1085 $this->fallDistance = 0.0;
1088 protected function updateFallState(
float $distanceThisTick,
bool $onGround) : ?float{
1089 if($distanceThisTick < $this->fallDistance){
1092 $this->fallDistance -= $distanceThisTick;
1096 $this->fallDistance = 0;
1098 if($onGround && $this->fallDistance > 0){
1099 $newVerticalVelocity = $this->onHitGround();
1100 $this->resetFallDistance();
1101 return $newVerticalVelocity;
1113 public function getEyeHeight() : float{
1114 return $this->size->getEyeHeight();
1117 public function getEyePos() : Vector3{
1118 return new Vector3($this->location->x, $this->location->y + $this->getEyeHeight(), $this->location->z);
1121 public function onCollideWithPlayer(Player $player) : void{
1132 public function isUnderwater() : bool{
1133 $block = $this->getWorld()->getBlockAt((int) floor($this->location->x), $blockY = (int) floor($y = ($this->location->y + $this->getEyeHeight())), (int) floor($this->location->z));
1135 if($block instanceof
Water){
1136 $f = ($blockY + 1) - ($block->getFluidHeightPercent() - 0.1111111);
1143 public function isInsideOfSolid() : bool{
1144 $block = $this->getWorld()->getBlockAt((int) floor($this->location->x), (int) floor($y = ($this->location->y + $this->getEyeHeight())), (int) floor($this->location->z));
1146 return $block->isSolid() && !$block->isTransparent() && $block->collidesWithBB($this->getBoundingBox());
1149 protected function move(
float $dx,
float $dy,
float $dz) : void{
1150 $this->blocksAround = null;
1152 Timings::$entityMove->startTiming();
1153 Timings::$entityMoveCollision->startTiming();
1159 if($this->keepMovement){
1160 $this->boundingBox->offset($dx, $dy, $dz);
1162 $this->ySize *= self::STEP_CLIP_MULTIPLIER;
1164 $moveBB = clone $this->boundingBox;
1166 assert(abs($dx) <= 20 && abs($dy) <= 20 && abs($dz) <= 20,
"Movement distance is excessive: dx=$dx, dy=$dy, dz=$dz");
1168 $list = $this->getWorld()->getBlockCollisionBoxes($moveBB->addCoord($dx, $dy, $dz));
1170 foreach($list as $bb){
1171 $dy = $bb->calculateYOffset($moveBB, $dy);
1174 $moveBB->offset(0, $dy, 0);
1176 $fallingFlag = ($this->onGround || ($dy !== $wantedY && $wantedY < 0));
1178 foreach($list as $bb){
1179 $dx = $bb->calculateXOffset($moveBB, $dx);
1182 $moveBB->offset($dx, 0, 0);
1184 foreach($list as $bb){
1185 $dz = $bb->calculateZOffset($moveBB, $dz);
1188 $moveBB->offset(0, 0, $dz);
1190 if($this->stepHeight > 0 && $fallingFlag && ($wantedX !== $dx || $wantedZ !== $dz)){
1195 $dy = $this->stepHeight;
1198 $stepBB = clone $this->boundingBox;
1200 $list = $this->getWorld()->getBlockCollisionBoxes($stepBB->addCoord($dx, $dy, $dz));
1201 foreach($list as $bb){
1202 $dy = $bb->calculateYOffset($stepBB, $dy);
1205 $stepBB->offset(0, $dy, 0);
1207 foreach($list as $bb){
1208 $dx = $bb->calculateXOffset($stepBB, $dx);
1211 $stepBB->offset($dx, 0, 0);
1213 foreach($list as $bb){
1214 $dz = $bb->calculateZOffset($stepBB, $dz);
1217 $stepBB->offset(0, 0, $dz);
1220 foreach($list as $bb){
1221 $reverseDY = $bb->calculateYOffset($stepBB, $reverseDY);
1224 $stepBB->offset(0, $reverseDY, 0);
1226 if(($cx ** 2 + $cz ** 2) >= ($dx ** 2 + $dz ** 2)){
1232 $this->ySize += $dy;
1236 $this->boundingBox = $moveBB;
1238 Timings::$entityMoveCollision->stopTiming();
1240 $this->location =
new Location(
1241 ($this->boundingBox->minX + $this->boundingBox->maxX) / 2,
1242 $this->boundingBox->minY - $this->ySize,
1243 ($this->boundingBox->minZ + $this->boundingBox->maxZ) / 2,
1244 $this->location->world,
1245 $this->location->yaw,
1246 $this->location->pitch
1249 $this->getWorld()->onEntityMoved($this);
1250 $this->checkBlockIntersections();
1251 $this->checkGroundState($wantedX, $wantedY, $wantedZ, $dx, $dy, $dz);
1252 $postFallVerticalVelocity = $this->updateFallState($dy, $this->onGround);
1254 $this->motion = $this->motion->withComponents(
1255 $wantedX !== $dx ? 0 :
null,
1256 $postFallVerticalVelocity ?? ($wantedY !== $dy ? 0 :
null),
1257 $wantedZ !== $dz ? 0 :
null
1262 Timings::$entityMove->stopTiming();
1265 protected function checkGroundState(
float $wantedX,
float $wantedY,
float $wantedZ,
float $dx,
float $dy,
float $dz) : void{
1266 $this->isCollidedVertically = $wantedY !== $dy;
1267 $this->isCollidedHorizontally = ($wantedX !== $dx || $wantedZ !== $dz);
1268 $this->isCollided = ($this->isCollidedHorizontally || $this->isCollidedVertically);
1269 $this->onGround = ($wantedY !== $dy && $wantedY < 0);
1278 $minX = (int) floor($this->boundingBox->minX + $inset);
1279 $minY = (int) floor($this->boundingBox->minY + $inset);
1280 $minZ = (int) floor($this->boundingBox->minZ + $inset);
1281 $maxX = (int) floor($this->boundingBox->maxX - $inset);
1282 $maxY = (int) floor($this->boundingBox->maxY - $inset);
1283 $maxZ = (int) floor($this->boundingBox->maxZ - $inset);
1285 $world = $this->getWorld();
1287 for($z = $minZ; $z <= $maxZ; ++$z){
1288 for($x = $minX; $x <= $maxX; ++$x){
1289 for($y = $minY; $y <= $maxY; ++$y){
1290 yield $world->getBlockAt($x, $y, $z);
1300 if($this->blocksAround === null){
1301 $this->blocksAround = [];
1304 foreach($this->getBlocksIntersected($inset) as $block){
1305 if($block->hasEntityCollision()){
1306 $this->blocksAround[] = $block;
1311 return $this->blocksAround;
1321 protected function checkBlockIntersections() : void{
1322 $this->checkBlockIntersectionsNextTick = false;
1325 foreach($this->getBlocksAroundWithEntityInsideActions() as $block){
1326 if(!$block->onEntityInside($this)){
1327 $this->blocksAround =
null;
1329 if(($v = $block->addVelocityToEntity($this)) !==
null){
1334 if(count($vectors) > 0){
1335 $vector = Vector3::sum(...$vectors);
1336 if($vector->lengthSquared() > 0){
1338 $this->motion = $this->motion->addVector($vector->normalize()->multiply($d));
1344 return $this->location->asPosition();
1347 public function getLocation() : Location{
1348 return $this->location->asLocation();
1351 public function getWorld() : World{
1352 return $this->location->getWorld();
1355 protected function setPosition(Vector3 $pos) : bool{
1360 $oldWorld = $this->getWorld();
1361 $newWorld = $pos instanceof Position ? $pos->getWorld() : $oldWorld;
1362 if($oldWorld !== $newWorld){
1363 $this->despawnFromAll();
1364 $oldWorld->removeEntity($this);
1367 $this->location = Location::fromObject(
1370 $this->location->yaw,
1371 $this->location->pitch
1374 $this->recalculateBoundingBox();
1376 $this->blocksAround =
null;
1378 if($oldWorld !== $newWorld){
1379 $newWorld->addEntity($this);
1381 $newWorld->onEntityMoved($this);
1387 public function setRotation(
float $yaw,
float $pitch) : void{
1388 Utils::checkFloatNotInfOrNaN(
"yaw", $yaw);
1389 Utils::checkFloatNotInfOrNaN(
"pitch", $pitch);
1390 $this->location->yaw = $yaw;
1391 $this->location->pitch = $pitch;
1392 $this->scheduleUpdate();
1395 protected function setPositionAndRotation(Vector3 $pos,
float $yaw,
float $pitch) : bool{
1396 if($this->setPosition($pos)){
1397 $this->setRotation($yaw, $pitch);
1405 protected function resetLastMovements() : void{
1406 $this->lastLocation = $this->location->asLocation();
1407 $this->lastMotion = clone $this->motion;
1410 public function getMotion() : Vector3{
1411 return clone $this->motion;
1414 public function setMotion(Vector3 $motion) : bool{
1415 Utils::checkVector3NotInfOrNaN($motion);
1416 if(!$this->justCreated){
1417 $ev =
new EntityMotionEvent($this, $motion);
1419 if($ev->isCancelled()){
1424 $this->motion = clone $motion;
1426 if(!$this->justCreated){
1427 $this->updateMovement();
1436 public function addMotion(
float $x,
float $y,
float $z) : void{
1437 Utils::checkFloatNotInfOrNaN(
"x", $x);
1438 Utils::checkFloatNotInfOrNaN(
"y", $y);
1439 Utils::checkFloatNotInfOrNaN(
"z", $z);
1440 $this->motion = $this->motion->add($x, $y, $z);
1443 public function isOnGround() : bool{
1444 return $this->onGround;
1451 Utils::checkVector3NotInfOrNaN($pos);
1453 $yaw = $yaw ?? $pos->yaw;
1454 $pitch = $pitch ?? $pos->pitch;
1457 Utils::checkFloatNotInfOrNaN(
"yaw", $yaw);
1459 if($pitch !==
null){
1460 Utils::checkFloatNotInfOrNaN(
"pitch", $pitch);
1463 $from = $this->location->asPosition();
1464 $to = Position::fromObject($pos, $pos instanceof Position ? $pos->getWorld() : $this->getWorld());
1465 $ev =
new EntityTeleportEvent($this, $from, $to);
1467 if($ev->isCancelled()){
1471 $pos = $ev->getTo();
1473 $this->setMotion(
new Vector3(0, 0, 0));
1474 if($this->setPositionAndRotation($pos, $yaw ?? $this->location->yaw, $pitch ?? $this->location->pitch)){
1475 $this->resetFallDistance();
1476 $this->setForceMovementUpdate();
1478 $this->updateMovement(
true);
1486 public function getId() : int{
1494 return $this->hasSpawned;
1497 abstract public static function getNetworkTypeId() : string;
1503 $player->getNetworkSession()->sendDataPacket(
AddActorPacket::create(
1506 static::getNetworkTypeId(),
1507 $this->getOffsetPosition($this->location->asVector3()),
1509 $this->location->pitch,
1510 $this->location->yaw,
1511 $this->location->yaw,
1512 $this->location->yaw,
1513 array_map(function(
Attribute $attr) : NetworkAttribute{
1514 return new NetworkAttribute($attr->getId(), $attr->getMinValue(), $attr->getMaxValue(), $attr->getValue(), $attr->getDefaultValue(), []);
1515 }, $this->attributeMap->getAll()),
1516 $this->getAllNetworkData(),
1522 public function spawnTo(
Player $player) : void{
1523 $id = spl_object_id($player);
1527 if(!isset($this->hasSpawned[$id]) && $player->getWorld() === $this->getWorld() && $player->
hasReceivedChunk($this->location->getFloorX() >> Chunk::COORD_BIT_SIZE, $this->location->getFloorZ() >> Chunk::COORD_BIT_SIZE)){
1528 $this->hasSpawned[$id] = $player;
1530 $this->sendSpawnPacket($player);
1534 public function spawnToAll() : void{
1538 foreach($this->getWorld()->getViewersForPosition($this->location) as $player){
1539 $this->spawnTo($player);
1543 public function respawnToAll() : void{
1544 foreach($this->hasSpawned as $key => $player){
1545 unset($this->hasSpawned[$key]);
1546 $this->spawnTo($player);
1555 $id = spl_object_id($player);
1556 if(isset($this->hasSpawned[$id])){
1558 $player->getNetworkSession()->getEntityEventBroadcaster()->onEntityRemoved([$player->getNetworkSession()], $this);
1560 unset($this->hasSpawned[$id]);
1571 fn(
EntityEventBroadcaster $broadcaster, array $recipients) => $broadcaster->onEntityRemoved($recipients, $this)
1573 $this->hasSpawned = [];
1587 $this->needsDespawn = true;
1588 $this->scheduleUpdate();
1591 public function isFlaggedForDespawn() : bool{
1592 return $this->needsDespawn;
1599 return $this->closed;
1608 if($this->closeInFlight){
1613 $this->closeInFlight =
true;
1617 $this->closed =
true;
1618 $this->destroyCycles();
1619 $this->closeInFlight =
false;
1628 $this->despawnFromAll();
1629 if($this->location->isValid()){
1630 $this->getWorld()->removeEntity($this);
1641 $this->lastDamageCause = null;
1650 public function sendData(?array $targets, ?array $data =
null) : void{
1651 $targets = $targets ?? $this->hasSpawned;
1652 $data = $data ?? $this->getAllNetworkData();
1654 NetworkBroadcastUtils::broadcastEntityEvent($targets, fn(
EntityEventBroadcaster $broadcaster, array $recipients) => $broadcaster->
syncActorData($recipients, $this, $data));
1662 if($this->networkPropertiesDirty){
1663 $this->syncNetworkData($this->networkProperties);
1664 $this->networkPropertiesDirty =
false;
1666 return $this->networkProperties->getDirty();
1674 if($this->networkPropertiesDirty){
1675 $this->syncNetworkData($this->networkProperties);
1676 $this->networkPropertiesDirty =
false;
1678 return $this->networkProperties->getAll();
1681 protected function syncNetworkData(EntityMetadataCollection $properties) : void{
1682 $properties->setByte(EntityMetadataProperties::ALWAYS_SHOW_NAMETAG, $this->alwaysShowNameTag ? 1 : 0);
1683 $properties->setFloat(EntityMetadataProperties::BOUNDING_BOX_HEIGHT, $this->size->getHeight() / $this->scale);
1684 $properties->setFloat(EntityMetadataProperties::BOUNDING_BOX_WIDTH, $this->size->getWidth() / $this->scale);
1685 $properties->setFloat(EntityMetadataProperties::SCALE, $this->scale);
1686 $properties->setLong(EntityMetadataProperties::LEAD_HOLDER_EID, -1);
1687 $properties->setLong(EntityMetadataProperties::OWNER_EID, $this->ownerId ?? -1);
1688 $properties->setLong(EntityMetadataProperties::TARGET_EID, $this->targetId ?? 0);
1689 $properties->setString(EntityMetadataProperties::NAMETAG, $this->nameTag);
1690 $properties->setString(EntityMetadataProperties::SCORE_TAG, $this->scoreTag);
1691 $properties->setByte(EntityMetadataProperties::COLOR, 0);
1693 $properties->setGenericFlag(EntityMetadataFlags::AFFECTED_BY_GRAVITY, $this->gravityEnabled);
1694 $properties->setGenericFlag(EntityMetadataFlags::CAN_CLIMB, $this->canClimb);
1695 $properties->setGenericFlag(EntityMetadataFlags::CAN_SHOW_NAMETAG, $this->nameTagVisible);
1696 $properties->setGenericFlag(EntityMetadataFlags::HAS_COLLISION,
true);
1697 $properties->setGenericFlag(EntityMetadataFlags::NO_AI, $this->noClientPredictions);
1698 $properties->setGenericFlag(EntityMetadataFlags::INVISIBLE, $this->invisible);
1699 $properties->setGenericFlag(EntityMetadataFlags::SILENT, $this->silent);
1700 $properties->setGenericFlag(EntityMetadataFlags::ONFIRE, $this->isOnFire());
1701 $properties->setGenericFlag(EntityMetadataFlags::WALLCLIMBING, $this->canClimbWalls);
1717 $this->getWorld()->addSound($this->location->asVector3(), $sound, $targets ?? $this->getViewers());
1721 public function __destruct(){
1725 public function __toString(){
1726 return (
new \ReflectionClass($this))->getShortName() .
"(" . $this->getId() .
")";