Entity and Player System
Entity and Player System
Entity Class Hierarchy
Entity (abstract)
├── LivingEntity (abstract)
│ └── Player
└── BlockEntity
Entity
Base class for all entities. Implements Component<EntityStore>.
Fields:
networkId- Unique network identifierlegacyUuid- UUID for persistenceworld- Parent world referencereference-Ref<EntityStore>referencewasRemoved- AtomicBoolean removal flag
Key Methods:
remove()- Removes entity from worldloadIntoWorld(World)- Adds entity to worldunloadFromWorld()- Removes from world without eventssetReference(Ref)- Sets ECS referencetoHolder()- Converts to component holderisCollidable()- Collision check
LivingEntity
Entities that can have inventory, take damage, and fall.
Fields:
statModifiersManager- Stat modifications (armor, buffs)inventory- Inventory systemcurrentFallDistance- Fall damage accumulator
Key Methods:
getInventory()/setInventory()canBreathe()- Check breathing in current blockmoveTo()- Movement with fall damagedecreaseItemStackDurability()- Durability damageinvalidateEquipmentNetwork()- Flag equipment for update
Player
Player-specific functionality. Implements CommandSender, PermissionHolder, MetricProvider.
Fields:
gameMode- Survival, Creative, AdventureplayerRef- Connection/session linkdata- PlayerConfigData (persistent)worldMapTracker- Minimap trackingwindowManager- GUI windowspageManager- Page navigationhudManager- HUD elementshotbarManager- 10 saved hotbar configurationsclientViewRadius- View distancevelocitySamples/velocitySampleIndex- Movement velocityoverrideBlockPlacementRestrictions- Creative mode overridemountEntityId- Mounted entity IDlastSpawnTimeNanos- Respawn invulnerability timestamp
Key Methods:
getGameMode()/setGameMode()- With eventsmoveToLocation()- With collision and velocityhasSpawnProtection()- 3-second post-spawn invulnerabilityisHiddenFromLivingEntity()- Hidden player checkgetRespawnPosition()- Safe respawn with collision checkscanDecreaseItemStackDurability()- Creative mode immunity
Component System (ECS)
Component Interface
interface Component<ECS_TYPE> extends Cloneable {
Component<ECS_TYPE> clone();
Component<ECS_TYPE> cloneSerializable();
}
Core ECS Classes
| Class | Purpose |
|---|---|
Store<ECS_TYPE> | Core store managing entities and components. Uses archetype chunks. |
Archetype<ECS_TYPE> | Blueprint of component composition for entity groups. |
Holder<ECS_TYPE> | Temporary container for component data during creation/serialization. |
Ref<ECS_TYPE> | Reference to entity in store. Becomes invalid on removal. |
ComponentType<ECS_TYPE, T> | Type metadata for component class. |
ComponentRegistry<ECS_TYPE> | Registry of all component and system types. |
Store Methods
getComponent(ref, componentType)- Get component from entityputComponent(ref, component)- Set component on entityaddEntity(holder, reason)- Add entity to storeremoveEntity(ref, reason)- Remove entity from store
Ref Lifecycle
Valid Ref Invalid Ref
│ │
▼ ▼
ref.isValid() = true ref.isValid() = false
ref.getIndex() = N ref.getIndex() = Integer.MIN_VALUE
Inventory System
Section IDs
| Section | ID | Default Slots |
|---|---|---|
| Hotbar | -1 | 9 |
| Storage | -2 | 36 (4x9) |
| Armor | -3 | ItemArmorSlot.VALUES.length |
| Utility | -5 | 4 |
| Tools | -8 | 23 (deprecated) |
| Backpack | -9 | variable |
Container Types
| Type | Description |
|---|---|
SimpleItemContainer | Basic slot storage |
CombinedItemContainer | Logical grouping of containers |
BlockWindow | Window for block containers |
ItemContainerWindow | Window for inventory UI |
Combined Containers
combinedHotbarFirst- Hotbar + StoragecombinedStorageFirst- Storage + HotbarcombinedArmorHotbarUtilityStorage- Armor + Hotbar + Utility + StoragecombinedEverything- All sections
ItemStack
Fields:
itemId- Item type IDquantity- Stack countdurability/maxDurability- Durability valuesmetadata- BsonDocument for extra data
Methods:
isUnbreakable()- Check unbreakable flagisBroken()- Durability depletedisEmpty()- Zero quantitygetItem()- Get Item asset
Active Slots
activeHotbarSlot- Current hotbar slot (byte)activeUtilitySlot- Current utility slot (byte)activeToolsSlot- Current tool slot (byte)
Entity Lifecycle
Spawning
1. Entity created: new Entity(world)
2. Network ID assigned: world.getEntityStore().takeNextNetworkId()
3. Load into world: entity.loadIntoWorld(world)
4. Components assembled into Holder<EntityStore>
5. Entity added: store.addEntity(holder, AddReason.SPAWN)
6. Reference set: entity.setReference(ref)
7. Systems triggered: onEntityAdded()
Removal
1. entity.remove() called
2. wasRemoved flag set (atomic)
3. EntityRemoveEvent dispatched
4. store.removeEntity(ref, RemoveReason.REMOVE)
5. Player cleanup: ChunkTracker cleared, connection dropped
6. Systems triggered: onEntityRemove()
Add/Remove Reasons
| AddReason | Description |
|---|---|
SPAWN | Normal spawn |
LOAD | Loaded from storage |
| RemoveReason | Description |
|---|---|
REMOVE | Explicit removal |
UNLOAD | Chunk/world unload |
System Types
| Type | Description |
|---|---|
System<ECS_TYPE> | Base system class |
ISystem<ECS_TYPE> | System interface with lifecycle hooks |
QuerySystem | Processes entities matching component query |
TickingSystem | Runs every tick |
EntityTickingSystem | Tick per matching entity |
RefSystem | Listens to entity add/remove events |
EventSystem | Dispatches ECS events |
System Lifecycle
interface ISystem<ECS_TYPE> {
void onSystemRegistered();
void onSystemUnregistered();
Set<Dependency> getDependencies();
Group getGroup();
}
RefSystem Callbacks
void onEntityAdded(Ref ref, AddReason reason, Store store, CommandBuffer buffer);
void onEntityRemove(Ref ref, RemoveReason reason, Store store, CommandBuffer buffer);
Player Managers
| Manager | Purpose |
|---|---|
WindowManager | GUI windows (inventory, crafting) |
PageManager | UI pages |
HudManager | HUD display and custom UI |
HotbarManager | 10 saved hotbar configurations |
MovementManager | Movement settings, flying |
CameraManager | Camera position and rotation |
ChunkTracker | Tracks loaded chunks around player |
Events
Entity Events
| Event | Description |
|---|---|
EntityRemoveEvent | Entity removed from world |
ChangeGameModeEvent | Player changes game mode (cancellable) |
SwitchActiveSlotEvent | Player switches inventory slot |
DropItemEvent | Player drops item |
InteractivelyPickupItemEvent | Player picks up item |
CraftRecipeEvent | Player crafts recipe |
PlaceBlockEvent | Player places block |
BreakBlockEvent | Player breaks block |
DamageBlockEvent | Player damages block |
UseBlockEvent | Block interaction |
DiscoverZoneEvent | Player discovers zone |
Inventory Events
| Event | Description |
|---|---|
LivingEntityInventoryChangeEvent | Inventory changed |
Network Packets
| Packet | Purpose |
|---|---|
SetMovementStates | Sync movement states |
SetGameMode | Change game mode |
SetBlockPlacementOverride | Block placement permissions |
UpdatePlayerInventory | Send inventory state |
ClientReady | Client signals ready |
ClientMovement | Player movement input |
MouseInteraction | Mouse aim/click |
ClientPlaceBlock | Block placement request |
ClientTeleport | Teleport request |
Design Patterns
- Entity Component System (ECS) - Data-driven architecture
- Archetype Chunking - Cache-efficient entity grouping
- Reference Pattern -
Ref<ECS_TYPE>with invalidation tracking - Manager Pattern - Players use composable managers
- Transaction Pattern - Inventory operations return Transactions
- Event System - Traditional and ECS events
- Composition over Inheritance - Functionality via components
- System Dependency Injection - Automatic dependency resolution
- Thread-Safe Design - Atomic flags, concurrent maps, stamped locks
- Holder Pattern - Temporary containers for serialization