Skip to content

iKryptonic/RBXStateMachine

Repository files navigation

RBXStateMachine

RBXStateMachine is a high-performance, full-stack architectural framework for Roblox. It is designed to manage complex gameplay logic, server-authoritative state replication, and CPU budgeting for games that need to scale from a handful of agents to thousands.

It is not just a finite-state-machine library. It is a complete runtime β€” registry, scheduler, networking, persistence, dev console, and AI primitives β€” built around four cooperating components: Brain, Body, Pulse, and Nervous System.

πŸ“– Full documentation lives in the Project Wiki (36 pages, ~500 KB). Start with the 5-Minute Quick Start or the System Architecture deep dive.


πŸ›οΈ The "4 Pillars" Architecture

The framework enforces a strict separation of concerns through four cooperating components:

Pillar Component Responsibility Analog
🧠 Brain BaseStateMachine Decision making, transitions, AI logic The thinker
πŸ›‘οΈ Body BaseEntity Schema-validated data + Instance proxy The actor
⚑ Pulse Scheduler Frame-budgeted time-slicing The heartbeat
πŸ•ΈοΈ Nervous System Orchestrator Registry, factory, replication, lifecycle The microkernel

This separation is what lets you put 500+ NPCs on a server without dropping frames, replicate state to clients without writing a single RemoteEvent, and refactor the AI for one entity without touching the visuals for another.

πŸ“ See System Architecture for the runtime diagram and bootstrap order.


🌟 Key Features

Core Runtime

  • ⚑ Frame-Budgeted Execution β€” The Scheduler caps work per frame at a configurable budget (default 5–15 ms) with priority aging so background jobs never starve.
  • 🧬 Hierarchical FSMs (HFSM) β€” Nest sub-machines inside states (e.g. a Combat state containing Melee / Ranged). See Hierarchical FSM.
  • 🌳 Functional Behavior Trees β€” Composable Sequence, Selector, Parallel, Decorator, Action, Condition nodes via BehaviorTree.
  • ♻️ Resource Tracking β€” Every FSM/Entity has a Manage() method that auto-disconnects connections, destroys instances, and runs cleanup callbacks on Stop().

Data & Replication

  • πŸ”’ Transactional Schema β€” Entities use a stage-and-commit flow (SetField β†’ UpdateEntity()); validation fails atomically with no partial writes. See Replication Pipeline.
  • πŸ“‘ Automatic Replication β€” Mark a schema field with Replicate = true and the framework wires the RemoteEvent, batches deltas, applies rate limits, and sanitizes inbound writes.
  • πŸ’Ύ Integrated Persistence β€” One-line opt-in via EntityPersistence saves entity state to DataStores. Includes versioning + migrations (Versioning) and a 7-second write throttle out of the box.
  • πŸ›‘οΈ Server Authority β€” Inbound RemoteEvent payloads are sanitized to a configurable depth (default 8) and rate-limited per player.

Performance & Scaling

  • 🧡 Parallel Workers β€” ActorPool dispatches CPU-heavy jobs to Roblox Actor instances for true parallel execution.
  • ♻️ Entity Pooling β€” Recycle entities across spawns to avoid GC pressure in high-frequency systems (projectiles, particles). See Pooling Strategy.
  • πŸ“Š Performance Tuning β€” Capacity planning, profiling, and budget math: Performance Tuning.

Operations & Debugging

  • πŸ–₯️ Built-in Dev Console β€” ServiceManager ships a 9-page in-game UI: logs, entities, FSMs, performance, history, terminal, settings, etc.
  • πŸ“ Structured Logger β€” Logger with a 500-entry circular buffer, log levels, and console streaming.
  • πŸ§ͺ Spec-style Tests β€” Full unit + integration suite under FSM/Tests/ (Replication, Pooling, Discovery, Scheduler, Logger, Mocking, etc.). See Testing & Validation.

πŸ“‚ Project Structure

RBXStateMachine/
β”œβ”€β”€ FSM/                          ← The core engine (4 Pillars + auxiliary systems)
β”‚   β”œβ”€β”€ Orchestrator/             ← Registry, Factory, ActorPool, ServiceManager, NetworkManager
β”‚   β”œβ”€β”€ Factory/                  ← BaseEntity, BaseStateMachine, PersistenceManager, Registry
β”‚   β”œβ”€β”€ EntityRegistry.luau       ← Runtime entity registry
β”‚   β”œβ”€β”€ StateMachineRegistry.luau ← Runtime state-machine registry
β”‚   β”œβ”€β”€ Client.client.luau        ← Client bootstrap script
β”‚   β”œβ”€β”€ Tests/                    ← Spec-style unit & integration tests
β”‚   └── README.md                 ← Deep technical implementation reference
β”‚
β”œβ”€β”€ example/                      ← Working reference implementations
β”‚   β”œβ”€β”€ DoorEntityExample.luau    ← Schema, replication, instance proxying
β”‚   β”œβ”€β”€ DoorStateMachineExample.luau ← Multi-state FSM with validation & failure paths
β”‚   └── GameControllerExample.luau   ← Bootstrap + entity/FSM creation flow
β”‚
└── RBXStateMachine.wiki/         ← Wiki source (36 pages, comprehensive guide)

