# Metaverse Service

3D virtual world engine for Lilith's immersive meditation and learning environments.

## Overview

The Metaverse service provides:
- **3D Rendering Engine**: WebGL/WebGPU-based scene management
- **Physics Simulation**: Realistic object interactions and collision
- **Multiplayer Synchronization**: Real-time state sync for 1000+ concurrent users
- **80+ AI Guides**: Embodied spiritual teachers from all wisdom traditions
- **Spatial Audio**: 3D positional sound with binaural processing
- **Sacred Environments**: 20+ pre-built meditation spaces
- **User-Generated Worlds**: Visual world builder and asset library

## Architecture

```
metaverse/
├── src/
│   ├── app.ts              # Fastify application setup
│   ├── server.ts           # Server entry point
│   ├── engine/             # Core 3D engine
│   ├── physics/            # Physics simulation
│   ├── multiplayer/        # State synchronization
│   ├── ai/                 # AI guide system (80+ personalities)
│   ├── avatars/            # Avatar system
│   ├── environments/       # Sacred spaces
│   ├── audio/              # Spatial audio
│   ├── geometry/           # Sacred geometry generation
│   ├── optimization/       # Performance optimization
│   ├── platform/           # Cross-platform support
│   ├── world/              # World management
│   ├── advanced/           # Advanced features
│   └── creator/            # World builder tools
├── __tests__/              # Test suites
└── package.json
```

## AI Guide System

### Categories (80+ Personalities)

| Category | Examples |
|----------|----------|
| Eastern Masters | Zen Roshis, Tibetan Lamas, Hindu Gurus, Taoist Sages |
| Western Mystics | Gnostic Teachers, Hermetic Adepts, Christian Mystics |
| Indigenous Guides | Shamans, Medicine People, Elders |
| Modern Teachers | Neuroscientists, Quantum Physicists, Psychologists |
| Ancient Wisdom | Egyptian Priests, Greek Philosophers, Norse Seers |
| Feminine Divine | Goddess Priestesses, Dakinis, Wise Women |

### AI Capabilities

- GPT-4/Claude integration with custom fine-tuning
- Persistent memory via vector embeddings
- Emotional intelligence and empathy modeling
- Teaching style adaptation
- Multi-modal responses (text, voice, gestures)
- Cultural context awareness
- Lineage-authentic teachings

## Sacred Environments

Pre-built meditation spaces:
- Zen gardens with raked sand physics
- Tibetan monasteries with prayer wheels
- Egyptian temples with hieroglyphic wisdom
- Greek philosophy academies
- Sufi shrines with whirling spaces
- Hindu temples with deity presence
- Celtic stone circles
- Mayan pyramids
- Crystal caves
- Underwater temples
- Cosmic void spaces
- Quantum realms

## API Endpoints

### World Management

```http
GET  /v1/metaverse/worlds              # List available worlds
GET  /v1/metaverse/worlds/:id          # Get world details
POST /v1/metaverse/worlds              # Create user world
PUT  /v1/metaverse/worlds/:id          # Update world

GET  /v1/metaverse/worlds/:id/state    # Get world state
WS   /v1/metaverse/worlds/:id/sync     # Real-time state sync
```

### Session Management

```http
POST /v1/metaverse/sessions            # Create session
GET  /v1/metaverse/sessions/:id        # Get session
DELETE /v1/metaverse/sessions/:id      # End session

POST /v1/metaverse/sessions/:id/join   # Join session
POST /v1/metaverse/sessions/:id/leave  # Leave session
```

### Avatar

```http
GET  /v1/metaverse/avatars             # List avatars
POST /v1/metaverse/avatars             # Create avatar
PUT  /v1/metaverse/avatars/:id         # Update avatar

GET  /v1/metaverse/avatars/:id/state   # Get avatar state
POST /v1/metaverse/avatars/:id/action  # Trigger action
```

### AI Guides

```http
GET  /v1/metaverse/guides              # List AI guides
GET  /v1/metaverse/guides/:id          # Get guide details
POST /v1/metaverse/guides/:id/interact # Interact with guide
POST /v1/metaverse/guides/:id/summon   # Summon to location
```

### Environment

```http
GET  /v1/metaverse/environments        # List environments
GET  /v1/metaverse/environments/:id    # Get environment
POST /v1/metaverse/environments/:id/enter # Enter environment
```

## WebSocket Protocol

### Connection

```javascript
const ws = new WebSocket('wss://api.lilith.app/v1/metaverse/worlds/123/sync');

ws.onopen = () => {
  ws.send(JSON.stringify({
    type: 'join',
    userId: 'user_123',
    avatarId: 'avatar_456'
  }));
};
```

### Message Types

| Type | Description |
|------|-------------|
| `join` | Join world session |
| `leave` | Leave world session |
| `move` | Avatar movement |
| `action` | Avatar action/gesture |
| `chat` | Text/voice message |
| `interact` | Object interaction |
| `state_sync` | Full state synchronization |
| `delta_sync` | Delta state update |

### State Sync Payload

```json
{
  "type": "state_sync",
  "timestamp": 1704292800000,
  "entities": [
    {
      "id": "avatar_123",
      "type": "avatar",
      "position": [10.5, 0, 5.2],
      "rotation": [0, 45, 0],
      "animation": "idle",
      "state": {"meditating": true}
    }
  ],
  "events": []
}
```

## Performance Targets

| Metric | Target |
|--------|--------|
| Frame Rate | 60 FPS |
| Concurrent Users | 1000+ per realm |
| State Sync Latency | <100ms |
| Audio Latency | <50ms |
| World Load Time | <5s |

## Configuration

```yaml
# config/default.yaml
metaverse:
  maxUsersPerWorld: 1000
  syncTickRate: 30 # Hz
  physics:
    engine: "rapier"
    timeStep: 1/60
  rendering:
    shadowQuality: "high"
    antiAliasing: true
    lodLevels: 4
  audio:
    spatialEnabled: true
    binauralEnabled: true
    maxAudioSources: 64
```

## Development

```bash
# Install dependencies
npm install

# Start development server
npm run dev

# Run tests
npm test

# Build for production
npm run build
```

## Environment Variables

```env
PORT=8080
NODE_ENV=development
REDIS_URL=redis://localhost:6379
AI_SERVICE_URL=http://localhost:8081
MEDIA_SERVICE_URL=http://localhost:8082
```

## Dependencies

- **Fastify**: HTTP framework
- **ws**: WebSocket server
- **Rapier**: Physics engine (WASM)
- **Redis**: State management and pub/sub
- **Three.js types**: 3D type definitions

## Testing

```bash
# Unit tests
npm test

# Integration tests
npm run test:integration

# Load tests
npm run test:load
```

## Known Limitations

1. **WebGL 2.0 Required**: Older browsers not supported
2. **Memory Usage**: Large worlds may require 4GB+ RAM
3. **Mobile Performance**: Reduced quality on mobile devices
4. **VR Latency**: WebXR adds ~10ms latency

## Related Documentation

- [Metaverse WebGL Engine](/docs/metaverse-webgl-engine.md)
- [Metaverse Physics](/docs/metaverse/physics.md)
- [Metaverse Networking](/docs/metaverse/networking.md)
- [AI Teacher Registry](/docs/ai-teacher-personality-registry.md)
