NPC System Overview
NPC System Overview
Section titled “NPC System Overview”The NPC (Non-Player Character) System manages AI-controlled entities in Hytale. It uses a sophisticated role-based behavior system with support for flocking, spawning, and complex decision making.
Package Location
Section titled “Package Location”- NPC entities:
com.hypixel.hytale.server.npc - Flock system:
com.hypixel.hytale.server.flock - Role system:
com.hypixel.hytale.server.npc.role - Blackboard:
com.hypixel.hytale.server.npc.blackboard
Architecture
Section titled “Architecture”┌─────────────────────────────────────────────────────────────┐│ NPC System ││ ┌─────────────────────────────────────────────────────────┐││ │ NPCEntity │││ │ ┌─────────┐ ┌─────────┐ ┌─────────────┐ ┌───────────┐ │││ │ │ Role │ │Blackboard│ │ PathManager │ │DamageData │ │││ │ └─────────┘ └─────────┘ └─────────────┘ └───────────┘ │││ └─────────────────────────────────────────────────────────┘││ ┌─────────────────────────────────────────────────────────┐││ │ Flock System │││ │ ┌─────────┐ ┌─────────────┐ ┌─────────────────────┐ │││ │ │ Flock │ │FlockMembership│ │FlockPlugin │ │││ │ └─────────┘ └─────────────┘ └─────────────────────┘ │││ └─────────────────────────────────────────────────────────┘││ ┌─────────────────────────────────────────────────────────┐││ │ Spawning System │││ │ ┌────────────┐ ┌────────────┐ ┌────────────────────┐ │││ │ │SpawnBeacon │ │SpawnMarker │ │SpawnController │ │││ │ └────────────┘ └────────────┘ └────────────────────┘ │││ └─────────────────────────────────────────────────────────┘│└─────────────────────────────────────────────────────────────┘Core Components
Section titled “Core Components”NPCEntity
Section titled “NPCEntity”NPCEntity extends LivingEntity and is the base class for AI-controlled characters.
public class NPCEntity extends LivingEntity implements INonPlayerCharacter { // Role management public Role getRole();
// Position tracking public Vector3d getLeashPoint(); // Spawn anchor point public float getLeashHeading(); public float getLeashPitch();
// Spawning public Instant getSpawnInstant(); public String getSpawnConfigurationName();
// Pathing public PathManager getPathManager();
// Events public AlarmStore getAlarmStore(); public DamageData getDamageData();}Getting NPCEntity Component Type
Section titled “Getting NPCEntity Component Type”ComponentType<EntityStore, NPCEntity> npcType = NPCEntity.getComponentType();
// Query for NPCsQuery<EntityStore> query = npcType;Role System
Section titled “Role System”Roles define NPC behavior, stats, and AI decision making.
Role Class
Section titled “Role Class”public class Role implements IAnnotatedComponentCollection { // Support objects CombatSupport combatSupport; // Combat behavior StateSupport stateSupport; // State machine MarkedEntitySupport markedEntitySupport; // Target tracking WorldSupport worldSupport; // World interaction EntitySupport entitySupport; // Entity queries PositionCache positionCache; // Position caching DebugSupport debugSupport; // Debug features
// Stats int initialMaxHealth; double knockbackScale; double inertia; boolean invulnerable;
// Movement Map<String, MotionController> motionControllers; MotionController activeMotionController; Steering bodySteering; Steering headSteering;
// Behavior Instruction rootInstruction; Instruction interactionInstruction; Instruction deathInstruction;
// Spawning String[] flockSpawnTypes; String[] flockAllowedRoles; boolean canLeadFlock;
// Lifecycle void loaded(); void unloaded(); void removed();}Role Configuration Properties
Section titled “Role Configuration Properties”| Property | Type | Description |
|---|---|---|
maxHealth | int | Maximum health points |
knockbackScale | double | Knockback force multiplier |
inertia | double | Movement inertia |
invulnerable | bool | Cannot take damage |
deathAnimationTime | double | Death animation duration |
despawnAnimationTime | float | Despawn animation duration |
dropListId | string | Loot drop list |
balanceAsset | string | Balance configuration |
hotbarItems | string[] | Starting hotbar items |
offHandItems | string[] | Starting offhand items |
armor | string[] | Starting armor |
Motion Controllers
Section titled “Motion Controllers”Motion controllers handle NPC movement patterns:
// Built-in motion controllersBodyMotionWander // Random wanderingBodyMotionMaintainDistance // Keep distance from targetBodyMotionFindWithTarget // Pathfind to targetBodyMotionMatchLook // Match look directionBodyMotionFlock // Flock movementBodyMotionTeleport // TeleportationBlackboard System
Section titled “Blackboard System”The Blackboard is shared memory for NPC decision making.
Blackboard Views
Section titled “Blackboard Views”| View | Description |
|---|---|
BlockTypeView | Track block type changes |
BlockEventView | Track block events |
EntityEventView | Track entity events |
Block Event Types
Section titled “Block Event Types”public enum BlockEventType { PLACED, REMOVED, INTERACTED}Entity Event Types
Section titled “Entity Event Types”public enum EntityEventType { SPAWNED, DESPAWNED, DAMAGED, KILLED}Flock System
Section titled “Flock System”Flocks group NPCs for coordinated behavior.
Flock Component
Section titled “Flock Component”public class Flock implements Component<EntityStore> { // Flock data PersistentFlockData getFlockData();
// Damage tracking DamageData getDamageData(); DamageData getLeaderDamageData();
// Status FlockRemovedStatus getRemovedStatus();}FlockMembership Component
Section titled “FlockMembership Component”public class FlockMembership implements Component<EntityStore> { UUID getFlockId(); void setFlockId(UUID flockId); Ref<EntityStore> getFlockRef(); void setFlockRef(Ref<EntityStore> flockRef); Type getMembershipType(); void setMembershipType(Type membershipType);}FlockMembership.Type Enum
Section titled “FlockMembership.Type Enum”| Value | Acts as Leader | Description |
|---|---|---|
JOINING | No | Joining a flock |
MEMBER | No | Regular flock member |
LEADER | Yes | Flock leader |
INTERIM_LEADER | Yes | Temporary leader |
Flock Status
Section titled “Flock Status”public enum FlockRemovedStatus { NOT_REMOVED, DISSOLVED, UNLOADED}Flock Configuration
Section titled “Flock Configuration”{ "Id": "MyPlugin_WolfPack", "MinSize": 2, "MaxSize": 6, "AllowedRoles": ["Wolf", "AlphaWolf"], "WeightAlignment": 1.0, "WeightSeparation": 1.5, "WeightCohesion": 1.0, "InfluenceRange": 20.0}Flock Behaviors
Section titled “Flock Behaviors”| Behavior | Description |
|---|---|
Alignment | Match velocity with nearby flock members |
Separation | Maintain distance from other members |
Cohesion | Stay close to flock center |
Spawning System
Section titled “Spawning System”The spawning system controls when and where NPCs appear.
SpawnBeacon
Section titled “SpawnBeacon”Spawn beacons define spawn locations:
public class SpawnBeacon implements Component<EntityStore> { // Configured in assets}SpawnMarker
Section titled “SpawnMarker”Spawn markers define specific spawn points:
public class SpawnMarkerEntity extends Entity { // Spawn marker data}Spawn Configuration
Section titled “Spawn Configuration”{ "Id": "MyPlugin_ZombieSpawn", "Role": "Zombie", "MinCount": 1, "MaxCount": 3, "SpawnChance": 0.5, "Conditions": { "TimeOfDay": "Night", "LightLevel": { "Max": 7 } }}WorldNPCSpawn
Section titled “WorldNPCSpawn”World spawn configuration for natural spawning:
// Spawn parametersLightType lightType; // BLOCK, SKY, COMBINEDint minLightLevel;int maxLightLevel;Spawn Suppression
Section titled “Spawn Suppression”Control spawn rates in areas:
public class SpawnSuppressionComponent implements Component<EntityStore> { // Suppress spawns in area}NPC Systems
Section titled “NPC Systems”The NPC plugin registers many systems for NPC behavior:
| System | Description |
|---|---|
NPCPreTickSystem | Pre-tick setup |
StateEvaluatorSystem | Evaluate state transitions |
SteeringSystem | Calculate steering forces |
ComputeVelocitySystem | Compute final velocity |
AvoidanceSystem | Collision avoidance |
MovementStatesSystem | Movement state updates |
RoleChangeSystem | Handle role changes |
NPCDamageSystems | Damage handling |
NPCDeathSystems | Death handling |
NPCInteractionSystems | Player interactions |
Instructions and Actions
Section titled “Instructions and Actions”NPCs use instructions for behavior trees:
Instruction Types
Section titled “Instruction Types”| Type | Description |
|---|---|
BodyMotion | Movement instructions |
Action | Discrete actions |
Sensor | Environmental sensing |
Common Actions
Section titled “Common Actions”ActionRecomputePath // Recalculate pathActionOverrideAltitude // Set altitudeActionFlockJoin // Join a flockActionFlockLeave // Leave flockActionFlockBeacon // Respond to beaconActionFlockSetTarget // Set flock targetActionTriggerSpawnBeacon // Trigger spawnSensors
Section titled “Sensors”SensorOnGround // Ground detectionSensorFlockLeader // Leader detectionSensorFlockCombatDamage // Combat damage sensingSensorInflictedDamage // Damage dealt sensingState Transitions
Section titled “State Transitions”NPCs use state machines for behavior:
public class StateTransitionController { // Manage state transitions}
// State transition edgespublic class BuilderStateTransitionEdges { // Define transition conditions}Expressions
Section titled “Expressions”NPCs support expression evaluation for conditions:
// Expression syntax"health < 50""distance(target) > 10""hasTag(\"hostile\")"NPC Events
Section titled “NPC Events”NPC Lifecycle
Section titled “NPC Lifecycle”// NPC added to worldgetEventRegistry().register(AddPlayerToWorldEvent.class, event -> { // Not for NPCs - use RefSystem for NPC lifecycle});
// Use RefSystem for NPC trackingpublic class MyNPCSystem extends RefSystem<EntityStore> { @Override public void onEntityAdded(Ref<EntityStore> ref, AddReason reason, Store<EntityStore> store, CommandBuffer<EntityStore> buffer) { NPCEntity npc = store.getComponent(ref, NPCEntity.getComponentType()); // Handle NPC spawn }
@Override public Query<EntityStore> getQuery() { return NPCEntity.getComponentType(); }}Combat Events
Section titled “Combat Events”// NPC kill eventgetEventRegistry().register(KillFeedEvent.class, event -> { // Handle kill});Creating NPCs
Section titled “Creating NPCs”Spawn NPC Programmatically
Section titled “Spawn NPC Programmatically”// Create NPC holderHolder<EntityStore> holder = EntityStore.REGISTRY.newHolder();
// Add NPCEntity componentNPCEntity npc = new NPCEntity();holder.addComponent(NPCEntity.getComponentType(), npc);
// Add transformTransformComponent transform = new TransformComponent(x, y, z, 0, 0, 0);holder.addComponent(TransformComponent.getComponentType(), transform);
// Add UUIDholder.addComponent(UUIDComponent.getComponentType(), new UUIDComponent(UUID.randomUUID()));
// SpawnStore<EntityStore> store = world.getEntityStore().getStore();Ref<EntityStore> ref = store.spawn(holder);NPC Configuration Assets
Section titled “NPC Configuration Assets”NPCs are configured through role assets:
{ "Id": "MyPlugin_CustomNPC", "MaxHealth": 20, "Appearance": "Models/NPCs/custom_npc", "DropList": "MyPlugin_CustomDrops", "Behavior": { "Root": { "Type": "Selector", "Children": [ { "Type": "Sequence", "Conditions": ["health < 50"], "Actions": ["Flee"] }, { "Type": "Wander" } ] } }}Best Practices
Section titled “Best Practices”- Use roles: Define behavior through role configurations
- Leverage flocks: Group related NPCs for coordinated behavior
- Optimize queries: Use efficient ECS queries for NPC systems
- Handle lifecycle: Properly handle NPC add/remove events
- Use blackboards: Share state through blackboard system
- Configure spawning: Use spawn beacons and markers for controlled spawning
Related
Section titled “Related”- Entity System - Base entity documentation
- ECS Overview - Component system
- Events - Event handling