# Device Reaction Engine API Reference

`@aphrodite/device-reaction-engine` — Translates game events into haptic device
commands with genre-specific profiles, pattern synthesis, and safety
enforcement.

---

## Architecture

```
Game Event Bus
     │
     ├──► Translation Rules ──► Intensity/Duration Mapping
     │         │
     │         ▼
     │    Device Command
     │         │
     ├──► Safety Limiter ──► Clamped Command
     │         │
     │         ▼
     └──► Device Protocol Layer ──► Physical Device
```

---

## Core Classes

### ReactionEngine

Main engine that processes game events and produces device commands.

#### Device Model

```typescript
interface DeviceProfile {
  id: string;
  name: string;
  capabilities: DeviceCapability[];
  intensityRange: { min: number; max: number };
  latency: number; // ms
  maxConcurrentCommands: number;
  connected: boolean;
  metadata: Record<string, unknown>;
}
```

#### Device Capabilities

| Capability  | Description            |
| ----------- | ---------------------- |
| `Vibrate`   | Motor vibration        |
| `Rotate`    | Rotational movement    |
| `Linear`    | Linear stroke/thrust   |
| `Constrict` | Tightening/squeezing   |
| `Oscillate` | Rapid back-and-forth   |
| `Inflate`   | Expansion/inflation    |
| `Heat`      | Temperature increase   |
| `Cool`      | Temperature decrease   |
| `Electro`   | Electrical stimulation |
| `Suction`   | Vacuum/suction         |

#### Device Commands

```typescript
interface DeviceCommand {
  id: string;
  deviceId: string;
  type:
    | 'Start'
    | 'Stop'
    | 'SetIntensity'
    | 'Pattern'
    | 'Ramp'
    | 'Pulse'
    | 'Hold';
  capability: DeviceCapability;
  intensity: number; // 0–1
  durationMs: number;
  rampTime: number; // ms, for Ramp type
  pattern: PatternSample[]; // for Pattern type
  priority: number;
  timestamp: number;
  sourceEventType: string;
  metadata: Record<string, unknown>;
}
```

---

## Translation Rules

Rules that map game events to device commands.

```typescript
interface TranslationRule {
  name: string;
  eventPattern: string; // wildcard: 'combat.*', 'vehicle.collision'
  targetCapability: DeviceCapability;
  strategy: TranslationStrategy;
  intensityMapping: (eventData: unknown) => number; // 0–1
  durationMapping: (eventData: unknown) => number; // milliseconds
  fallbackCapability?: DeviceCapability;
  priority: number;
  enabled: boolean;
}

type TranslationStrategy =
  | 'Direct'
  | 'Scaled'
  | 'Mapped'
  | 'Composite'
  | 'Fallback';
```

### Built-In Rules

| Rule                     | Event Pattern      | Intensity          | Duration               |
| ------------------------ | ------------------ | ------------------ | ---------------------- |
| `COLLISION_TO_VIBRATE`   | `impact.collision` | force → 0–1        | force × 2 (50–2000 ms) |
| `DAMAGE_TO_VIBRATE`      | `impact.damage`    | damage / maxHealth | proportional           |
| `EXPLOSION_TO_PULSE`     | `impact.explosion` | proximity → 0–1    | radius → ms            |
| `RHYTHM_BEAT_TO_VIBRATE` | `rhythm.beat-hit`  | strength → 0–1     | 60000 / BPM            |

### Pattern Matching

Event patterns support wildcards:

| Pattern             | Matches               |
| ------------------- | --------------------- |
| `impact.collision`  | Exact match           |
| `combat.*`          | All combat sub-events |
| `vehicle.collision` | Specific nested event |

---

## Genre-Specific Profiles

Each genre has a complete set of event-to-device mappings with three factory
difficulty levels: `casual`, `competitive`, `hardcore`.

### FPS Profile

**Factory**: `createFPSProfile(difficulty)`

| Event              | Haptic Response                           |
| ------------------ | ----------------------------------------- |
| `weapon.fire`      | Short burst matching weapon type          |
| `damage.received`  | Directional intensity from damage amount  |
| `explosion.nearby` | Proximity-scaled pulse with falloff       |
| `player.kill`      | Confirmation pulse                        |
| `player.death`     | Strong sustained vibration                |
| `weapon.reload`    | Subtle rhythmic pattern                   |
| `heartbeat.low_hp` | Pulsing heartbeat, increasing as HP drops |

