0x0F S0FPacketSpawnMob
Spawns a living entity (mob/animal/monster) with entity type, position, rotation, velocity, and metadata.
Published 2026-06-18 · Updated 2026-10-14
Fields
| Field | Type | Description |
|---|---|---|
| entityId | VarInt | Entity ID |
| type | unsigned byte | Mob type (50=creeper, 51=skeleton, 52=spider, 54=zombie, etc.) |
| x/y/z | fixed-point int | Position × 32 |
| yaw/pitch/headYaw | byte | Rotations × 256/360 |
| velocityX/Y/Z | short | Velocity × 8000 |
| metadata | DataWatcher | Entity data watcher |
Wire Encoding
| Field | Type | Notes |
|---|---|---|
| Entity ID | VarInt | |
| Type | Unsigned Byte | EntityList ID |
| X | Int | x * 32 |
| Y | Int | y * 32 |
| Z | Int | z * 32 |
| Yaw | byte | yaw * 256/360 |
| Pitch | byte | pitch * 256/360 |
| Head Pitch | byte | headYaw * 256/360 |
| Velocity X | short | |
| Velocity Y | short | |
| Velocity Z | short | |
| Metadata | DataWatcher |
MCP References
NetHandlerPlayClient.handleSpawnMob()Handler Interface
INetHandlerPlayClientNotes
Vanilla Source
| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | |
| 18 | |
| 19 | |
| 20 | |
| 21 | |
| 22 | |
| 23 | |
| 24 | |
| 25 | |
| 26 | |
| 27 | |
| 28 | |
| 29 | |
| 30 | |
| 31 | |
| 32 | |
| 33 | |
| 34 | |
| 35 | |
| 36 | |
| 37 | |
| 38 | |
| 39 | |
| 40 | |
| 41 | |
| 42 | |
| 43 | |
| 44 | |
| 45 | |
| 46 | |
| 47 | |
| 48 | |
| 49 | |
| 50 | |
| 51 | |
| 52 | |
| 53 | |
| 54 | |
| 55 | |
| 56 | |
| 57 | |
| 58 | |
| 59 | |
| 60 | |
| 61 | |
| 62 | |
| 63 | |
| 64 | |
| 65 | |
| 66 | |
| 67 | |
| 68 | |
| 69 | |
| 70 | |
| 71 | |
| 72 | |
| 73 | |
| 74 | |
| 75 | |
| 76 | |
| 77 | |
| 78 | |
| 79 | |
| 80 | |
| 81 | |
| 82 | |
| 83 | |
| 84 | |
| 85 | |
| 86 | |
| 87 | |
| 88 | |
| 89 | |
| 90 | |
| 91 | |
| 92 | |
| 93 | |
| 94 | |
| 95 | |
| 96 | |
| 97 | |
| 98 | |
| 99 | |
| 100 | |
| 101 | |
| 102 | |
| 103 | |
| 104 | |
| 105 | |
| 106 | |
| 107 | |
| 108 | |
| 109 | |
| 110 | |
| 111 | |
| 112 | |
| 113 | |
| 114 | |
| 115 | |
| 116 | |
| 117 | |
| 118 | |
| 119 | |
| 120 | |
| 121 | |
| 122 | |
| 123 | |
| 124 | |
| 125 | |
| 126 | |
| 127 | |
| 128 | |
| 129 | |
| 130 | |
| 131 | |
| 132 | |
| 133 | |
| 134 | |
| 135 | |
| 136 | |
| 137 | |
| 138 | |
| 139 | |
| 140 | |
| 141 | |
| 142 | |
| 143 | |
| 144 | |
| 145 | |
| 146 | |
| 147 | |
| 148 | |
| 149 | |
| 150 | |
| 151 | |
| 152 | |
| 153 | |
| 154 | |
| 155 | |
| 156 | |
| 157 | |
| 158 | |
| 159 | |
| 160 | |
| 161 | |
| 162 | |
| 163 | |
| 164 | |
| 165 | |
| 166 | |
| 167 | |
| 168 | |
| 169 | |
| 170 | |
| 171 | |
| 172 | |
| 173 | |
| 174 | |
| 175 | |
| 176 | |
| 177 | |
| 178 | |
| 179 | |
| 180 | |
| 181 | |
| 182 | |
| 183 | |
| 184 | |
| 185 | |
| 186 | |
| 187 | |
| 188 | |
| 189 | |
| 190 | |
| 191 | |
| 192 | |
| 193 | |
| 194 | |
Deobfuscated MCP 1.8.9 source of S0FPacketSpawnMob, fetched directly from Marcelektro/MavenMCP-1.8.9 (net/minecraft/network/play/server/S0FPacketSpawnMob.java) at build time and verified present.
Deep Dive
Role in the protocol
The living-entity counterpart of S0E: mobs, animals and monsters spawn through S0F instead of S0E. EntityTrackerEntry.getPacket returns it for every EntityLivingBase; the payload carries the entity id, the EntityList type code (50=creeper up through 120=villager), fixed-point position (x32), yaw/pitch/head rotations (x256/360), velocity shorts (x8000) and a full DataWatcher block. The metadata is what renders health, potion effects and nametags without follow-up packets, which makes S0F one of the heaviest spawn packets on the wire.
Vanilla handling
handleSpawnMob creates the living entity through EntityList.createEntityByID, sets position and rotations, applies the velocity and reads the DataWatcher. Server side, EntityTrackerEntry deliberately suppresses the velocity-update packet on the spawn tick: the sendVelocityUpdates branch skips entities that just arrived via S0F because the spawn packet already carries the initial motion, avoiding a redundant S12 immediately after spawn.
Why clients touch it
No user-facing module in the 8 clients references S0F. Mob ESP, KillAura target lists and Tracers here iterate the loaded entity list each render frame rather than hooking spawn packets, so they consume the spawned EntityLivingBase objects after vanilla handling instead of the packet itself. The only non-vanilla client code is Rise's TranslationComponent (the PacketType enum's SPAWN_MOB entry decodes the fixed-point coordinates into the entity-position map used by the Translation bypass) and the NetworkAPI script registry listing the class.
Exploit surface
The DataWatcher is the attack surface: a crafted metadata block can declare absurd health, invisible flags or armor values, and mob spawn floods are the classic lag vector. The type byte is unvalidated by the client, so a proxy-crafted id despawns the entity silently. For bypass engineering the interesting property is that S0F is the only clientbound packet that fully defines an entity's state at once, which is why the Translation component hooks it: rewriting the spawn position desyncs the client's rendering from the server's simulation without emitting a single movement packet.
Server-Side Handling
EntityTrackerEntry.getPacket returns new S0FPacketSpawnMob((EntityLivingBase) trackedEntity) for any tracked living entity, and the sendVelocityUpdates branch skips S12 on the same tick the mob spawns because the spawn packet already carries initial velocity. The packet constructor snapshots position, rotations, velocity and the full DataWatcher at tracking time. The client handler reverses this: create entity, set transform, apply motion, read metadata.
Protocol Analysis
Same fixed-point layout as S0E: VarInt entity id, unsigned byte type, three x32 ints, three rotation bytes, three x8000 velocity shorts, then the DataWatcher block which is mandatory for living entities and can run to dozens of bytes. Because the type id is the EntityList id and not the entity class, the client must have a matching entity registry or the spawn is dropped.
Anti-Cheat Landscape
Anti-cheats use S0F as a state anchor: knockback checks know the mob's spawn velocity, and bot-detection heuristics on some servers correlate S0F rate with chunk activity. The Translation-style spawn repositioning is a rendering-layer desync, invisible to server-side movement checks but detectable by servers that verify client-reported entity positions. No reference client ships a module that abuses it; the corpus hit is purely the component infrastructure.
implementation Implementation Cases
The spawn packet for every living mob, carrying a full DataWatcher. No module in the 8 clients hooks it: ESP and KillAura read the world entity list instead. The one piece of real client code is Rise's TranslationComponent, whose PacketType enum decodes S0F spawn coordinates into the position map that powers its spawn-repositioning bypass.
Decode S0F spawn coordinates and rotations into the entity-position map that the Translation bypass feeds on.
PacketType is an enum registry consumed by TranslationComponent on every PacketReceiveEvent: the SPAWN_MOB entry casts to S0FPacketSpawnMob, converts x32 ints to doubles and x256/360 bytes to floats, and stores a Position in the entityPositions map keyed by entity id. Subsequent S14/S18 packets update the same map, and S13 removes entries.
// ===== FILE: Rise 6.2.4, Client-release2/Client/src/main/java/com/alan/clients/component/impl/player/translation/PacketType.java =====
package com.alan.clients.component.impl.player.translation;
import lombok.Getter;
import net.minecraft.network.Packet;
import net.minecraft.network.play.server.*;
import java.util.Map;
import java.util.function.BiFunction;
public enum PacketType {
SPAWN_MOB(S0FPacketSpawnMob.class, (packet, entityPositions) -> {
S0FPacketSpawnMob spawnMobPacket = (S0FPacketSpawnMob) packet;
int entityId = spawnMobPacket.getEntityID();
double posX = spawnMobPacket.getX() / 32.0;
double posY = spawnMobPacket.getY() / 32.0;
double posZ = spawnMobPacket.getZ() / 32.0;
float yaw = (spawnMobPacket.getYaw() * 360) / 256.0F;
float pitch = (spawnMobPacket.getPitch() * 360) / 256.0F;
Position newPosition = new Position(posX, posY, posZ, yaw, pitch);
entityPositions.put(entityId, newPosition);
return entityPositions;
}),
ENTITY_TELEPORT(S18PacketEntityTeleport.class, (packet, entityPositions) -> {
S18PacketEntityTeleport teleportPacket = (S18PacketEntityTeleport) packet;
int entityId = teleportPacket.getEntityId();
double posX = teleportPacket.getX() / 32.0;
double posY = teleportPacket.getY() / 32.0;
double posZ = teleportPacket.getZ() / 32.0;
float yaw = (teleportPacket.getYaw() * 360) / 256.0F;
float pitch = (teleportPacket.getPitch() * 360) / 256.0F;
Position newPosition = new Position(posX, posY, posZ, yaw, pitch);
entityPositions.put(entityId, newPosition);
return entityPositions;
}),
ENTITY_REL_MOVE(S14PacketEntity.S15PacketEntityRelMove.class, (packet, entityPositions) -> {
S14PacketEntity.S15PacketEntityRelMove relMovePacket = (S14PacketEntity.S15PacketEntityRelMove) packet;
int entityId = relMovePacket.entityId;
Position currentPosition = entityPositions.get(entityId);
if (currentPosition != null) {
double newPosX = currentPosition.posX + relMovePacket.getPosX() / 32.0;
double newPosY = currentPosition.posY + relMovePacket.getPosY() / 32.0;
double newPosZ = currentPosition.posZ + relMovePacket.getPosZ() / 32.0;
float yaw = currentPosition.yaw;
float pitch = currentPosition.pitch;
Position newPosition = new Position(newPosX, newPosY, newPosZ, yaw, pitch);
entityPositions.put(entityId, newPosition);
return entityPositions;
}
return null;
}),
ENTITY_LOOK_MOVE(S14PacketEntity.S17PacketEntityLookMove.class, (packet, entityPositions) -> {
S14PacketEntity.S17PacketEntityLookMove lookMovePacket = (S14PacketEntity.S17PacketEntityLookMove) packet;
int entityId = lookMovePacket.getEntityId();
double deltaX = lookMovePacket.getPosX() / 32.0;
double deltaY = lookMovePacket.getPosY() / 32.0;
double deltaZ = lookMovePacket.getPosZ() / 32.0;
float yaw = (lookMovePacket.getYaw() * 360) / 256.0F;
float pitch = (lookMovePacket.getPitch() * 360) / 256.0F;
Position currentPosition = entityPositions.get(entityId);
if (currentPosition != null) {
double newPosX = currentPosition.posX + deltaX;
double newPosY = currentPosition.posY + deltaY;
double newPosZ = currentPosition.posZ + deltaZ;
// Ensure yaw and pitch are updated
Position newPosition = new Position(newPosX, newPosY, newPosZ, yaw, pitch);
entityPositions.put(entityId, newPosition);
return entityPositions;
}
return null;
}),
ENTITY_LOOK(S14PacketEntity.S16PacketEntityLook.class, (packet, entityPositions) -> {
S14PacketEntity.S16PacketEntityLook lookPacket = (S14PacketEntity.S16PacketEntityLook) packet;
int entityId = lookPacket.getEntityId();
float yaw = (lookPacket.getYaw() * 360) / 256.0F;
float pitch = (lookPacket.getPitch() * 360) / 256.0F;
Position currentPosition = entityPositions.get(entityId);
if (currentPosition != null) {
Position newPosition = new Position(currentPosition.posX, currentPosition.posY, currentPosition.posZ, yaw, pitch);
entityPositions.put(entityId, newPosition);
return entityPositions;
}
return null;
}),
DESTROY_ENTITY(S13PacketDestroyEntities.class, (packet, entityPositions) -> {
S13PacketDestroyEntities destroyEntitiesPacket = (S13PacketDestroyEntities) packet;
int[] entityIds = destroyEntitiesPacket.getEntityIDs();
for (int entityId : entityIds) {
entityPositions.remove(entityId);
}
return entityPositions;
}),
ENTITY_HEAD_LOOK(S19PacketEntityHeadLook.class, (packet, entityPositions) -> {
S19PacketEntityHeadLook headLookPacket = (S19PacketEntityHeadLook) packet;
int entityId = headLookPacket.getEntityId();
float headYaw = (headLookPacket.getYaw() * 360) / 256.0F;
Position currentPosition = entityPositions.get(entityId);
if (currentPosition != null) {
Position newPosition = new Position(currentPosition.posX, currentPosition.posY, currentPosition.posZ, headYaw, currentPosition.pitch);
entityPositions.put(entityId, newPosition);
return entityPositions;
}
return null;
});
@Getter
private final Class<? extends Packet<?>> packetClass;
private final BiFunction<Packet<?>, Map<Integer, Position>, Map<Integer, Position>> handler;
PacketType(Class<? extends Packet<?>> packetClass, BiFunction<Packet<?>, Map<Integer, Position>, Map<Integer, Position>> handler) {
this.packetClass = packetClass;
this.handler = handler;
}
public Map<Integer, Position> handle(Packet<?> packet, Map<Integer, Position> positions) {
return handler.apply(packet, positions);
}
}
// NOTE (AI): The TranslationComponent packet registry. SPAWN_MOB decodes the fixed-point spawn coordinates (x32) and byte rotations (x256/360) into the entityPositions map that the Translation bypass feeds on, so the client keeps its own copy of every mob's server-side position. DESTROY_ENTITY removes entries when S13 arrives, and the same enum covers S18 teleport, S14 relative moves and looks, and S19 head look.anticheat Anti-Cheat Checks
The living-entity spawn packet carries the full state of a mob: type, position, rotations, velocity and the DataWatcher. Anticheats consume it on the send side to learn entity ids and types before any reach or hitbox measurement: Photon caches the entity type per id, TruthfulAC snapshots the spawn box into its compensation history, and Grim replicates the entity into the simulation used by reach and knockback checks. The type byte matters because hitbox dimensions depend on it, and a spawn without a tracker entry would leave every later entity packet orphaned.
Cache the entity type for every spawned living entity so later modules can resolve an entity id to its type without Bukkit lookups.
LivingEntityIdLookup registers a PacketSendEvent listener for SPAWN_LIVING_ENTITY, wraps the packet as WrapperPlayServerSpawnLivingEntity and stores (entityId, entityType) in a Guava cache capped at one million entries with a five-second default expiry. A delayed task pre-warms the cache from all loaded worlds at startup, and getEntityType serves id-to-type lookups for modules that need hitbox or behavior data.
// ===== FILE: Photon-GitHub-AntiCheatAddition, src/main/java/de/photon/anticheataddition/util/protocol/LivingEntityIdLookup.java =====
package de.photon.anticheataddition.util.protocol;
import com.github.retrooper.packetevents.PacketEvents;
import com.github.retrooper.packetevents.event.PacketListenerAbstract;
import com.github.retrooper.packetevents.event.PacketSendEvent;
import com.github.retrooper.packetevents.protocol.entity.type.EntityType;
import com.github.retrooper.packetevents.protocol.packettype.PacketType;
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerSpawnLivingEntity;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import de.photon.anticheataddition.AntiCheatAddition;
import de.photon.anticheataddition.util.log.Log;
import io.github.retrooper.packetevents.util.SpigotConversionUtil;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.entity.LivingEntity;
import org.jspecify.annotations.NonNull;
import javax.annotation.Nullable;
public final class LivingEntityIdLookup
{
// Track at most 1 millon entities
private static final long MAXIMUM_CACHE_CAPACITY = 1 << 20;
private static final int MINIMUM_CACHE_CAPACITY = 1 << 11;
private static final long CACHE_TIME = 20L * 5L;
public static final LivingEntityIdLookup INSTANCE = new LivingEntityIdLookup();
private final Cache<Integer, EntityType> entityTypeCache = CacheBuilder.newBuilder().initialCapacity(MINIMUM_CACHE_CAPACITY).concurrencyLevel(2).maximumSize(MAXIMUM_CACHE_CAPACITY).build();
private LivingEntityIdLookup()
{
PacketEvents.getAPI().getEventManager().registerListener(new PacketListenerAbstract()
{
@Override
public void onPacketSend(@NonNull PacketSendEvent event)
{
if (event.getPacketType() == PacketType.Play.Server.SPAWN_LIVING_ENTITY) {
final WrapperPlayServerSpawnLivingEntity wrapper = new WrapperPlayServerSpawnLivingEntity(event);
cacheEntityId(wrapper.getEntityId(), wrapper.getEntityType());
}
}
});
// Do not immediately loop through all entities to cache them, as Bukkit may not have loaded all entities yet which leads to connection errors when players try to join.
Bukkit.getScheduler().runTaskLater(AntiCheatAddition.getInstance(), this::cacheAllEntities, CACHE_TIME);
}
private void cacheAllEntities()
{
for (World world : Bukkit.getWorlds()) {
for (LivingEntity entity : world.getLivingEntities()) cacheEntity(entity);
}
}
private void cacheEntity(LivingEntity entity)
{
final int entityId = entity.getEntityId();
final var entityType = SpigotConversionUtil.fromBukkitEntityType(entity.getType());
if (entityType == null) {
Log.fine(() -> "Attempted to cache null entityType: Entity ID " + entityId + " Raw type: " + entity.getType().name());
return;
}
entityTypeCache.put(entityId, entityType);
}
public void cacheEntityId(int entityId, EntityType entityType)
{
if (entityType == null) {
Log.fine(() -> "Attempted to cache null entityType: Entity ID " + entityId);
return;
}
entityTypeCache.put(entityId, entityType);
}
/**
* Gets the EntityType from a valid entityId of a living entity.
*/
@Nullable
public EntityType getEntityType(int entityId)
{
return entityTypeCache.getIfPresent(entityId);
}
}
// NOTE (AI): The SPAWN_LIVING_ENTITY branch is lines 40-43. The cache's five-second expiry is tuned to spawn traffic volume, and cacheEntityId also accepts manual feeds so replay-style spawns can be registered.
Snapshot every spawned entity's position and hitbox into the compensation history so reach checks can backtrack against it.
TruthfulPacketListener routes SPAWN_ENTITY (the 1.19+ living spawn) into CompensationTracker.handleSpawn, which stores a CompensatedEntity keyed by id with a ring of up to 30 tick snapshots and a base reach taken from the entity type (3.0 for players, 1.5 boats, 4.5 shulkers). handleEntitySnapshot re-stamps live Bukkit entities each tick, and getEntityData serves the backtracking reach check with up to 8 ticks of history.
// ===== FILE: TawnyE-TruthfulAC, src/main/java/ret/tawny/truthful/compensation/CompensationTracker.java =====
package ret.tawny.truthful.compensation;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.util.BoundingBox;
import ret.tawny.truthful.Truthful;
import ret.tawny.truthful.utils.hitbox.SimpleHitbox;
import ret.tawny.truthful.utils.tick.ITickable;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
public final class CompensationTracker implements ITickable {
public int getCurrentTick() {
return tickCounter;
}
private static final int HISTORY_SIZE = 30;
public static final int MAX_BACKTRACK_TICKS = 8;
private static final int CLEANUP_INTERVAL = 100;
private static final int MAX_STALE_TICKS = 1200;
private static final int DESTROY_GRACE_TICKS = 6;
private static final double LIVE_RESYNC_DISTANCE_SQUARED = 4.0;
private final Map<Integer, CompensatedEntity> compensationMap = new ConcurrentHashMap<>();
private final Map<Integer, java.lang.ref.WeakReference<Entity>> entityCache = new ConcurrentHashMap<>();
private volatile int tickCounter = 0;
@Override
public void tick() {
tickCounter++;
if (tickCounter % CLEANUP_INTERVAL == 0) {
int currentTick = this.tickCounter;
compensationMap.entrySet().removeIf(entry -> {
if (entry.getValue().isExpired(currentTick)) {
entityCache.remove(entry.getKey());
return true;
}
return false;
});
}
}
public void handleSpawn(int id, UUID uuid, double x, double y, double z, double width, double height,
boolean isPlayer) {
int currentTick = this.tickCounter;
CompensatedEntity data = new CompensatedEntity(id, uuid, isPlayer, 3.0);
compensationMap.put(id, data);
data.snapshot(currentTick, x, y, z, width, height);
}
public void handleEntitySnapshot(Entity entity) {
if (entity == null || !entity.isValid()) return;
int currentTick = this.tickCounter;
int entityId = entity.getEntityId();
entityCache.put(entityId, new java.lang.ref.WeakReference<>(entity));
EntityBox box = readEntityBox(entity);
double baseReach = getBaseReachForType(entity.getType(), entity instanceof Player);
CompensatedEntity data = compensationMap.computeIfAbsent(entityId,
id -> new CompensatedEntity(id, entity.getUniqueId(), entity instanceof Player, baseReach));
data.snapshot(currentTick, box.x, box.y, box.z, box.width, box.height);
}
private static double getBaseReachForType(EntityType type, boolean isPlayer) {
if (isPlayer) return 3.0;
if (type == null) return 3.0;
return switch (type) {
case BOAT -> 1.5;
case MINECART, CHEST_MINECART, HOPPER_MINECART, TNT_MINECART -> 1.0;
case ITEM_FRAME, GLOW_ITEM_FRAME, ARMOR_STAND -> 3.0;
case SHULKER -> 4.5;
default -> 3.0;
};
}
public void handleTeleport(int id, double x, double y, double z) {
int currentTick = this.tickCounter;
CompensatedEntity data = compensationMap.get(id);
if (data != null) {
data.snapshot(currentTick, x, y, z, data.lastWidth, data.lastHeight);
}
}
public void handleRelMove(int id, double dx, double dy, double dz) {
int currentTick = this.tickCounter;
CompensatedEntity data = compensationMap.get(id);
if (data != null) {
EntitySnapshot last = data.getLatest();
if (last != null) {
data.snapshot(currentTick, last.x + dx, last.y + dy, last.z + dz, data.lastWidth, data.lastHeight);
}
}
}
public void handleVelocity(int id, double vx, double vy, double vz) {
int currentTick = this.tickCounter;
CompensatedEntity data = compensationMap.get(id);
if (data != null) {
EntitySnapshot last = data.getLatest();
if (last != null) {
data.snapshot(currentTick, last.x + vx, last.y + vy, last.z + vz, data.lastWidth, data.lastHeight);
}
}
}
public void handleDestroy(int id) {
CompensatedEntity data = compensationMap.get(id);
if (data != null) {
data.markDestroyed(this.tickCounter);
}
}
public CompensatedEntity getEntityData(int entityId) {
CompensatedEntity data = compensationMap.get(entityId);
if (data == null)
return null;
int currentTick = this.tickCounter;
if (data.isExpired(currentTick)) {
compensationMap.remove(entityId, data);
return null;
}
syncFromLiveEntityIfNeeded(entityId, data, currentTick);
return data;
}
public boolean hasEntityData(int entityId) {
return getEntityData(entityId) != null;
}
public static final class CompensatedEntity {
public final int entityId;
public final UUID uuid;
public final boolean isPlayer;
public final double baseReach;
private volatile int lastSeenTick;
private volatile int destroyedTick = -1;
private final EntitySnapshot[] snapshots = new EntitySnapshot[HISTORY_SIZE];
private final int[] ticks = new int[HISTORY_SIZE];
private int head = 0;
private int count = 0;
protected double lastWidth = 0.6;
protected double lastHeight = 1.8;
public CompensatedEntity(int entityId, UUID uuid, boolean isPlayer, double baseReach) {
this.entityId = entityId;
this.uuid = uuid;
this.isPlayer = isPlayer;
this.baseReach = baseReach;
}
public synchronized void snapshot(int tick, double x, double y, double z, double width, double height) {
this.lastSeenTick = tick;
this.destroyedTick = -1;
this.lastWidth = width;
this.lastHeight = height;
snapshots[head] = new EntitySnapshot(x, y, z, width, height);
ticks[head] = tick;
head = (head + 1) % HISTORY_SIZE;
if (count < HISTORY_SIZE)
count++;
}
public synchronized EntitySnapshot getLatest() {
if (count == 0)
return null;
return snapshots[(head - 1 + HISTORY_SIZE) % HISTORY_SIZE];
}
public void markDestroyed(int tick) {
this.destroyedTick = tick;
}
public boolean isExpired(int currentTick) {
int destroyedAt = this.destroyedTick;
if (destroyedAt >= 0 && currentTick - destroyedAt > DESTROY_GRACE_TICKS) {
return true;
}
return currentTick - this.lastSeenTick > MAX_STALE_TICKS;
}
public synchronized void snapshot(int tick, Location loc, double width, double height) {
snapshot(tick, loc.getX(), loc.getY(), loc.getZ(), width, height);
}
public synchronized SimpleHitbox getHitboxAt(int serverTickDelay) {
return getHitboxAt(serverTickDelay, Truthful.getInstance().getCompensationTracker().getCurrentTick());
}
public synchronized SimpleHitbox getHitboxAt(int serverTickDelay, int currentTick) {
if (serverTickDelay > MAX_BACKTRACK_TICKS)
serverTickDelay = MAX_BACKTRACK_TICKS;
if (serverTickDelay < 0)
serverTickDelay = 0;
int targetTick = currentTick - serverTickDelay;
EntitySnapshot bestPrev = null;
int bestPrevTick = Integer.MIN_VALUE;
EntitySnapshot bestNext = null;
int bestNextTick = Integer.MAX_VALUE;
for (int i = 0; i < count; i++) {
int tick = ticks[i];
EntitySnapshot s = snapshots[i];
if (tick == targetTick)
return s.toHitbox();
if (tick < targetTick && tick > bestPrevTick) {
bestPrevTick = tick;
bestPrev = s;
} else if (tick > targetTick && tick < bestNextTick) {
bestNextTick = tick;
bestNext = s;
}
}
if (bestPrev != null && bestNext != null) {
int tickDelta = bestNextTick - bestPrevTick;
if (tickDelta <= 0)
return bestPrev.toHitbox();
double progress = (double) (targetTick - bestPrevTick) / (double) tickDelta;
return EntitySnapshot.interpolate(bestPrev, bestNext, progress);
}
if (count > 0) {
int latestIdx = (head - 1 + HISTORY_SIZE) % HISTORY_SIZE;
return snapshots[latestIdx].toHitbox();
}
return null;
}
}
private void syncFromLiveEntityIfNeeded(int entityId, CompensatedEntity data, int currentTick) {
if (!Bukkit.isPrimaryThread()) return;
Entity entity = findEntity(entityId);
if (entity == null || !entity.isValid()) return;
EntitySnapshot latest = data.getLatest();
if (latest == null) {
handleEntitySnapshot(entity);
return;
}
EntityBox live = readEntityBox(entity);
double dx = latest.x - live.x;
double dy = latest.y - live.y;
double dz = latest.z - live.z;
double distanceSquared = dx * dx + dy * dy + dz * dz;
if (distanceSquared > LIVE_RESYNC_DISTANCE_SQUARED || currentTick - data.lastSeenTick > MAX_STALE_TICKS) {
data.snapshot(currentTick, live.x, live.y, live.z, live.width, live.height);
}
}
private Entity findEntity(int entityId) {
java.lang.ref.WeakReference<Entity> ref = entityCache.get(entityId);
if (ref != null) {
Entity e = ref.get();
if (e != null && e.isValid()) return e;
}
for (World world : Bukkit.getWorlds()) {
for (Entity entity : world.getEntities()) {
if (entity.getEntityId() == entityId) {
entityCache.put(entityId, new java.lang.ref.WeakReference<>(entity));
return entity;
}
}
}
return null;
}
private EntityBox readEntityBox(Entity entity) {
try {
BoundingBox box = entity.getBoundingBox();
double width = Math.max(box.getMaxX() - box.getMinX(), box.getMaxZ() - box.getMinZ());
double height = box.getMaxY() - box.getMinY();
return new EntityBox(
(box.getMinX() + box.getMaxX()) * 0.5,
box.getMinY(),
(box.getMinZ() + box.getMaxZ()) * 0.5,
width,
height
);
} catch (Throwable ignored) {
Location location = entity.getLocation();
return new EntityBox(location.getX(), location.getY(), location.getZ(), 0.6, 1.8);
}
}
private static final class EntityBox {
final double x, y, z, width, height;
EntityBox(double x, double y, double z, double width, double height) {
this.x = x;
this.y = y;
this.z = z;
this.width = width;
this.height = height;
}
}
public static class EntitySnapshot {
final double x, y, z, width, height;
EntitySnapshot(double x, double y, double z, double width, double height) {
this.x = x;
this.y = y;
this.z = z;
this.width = width;
this.height = height;
}
public SimpleHitbox toHitbox() {
return new SimpleHitbox(x, y, z, width, height);
}
static SimpleHitbox interpolate(EntitySnapshot from, EntitySnapshot to, double t) {
return new SimpleHitbox(
from.x + (to.x - from.x) * t,
from.y + (to.y - from.y) * t,
from.z + (to.z - from.z) * t,
from.width + (to.width - from.width) * t,
from.height + (to.height - from.height) * t);
}
}
}
// NOTE (AI): handleSpawn is lines 50-56, and the destroy counterpart handleDestroy (116-121) marks the entity destroyed with a 6-tick grace so late attacks do not retroactively flag.
Replicate every spawned entity, including mobs, into the compensated entity map so reach, hitbox and velocity checks see the client's view.
PacketEntityReplication.onPacketSend wraps SPAWN_LIVING_ENTITY as WrapperPlayServerSpawnLivingEntity and calls addEntity with entity id, uuid, type, position, rotations and the full metadata. The replicated entity then receives S14 relative moves and S18 teleports exactly like the client's copy, and DESTROY_ENTITIES removes it after the transaction that delivers the packet. Spawn velocity from the packet feeds knockback compensation without a separate S12.
// ===== FILE: GrimAnticheat-Grim, common/src/main/java/ac/grim/grimac/events/packets/PacketEntityReplication.java =====
package ac.grim.grimac.events.packets;
import ac.grim.grimac.GrimAPI;
import ac.grim.grimac.api.config.ConfigManager;
import ac.grim.grimac.checks.Check;
import ac.grim.grimac.checks.type.PacketReceiveListener;
import ac.grim.grimac.checks.type.PacketSendListener;
import ac.grim.grimac.player.GrimPlayer;
import ac.grim.grimac.utils.anticheat.LogUtil;
import ac.grim.grimac.utils.data.SprintingState;
import ac.grim.grimac.utils.data.TrackerData;
import ac.grim.grimac.utils.data.packetentity.DashableEntity;
import ac.grim.grimac.utils.data.packetentity.PacketEntity;
import ac.grim.grimac.utils.data.packetentity.PacketEntityHook;
import ac.grim.grimac.utils.data.packetentity.PacketEntityTrackXRot;
import ac.grim.grimac.utils.enums.Pose;
import ac.grim.grimac.utils.nmsutil.EntityMetadataPoseUtil;
import ac.grim.grimac.utils.viaversion.ViaVersionUtil;
import com.github.retrooper.packetevents.PacketEvents;
import com.github.retrooper.packetevents.event.PacketReceiveEvent;
import com.github.retrooper.packetevents.event.PacketSendEvent;
import com.github.retrooper.packetevents.manager.server.ServerVersion;
import com.github.retrooper.packetevents.protocol.entity.EntityPositionData;
import com.github.retrooper.packetevents.protocol.entity.data.EntityData;
import com.github.retrooper.packetevents.protocol.entity.type.EntityType;
import com.github.retrooper.packetevents.protocol.entity.type.EntityTypes;
import com.github.retrooper.packetevents.protocol.packettype.PacketType;
import com.github.retrooper.packetevents.protocol.player.ClientVersion;
import com.github.retrooper.packetevents.protocol.player.InteractionHand;
import com.github.retrooper.packetevents.protocol.player.UserProfile;
import com.github.retrooper.packetevents.protocol.potion.PotionType;
import com.github.retrooper.packetevents.util.Vector3d;
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerAttachEntity;
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerDestroyEntities;
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityEffect;
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityEquipment;
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityMetadata;
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityPositionSync;
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityRelativeMove;
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityRelativeMoveAndRotation;
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityRotation;
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityStatus;
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityTeleport;
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerPlayerInfo;
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerPlayerInfoRemove;
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerPlayerInfoUpdate;
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerRemoveEntityEffect;
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerSetPassengers;
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerSetSlot;
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerSpawnEntity;
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerSpawnLivingEntity;
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerSpawnPainting;
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerSpawnPlayer;
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerUpdateAttributes;
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerWindowItems;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean;
public class PacketEntityReplication extends Check implements PacketReceiveListener, PacketSendListener {
private final AtomicBoolean hasSentPreWavePacket = new AtomicBoolean(true);
// Let's imagine the player is on a boat.
// The player breaks this boat
// If we were to despawn the boat without an extra transaction, then the boat would disappear before
// it disappeared on the client side, creating a ghost boat to flag checks with
//
// If we were to despawn the tick after, spawning must occur the transaction before to stop the same exact
// problem with ghost boats in reverse.
//
// Therefore, we despawn the transaction after, and spawn the tick before.
//
// If we despawn then spawn an entity in the same transaction, then this solution would despawn the new entity
// instead of the old entity, so we wouldn't see the boat at all
//
// Therefore, if the server sends a despawn and then a spawn in the same transaction for the same entity,
// We should simply add a transaction (which will clear this list!)
//
// Another valid solution is to simply spam more transactions, but let's not waste bandwidth.
private final List<Integer> despawnedEntitiesThisTransaction = new ArrayList<>();
// Maximum ping when a firework boost is removed from the player.
private int maxFireworkBoostPing = 1000;
public PacketEntityReplication(GrimPlayer player) {
super(player);
}
@Override
public void onPacketReceive(PacketReceiveEvent event) {
// Teleports don't interpolate, duplicate 1.17 packets don't interpolate
if (!isTickPacket(event.getPacketType())) return;
player.compensatedEntities.entitiesRemovedThisTick.clear();
boolean isTickingReliably = player.isTickingReliablyFor(3);
PacketEntity playerVehicle = player.compensatedEntities.self.getRiding();
for (PacketEntity entity : player.compensatedEntities.entityMap.values()) {
if (entity == playerVehicle && !player.vehicleData.lastDummy) {
// The player has this as their vehicle, so they aren't interpolating it.
// And it isn't a dummy position
entity.setPositionRaw(player, entity.getPossibleLocationBoxes());
} else {
entity.onMovement(isTickingReliably);
}
}
if (player.vehicleData.camelSprintingState == SprintingState.STOPPING) {
player.vehicleData.camelSprintingState = SprintingState.STOPPED;
} else if (player.vehicleData.camelSprintingState == SprintingState.STOPPED && player.isSprinting) { // For sprint desyncs
player.vehicleData.camelSprintingState = SprintingState.STARTED;
}
}
@Override
public void onPacketSend(PacketSendEvent event) {
// ensure grim is the one that sent the transaction
if ((event.getPacketType() == PacketType.Play.Server.PING || event.getPacketType() == PacketType.Play.Server.WINDOW_CONFIRMATION) && player.packetStateData.lastServerTransWasValid) {
despawnedEntitiesThisTransaction.clear();
} else if (event.getPacketType() == PacketType.Play.Server.SPAWN_LIVING_ENTITY) {
WrapperPlayServerSpawnLivingEntity packetOutEntity = new WrapperPlayServerSpawnLivingEntity(event);
addEntity(packetOutEntity.getEntityId(), packetOutEntity.getEntityUUID(), packetOutEntity.getEntityType(), packetOutEntity.getPosition(), packetOutEntity.getYaw(), packetOutEntity.getPitch(), packetOutEntity.getEntityMetadata(), 0);
} else if (event.getPacketType() == PacketType.Play.Server.SPAWN_ENTITY) {
WrapperPlayServerSpawnEntity packetOutEntity = new WrapperPlayServerSpawnEntity(event);
addEntity(packetOutEntity.getEntityId(), packetOutEntity.getUUID().orElse(null), packetOutEntity.getEntityType(), packetOutEntity.getPosition(), packetOutEntity.getYaw(), packetOutEntity.getPitch(), null, packetOutEntity.getData());
} else if (event.getPacketType() == PacketType.Play.Server.SPAWN_PLAYER) {
WrapperPlayServerSpawnPlayer packetOutEntity = new WrapperPlayServerSpawnPlayer(event);
addEntity(packetOutEntity.getEntityId(), packetOutEntity.getUUID(), EntityTypes.PLAYER, packetOutEntity.getPosition(), packetOutEntity.getYaw(), packetOutEntity.getPitch(), packetOutEntity.getEntityMetadata(), 0);
} else if (event.getPacketType() == PacketType.Play.Server.SPAWN_PAINTING) {
WrapperPlayServerSpawnPainting packetOutEntity = new WrapperPlayServerSpawnPainting(event);
addEntity(packetOutEntity.getEntityId(), packetOutEntity.getUUID(), EntityTypes.PAINTING, packetOutEntity.getPosition().toVector3d(), 0, 0f, null, packetOutEntity.getDirection().getHorizontalIndex());
} else if (event.getPacketType() == PacketType.Play.Server.ENTITY_RELATIVE_MOVE) {
WrapperPlayServerEntityRelativeMove move = new WrapperPlayServerEntityRelativeMove(event);
handleMoveEntity(event, move.getEntityId(), move.getDeltaX(), move.getDeltaY(), move.getDeltaZ(), null, null, true, true);
} else if (event.getPacketType() == PacketType.Play.Server.ENTITY_RELATIVE_MOVE_AND_ROTATION) {
WrapperPlayServerEntityRelativeMoveAndRotation move = new WrapperPlayServerEntityRelativeMoveAndRotation(event);
handleMoveEntity(event, move.getEntityId(), move.getDeltaX(), move.getDeltaY(), move.getDeltaZ(), move.getYaw() * 0.7111111F, move.getPitch() * 0.7111111F, true, true);
} else if (event.getPacketType() == PacketType.Play.Server.ENTITY_TELEPORT) {
WrapperPlayServerEntityTeleport move = new WrapperPlayServerEntityTeleport(event);
Vector3d pos = move.getPosition();
handleMoveEntity(event, move.getEntityId(), pos.getX(), pos.getY(), pos.getZ(), move.getYaw(), move.getPitch(), false, true);
} else if (event.getPacketType() == PacketType.Play.Server.ENTITY_POSITION_SYNC) {
// ENTITY_TELEPORT but without relative flags
WrapperPlayServerEntityPositionSync move = new WrapperPlayServerEntityPositionSync(event);
final EntityPositionData values = move.getValues();
final Vector3d pos = values.getPosition();
// TODO this isn't technically correct
// If the position sync is to a pos > 4096 from the entity pos, client does some special stuff without interpolation
handleMoveEntity(event, move.getId(), pos.getX(), pos.getY(), pos.getZ(), values.getYaw(), values.getPitch(), false, true);
} else if (event.getPacketType() == PacketType.Play.Server.ENTITY_ROTATION) { // Affects interpolation
WrapperPlayServerEntityRotation move = new WrapperPlayServerEntityRotation(event);
handleMoveEntity(event, move.getEntityId(), 0, 0, 0, move.getYaw() * 0.7111111F, move.getPitch() * 0.7111111F, true, false);
} else if (event.getPacketType() == PacketType.Play.Server.ENTITY_METADATA) {
WrapperPlayServerEntityMetadata entityMetadata = new WrapperPlayServerEntityMetadata(event);
schedulePoseTransition(entityMetadata, event);
player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), () -> player.compensatedEntities.updateEntityMetadata(entityMetadata.getEntityId(), entityMetadata.getEntityMetadata()));
} else if (event.getPacketType() == PacketType.Play.Server.ENTITY_EQUIPMENT) {
WrapperPlayServerEntityEquipment equipment = new WrapperPlayServerEntityEquipment(event);
player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), () -> player.compensatedEntities.updateEntityEquipment(equipment.getEntityId(), equipment.getEquipment()));
}
// 1.19.3+
else if (event.getPacketType() == PacketType.Play.Server.PLAYER_INFO_UPDATE) {
WrapperPlayServerPlayerInfoUpdate info = new WrapperPlayServerPlayerInfoUpdate(event);
if (info.getActions().contains(WrapperPlayServerPlayerInfoUpdate.Action.ADD_PLAYER)) {
player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), () -> {
for (WrapperPlayServerPlayerInfoUpdate.PlayerInfo entry : info.getEntries()) {
final UserProfile gameProfile = entry.getGameProfile();
final UUID uuid = gameProfile.getUUID();
player.compensatedEntities.profiles.put(uuid, gameProfile);
}
});
}
} else if (event.getPacketType() == PacketType.Play.Server.PLAYER_INFO_REMOVE) {
WrapperPlayServerPlayerInfoRemove remove = new WrapperPlayServerPlayerInfoRemove(event);
player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), () -> remove.getProfileIds().forEach(player.compensatedEntities.profiles::remove));
} else if (event.getPacketType() == PacketType.Play.Server.PLAYER_INFO) {
WrapperPlayServerPlayerInfo info = new WrapperPlayServerPlayerInfo(event);
player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), () -> {
if (info.getAction() == WrapperPlayServerPlayerInfo.Action.ADD_PLAYER) {
for (WrapperPlayServerPlayerInfo.PlayerData entry : info.getPlayerDataList()) {
final UserProfile gameProfile = entry.getUserProfile();
final UUID uuid = gameProfile.getUUID();
player.compensatedEntities.profiles.put(uuid, gameProfile);
}
} else if (info.getAction() == WrapperPlayServerPlayerInfo.Action.REMOVE_PLAYER) {
info.getPlayerDataList().forEach(profile -> player.compensatedEntities.profiles.remove(profile.getUserProfile().getUUID()));
}
});
} else if (event.getPacketType() == PacketType.Play.Server.ENTITY_EFFECT) {
WrapperPlayServerEntityEffect effect = new WrapperPlayServerEntityEffect(event);
PotionType type = effect.getPotionType();
// ViaVersion tries faking levitation effects and fails badly lol, flagging the anticheat
// Block other effects just in case ViaVersion gets any ideas
//
// Set to 24 so ViaVersion blocks it
// 24 is the levitation effect
if (player.getClientVersion().isOlderThan(ClientVersion.V_1_9) && ViaVersionUtil.isAvailable && type.getId(player.getClientVersion()) > 23) {
event.setCancelled(true);
return;
}
// ViaVersion dolphin's grace also messes us up, set it to a potion effect that doesn't exist on 1.12
// Effect 31 is bad omen
if (player.getClientVersion().isOlderThan(ClientVersion.V_1_13) && ViaVersionUtil.isAvailable && type.getId(player.getClientVersion()) == 30) {
event.setCancelled(true);
return;
}
if (isDirectlyAffectingPlayer(player, effect.getEntityId())) player.sendTransaction();
player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), () -> {
PacketEntity entity = player.compensatedEntities.getEntity(effect.getEntityId());
if (entity == null) return;
entity.addPotionEffect(type, effect.getEffectAmplifier());
});
} else if (event.getPacketType() == PacketType.Play.Server.REMOVE_ENTITY_EFFECT) {
WrapperPlayServerRemoveEntityEffect effect = new WrapperPlayServerRemoveEntityEffect(event);
if (isDirectlyAffectingPlayer(player, effect.getEntityId())) player.sendTransaction();
player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), () -> {
PacketEntity entity = player.compensatedEntities.getEntity(effect.getEntityId());
if (entity == null) return;
entity.removePotionEffect(effect.getPotionType());
});
} else if (event.getPacketType() == PacketType.Play.Server.UPDATE_ATTRIBUTES) {
WrapperPlayServerUpdateAttributes attributes = new WrapperPlayServerUpdateAttributes(event);
int entityID = attributes.getEntityId();
// The attributes for this entity is active, currently
if (isDirectlyAffectingPlayer(player, entityID)) player.sendTransaction();
player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(),
() -> player.compensatedEntities.updateAttributes(entityID, attributes.getProperties()));
} else if (event.getPacketType() == PacketType.Play.Server.ENTITY_STATUS) {
WrapperPlayServerEntityStatus status = new WrapperPlayServerEntityStatus(event);
// This hasn't changed from 1.7.2 to 1.17
// Needed to exempt players on dead vehicles, as dead entities have strange physics.
if (status.getStatus() == 3) {
PacketEntity entity = player.compensatedEntities.getEntity(status.getEntityId());
if (entity == null) return;
entity.isDead = true;
}
if (status.getStatus() == 9) {
if (status.getEntityId() != player.entityID) return;
player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), () -> player.packetStateData.setSlowedByUsingItem(false));
player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get() + 1, () -> player.packetStateData.setSlowedByUsingItem(false));
}
if (status.getStatus() == 31) {
PacketEntity hook = player.compensatedEntities.getEntity(status.getEntityId());
if (!(hook instanceof PacketEntityHook hookEntity)) return;
if (hookEntity.attached == player.entityID) {
player.sendTransaction();
// We don't transaction sandwich this, it's too rare to be a real problem.
player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), () -> player.uncertaintyHandler.fishingRodPulls.add(hookEntity.owner));
}
}
if (status.getStatus() >= 24 && status.getStatus() <= 28 && status.getEntityId() == player.entityID) {
player.compensatedEntities.self.opLevel = status.getStatus() - 24;
}
} else if (event.getPacketType() == PacketType.Play.Server.SET_SLOT) {
WrapperPlayServerSetSlot slot = new WrapperPlayServerSetSlot(event);
if (slot.getWindowId() == 0) {
Runnable task = () -> {
if (slot.getSlot() - 36 == player.packetStateData.lastSlotSelected && (
!player.inventory.getHeldItem().is(slot.getItem().getType()) || player.getClientVersion().isOlderThanOrEquals(ClientVersion.V_1_8)
) || slot.getSlot() == 45 && !player.inventory.getOffHand().is(slot.getItem().getType())) {
InteractionHand hand = slot.getSlot() == 45 ? InteractionHand.OFF_HAND : InteractionHand.MAIN_HAND;
if (hand == player.packetStateData.itemInUseHand) {
player.packetStateData.setSlowedByUsingItem(false);
}
if (player.isResetItemUsageOnItemUpdate() && hand == GrimAPI.INSTANCE.getItemResetHandler().getItemUsageHand(player.platformPlayer)) {
GrimAPI.INSTANCE.getItemResetHandler().resetItemUsage(player.platformPlayer);
}
}
};
player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), task);
player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get() + 1, task);
}
} else if (event.getPacketType() == PacketType.Play.Server.WINDOW_ITEMS) {
WrapperPlayServerWindowItems items = new WrapperPlayServerWindowItems(event);
if (items.getWindowId() == 0) { // Player inventory
Runnable task = () -> {
if (player.getClientVersion().isOlderThanOrEquals(ClientVersion.V_1_8)) {
player.packetStateData.setSlowedByUsingItem(false);
if (player.isResetItemUsageOnItemUpdate()) {
GrimAPI.INSTANCE.getItemResetHandler().resetItemUsage(player.platformPlayer);
}
} else {
if (items.getItems().size() > 45 && !player.inventory.getOffHand().is(items.getItems().get(45).getType())) {
if (player.packetStateData.itemInUseHand == InteractionHand.OFF_HAND) {
player.packetStateData.setSlowedByUsingItem(false);
}
if (player.isResetItemUsageOnItemUpdate() && GrimAPI.INSTANCE.getItemResetHandler().getItemUsageHand(player.platformPlayer) == InteractionHand.OFF_HAND) {
GrimAPI.INSTANCE.getItemResetHandler().resetItemUsage(player.platformPlayer);
}
}
if (!player.inventory.getHeldItem().is(items.getItems().get(player.packetStateData.lastSlotSelected + 36).getType())) {
if (player.packetStateData.itemInUseHand == InteractionHand.MAIN_HAND) {
player.packetStateData.setSlowedByUsingItem(false);
}
if (player.isResetItemUsageOnItemUpdate() && GrimAPI.INSTANCE.getItemResetHandler().getItemUsageHand(player.platformPlayer) == InteractionHand.MAIN_HAND) {
GrimAPI.INSTANCE.getItemResetHandler().resetItemUsage(player.platformPlayer);
}
}
}
};
player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), task);
player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get() + 1, task);
}
}
// 1.8 clients fail to send the RELEASE_USE_ITEM packet when a window is opened client sided while using an item
else if (event.getPacketType() == PacketType.Play.Server.OPEN_WINDOW) {
player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), () -> player.packetStateData.setSlowedByUsingItem(false));
player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get() + 1, () -> player.packetStateData.setSlowedByUsingItem(false));
} else if (event.getPacketType() == PacketType.Play.Server.OPEN_HORSE_WINDOW) {
player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), () -> player.packetStateData.setSlowedByUsingItem(false));
player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get() + 1, () -> player.packetStateData.setSlowedByUsingItem(false));
} else if (event.getPacketType() == PacketType.Play.Server.SET_PASSENGERS) {
WrapperPlayServerSetPassengers mount = new WrapperPlayServerSetPassengers(event);
int vehicleID = mount.getEntityId();
int[] passengers = mount.getPassengers();
handleMountVehicle(event, vehicleID, passengers);
} else if (event.getPacketType() == PacketType.Play.Server.ATTACH_ENTITY) {
WrapperPlayServerAttachEntity attach = new WrapperPlayServerAttachEntity(event);
// This packet was replaced by the mount packet on 1.9+ servers - to support multiple passengers on one vehicle
if (PacketEvents.getAPI().getServerManager().getVersion().isNewerThanOrEquals(ServerVersion.V_1_9))
return;
// If this is mounting rather than leashing
if (!attach.isLeash()) {
// Alright, let's convert this to the 1.9+ format to make it easier for grim
int vehicleID = attach.getHoldingId();
int attachID = attach.getAttachedId();
TrackerData trackerData = player.compensatedEntities.getTrackedEntity(attachID);
if (trackerData != null) {
// 1.8 sends a vehicle ID of -1 to dismount the entity from its vehicle
// This is opposite of the 1.9+ format, which sends the vehicle ID and then an empty array.
if (vehicleID == -1) { // Dismounting
vehicleID = trackerData.getLegacyPointEightMountedUpon();
handleMountVehicle(event, vehicleID, new int[]{}); // The vehicle is empty
} else { // Mounting
trackerData.setLegacyPointEightMountedUpon(vehicleID);
handleMountVehicle(event, vehicleID, new int[]{attachID});
}
} else {
// I don't think we can recover from this... warn and move on as this shouldn't happen.
LogUtil.warn("Server sent an invalid attach entity packet for entity " + attach.getHoldingId() + " with passenger " + attach.getAttachedId() + "! The client ignores this.");
}
}
} else if (event.getPacketType() == PacketType.Play.Server.DESTROY_ENTITIES) {
WrapperPlayServerDestroyEntities destroy = new WrapperPlayServerDestroyEntities(event);
int[] destroyEntityIds = destroy.getEntityIds();
for (int entityID : destroyEntityIds) {
despawnedEntitiesThisTransaction.add(entityID);
player.compensatedEntities.serverPositionsMap.remove(entityID);
// Remove the tracked vehicle (handling tracking knockback) if despawned
if (player.compensatedEntities.serverPlayerVehicle != null && player.compensatedEntities.serverPlayerVehicle == entityID) {
player.compensatedEntities.serverPlayerVehicle = null;
}
}
final int destroyTransaction = player.lastTransactionSent.get() + 1;
player.latencyUtils.addRealTimeTask(destroyTransaction, () -> {
for (int entityId : destroyEntityIds) {
player.compensatedEntities.removeEntity(entityId);
player.dashableEntities.removeEntity(entityId);
player.fireworks.removeFirework(entityId);
player.compensatedEntities.entitiesRemovedThisTick.add(entityId);
}
});
// Don't let the player freeze transactions to keep the firework boost velocity + uncertainty
// Also generally prevents people with high ping gaining too high an advantage in firework use
if (maxFireworkBoostPing > 0) {
player.runNettyTaskInMs(() -> {
if (player.lastTransactionReceived.get() >= destroyTransaction) return;
for (int entityID : destroyEntityIds) {
// If the player has a firework boosting them, setback
if (player.fireworks.hasFirework(entityID)) {
player.getSetbackTeleportUtil().executeViolationSetback();
break;
}
}
}, maxFireworkBoostPing);
}
}
}
private void handleMountVehicle(PacketSendEvent event, int vehicleID, int[] passengers) {
boolean wasInVehicle = player.compensatedEntities.serverPlayerVehicle != null && player.compensatedEntities.serverPlayerVehicle == vehicleID;
boolean inThisVehicle = false;
for (int passenger : passengers) {
inThisVehicle = passenger == player.entityID;
if (inThisVehicle) break;
}
if (inThisVehicle && !wasInVehicle) {
player.handleMountVehicle(vehicleID);
}
if (!inThisVehicle && wasInVehicle) {
player.handleDismountVehicle(event);
}
// Better lag compensation if we were affected by this
if (wasInVehicle || inThisVehicle) {
player.sendTransaction();
}
player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), () -> {
PacketEntity vehicle = player.compensatedEntities.getEntity(vehicleID);
// Vanilla likes sending null vehicles, so we must ignore those like the client ignores them
if (vehicle == null) return;
// Eject existing passengers for this vehicle
for (PacketEntity passenger : new ArrayList<>(vehicle.passengers)) {
passenger.eject();
}
// Add the entities as vehicles
for (int entityID : passengers) {
PacketEntity passenger = player.compensatedEntities.getEntity(entityID);
if (passenger == null) continue;
passenger.mount(vehicle);
}
});
}
private void handleMoveEntity(PacketSendEvent event, int entityId, double deltaX, double deltaY, double deltaZ, Float yaw, Float pitch, boolean isRelative, boolean hasPos) {
TrackerData data = player.compensatedEntities.getTrackedEntity(entityId);
final boolean didNotSendPreWave = hasSentPreWavePacket.compareAndSet(false, true);
if (didNotSendPreWave) player.sendTransaction();
if (data != null) {
// Update the tracked server's entity position
if (isRelative) {
// There is a bug where vehicles may start flying due to mojang setting packet position on the client
// (Works at 0 ping but causes funny bugs at any higher ping)
// As we don't want vehicles to fly, we need to replace it with a teleport if it is player vehicle
//
// Don't bother with client controlled vehicles though
boolean vanillaVehicleFlight = player.compensatedEntities.serverPlayerVehicle != null
&& player.compensatedEntities.serverPlayerVehicle == entityId
&& player.getClientVersion().isNewerThanOrEquals(ClientVersion.V_1_9)
// TODO: https://discord.com/channels/721686193061888071/721686193515003966/1310659538831020123
// Why does the server now send an entity rel move packet matching the player's vehicle movement every time?
&& PacketEvents.getAPI().getServerManager().getVersion().isOlderThan(ServerVersion.V_1_21_2)
&& PacketEvents.getAPI().getServerManager().getVersion().isNewerThanOrEquals(ServerVersion.V_1_9);
// ViaVersion sends two relative packets when moving more than 4 blocks
// This is broken and causes the client to interpolate like (0, 4) and (1, 3) instead of (1, 7)
// This causes impossible hits, so grim must replace this with a teleport entity packet
// Not ideal, but neither is 1.8 players on a 1.9+ server.
if (vanillaVehicleFlight ||
((Math.abs(deltaX) >= 3.9375 || Math.abs(deltaY) >= 3.9375 || Math.abs(deltaZ) >= 3.9375) && player.getClientVersion().isOlderThan(ClientVersion.V_1_9) && PacketEvents.getAPI().getServerManager().getVersion().isNewerThanOrEquals(ServerVersion.V_1_9))) {
player.user.writePacket(new WrapperPlayServerEntityTeleport(entityId, new Vector3d(data.getX() + deltaX, data.getY() + deltaY, data.getZ() + deltaZ), yaw == null ? data.getXRot() : yaw, pitch == null ? data.getYRot() : pitch, false));
event.setCancelled(true);
return;
}
data.setX(data.getX() + deltaX);
data.setY(data.getY() + deltaY);
data.setZ(data.getZ() + deltaZ);
} else {
data.setX(deltaX);
data.setY(deltaY);
data.setZ(deltaZ);
}
if (yaw != null) {
data.setXRot(yaw);
data.setYRot(pitch);
}
// We can't hang two relative moves on one transaction
if (data.getLastTransactionHung() == player.lastTransactionSent.get()) {
player.sendTransaction();
}
data.setLastTransactionHung(player.lastTransactionSent.get());
}
int lastTrans = player.lastTransactionSent.get();
player.latencyUtils.addRealTimeTask(lastTrans, () -> {
PacketEntity entity = player.compensatedEntities.getEntity(entityId);
if (entity == null) return;
if (entity instanceof PacketEntityTrackXRot xRotEntity && yaw != null) {
xRotEntity.packetYaw = yaw;
xRotEntity.steps = entity.isBoat ? 10 : 3;
}
entity.onFirstTransaction(isRelative, hasPos, deltaX, deltaY, deltaZ, player);
});
player.latencyUtils.addRealTimeTask(lastTrans + 1, () -> {
PacketEntity entity = player.compensatedEntities.getEntity(entityId);
if (entity == null) return;
entity.onSecondTransaction();
});
}
public void addEntity(int entityID, UUID uuid, EntityType type, Vector3d position, float xRot, float yRot, List<EntityData<?>> entityMetadata, int extraData) {
if (despawnedEntitiesThisTransaction.contains(entityID)) {
player.sendTransaction();
}
player.compensatedEntities.serverPositionsMap.put(entityID, new TrackerData(position.getX(), position.getY(), position.getZ(), xRot, yRot, type, player.lastTransactionSent.get()));
player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), () -> {
PacketEntity entity = player.compensatedEntities.addEntity(entityID, uuid, type, position, xRot, extraData);
if (entity instanceof DashableEntity dashable) {
player.dashableEntities.addEntity(entityID, dashable);
}
if (entityMetadata != null) {
if (EntityMetadataPoseUtil.usesPoseMetadata(entity) && player.getClientVersion().isNewerThanOrEquals(ClientVersion.V_1_14)) {
Pose initialPose = EntityMetadataPoseUtil.getPoseFromMetadata(entityMetadata);
if (initialPose != null) {
entity.currentPose = initialPose;
}
}
player.compensatedEntities.updateEntityMetadata(entityID, entityMetadata);
}
});
}
private void schedulePoseTransition(WrapperPlayServerEntityMetadata entityMetadata, PacketSendEvent event) {
if (player.getClientVersion().isOlderThan(ClientVersion.V_1_14)) return;
int entityId = entityMetadata.getEntityId();
if (entityId == player.entityID) return;
Pose newPose = EntityMetadataPoseUtil.getPoseFromMetadata(entityMetadata.getEntityMetadata());
if (newPose == null) return;
boolean shouldTrackPoseTransition = false;
PacketEntity entity = player.compensatedEntities.getEntity(entityId);
if (entity != null) {
shouldTrackPoseTransition = EntityMetadataPoseUtil.usesPoseMetadata(entity);
} else {
// If the client didn't respond to the spawn packet yet, we need to check if we should track the pose transition based on the entity type
// is there a better way to do this?
TrackerData trackedEntity = player.compensatedEntities.getTrackedEntity(entityId);
if (trackedEntity != null) {
shouldTrackPoseTransition = EntityMetadataPoseUtil.usesPoseMetadata(trackedEntity.getEntityType());
}
}
if (!shouldTrackPoseTransition) return;
player.sendTransaction();
player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), () -> {
PacketEntity target = player.compensatedEntities.getEntity(entityId);
if (target == null) {
return;
}
target.beginPoseTransition(newPose);
});
event.getTasksAfterSend().add(() -> {
player.sendTransaction();
player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), () -> {
PacketEntity target = player.compensatedEntities.getEntity(entityId);
if (target == null) {
return;
}
target.completePoseTransition(newPose);
});
});
}
private boolean isDirectlyAffectingPlayer(GrimPlayer player, int entityID) {
// The attributes for this entity is active, currently
return (player.compensatedEntities.serverPlayerVehicle == null && entityID == player.entityID) ||
(player.compensatedEntities.serverPlayerVehicle != null && entityID == player.compensatedEntities.serverPlayerVehicle);
}
public void onEndOfTickEvent(boolean async, boolean flush) {
// Only send a transaction at the end of the tick if we are tracking players
player.sendTransaction(async);
if (flush) player.user.flushPackets();
}
public void tickStartTick() {
hasSentPreWavePacket.set(false);
}
@Override
public void onReload(@NotNull ConfigManager config) {
maxFireworkBoostPing = config.getIntElse("max-ping-firework-boost", 1000);
}
}
// NOTE (AI): The SPAWN_LIVING_ENTITY branch is lines 123-125. The file also handles SPAWN_ENTITY, SPAWN_PLAYER and SPAWN_PAINTING in the same dispatch, and the DESTROY_ENTITIES branch (379-415) schedules removal on the destroy transaction.
Related Packets
Wiki Cross-Reference
Living-entity spawn: VarInt id, unsigned-byte EntityList type (50 creeper through 120 villager), pos x/32, angles x360/256, vel /8000.
Carries a mandatory DataWatcher block rendering health, effects and nametags; tracker skips a duplicate S12 on the spawn tick.
MCP 1.8.9 S0FPacketSpawnMob implements Packet
1.8.9 callers: EntityTrackerEntry.createSpawnPacket sends new S0FPacketSpawnMob (line 515): https://github.com/Marcelektro/MavenMCP-1.8.9/blob/master/src/main/java/net/minecraft/entity/EntityTrackerEntry.java
Cross-checked against minecraft.wiki (CC BY-SA 3.0) for 1.8.9 accuracy.
Vanilla Internals
Full 1.8.9 logic-class sources that send or handle this packet, stored verbatim.
Module Analyses Using S0FPacketSpawnMob
Full source walkthroughs of the modules and anti-cheats that use this packet.