Verekia architecture

From verekia/r3f-gamedev · View interactive version

Verekia architecture is an AI agent skill from the GitHub repository verekia/r3f-gamedev. Day-to-day coding style and patterns for R3F game development with Miniplex ECS.

How to use this skill

Skill file

Architecture

The core principle of R3F game development is separating game logic from rendering. React components are views, not the source of truth.

Systems vs Views

Systems contain all game logic:

Views (React components) only render:

Headless-First Mindset

Games should be capable of running entirely without a renderer:

┌─────────────────────────────────────────┐
│            Game Logic Layer             │
│  (Systems, ECS, World State, Entities)  │
└─────────────────────────────────────────┘
                    │
                    ▼
┌─────────────────────────────────────────┐
│            View Layer (optional)        │
│   React Three Fiber / DOM / Headless    │
└─────────────────────────────────────────┘

This means:

Miniplex: What NOT to Use

From miniplex-react:

From miniplex core:

Miniplex: Preferred Methods

Only use these:

Entity Types and Queries

// lib/ecs.ts
import { World } from 'miniplex'
import createReactAPI from 'miniplex-react'

type Entity = {
  position?: { x: number; y: number; z: number }
  velocity?: { x: number; y: number; z: number }
  isCharacter?: true
  isEnemy?: true
  three?: Object3D | null
}

export const world = new World<Entity>()

export const characterQuery = world.with('position', 'isCharacter', 'three')
export type CharacterEntity = (typeof characterQuery)['entities'][number]

// Only destructure Entities from React API
export const { Entities } = createReactAPI(world)

ModelContainer Pattern

Capture Three.js object references on entities using a wrapper component, allowing systems to manipulate objects directly.

Similar to the Redux container/component pattern:

┌─────────────────────────────────────────┐
│  PlayerEntity (smart)                   │
│  - Wraps with ModelContainer            │
│  - Passes entity data as props          │
│                                         │
│    ┌─────────────────────────────────┐  │
│    │  PlayerModel (dumb)             │  │
│    │  - Pure rendering               │  │
│    │  - Receives props               │  │
│    │  - No knowledge of entities     │  │
│    └─────────────────────────────────┘  │
└─────────────────────────────────────────┘

Entity as Props Pattern

The component passed to <Entities> receives the entity directly as props:

// Dumb component - only renders, no entity knowledge
const CharacterModel = () => (
  <mesh>
    <sphereGeometry />
    <meshBasicMaterial color="blue" />
  </mesh>
)

// Smart wrapper - connects entity to model via ModelContainer
const CharacterEntity = (entity: CharacterEntity) => (
  <ModelContainer entity={entity}>
    <CharacterModel />
  </ModelContainer>
)

// entities/entities.tsx (contains <Entities> for all renderable entities)

const isCharacterQuery = world.with('isCharacter')

export const CharacterEntities = () => <Entities in={isCharacterQuery}>{CharacterEntity}</Entities>

Systems and Queries

Query Placement

Define queries near where they are used (in the system file), not in a central file. But define them outside the loop at module scope:

import { world } from '@/lib/ecs'

// ✅ Query defined at module scope, near where it's used
const movingEntities = world.with('position', 'velocity')
type MovingEntity = (typeof movingEntities)['entities'][number]

One + System Pattern

Split logic into a "One" function (operates on a single entity) and the system (iterates and calls One):

import { world } from '@/lib/ecs'

// Query at module scope
const movingEntities = world.with('position', 'velocity')
type MovingEntity = (typeof movingEntities)['entities'][number]

// "One" function - single entity logic, easy to test
const velocityOne = (e: MovingEntity, dt: number) => {
  e.position.x += e.velocity.x * dt
  e.position.y += e.velocity.y * dt
  e.position.z += e.velocity.z * dt
}

// System - just iteration
export const VelocitySystem = () => {
  useFrame((_, dt) => {
    for (const e of movingEntities) {
      velocityOne(e, dt)
    }
  })

  return null
}

Query by Components, Not Types

Systems must iterate over queries tailored to their specific needs, not over entity types:

// ✅ GOOD - Query targets entities with the components the system needs
const entitiesWithVelocity = world.with('position', 'velocity')

const VelocitySystem = () => {
  useFrame((_, delta) => {
    for (const entity of entitiesWithVelocity) {
      entity.position.x += entity.velocity.x * delta
    }
  })
  return null
}

// ❌ BAD - Iterating over specific entity types
const VelocitySystem = () => {
  useFrame((_, delta) => {
    for (const player of players) {
      /* ... */
    }
    for (const enemy of enemies) {
      /* ... */
    }
    for (const projectile of projectiles) {
      /* ... */
    }
  })
  return null
}

The point of an ECS is that systems operate on a subset of entities matching exactly what they need. A VelocitySystem targets entities with velocity, not "players + enemies + projectiles".

ThreeSystem - Syncing Three.js

const threeEntities = world.with('position', 'three')
type ThreeEntity = (typeof threeEntities)['entities'][number]

const threeOne = (e: ThreeEntity) => {
  e.three.position.set(e.position.x, e.position.y, e.position.z)
}

export const ThreeSystem = () => {
  useFrame(() => {
    for (const e of threeEntities) {
      threeOne(e)
    }
  })

  return null
}

Spawning Entities

const SpawnSystem = () => {
  useEffect(() => {
    world.add({ position: { x: 0, y: 0, z: 0 }, isCharacter: true })
  }, [])

  return null
}

Zustand Store Usage

Zustand stores are for state that doesn't belong in the ECS. Each store has a consistent API pattern:

// In React components (reactive)
const areSettingsOpen = useUI('areSettingsOpen')

// Outside React / in systems (non-reactive)
const settings = getUI().areSettingsOpen

// Setting values
setUI('areSettingsOpen', true)
setUI({ areSettingsOpen: true, debug: { drawCalls: 100 } })

// Reset to defaults
resetUI()

Key Principles


This skill is part of verekia's **r3f-gamedev**.

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.