### Racing Profile

**Factory**: `createRacingProfile(difficulty)`

| Event                | Haptic Response                    |
| -------------------- | ---------------------------------- |
| `engine.rpm`         | Continuous vibration mapped to RPM |
| `vehicle.collision`  | Impact burst from collision force  |
| `vehicle.drift`      | Sustained rumble during drift      |
| `terrain.change`     | Texture pattern for surface type   |
| `vehicle.nitro`      | Escalating surge                   |
| `vehicle.gear_shift` | Click/thud pattern                 |
| `vehicle.brake`      | Resistance vibration               |
| `lap.complete`       | Celebration pattern                |

### Platformer Profile

**Factory**: `createPlatformerProfile(difficulty)`

| Event                | Haptic Response                    |
| -------------------- | ---------------------------------- |
| `player.jump`        | Quick upward pulse                 |
| `player.land`        | Impact proportional to fall height |
| `collectible.pickup` | Light sparkle pattern              |
| `player.wall_slide`  | Continuous light friction          |
| `enemy.stomp`        | Satisfying squash pulse            |
| `player.death`       | Dramatic descending pattern        |

### Puzzle Profile

**Factory**: `createPuzzleProfile(difficulty)`

| Event              | Haptic Response                    |
| ------------------ | ---------------------------------- |
| `tile.match`       | Click confirmation                 |
| `combo.chain`      | Escalating pulses per chain length |
| `timer.pressure`   | Increasing heartbeat               |
| `level.complete`   | Celebration flourish               |
| `powerup.activate` | Warm sustained glow                |
| `move.invalid`     | Short error buzz                   |

### RPG Profile

**Factory**: `createRPGProfile(difficulty)`

| Event             | Haptic Response            |
| ----------------- | -------------------------- |
| `spell.cast`      | Magical charge and release |
| `melee.attack`    | Swing impact               |
| `player.level_up` | Dramatic crescendo         |
| `status.effect`   | Continuous overlay pattern |
| `critical.hit`    | Sharp double pulse         |
| `boss.encounter`  | Deep rumble introduction   |

### Fighting Profile

**Factory**: `createFightingProfile(difficulty)`

| Event             | Haptic Response               |
| ----------------- | ----------------------------- |
| `strike.land`     | Impact scaled by damage       |
| `block.success`   | Firm resistance pulse         |
| `combo.chain`     | Accelerating pattern          |
| `super.move`      | Dramatic multi-phase sequence |
| `health.critical` | Heartbeat at low HP           |
| `grab.connect`    | Sustained grip vibration      |
| `counter.success` | Sharp reversal pulse          |

### Strategy Profile

**Factory**: `createStrategyProfile(difficulty)`

| Event               | Haptic Response       |
| ------------------- | --------------------- |
| `unit.select`       | Soft click            |
| `battle.engage`     | Rising rumble         |
| `resource.collect`  | Gentle confirmation   |
| `building.complete` | Solid completion thud |
| `research.complete` | Discovery chime       |
| `diplomacy.event`   | Subtle notification   |

### Horror Profile

**Factory**: `createHorrorProfile(difficulty)`

| Event                | Haptic Response                    |
| -------------------- | ---------------------------------- |
| `ambient.dread`      | Low persistent rumble              |
| `jumpscare.trigger`  | Violent sudden spike               |
| `heartbeat.tension`  | Accelerating heartbeat             |
| `tension.peak`       | Sustained high-frequency vibration |
| `tension.relief`     | Gentle descending release          |
| `creature.proximity` | Subtle increasing pulse            |

### Sports Profile

**Factory**: `createSportsProfile(difficulty)`

| Event            | Haptic Response              |
| ---------------- | ---------------------------- |
| `ball.impact`    | Hit proportional to force    |
| `player.sprint`  | Rhythmic footfall pattern    |
| `goal.scored`    | Celebration burst            |
| `crowd.reaction` | Rumble proportional to crowd |
| `tackle.connect` | Impact pulse                 |
| `pass.complete`  | Clean confirmation           |
| `foul.commit`    | Warning buzz                 |

### Rhythm Profile

**Factory**: `createRhythmProfile(difficulty)`