The wiki is a separate git repository mounted as a nested directory; it is published at https://github.com/iKryptonic/RBXStateMachine/wiki.


πŸš€ Quick Installation

1. Sync into your project

Use Rojo (or your tool of choice) to sync the FSM/ directory into ReplicatedStorage as RBXStateMachine. Place your custom Entity and StateMachine modules as direct children of ReplicatedStorage β€” the Orchestrator's Factory discovers these folders by name:

ReplicatedStorage/
β”œβ”€β”€ RBXStateMachine/    ← The framework (this repo's FSM/ folder)
β”œβ”€β”€ Entity/             ← Your *Entity.luau modules go here
└── StateMachine/       ← Your *StateMachine.luau modules go here

πŸ“š Folder layout details: Registration Guide.

2. Bootstrap (Server)

-- ServerScriptService/Bootstrap.server.luau
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local FSM = require(ReplicatedStorage:WaitForChild("RBXStateMachine"))

-- Discover Entity/StateMachine modules and wire up remotes, scheduler, logger.
FSM.Orchestrator:RegisterComponents()

3. Bootstrap (Client)

-- StarterPlayerScripts/Bootstrap.client.luau
local ReplicatedStorage = game:GetService("ReplicatedStorage")
ReplicatedStorage:WaitForChild("Entity")
ReplicatedStorage:WaitForChild("StateMachine")

local FSM = require(ReplicatedStorage:WaitForChild("RBXStateMachine"))
FSM.Orchestrator:RegisterComponents()

FSM/Client.client.luau ships as a ready-to-use client bootstrap if you'd rather sync that directly under StarterPlayerScripts.

πŸ“š Full walkthrough with error handling and verification: Installation Guide.


⚑ Hello, World β€” A Spinning Part

-- ServerScriptService/Bootstrap.server.luau
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local FSM = require(ReplicatedStorage:WaitForChild("RBXStateMachine"))
FSM.Orchestrator:RegisterComponents()

local part = workspace.SpinningPart -- any Part in workspace

-- 1. Wrap the Instance in a schema-validated Entity.
local entity = FSM.Orchestrator.CreateEntity({
    EntityClass = "SpinnerEntity",
    EntityId    = "Spinner1",
    Context     = { Instance = part },
})

-- 2. Attach a brain that drives it.
local fsm = FSM.Orchestrator.CreateStateMachine({
    StateMachineClass = "SpinnerStateMachine",
    StateMachineId    = "Spinner1_FSM",
    Context           = { SpinnerEntity = entity },
})

fsm:Start({ State = "Spinning" })

The SpinnerEntity and SpinnerStateMachine modules live under ReplicatedStorage/Entity/ and ReplicatedStorage/StateMachine/ respectively. See example/DoorEntityExample.luau for a complete reference implementation, or the Quick Start for a full walkthrough.


πŸ“– Documentation Map

The wiki is structured by audience:

You want to… Go to
Build your first agent in 5 minutes Quick Start
Understand the runtime end-to-end Architecture
Look up a method signature API Reference
Learn how state replicates to clients Replication Pipeline
Build nested AI states Hierarchical FSM
Persist player/entity data EntityPersistence + Versioning
Hit 60 FPS with 500+ NPCs Performance Tuning + Pooling Strategy
Write production-grade code Best Practices + Production Readiness
Diagnose a bug Debugging + FAQ
Migrate from another FSM library Migration Guide
Look up unfamiliar terms Glossary

πŸ’‘ The Wiki Home has full Beginner / Intermediate / Expert learning paths.


🎯 Should I Use This Framework?

βœ… Use RBXStateMachine if you are…

  • Building a multiplayer game with server authority
  • Managing 50+ NPCs / agents / entities concurrently
  • Need persistent player or world data
  • Working in a team where consistent patterns matter
  • Building anything where dropped frames are unacceptable

❌ Consider alternatives if you are…

  • Prototyping a 3-day game jam entry
  • Building a single-player showcase with simple if/else logic
  • Working solo on a small project where the architectural overhead outweighs the benefits

πŸ§ͺ Testing

The framework ships with a comprehensive Spec-style test suite under FSM/Tests/:

  • Unit tests: Logger, Mocking, Orchestrator, Discovery, Scheduler, Replication Security, Registry, Pool Reuse, Fail-with-nil-history, …
  • Integration tests: DataStoreEntity, EntityPooling, Factory, ServiceManager, Replication, Iteration Safety, …

Run them via your Roblox test runner of choice. See Testing & Validation for setup and authoring conventions.


πŸ“š Learn More

  • 🏠 Wiki Home β€” Full table of contents and learning paths
  • πŸ“ FSM/README.md β€” Deep technical reference for framework internals
  • πŸ’¬ FAQ & Troubleshooting β€” Common questions answered
  • πŸ› Issues β€” Bug reports and feature requests welcome

About

No description, website, or topics provided.

Resources

Contributing

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages