Eve library

Aphrodite Game Platform Architecture

Guide

Revision 1

On this page

Technical architecture documentation for the Aphrodite game platform — a modular, event-driven game engine ecosystem built in TypeScript within the Oshun Nx monorepo.


Table of Contents#

  1. System Architecture Overview
  2. Library Catalog
  3. Event Bus and Data Flow
  4. Device Reaction Engine Design
  5. Music Engine Architecture
  6. Rendering Pipeline
  7. Testing Infrastructure

System Architecture Overview#

The Aphrodite game platform is organized as a collection of independent libraries under libs/aphrodite/. Each library owns a single domain concern and communicates via typed event emitters. The platform supports real-time game experiences with adaptive music, haptic feedback, visual effects, and performance optimization.

Core Design Principles#

  • Modular independence: Each library is a standalone Nx project with its own types, implementation, tests, and barrel exports.
  • Event-driven communication: Engines emit typed events rather than calling each other directly, enabling loose coupling.
  • Orchestrator pattern: Complex subsystems aggregate specialized sub-engines via orchestrator classes that forward events.
  • Factory-first instantiation: All engines are created via factory functions with partial configuration objects and sensible defaults.
  • Comprehensive type safety: Separate *-types.ts files define all domain types, const enums, interfaces, and configuration defaults.

Module File Convention#

Every module follows this structure:

text
libs/aphrodite/<library>/src/
  <module>-types.ts      # Types, interfaces, const enums, config defaults
  <module>.ts            # Implementation (engines, classes, factory functions)
  <module>.spec.ts       # Vitest unit tests
  index.ts               # Barrel export

Submodules live in subdirectories with their own barrel:

text
libs/aphrodite/<library>/src/<submodule>/
  <submodule>-types.ts
  <submodule>.ts
  <submodule>.spec.ts
  index.ts

Library Catalog#

Core Infrastructure#

Library Path Purpose
game-ecs libs/aphrodite/game-ecs/ Entity-Component-System framework
game-event-bus libs/aphrodite/game-event-bus/ Global typed event bus
game-input libs/aphrodite/game-input/ Input handling and mapping
game-physics libs/aphrodite/game-physics/ Physics simulation
game-assets libs/aphrodite/game-assets/ Asset loading and management
game-networking libs/aphrodite/game-networking/ Multiplayer networking
game-runtime libs/aphrodite/game-runtime/ Game loop and lifecycle
core libs/aphrodite/core/ Shared utilities and base types

Performance and Optimization#

Library Path Engines
game-performance libs/aphrodite/game-performance/ LODManager, TextureStreamingManager, DrawCallBatcher, OcclusionCullingEngine, FrameBudgetMonitor
game-performance/network .../network/ DeltaCompressionEngine, PacketSchedulerEngine, AdaptiveTickRateEngine, JitterBufferEngine
game-performance/device-latency .../device-latency/ DeviceCommandPreBuffer, BLEConnectionOptimizer, CommandCoalescing, LatencyCompensation
game-performance/profiler .../profiler/ GPUTimingProfilerEngine, MemoryAllocationTrackerEngine, ShaderCompilationMonitorEngine, RegressionDetectorEngine

Music and Audio#

Library Path Engines
cinematic-music-engine libs/aphrodite/cinematic-music-engine/ 21 specialized music engines (see Music Engine Architecture)
game-audio libs/aphrodite/game-audio/ Core audio playback and mixing
spatial-audio libs/aphrodite/spatial-audio/ 3D spatial audio positioning
audio-haptics libs/aphrodite/audio-haptics/ Audio-to-haptic translation

Haptics and Device Control#

Library Path Purpose
haptics libs/aphrodite/haptics/ Core haptic feedback system
bidirectional-haptics libs/aphrodite/bidirectional-haptics/ Two-way haptic communication
motion-haptics libs/aphrodite/motion-haptics/ Movement-based haptic feedback
device-reaction-engine libs/aphrodite/device-reaction-engine/ Device reaction pattern system
device-safety libs/aphrodite/device-safety/ Safety limits and compliance

Scene and Environment#

Library Path Engines
scene-nature libs/aphrodite/scene-nature/ JungleSceneEngine, UnderwaterSceneEngine, VolcanicSceneEngine, ArcticSceneEngine, ZenGardenEngine, StormSceneEngine
scene-cosmic libs/aphrodite/scene-cosmic/ Space and celestial environments
scene-abstract libs/aphrodite/scene-abstract/ Abstract and procedural scenes
scene-fantasy libs/aphrodite/scene-fantasy/ Fantasy world environments
scene-urban libs/aphrodite/scene-urban/ City and architectural scenes
scene-composer libs/aphrodite/scene-composer/ Scene composition and layering

Rendering and VFX#

Library Path Purpose
game-renderer libs/aphrodite/game-renderer/ Core rendering pipeline
neural-rendering libs/aphrodite/neural-rendering/ AI-powered rendering
vfx-particles libs/aphrodite/vfx-particles/ Particle effects system
vfx-post-processing libs/aphrodite/vfx-post-processing/ Post-processing effects
vfx-volumetric libs/aphrodite/vfx-volumetric/ Volumetric rendering
cinematic-camera libs/aphrodite/cinematic-camera/ Camera system and cinematography

Game Genre Engines#

Library Path Genre
game-fps libs/aphrodite/game-fps/ First-person shooter
game-rpg libs/aphrodite/game-rpg/ Role-playing games
game-fighting libs/aphrodite/game-fighting/ Fighting games
game-platformer libs/aphrodite/game-platformer/ Platformers
game-racing libs/aphrodite/game-racing/ Racing games
game-puzzle libs/aphrodite/game-puzzle/ Puzzle games
game-rhythm libs/aphrodite/game-rhythm/ Rhythm games
game-strategy libs/aphrodite/game-strategy/ Strategy games
game-horror libs/aphrodite/game-horror/ Horror games
game-sports libs/aphrodite/game-sports/ Sports games
game-simulation libs/aphrodite/game-simulation/ Simulation games
game-openworld libs/aphrodite/game-openworld/ Open-world games

Testing#

Library Path Test Modules
game-testing libs/aphrodite/game-testing/ GameSimulationHarness, DeviceReactionAssertions, MusicStateAssertions, ScreenshotComparisonEngine, EventRecorderPlaybackEngine
game-testing/device-tests .../device-tests/ GenreReactionProfileValidator, SafetyLimitVerifier, MultiDeviceChoreographyTester, DeviceLatencyMeasurer, IntensityCurveSmoothnessTester
game-testing/music-tests .../music-tests/ BeatTimingAccuracyTester, MusicalTransitionSmoothnessTester, BiometricMusicCorrelationTester, GameEventStingerTimingTester
game-testing/visual-tests .../visual-tests/ ParticleEffectPerformanceBenchmarker, PostProcessingQualityTester, SceneRenderingRegressionTester, PerformerOverlayCompositingTester
game-testing/performance-tests .../performance-tests/ FrameRateStabilityTester, MemoryLeakDetector, NetworkBandwidthProfiler, ConcurrentViewerScalabilityTester

Platform Bridges#

Library Purpose
nyx-game-bridge Integration with Nyx cosmic observatory
hathor-game-bridge Integration with Hathor worldbuilding
isis-game-bridge Integration with Isis generative factory
lilith-game-bridge Integration with Lilith consciousness
maya-bridge Integration with Maya game engine
nike-game-bridge Integration with Nike fitness platform

Event Bus and Data Flow#

Event Emitter Pattern#

Every engine implements a local event emitter with typed event constants:

typescript
// Types file defines event constants
export const DEVICE_EVENTS = {
  COMMAND_DISPATCHED: 'device:command:dispatched',
  PROBE_RECORDED: 'device:probe:recorded',
  QUALITY_CHANGED: 'device:quality:changed',
} as const;

// Engine emits events internally
class DeviceCommandPreBufferEngine {
  private readonly emitter = createEventEmitter();

  dispatch(command: ScheduledCommand): DispatchResult {
    // ... logic
    this.emitter.emit(DEVICE_EVENTS.COMMAND_DISPATCHED, result);
    return result;
  }

  on(event: string, listener: (...args: unknown[]) => void): void {
    this.emitter.on(event, listener);
  }
}

Orchestrator Event Forwarding#

Orchestrator engines aggregate sub-engines and forward their events:

typescript
class DeviceLatencyEngine {
  private readonly preBuffer: DeviceCommandPreBufferEngine;
  private readonly bleOptimizer: BLEConnectionOptimizerEngine;
  private readonly coalescing: CommandCoalescingEngine;
  private readonly compensation: LatencyCompensationEngine;

  constructor(config: DeviceLatencyConfig) {
    this.preBuffer = new DeviceCommandPreBufferEngine(config.preBuffer);
    this.bleOptimizer = new BLEConnectionOptimizerEngine(config.bleOptimizer);
    // ...

    // Forward all sub-engine events through the orchestrator
    this.forwardEvents(this.preBuffer);
    this.forwardEvents(this.bleOptimizer);
    this.forwardEvents(this.coalescing);
    this.forwardEvents(this.compensation);
  }

  private forwardEvents(source: { on: unknown }): void {
    (source.on as (event: string, listener: (data: never) => void) => void)(
      '*',
      (data) => this.emitter.emit('*', data)
    );
  }
}

Data Flow Diagram#

text
[Game Events] ──> [Game Event Bus] ──> [Device Reaction Engine]
                        │                        │
                        │                        ├──> [Haptics Engine]
                        │                        └──> [Device Safety Limiter]
                        │
                        ├──> [Cinematic Music Engine]
                        │         │
                        │         ├──> [Adaptive Music] ──> [Audio Output]
                        │         ├──> [Biometric Engine] <── [Biometric Input]
                        │         └──> [Game Scoring]
                        │
                        ├──> [Scene Engine]
                        │         │
                        │         ├──> [Particle VFX]
                        │         ├──> [Post-Processing]
                        │         └──> [Renderer] ──> [GPU]
                        │
                        └──> [Performance Monitor]
                                  │
                                  ├──> [Frame Budget Monitor]
                                  ├──> [GPU Profiler]
                                  └──> [Network Optimizer]

Configuration Flow#

All engines accept partial configuration objects that merge with defaults:

typescript
export interface DeviceLatencyConfig {
  preBuffer?: Partial<PreBufferConfig>;
  bleOptimizer?: Partial<BLEOptimizerConfig>;
  coalescing?: Partial<CommandCoalescingConfig>;
  compensation?: Partial<LatencyCompensationConfig>;
}

// Factory with defaults
export function createDeviceLatencyEngine(
  config?: Partial<DeviceLatencyConfig>
): DeviceLatencyEngine {
  return new DeviceLatencyEngine({
    preBuffer: { ...DEFAULT_PRE_BUFFER_CONFIG, ...config?.preBuffer },
    bleOptimizer: { ...DEFAULT_BLE_CONFIG, ...config?.bleOptimizer },
    // ...
  });
}

Device Reaction Engine Design#

The device reaction system translates game events into physical feedback through multiple layers of processing, safety verification, and optimization.

Architecture Layers#

text
[Game Event] ──> [Reaction Pattern Matcher]
                          │
                          v
                 [Intensity Calculator]
                          │
                          v
                  [Safety Limiter] ──> Clamp intensity, enforce cooldowns
                          │
                          v
               [Command Pre-Buffer] ──> Schedule ahead of time
                          │
                          v
              [Command Coalescing] ──> Merge redundant commands
                          │
                          v
            [BLE Connection Optimizer] ──> Optimize connection params
                          │
                          v
            [Latency Compensation] ──> Predict and offset timing
                          │
                          v
                   [Device Output]

Safety Limits#

The SafetyLimitVerifier enforces hard constraints:

Limit Default Description
Max Intensity 0.85 Absolute maximum device intensity (0..1)
Max Duration 5000ms Maximum single reaction duration
Max Frequency 30Hz Maximum reactions per second
Cooldown 33ms Minimum gap between reactions (~30Hz)
Max Concurrent Devices 8 Maximum simultaneously active devices
Max Total Intensity 3.0 Sum of all concurrent device intensities

Genre Reaction Profiles#

Each game genre has a predefined reaction profile constraining intensity, duration, frequency, and allowed reaction types:

Genre Intensity Range Duration Range Max Frequency Allowed Types
Action 0.1 – 0.85 20 – 2000ms 25Hz haptic, vibration, rumble, impact, explosion
Horror 0.05 – 0.7 50 – 5000ms 10Hz haptic, vibration, rumble, pulse, ambient
Racing 0.1 – 0.9 10 – 3000ms 30Hz haptic, vibration, rumble, engine, crash, surface
Rhythm 0.2 – 0.8 10 – 500ms 20Hz haptic, vibration, beat, tap, pulse
RPG 0.05 – 0.75 30 – 3000ms 15Hz haptic, vibration, rumble, magic, hit, heal
Puzzle 0.05 – 0.5 20 – 1000ms 5Hz haptic, vibration, click, snap, solve
Simulation 0.05 – 0.6 30 – 4000ms 10Hz haptic, vibration, rumble, feedback, ambient
Sports 0.1 – 0.85 15 – 2000ms 20Hz haptic, vibration, rumble, impact, kick, catch