| Event                | Haptic Response             |
| -------------------- | --------------------------- |
| `beat.hit`           | Pulse on beat accuracy      |
| `beat.miss`          | Light error buzz            |
| `combo.milestone`    | Escalating celebration      |
| `bass.drop`          | Deep sustained pulse        |
| `section.change`     | Transitional pattern        |
| `overdrive.activate` | Intense sustained vibration |

### Simulation Profile

**Factory**: `createSimulationProfile(difficulty)`

| Event               | Haptic Response                  |
| ------------------- | -------------------------------- |
| `vehicle.operate`   | Engine-like continuous vibration |
| `task.success`      | Completion confirmation          |
| `task.failure`      | Gentle error notification        |
| `environment.event` | Weather/ambient texture          |
| `milestone.reach`   | Achievement burst                |
| `weather.change`    | Gradual texture shift            |

### Open World Profile

**Factory**: `createOpenWorldProfile(difficulty)`

| Event                  | Haptic Response               |
| ---------------------- | ----------------------------- |
| `weather.event`        | Environmental texture pattern |
| `discovery.find`       | Exciting pulse                |
| `combat.engage`        | Rising alert vibration        |
| `mount.ride`           | Galloping/engine rhythm       |
| `quest.update`         | Notification pulse            |
| `hazard.enter`         | Warning vibration             |
| `day_night.transition` | Subtle shift pattern          |

---

## Pattern Library

### Pattern Definition

```typescript
interface PatternDef {
  name: string;
  category: PatternCategory;
  samples: PatternSample[]; // normalised 0–1 intensity values
  durationMs: number;
  sampleRateHz: number; // default: 100
  loopable: boolean;
  description: string;
  tags: string[];
}

type PatternCategory =
  | 'Impact'
  | 'Rhythmic'
  | 'Continuous'
  | 'Texture'
  | 'Composite'
  | 'Custom';
```

### Pattern Categories

| Category     | Examples                                   |
| ------------ | ------------------------------------------ |
| `Impact`     | Single hit, double tap, slam, shockwave    |
| `Rhythmic`   | Heartbeat, pulse train, gallop, march      |
| `Continuous` | Steady vibration, ramp up, ramp down, wave |
| `Texture`    | Rain, gravel, smooth, rough, electric      |
| `Composite`  | Multi-phase sequences combining the above  |
| `Custom`     | User-defined patterns                      |

### Waveform Generators

| Function               | Signature                                                  | Output          |
| ---------------------- | ---------------------------------------------------------- | --------------- |
| `generateSineWave`     | `(frequency, durationMs, sampleRate): number[]`            | Smooth periodic |
| `generateSquareWave`   | `(frequency, durationMs, sampleRate, dutyCycle): number[]` | On/off pulses   |
| `generateTriangleWave` | `(frequency, durationMs, sampleRate): number[]`            | Ramping peaks   |

### Pattern Blending

```typescript
function blendPatterns(
  patternA: PatternDef,
  patternB: PatternDef,
  blendMode: BlendMode,
  alpha: number // 0–1, weight of patternB
): PatternDef;
```

| Blend Mode | Behaviour                            |
| ---------- | ------------------------------------ |
| `Add`      | Sum intensities (clamped to 1.0)     |
| `Multiply` | Multiply intensities                 |
| `Max`      | Take higher intensity at each sample |
| `Average`  | Average of both                      |
| `Replace`  | Replace A with B where alpha > 0     |

### Pattern Parameters

```typescript
interface PatternParams {
  intensity: number; // scale factor
  speed: number; // playback speed multiplier
  durationMs: number; // override duration
  reverse: boolean;
  fadeIn: number; // ms
  fadeOut: number; // ms
  offset: number; // start offset in samples
}
```

---

## Safety System

### Global Safety Limits

| Limit          | Description                               | Override           |
| -------------- | ----------------------------------------- | ------------------ |
| Max intensity  | Absolute cap on device output (1.0)       | Cannot be exceeded |
| Max duration   | Maximum single-command duration           | Cannot be exceeded |
| Cooldown       | Minimum gap between high-intensity events | Cannot be bypassed |
| Emergency stop | Instant kill switch on all devices        | Always available   |

Safety limits are enforced at the device command level — after genre profiles
and tip effects have been processed but before commands reach the physical
device.

### Configuration

```typescript
interface DefaultPatternLibraryConfig {
  maxCustomPatterns: number; // default: 500
  defaultSampleRate: number; // default: 100 Hz
}
```
