# Device Reaction Development Guide

Complete guide for creating, configuring, and testing device reactions in the
Aphrodite gaming platform. Covers reaction patterns, intensity mapping, safety
enforcement, multi-device choreography, and genre-specific profiles.

---

## Table of Contents

1. [System Architecture](#1-system-architecture)
2. [Reaction Patterns](#2-reaction-patterns)
3. [Intensity Mapping](#3-intensity-mapping)
4. [Safety Limits and Best Practices](#4-safety-limits-and-best-practices)
5. [Multi-Device Choreography](#5-multi-device-choreography)
6. [Timing and Synchronization](#6-timing-and-synchronization)
7. [Genre-Specific Profiles](#7-genre-specific-profiles)
8. [Testing Device Reactions](#8-testing-device-reactions)
9. [Preview and Debugging](#9-preview-and-debugging)
10. [Reference](#10-reference)

---

## 1. System Architecture

The device reaction system is built as a layered pipeline:

```
Game Event → Translation Rules → Intensity Mapping → Pattern Selection
    → Safety Clamping → Timing/Scheduling → Device Command → Hardware
```

### Core Libraries

| Library                             | Purpose                                                                                   |
| ----------------------------------- | ----------------------------------------------------------------------------------------- |
| `@aphrodite/device-reaction-engine` | Core engine: translation rules, patterns, intensity, timing, choreography, genre profiles |
| `@aphrodite/haptics`                | Haptic pattern designer for creating and editing patterns                                 |
| `@aphrodite/motion-haptics`         | Motion-linked haptics with gesture recognition                                            |
| `@aphrodite/audio-haptics`          | Audio-reactive haptics with FFT analysis                                                  |
| `@aphrodite/bidirectional-haptics`  | Two-way device sync and remote control                                                    |
| `@aphrodite/vr-haptics`             | VR gloves, vests, and full-body suit integration                                          |
| `@aphrodite/game-testing`           | Testing validators for profiles, safety, choreography, latency, smoothness                |

### Data Flow

```
┌─────────────────────────────────────────────────────────┐
│                    Game Event Stream                     │
│  (collision, damage, explosion, rhythm_beat, emotion...) │
└───────────────────────┬─────────────────────────────────┘
                        │
                        ▼
┌──────────────────────────────────────┐
│         Translation Rules            │
│  matchEventPattern() → TranslationRule │
│  COLLISION_TO_VIBRATE                │
│  DAMAGE_TO_VIBRATE                   │
│  EXPLOSION_TO_PULSE                  │
│  RHYTHM_BEAT_TO_VIBRATE              │
│  TENSION_TO_CONSTRICT                │
│  EMOTION_JOY_TO_OSCILLATE            │
└──────────────────┬───────────────────┘
                   │
                   ▼
┌──────────────────────────────────────┐
│         Intensity Mapper             │
│  Curve functions: linear, exp, log,  │
│  s-curve, inverse-exp, step, bounce, │
│  ease                                │
│  + Performer profile scaling         │
│  + Ramp up/down                      │
│  + Sustained reaction reduction      │
└──────────────────┬───────────────────┘
                   │
                   ▼
┌──────────────────────────────────────┐
│         Pattern Library              │
│  50+ built-in patterns:              │
│  Impact, Rhythmic, Ambient, Cinematic│
│  Waveform generation (sine, square,  │
│  triangle, sawtooth, noise)          │
│  + Blending, crossfade, loop         │
└──────────────────┬───────────────────┘
                   │
                   ▼
┌──────────────────────────────────────┐
│        Safety Clamping               │
│  applySafetyLimits()                 │
│  Max intensity: 0.85                 │
│  Max duration: 5000ms                │
│  Max frequency: 30 Hz                │
│  Cooldown: 33ms                      │
│  Max concurrent devices: 8           │
│  Max total intensity: 3.0            │
└──────────────────┬───────────────────┘
                   │
                   ▼
┌──────────────────────────────────────┐
│        Timing Engine                 │
│  Latency compensation                │
│  Adaptive latency profiling          │
│  Audio/visual sync offsets           │
│  Predictive event scheduling         │
│  Phase-locked loop for rhythm        │
└──────────────────┬───────────────────┘
                   │
                   ▼
┌──────────────────────────────────────┐
│     Choreography Manager             │
│  Multi-device coordination           │
│  Spatial zone mapping                │
│  Role-based intensity multipliers    │
│  Wave, ripple, cascade patterns      │
└──────────────────┬───────────────────┘
                   │
                   ▼
┌──────────────────────────────────────┐
│        Device Command Output         │
│  { deviceId, type, intensity,        │
│    durationMs, pattern, ... }        │
└──────────────────────────────────────┘
```

---

## 2. Reaction Patterns

Patterns define the shape of a haptic reaction over time. They are arrays of
`PatternSample` objects (timestamp + intensity pairs).

### 2.1 Built-In Pattern Categories

The pattern library organizes 50+ built-in patterns into four categories:

**Impact Patterns** — Sharp, momentary reactions:

| Pattern       | Description             | Typical use              |
| ------------- | ----------------------- | ------------------------ |
| `SHARP_PULSE` | Quick single pulse      | UI confirmations         |
| `DOUBLE_TAP`  | Two quick pulses        | Double-click feedback    |
| `RIPPLE`      | Outward spreading wave  | Water splash, magic cast |
| `SHOCKWAVE`   | Intense expanding pulse | Explosions               |
| `THUD`        | Heavy single impact     | Landing, punch           |
| `CRACK`       | Sharp crack with decay  | Whip, bone break         |
| `SLAM`        | Heavy sustained impact  | Door slam, body slam     |
| `BURST`       | Quick burst of energy   | Gunshot                  |
| `STINGER`     | Sharp musical stinger   | Event cue                |
| `RUMBLE_HIT`  | Impact with rumble tail | Earthquake, boss stomp   |

**Rhythmic Patterns** — Repeating, tempo-driven reactions:

| Pattern     | Description            | Typical use           |
| ----------- | ---------------------- | --------------------- |
| `HEARTBEAT` | Lub-dub cardiac rhythm | Low health, tension   |
| `BREATHING` | Slow inhale-exhale     | Calm, stealth         |
| `TAPPING`   | Regular finger-tap     | Idle, countdown       |
| `PULSING`   | Smooth sine pulse      | Ambient, energy field |
| `GALLOP`    | Fast triple rhythm     | Horse riding, running |
| `MARCH`     | Even two-beat stride   | Walking, marching     |
| `WALTZ`     | Three-beat dance       | Music, dance          |
| `FLUTTER`   | Rapid irregular pulses | Wings, butterflies    |
| `THROB`     | Deep, slow pulse       | Pain, warning         |
| `TICK_TOCK` | Clock-like alternation | Timer, countdown      |

**Ambient Patterns** — Sustained textural reactions:

| Pattern         | Description          | Typical use         |
| --------------- | -------------------- | ------------------- |
| `ESCALATING`    | Gradually increasing | Tension build       |
| `DE_ESCALATING` | Gradually decreasing | Relief, calm down   |
| `OSCILLATING`   | Steady sine wave     | Engine idle, hum    |
| `CONSTANT`      | Flat sustained       | Continuous feedback |
| `WAVERING`      | Unstable fluctuation | Wind, turbulence    |
| `BUILDING`      | Slow crescendo       | Boss intro, drama   |
| `FADING`        | Slow fadeout         | Death, distance     |
| `SURGING`       | Wave-like swells     | Ocean, energy pulse |
| `FLICKERING`    | Random rapid changes | Fire, electricity   |
| `ROLLING`       | Smooth wave motion   | Vehicle, wave       |

**Texture Patterns** — Tactile qualities:

| Pattern    | Description            |
| ---------- | ---------------------- |
| `ROUGH`    | Gritty, uneven texture |
| `SMOOTH`   | Even, silky feeling    |
| `TINGLY`   | High-frequency sparkle |
| `WARM`     | Soft, enveloping feel  |
| `COOL`     | Crisp, light touch     |
| `BUZZY`    | Steady vibration hum   |
| `SILKY`    | Fluid, gentle glide    |
| `GRITTY`   | Coarse, raspy texture  |
| `ELECTRIC` | Sharp, tingling zaps   |
| `FEATHERY` | Barely-there lightness |

**Cinematic Patterns** — Complex multi-phase sequences:

| Pattern           | Description             | Duration |
| ----------------- | ----------------------- | -------- |
| `EXPLOSION_FULL`  | Full explosion sequence | ~2s      |
| `BOSS_ENTRANCE`   | Dramatic boss reveal    | ~3s      |
| `VICTORY_FANFARE` | Celebratory finale      | ~2.5s    |
| `TENSION_BUILD`   | Slow anxiety ramp       | ~4s      |
| `CLIMAX_RELEASE`  | Peak-then-relief        | ~2s      |
| `DAMAGE_SEQUENCE` | Multi-hit damage        | ~1.5s    |
| `RHYTHM_FLOW`     | Musical flow pattern    | ~2s      |
| `AMBIENT_STORM`   | Storm atmosphere        | ~5s      |
| `HEALING_WAVE`    | Restorative flow        | ~2s      |
| `POWER_UP`        | Energy collection       | ~1.5s    |

### 2.2 Creating Custom Patterns

#### Waveform Generation

Generate patterns from mathematical waveforms:

```typescript
import {
  generateSineWave,
  generateSquareWave,
  generateTriangleWave,
  generateSawtoothWave,
  generateNoiseWave,
  generateEnvelope,
} from '@aphrodite/device-reaction-engine';

// Generate a 500ms sine wave at 10Hz, 64 samples
const sine = generateSineWave(500, 10, 64);

// Generate an envelope (attack-sustain-decay shape)
const envelope = generateEnvelope({
  attackMs: 50,
  sustainMs: 200,
  decayMs: 250,
  peakIntensity: 0.8,
  sustainIntensity: 0.5,
  sampleCount: 32,
});
```

#### Pattern Manipulation

Transform existing patterns:

```typescript
import {
  scalePattern,
  timeStretch,
  reversePattern,
  fadeIn,
  fadeOut,
  loopPattern,
  truncatePattern,
} from '@aphrodite/device-reaction-engine';

// Scale intensity by 0.5 (halve all values)
const quietPattern = scalePattern(SHARP_PULSE, 0.5);

// Stretch duration to 2x
const slowPattern = timeStretch(SHARP_PULSE, 2.0);

// Reverse the pattern
const reversed = reversePattern(SHARP_PULSE);

// Add a 100ms fade-in
const withFade = fadeIn(SHARP_PULSE, 100);

// Loop 3 times
const looped = loopPattern(HEARTBEAT, 3);
```

#### Pattern Composition

Combine patterns:

```typescript
import {
  blendPatterns,
  concatenatePatterns,
  crossfade,
} from '@aphrodite/device-reaction-engine';

// Blend two patterns (additive, clamped to 1.0)
const blended = blendPatterns(HEARTBEAT, PULSING, 0.5); // 50% mix

// Concatenate patterns sequentially
const sequence = concatenatePatterns([BURST, RUMBLE_HIT, FADING]);

// Crossfade between patterns over 200ms
const smooth = crossfade(TENSION_BUILD, CLIMAX_RELEASE, 200);
```

### 2.3 Pattern Definition Format

A pattern is an array of `PatternSample` objects:

```typescript
interface PatternSample {
  timestamp: number; // ms from pattern start
  intensity: number; // 0.0 to 1.0
}
```

A minimal custom pattern:

```typescript
const MY_CUSTOM_PULSE: PatternSample[] = [
  { timestamp: 0, intensity: 0.0 },
  { timestamp: 20, intensity: 0.9 },
  { timestamp: 80, intensity: 0.6 },
  { timestamp: 150, intensity: 0.3 },
  { timestamp: 200, intensity: 0.0 },
];
```

### 2.4 Pattern Library

The `PatternLibrary` class manages pattern collections:

```typescript
import {
  createPatternLibrary,
  createFullLibrary,
} from '@aphrodite/device-reaction-engine';

// Create with all built-in patterns
const library = createFullLibrary();

// Or create with specific patterns
const minimal = createPatternLibrary({
  patterns: [SHARP_PULSE, HEARTBEAT, EXPLOSION_FULL],
});

// Look up patterns by category
const impacts = library.getPatternsByCategory('impact');
```

---

## 3. Intensity Mapping

The intensity mapper transforms raw game event intensities (0–1) into
device-appropriate intensities using mathematical curves and performer profiles.

### 3.1 Curve Types

Eight mapping curves are available:

| Curve                 | Function               | Character                            |
| --------------------- | ---------------------- | ------------------------------------ |
| `linear`              | `f(x) = x`             | Direct 1:1 mapping                   |
| `exponential`         | `f(x) = x^n`           | Gentle start, strong finish          |
| `logarithmic`         | `f(x) = ln(x+1)/ln(2)` | Strong start, gentle finish          |
| `s-curve`             | Sigmoid                | Compressed extremes, expanded middle |
| `inverse-exponential` | `f(x) = 1-(1-x)^n`     | Gentle start, fast middle            |
| `step`                | Quantized levels       | Discrete intensity levels            |
| `bounce`              | Damped oscillation     | Playful, bouncy feel                 |
| `ease`                | Cubic ease in-out      | Smooth acceleration/deceleration     |

### 3.2 Using Curves

```typescript
import {
  applyLinear,
  applyExponential,
  applyLogarithmic,
  applySCurve,
  applyStep,
  applyBounce,
  applyEase,
  applyIntensityCurve,
} from '@aphrodite/device-reaction-engine';

// Direct function call
const mapped = applyExponential(0.5, { exponent: 2.0 }); // 0.25

// Generic curve application
const result = applyIntensityCurve('logarithmic', 0.7, {});
```

### 3.3 Performer Profiles

Performer profiles customize intensity mapping per performer:

```typescript
interface PerformerProfile {
  minIntensity: number; // Floor (e.g., 0.1 — never below this)
  maxIntensity: number; // Ceiling (e.g., 0.8 — never above this)
  sensitivityMultiplier: number; // Scale factor (e.g., 1.2 = 20% more sensitive)
  curve: IntensityCurveValue; // Preferred curve type
  curveParams: CurveParams; // Curve-specific parameters
}
```

Apply a performer profile:

```typescript
import {
  applyProfile,
  mergeProfiles,
  DEFAULT_PERFORMER_PROFILE,
} from '@aphrodite/device-reaction-engine';

const gentlePerformer: PerformerProfile = {
  minIntensity: 0.05,
  maxIntensity: 0.6,
  sensitivityMultiplier: 0.8,
  curve: 'logarithmic',
  curveParams: {},
};

// Apply profile to raw intensity
const intensity = applyProfile(0.7, gentlePerformer); // ≈ 0.44

// Merge base + overlay profiles
const merged = mergeProfiles(DEFAULT_PERFORMER_PROFILE, gentlePerformer);
```

### 3.4 Ramps

Ramps provide smooth intensity transitions over time:

```typescript
import {
  createRamp,
  computeRampValue,
  isRampComplete,
} from '@aphrodite/device-reaction-engine';

// Create a ramp from 0.2 to 0.8 over 1000ms
const ramp = createRamp({
  fromIntensity: 0.2,
  toIntensity: 0.8,
  durationMs: 1000,
  direction: 'up',
});

// Compute ramp value at 500ms (midpoint)
const value = computeRampValue(ramp, 500); // ≈ 0.5

// Check if ramp is done
const done = isRampComplete(ramp, 1200); // true
```

### 3.5 Sustained Reaction Reduction

Prolonged reactions gradually decrease to prevent desensitization:

```typescript
import {
  shouldReduceSustained,
  computeReducedIntensity,
  updateSustainedTracker,
} from '@aphrodite/device-reaction-engine';

// Check if a reaction running for 5000ms should be reduced
const shouldReduce = shouldReduceSustained(5000, 3000); // true (past 3s threshold)

// Compute reduced intensity
const reduced = computeReducedIntensity(0.7, 5000, 3000); // < 0.7
```

### 3.6 IntensityMapper Class

The `IntensityMapper` orchestrates all mapping operations:

```typescript
import {
  createIntensityMapper,
  createGentleMapper,
  createResponsiveMapper,
} from '@aphrodite/device-reaction-engine';

// Factory functions for common presets
const gentle = createGentleMapper(); // Low sensitivity, log curve
const responsive = createResponsiveMapper(); // High sensitivity, exponential

// Custom configuration
const custom = createIntensityMapper({
  defaultCurve: 'exponential',
  defaultCurveParams: { exponent: 2.5 },
  sustainedReductionThresholdMs: 5000,
  sustainedReductionRate: 0.1,
});
```

---

## 4. Safety Limits and Best Practices

### 4.1 Default Safety Limits

All reactions are bounded by hard safety limits that cannot be overridden:

```typescript
const DEFAULT_SAFETY_LIMITS = {
  maxIntensity: 0.85, // No single device above 85%
  maxDurationMs: 5000, // No reaction longer than 5 seconds
  maxFrequencyHz: 30, // No more than 30 reactions/second
  cooldownMs: 33, // Minimum 33ms gap between reactions (~30 Hz)
  maxConcurrentDevices: 8, // Maximum 8 devices active at once
  maxTotalIntensity: 3.0, // Sum of all concurrent device intensities
};
```

### 4.2 Safety Enforcement

The `SafetyLimitVerifier` in `@aphrodite/game-testing` validates reaction
samples:

```typescript
import {
  createSafetyLimitVerifier,
  type ReactionSample,
} from '@aphrodite/game-testing';

const verifier = createSafetyLimitVerifier();

const samples: ReactionSample[] = [
  {
    deviceId: 'motor-1',
    type: 'vibration',
    intensity: 0.9,
    durationMs: 200,
    timestamp: 0,
  },
  {
    deviceId: 'motor-2',
    type: 'vibration',
    intensity: 0.7,
    durationMs: 200,
    timestamp: 10,
  },
];

const result = verifier.verify(samples);
// result.passed = false (intensity 0.9 exceeds 0.85 limit)
// result.violations = [{ type: 'intensity', message: '...', value: 0.9, limit: 0.85, sampleIndex: 0 }]
```

The `applySafetyLimits()` function in the core engine clamps values before
sending to devices:

```typescript
import { applySafetyLimits } from '@aphrodite/device-reaction-engine';

const clamped = applySafetyLimits(command, safetyConfig);
// Intensity clamped to maxIntensity
// Duration clamped to maxDurationMs
```

### 4.3 Safety Violation Types

| Type              | What it checks                    | Limit  |
| ----------------- | --------------------------------- | ------ |
| `intensity`       | Single device intensity           | 0.85   |
| `duration`        | Single reaction duration          | 5000ms |
| `frequency`       | Reactions per second              | 30 Hz  |
| `cooldown`        | Gap between consecutive reactions | 33ms   |
| `concurrent`      | Number of active devices          | 8      |
| `total_intensity` | Sum of all concurrent intensities | 3.0    |

### 4.4 Best Practices

**Intensity management:**

- Use performer profiles to set per-user intensity ceilings
- Apply sustained reaction reduction for reactions > 3 seconds
- Use ramps instead of instant intensity changes (smoother, safer)
- Keep average intensity in the 0.3–0.6 range for most genres

**Frequency management:**

- Space reactions at least 33ms apart (30 Hz ceiling)
- For rhythm games, match reaction frequency to BPM (120 BPM = 2 Hz)
- Use pattern blending instead of rapid separate reactions
- Coalesce rapid game events into single compound patterns

**Duration management:**

- Keep individual reactions under 2 seconds for most genres
- Use ambient patterns (sustained, low-intensity) for longer feedback
- Break long sequences into chained shorter patterns with crossfades
- Apply fadeout to any reaction approaching the 5-second limit

**Multi-device management:**

- Distribute intensity across devices rather than maximizing each one
- Use choreography for coordinated multi-device effects
- Keep total concurrent intensity below 3.0
- Assign device roles (primary, accent, ambient) for priority management

---

## 5. Multi-Device Choreography

The choreography system coordinates reactions across multiple physical devices,
enabling spatial haptic experiences.

### 5.1 Device Layout

Define the physical arrangement of devices:

```typescript
import type {
  DevicePosition,
  DeviceLayout,
} from '@aphrodite/device-reaction-engine';

const layout: DeviceLayout = {
  devices: [
    { deviceId: 'motor-left', x: -1.0, y: 0.0, z: 0.0, zone: 'left' },
    { deviceId: 'motor-right', x: 1.0, y: 0.0, z: 0.0, zone: 'right' },
    { deviceId: 'motor-center', x: 0.0, y: 0.0, z: 0.0, zone: 'center' },
    { deviceId: 'motor-back', x: 0.0, y: 0.0, z: -1.0, zone: 'back' },
  ],
};
```

### 5.2 Spatial Zones

Devices are grouped into spatial zones for targeted effects:

| Zone     | Typical devices                    | Use case                      |
| -------- | ---------------------------------- | ----------------------------- |
| `center` | Main controller, vest center       | Core feedback                 |
| `left`   | Left controller, left vest panel   | Directional damage from left  |
| `right`  | Right controller, right vest panel | Directional damage from right |
| `front`  | Front vest panels                  | Impact, environmental         |
| `back`   | Back vest panels                   | Rear damage, ambient          |
| `upper`  | Shoulder, neck devices             | Overhead effects              |
| `lower`  | Waist, leg devices                 | Ground effects, footsteps     |

### 5.3 Activation Patterns

Seven built-in activation patterns control the sequence of device activation:

| Pattern        | Behavior                        | Example          |
| -------------- | ------------------------------- | ---------------- |
| `sequential`   | One device at a time in order   | Scanning effect  |
| `simultaneous` | All devices at once             | Explosion        |
| `wave`         | Left-to-right sweep             | Shockwave        |
| `cascade`      | Fastest to slowest response     | Waterfall        |
| `ripple`       | Center outward by distance      | Impact ripple    |
| `random`       | Random order with random delays | Chaos, glitch    |
| `alternating`  | Odd/even toggle                 | Pulse, heartbeat |

### 5.4 Creating Choreographies

```typescript
import {
  createChoreographyManager,
  WAVE_LEFT_TO_RIGHT,
  RIPPLE_FROM_CENTER,
  HEARTBEAT_CHOREO,
} from '@aphrodite/device-reaction-engine';

const choreo = createChoreographyManager();

// Use a built-in choreography
choreo.play(WAVE_LEFT_TO_RIGHT, layout);

// Create a custom choreography
const customChoreo: ChoreoDef = {
  id: 'explosion-outward',
  name: 'Explosion Outward',
  steps: [
    {
      activation: 'ripple',
      pattern: SHOCKWAVE,
      intensity: 0.8,
      delayMs: 0,
      activationConfig: {
        originDeviceId: 'motor-center',
        speedMs: 50, // 50ms per unit distance
      },
    },
    {
      activation: 'simultaneous',
      pattern: RUMBLE_HIT,
      intensity: 0.5,
      delayMs: 200, // 200ms after the shockwave
    },
  ],
};
```

### 5.5 Device Roles

Assign roles to devices for priority-based intensity scaling:

| Role          | Intensity multiplier | Purpose                  |
| ------------- | -------------------- | ------------------------ |
| `primary`     | 1.0                  | Main feedback device     |
| `secondary`   | 0.7                  | Supporting feedback      |
| `accent`      | 0.5                  | Highlights and stingers  |
| `ambient`     | 0.3                  | Background texture       |
| `directional` | 0.8                  | Spatial positioning cues |

```typescript
import {
  assignRoles,
  computeRoleIntensityMultiplier,
} from '@aphrodite/device-reaction-engine';

const assignments = assignRoles(layout, {
  'motor-center': 'primary',
  'motor-left': 'directional',
  'motor-right': 'directional',
  'motor-back': 'ambient',
});

// Intensity is automatically scaled by role
const multiplier = computeRoleIntensityMultiplier('ambient'); // 0.3
```

### 5.6 Testing Choreography

Use `MultiDeviceChoreographyTester` from `@aphrodite/game-testing`:

```typescript
import {
  createMultiDeviceChoreographyTester,
  type ChoreographyEvent,
} from '@aphrodite/game-testing';

const tester = createMultiDeviceChoreographyTester();

const events: ChoreographyEvent[] = [
  {
    deviceId: 'motor-left',
    expectedTimestamp: 0,
    actualTimestamp: 2,
    intensity: 0.8,
    type: 'vibration',
  },
  {
    deviceId: 'motor-center',
    expectedTimestamp: 50,
    actualTimestamp: 53,
    intensity: 0.9,
    type: 'vibration',
  },
  {
    deviceId: 'motor-right',
    expectedTimestamp: 100,
    actualTimestamp: 98,
    intensity: 0.8,
    type: 'vibration',
  },
];

// Verify absolute timing within 10ms tolerance
const syncResult = tester.verifySynchronization(events, 10);
console.log(syncResult.passed); // true
console.log(syncResult.maxDeviation); // 3ms
console.log(syncResult.averageDeviation); // ~2.3ms

// Verify relative timing (50ms expected delay between devices)
const relativeResult = tester.verifyRelativeTiming(events, 50, 5);

// Verify per-device event ordering
const orderResult = tester.verifyPerDeviceOrdering(events);
```

---

## 6. Timing and Synchronization

The timing engine ensures reactions arrive at the right moment despite network
latency, processing delays, and synchronization requirements.

### 6.1 Latency Compensation

```typescript
import {
  createTimingEngine,
  createLowLatencyEngine,
  measureLatency,
  updateLatencyProfile,
  computeAdaptiveLatency,
} from '@aphrodite/device-reaction-engine';

const timing = createLowLatencyEngine();

// Measure latency to a device
const latency = measureLatency(sentAt, receivedAt);

// Build a latency profile over time
const profile = updateLatencyProfile(existingProfile, latency);

// Get adaptive latency estimate (accounts for jitter)
const estimate = computeAdaptiveLatency(profile);
```

### 6.2 Audio/Visual Sync

Sync haptic reactions with audio and visual events:

```typescript
import {
  computeAudioSyncOffset,
  computeVisualSyncOffset,
} from '@aphrodite/device-reaction-engine';

// Compute how much to offset haptics to match audio
const audioOffset = computeAudioSyncOffset(audioLatencyMs, hapticLatencyMs);

// Compute offset to match visual events
const visualOffset = computeVisualSyncOffset(displayLatencyMs, hapticLatencyMs);
```

### 6.3 Predictive Scheduling

For rhythm games and predictable events, pre-schedule reactions:

```typescript
import {
  scheduleCommand,
  getReadyCommands,
  predictNextEvent,
  shouldSendPreemptive,
} from '@aphrodite/device-reaction-engine';

// Schedule a command for future execution
const scheduled = scheduleCommand(command, executionTime);

// Get commands ready to execute now
const ready = getReadyCommands(scheduledCommands, currentTime);

// Predict when the next beat will occur (for rhythm games)
const prediction = predictNextEvent(recentBeatTimestamps);
```

### 6.4 Device Latency Testing

Use `DeviceLatencyMeasurer` from `@aphrodite/game-testing`:

```typescript
import { createDeviceLatencyMeasurer } from '@aphrodite/game-testing';

const measurer = createDeviceLatencyMeasurer();

// Record probes
measurer.recordProbe({ deviceId: 'motor-1', sentAt: 0, receivedAt: 12 });
measurer.recordProbe({ deviceId: 'motor-1', sentAt: 100, receivedAt: 115 });
measurer.recordProbe({ deviceId: 'motor-1', sentAt: 200, receivedAt: 211 });

// Generate a report with a 20ms budget
const report = measurer.generateReport('motor-1', 20);
console.log(report.averageMs); // ~12.7ms
console.log(report.p95Ms); // ~15ms
console.log(report.jitterMs); // ~1.7ms (standard deviation)
console.log(report.withinBudget); // true (12.7 < 20)
```

---

## 7. Genre-Specific Profiles

The device reaction engine includes 10 fully implemented genre profiles, each
with game-event-specific reaction rules and pre-designed patterns.

### 7.1 Available Genre Profiles

| Genre          | Factory Functions                                                                                                       | Key Events                                                                                                                                  |
| -------------- | ----------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
| **Puzzle**     | `createPuzzleProfile`, `createCasualPuzzleProfile`, `createCompetitivePuzzleProfile`, `createRelaxPuzzleProfile`        | Tile match, combo chain, time pressure, level complete, power-up, failure                                                                   |
| **FPS**        | `createFpsProfile`, `createTacticalFpsProfile`, `createArenaFpsProfile`, `createCasualFpsProfile`                       | Weapon fire, damage received, explosion, low health, kill, reload, footstep, grenade, melee, shield hit                                     |
| **Racing**     | `createRacingProfile`, `createArcadeRacingProfile`, `createSimRacingProfile`, `createCasualRacingProfile`               | Engine RPM, collision, drift, terrain change, nitro boost, gear shift, braking, lap complete                                                |
| **Open World** | `createOpenWorldProfile`, `createExplorationProfile`, `createCombatFocusedProfile`, `createRelaxedOpenWorldProfile`     | Ambient weather, discovery, combat intensity, mount movement, quest complete, environmental hazard, crafting                                |
| **Platformer** | `createPlatformerProfile`, `createPrecisionPlatformerProfile`, `createCasualPlatformerProfile`, `createSpeedrunProfile` | Jump, land, collectible, wall slide, enemy stomp, death, respawn, speed boost, power-up, checkpoint                                         |
| **Rhythm**     | `createRhythmProfile`, `createCompetitiveRhythmProfile`, `createCasualRhythmProfile`, `createPartyRhythmProfile`        | Beat hit, beat miss, combo multiplier, bass drop, song section, freestyle, perfect streak, BPM change, overdrive                            |
| **RPG**        | `createRpgProfile`, `createActionRpgProfile`, `createTurnBasedRpgProfile`, `createCasualRpgProfile`                     | Spell cast, melee attack, level up, status effect, critical hit, boss encounter, item pickup, quest complete, dialogue choice               |
| **Strategy**   | `createStrategyProfile`, `createRtsProfile`, `createTurnBasedStrategyProfile`, `createCasualStrategyProfile`            | Unit select, battle engage, resource collect, building complete, attack alert, victory/defeat, tech research, territory capture             |
| **Fighting**   | `createFightingProfile`, `createArcadeFightingProfile`, `createTechnicalFightingProfile`, `createCasualFightingProfile` | Strike, block, combo string, super move, health critical, grab, counter, round end, special cancel, guard break                             |
| **Horror**     | `createHorrorProfile`, `createPsychologicalHorrorProfile`, `createActionHorrorProfile`, `createMildHorrorProfile`       | Ambient dread, jump scare, heartbeat, environmental tension, relief, creature nearby, flashlight flicker, sanity                            |
| **Sports**     | `createSportsProfile`, `createCompetitiveSportsProfile`, `createCasualSportsProfile`, `createBroadcastSportsProfile`    | Ball impact, sprint, goal score, crowd reaction, whistle, tackle, pass complete, foul, match end                                            |
| **Simulation** | `createSimulationProfile`, `createRealisticSimProfile`, `createArcadeSimProfile`, `createTrainingSimProfile`            | Vehicle operation, success/failure outcome, environment awareness, mechanical feedback, weather effect, collision warning, mission complete |

### 7.2 Using a Genre Profile

```typescript
import { createFpsProfile } from '@aphrodite/device-reaction-engine';

const fpsProfile = createFpsProfile();

// Process a game event
const result = fpsProfile.processEvent({
  type: 'weapon_fire',
  data: {
    weaponType: 'rifle',
    direction: 'front',
    intensity: 0.7,
  },
});

// result.commands contains device commands
// result.patternUsed contains the pattern that was selected
```

### 7.3 Genre Profile Architecture

Each genre profile follows the same pattern:

```
GenreProfile
├── Event types (const enum of all game events)
├── Difficulty levels (casual, competitive, etc.)
├── Domain-specific enums (weapon types, terrain types, etc.)
├── Event data interfaces (per-event structured data)
├── Reaction rules (event → pattern + intensity mapping)
├── Pattern generators (event data → PatternSample[])
├── Intensity computer (event data → base intensity)
├── Pre-built patterns (e.g., PISTOL_SHOT, TERRAIN_GRAVEL)
├── Profile class (event processing, rule management)
└── Factory functions (presets for common configurations)
```

### 7.4 Creating a New Genre Profile

See the [Genre Development Guide](./genre-guide.md) for the full process. The
key steps for the device reaction portion:

1. Define event types for your genre
2. Create event data interfaces
3. Write pattern generators for each event
4. Define intensity computation logic
5. Create reaction rules mapping events to patterns
6. Implement the profile class with `processEvent()`
7. Add factory functions for preset configurations

---

## 8. Testing Device Reactions

### 8.1 Testing Tools

The `@aphrodite/game-testing` library provides five specialized testers:

| Tester                           | What it validates                        |
| -------------------------------- | ---------------------------------------- |
| `GenreReactionProfileValidator`  | Genre profile constraint compliance      |
| `SafetyLimitVerifier`            | Hard safety limit enforcement            |
| `MultiDeviceChoreographyTester`  | Multi-device timing synchronization      |
| `DeviceLatencyMeasurer`          | Device latency measurement and reporting |
| `IntensityCurveSmoothnessTester` | Intensity curve gradient smoothness      |

### 8.2 Intensity Curve Smoothness

Verify that intensity transitions are smooth (no jarring jumps):

```typescript
import {
  createIntensityCurveSmoothnessTester,
  type IntensitySample,
} from '@aphrodite/game-testing';

const tester = createIntensityCurveSmoothnessTester();

const samples: IntensitySample[] = [
  { timestamp: 0, intensity: 0.1 },
  { timestamp: 100, intensity: 0.2 },
  { timestamp: 200, intensity: 0.35 },
  { timestamp: 300, intensity: 0.5 },
  { timestamp: 400, intensity: 0.65 },
];

// Max allowed derivative: 2.0/s, jump threshold: 0.3
const analysis = tester.analyze(samples, 2.0, 0.3);

console.log(analysis.passed); // true
console.log(analysis.maxDerivative); // ~1.5/s
console.log(analysis.averageDerivative); // ~1.375/s
console.log(analysis.jumpCount); // 0
console.log(analysis.isMonotonic); // true
console.log(analysis.monotonicDirection); // 'increasing'
```

### 8.3 Genre Profile Validation

```typescript
import {
  createGenreReactionProfileValidator,
  GameGenre,
} from '@aphrodite/game-testing';

const validator = createGenreReactionProfileValidator();

// Validate samples against a genre
const result = validator.validate(GameGenre.ACTION, samples);

if (!result.passed) {
  console.log('Violations:', result.violations);
  console.log('Intensity stats:', result.intensityStats);
  console.log('Duration stats:', result.durationStats);
  console.log('Frequency:', result.frequencyHz, 'Hz');
}
```

### 8.4 Running Tests

```bash
# Type check the device reaction engine
cd libs/aphrodite/device-reaction-engine && npx tsc --noEmit

# Run device reaction engine tests
cd libs/aphrodite/device-reaction-engine && npx vitest run

# Run game-testing device tests
cd libs/aphrodite/game-testing && npx vitest run src/device-tests/
```

---

## 9. Preview and Debugging

### 9.1 Reaction Preview

The preview system simulates device reactions without physical hardware:

```typescript
import {
  createDeveloperPreview,
  createVirtualDevice,
  renderTextPreview,
} from '@aphrodite/device-reaction-engine';

const preview = createDeveloperPreview();

// Create virtual devices
const vDevice = createVirtualDevice('virtual-motor-1');

// Simulate a command
const frames = preview.simulateCommand(vDevice, command);

// Render as text visualization
const text = renderTextPreview(frames);
console.log(text);
// Output: ▁▂▄▆█▆▄▂▁ (intensity over time)
```

### 9.2 A/B Testing

Compare two reaction variants:

```typescript
import { runABTest } from '@aphrodite/device-reaction-engine';

const testResult = runABTest({
  variantA: commandA,
  variantB: commandB,
  metrics: ['intensity_range', 'smoothness', 'perceived_strength'],
  trials: 100,
});

console.log(testResult.winner); // 'A' or 'B' or 'tie'
console.log(testResult.confidence); // 0.95
```

### 9.3 Recording and Playback

Record reaction sessions for analysis:

```typescript
import {
  createPreviewRecording,
  addRecordingEntry,
  finalizeRecording,
  exportPreviewRecording,
  importPreviewRecording,
} from '@aphrodite/device-reaction-engine';

// Start recording
const recording = createPreviewRecording();

// Add entries as reactions occur
addRecordingEntry(recording, { timestamp: 0, command, device: vDevice });

// Finalize and export
const final = finalizeRecording(recording);
const json = exportPreviewRecording(final);

// Import for replay
const imported = importPreviewRecording(json);
```

---

## 10. Reference

### 10.1 Safety Limits Summary

| Limit                  | Value  | Rationale                              |
| ---------------------- | ------ | -------------------------------------- |
| Max intensity          | 0.85   | Prevent discomfort at extreme values   |
| Max duration           | 5000ms | Prevent desensitization and discomfort |
| Max frequency          | 30 Hz  | Human tactile perception limit         |
| Min cooldown           | 33ms   | Inverse of max frequency               |
| Max concurrent devices | 8      | Total intensity management             |
| Max total intensity    | 3.0    | Prevent overwhelming combined feedback |

### 10.2 Genre Reaction Profile Constraints

| Genre      | Intensity | Duration  | Max Hz | Key Types                 |
| ---------- | --------- | --------- | ------ | ------------------------- |
| ACTION     | 0.1–0.85  | 20–2000ms | 25     | impact, explosion, rumble |
| HORROR     | 0.05–0.7  | 50–5000ms | 10     | pulse, ambient, rumble    |
| RACING     | 0.1–0.9   | 10–3000ms | 30     | engine, crash, surface    |
| RHYTHM     | 0.2–0.8   | 10–500ms  | 20     | beat, tap, pulse          |
| RPG        | 0.05–0.75 | 30–3000ms | 15     | magic, hit, heal          |
| PUZZLE     | 0.05–0.5  | 20–1000ms | 5      | click, snap, solve        |
| SIMULATION | 0.05–0.6  | 30–4000ms | 10     | feedback, ambient         |
| SPORTS     | 0.1–0.85  | 15–2000ms | 20     | impact, kick, catch       |

### 10.3 Intensity Curve Selection Guide

| Scenario              | Recommended curve | Rationale                           |
| --------------------- | ----------------- | ----------------------------------- |
| Default / unknown     | `linear`          | Predictable 1:1 mapping             |
| Competitive games     | `exponential`     | Precise control at low values       |
| Casual games          | `logarithmic`     | Strong feedback for gentle input    |
| Narrative / cinematic | `s-curve`         | Compressed extremes, wide mid-range |
| Rhythm games          | `step`            | Discrete levels match hit accuracy  |
| Platformers           | `bounce`          | Playful, responsive feel            |
| Horror / atmospheric  | `ease`            | Smooth, deliberate transitions      |

### 10.4 Pattern Selection Guide

| Game moment     | Recommended patterns       | Notes                        |
| --------------- | -------------------------- | ---------------------------- |
| Button press    | `SHARP_PULSE`              | Keep under 50ms              |
| Gunshot         | `BURST` or weapon-specific | Scale intensity by caliber   |
| Explosion       | `EXPLOSION_FULL`           | Use ripple choreography      |
| Landing         | `THUD`                     | Scale by fall height         |
| Damage taken    | `DAMAGE_SEQUENCE`          | Use directional choreography |
| Low health      | `HEARTBEAT`                | Loop continuously            |
| Boss intro      | `BOSS_ENTRANCE`            | Use all devices              |
| Victory         | `VICTORY_FANFARE`          | Full intensity               |
| Ambient weather | `AMBIENT_STORM`            | Low intensity, sustained     |
| Music beat      | `TAPPING` / `PULSING`      | Sync with timing engine      |