Device Latency Optimization#

Four specialized engines minimize device latency:

  1. DeviceCommandPreBufferEngine: Schedules commands ahead of playback time with priority eviction and TTL expiration.
  2. BLEConnectionOptimizerEngine: Adapts BLE connection parameters per use case (low latency, balanced, power saving, high throughput, burst). Monitors RSSI with EWMA smoothing and assesses quality.
  3. CommandCoalescingEngine: Merges redundant commands within time windows using configurable strategies (keep latest, keep first, highest priority, merge payloads).
  4. LatencyCompensationEngine: Records round-trip probes per device, predicts latency with trend analysis, and applies adaptive timing offsets.

Music Engine Architecture#

The Cinematic Music Engine is the most complex subsystem, comprising 21 specialized engines organized in layers.

Engine Hierarchy#

text
[CinematicMusicEngine] (Orchestrator)
    │
    ├── Core Composition
    │   ├── AdaptiveMusicEngine     — State-driven music (exploration→action→climax)
    │   ├── VerticalOrchestrator    — Layer stacking (foundation→accent)
    │   ├── HorizontalSequencer     — Section flow (verse→chorus→bridge)
    │   └── ParameterSystem         — Real-time parameter automation
    │
    ├── Instrument Engines
    │   ├── OrchestraEngine         — Orchestral samples, velocity, articulation
    │   ├── PercussionEngine        — Drum patterns, builds, heartbeat sync
    │   ├── ChoirEngine             — Vocal sections, crescendos, expression
    │   ├── SynthEngine             — Pads, bass, arpeggios, haptic output
    │   └── AmbientEngine           — Soundscapes, drones, weather textures
    │
    ├── Intelligence Layer
    │   ├── BiometricEngine         — HR, HRV, breathing, GSR → music params
    │   ├── BiometricMixEngine      — Emotion-driven mixing, ducking, stereo
    │   ├── ExpressionMappingEngine — Facial expression → ornaments/texture
    │   ├── VocalScoringEngine      — Performer voice → harmonic analysis
    │   └── EmotionalArcEngine      — Narrative phases, leitmotifs, fatigue
    │
    ├── Game Integration
    │   ├── GameScoringEngine       — Game events → stingers/phrases/accents
    │   ├── BossBattleEngine        — Boss phases, health-based intensity
    │   ├── ComboEngine             — Combo tiers, phrase stacking, climax
    │   └── EnvironmentEngine       — Biome themes, weather, acoustics
    │
    ├── Context
    │   ├── CueSystem               — Stinger libraries, context selection
    │   ├── PaletteEngine           — Genre palettes, chord progressions
    │   └── MultiplayerEngine       — Team tension, competitive momentum
    │
    └── Output → [Audio Pipeline] → [Spatial Audio] → [Speaker/Headphones]

Biometric-to-Music Mapping#

The BiometricEngine maps physiological signals to musical parameters:

Biometric Signal Musical Parameter Correlation
Heart Rate Tempo Positive — faster heart = faster tempo
Heart Rate Variability Harmonic Complexity Positive — higher HRV = richer harmonics
Breathing Rate Phrase Length Inverse — slower breathing = longer phrases
Galvanic Skin Response Intensity / Dynamics Positive — higher GSR = louder dynamics
Skin Temperature Timbre Warmth Positive — warmer skin = warmer tones

The mapping pipeline:

text
[Biometric Sensors]
    │
    ├── Heart Rate ──> CalibrationEngine ──> NormalizedRate ──> TempoMapper
    ├── HRV ──────────> CoherenceAnalysis ──> HarmonicSelector
    ├── Breathing ────> PhaseTracker ──────> PhraseController
    ├── GSR ──────────> ResponseDetector ──> DynamicsController
    └── Temperature ──> TrendAnalyzer ─────> TimbreBlender
                                                    │
                                                    v
                                          [Emotional State Fusion]
                                                    │
                                                    v
                                          [Musical Output Parameters]

Transition System#

The HorizontalSequencer manages section transitions with multiple methods:

Method Description Use Case
Immediate Hard cut between sections Emergency transitions
Crossfade Gradual volume crossfade General-purpose
Beat Sync Transition on next beat boundary Rhythmic accuracy
Measure Sync Transition at measure boundary Musical coherence
Stinger Transition via a connecting musical phrase Dramatic moments
Fade Out/Fade In Complete fade out then fade in Scene changes

Each section defines phrase boundaries — safe exit points within the section where transitions sound musically coherent.

Game Event Scoring#

The GameScoringEngine maps game events to musical responses:

Event Category Musical Response Examples
Impact Percussion accent, brass stab
Achievement Fanfare, harmonic resolution
Tension String tremolo, dissonance
Discovery Melodic phrase, harp glissando
Failure Descending phrase, minor key shift
Combat Orchestral swell, electronic stinger
Stealth Suspense pad, choir accent

Rendering Pipeline#

Performance Optimization Stack#

The @aphrodite/game-performance library provides five core optimization engines:

text
[Scene Graph]
    │
    ├── OcclusionCullingEngine
    │   └── Frustum + occlusion queries → visible object set
    │
    ├── LODManager
    │   └── Distance-based LOD selection → reduced triangle count
    │
    ├── DrawCallBatcher
    │   └── Material/mesh instancing → batched draw calls
    │
    ├── TextureStreamingManager
    │   └── Priority-based mipmap streaming → managed VRAM
    │
    └── FrameBudgetMonitor
        └── Per-frame budget tracking → adaptive quality scaling

GPU Profiler#

The profiler subsystem tracks GPU and rendering performance:

  • GPUTimingProfilerEngine: Records per-pass timing (shadow, gbuffer, lighting, post-process, UI), computes percentile statistics (p50/p95/p99), detects slow passes.
  • MemoryAllocationTrackerEngine: Tracks GPU allocations by category (textures, buffers, render targets, shaders, pipelines, samplers, queries, acceleration structures, descriptors), monitors budgets, detects leaks.
  • ShaderCompilationMonitorEngine: Tracks compilation lifecycle with variant- aware caching (key: shaderName:variantKey), monitors hit/miss rates.
  • RegressionDetectorEngine: Records metrics over sliding windows, creates baselines, detects regressions (>5% info, >10% warning, >25% critical).

Network Optimization#

For multiplayer and streaming scenarios:

  • DeltaCompressionEngine: Only transmits state changes, reducing bandwidth by computing entity-level diffs.
  • PacketSchedulerEngine: Priority-based packet scheduling with bandwidth allocation across reliability levels.
  • AdaptiveTickRateEngine: Dynamically adjusts server tick rate based on network conditions and player count.
  • JitterBufferEngine: Smooths packet arrival timing for consistent playback.

Scene Rendering#

The @aphrodite/scene-nature library provides six procedurally-generated environment engines, each with specialized rendering features:

Scene Key Rendering Features
Jungle Plant sway simulation, bioluminescence glow, canopy shadows, river caustics
Underwater God rays, caustic patterns, coral growth, bubble particles, hair physics
Volcanic Lava flow simulation, crystal refraction, ember particles, heat distortion
Arctic Ice formation growth, aurora borealis, snow particles, ice palace generation
Zen Garden Cherry petal physics, sand raking patterns, wind chime triggers, stone arrangements
Storm Cloud formation, lightning branching, rain physics, tornado vortex, thunder delay

Testing Infrastructure#

The @aphrodite/game-testing library provides comprehensive testing utilities organized in five modules (255 total tests).

Test Module Summary#

Module Tests Engines
Core 65 GameSimulationHarness, DeviceReactionAssertions, MusicStateAssertions, ScreenshotComparisonEngine, EventRecorderPlaybackEngine
Device Tests 66 GenreReactionProfileValidator, SafetyLimitVerifier, MultiDeviceChoreographyTester, DeviceLatencyMeasurer, IntensityCurveSmoothnessTester
Music Tests 49 BeatTimingAccuracyTester, MusicalTransitionSmoothnessTester, BiometricMusicCorrelationTester, GameEventStingerTimingTester
Visual Tests 41 ParticleEffectPerformanceBenchmarker, PostProcessingQualityTester, SceneRenderingRegressionTester, PerformerOverlayCompositingTester
Performance Tests 34 FrameRateStabilityTester, MemoryLeakDetector, NetworkBandwidthProfiler, ConcurrentViewerScalabilityTester

Testing Patterns#

GameSimulationHarness: Headless game loop with configurable frame rate, tick callbacks, event injection at specific frames, and state snapshots at intervals.

Screenshot Regression: Pixel-by-pixel comparison with per-channel tolerance, region-of-interest support, and similarity scoring.

Biometric Correlation Testing: Pearson correlation analysis between biometric signals and music parameters with cross-correlation lag estimation.

Scalability Testing: SLA-based concurrent viewer analysis with degradation onset detection and stress test breaking point identification.