# Metaverse Environment System

Technical documentation for Lilith's comprehensive environment system covering
world building, terrain generation, weather systems, sacred spaces, and
procedural world generation.

## Overview

The Lilith Platform implements a multi-layered environment system supporting:

- **World Loading**: Dynamic streaming with spatial partitioning
- **World Building**: Visual editor for environment creation
- **Terrain Generation**: Procedural terrain with biomes and erosion
- **Weather System**: Dynamic day/night cycles and seasonal effects
- **Sacred Spaces**: 20+ pre-built spiritual environments
- **Ancient Sites**: Historically-accurate reconstructions
- **Procedural Generation**: Infinite exploration with seed-based worlds

## Architecture

```
┌─────────────────────────────────────────────────────────────────────────┐
│                     Environment System Architecture                      │
├─────────────────────────────────────────────────────────────────────────┤
│                                                                          │
│  ┌─────────────────────────────────────────────────────────────────┐    │
│  │                    World Management Layer                        │    │
│  │  ┌─────────────┐  ┌─────────────┐  ┌─────────────────────────┐  │    │
│  │  │   World     │  │   World     │  │   Procedural World      │  │    │
│  │  │   Loader    │──│   Builder   │──│   Generator             │  │    │
│  │  │  (Streaming)│  │   (Editor)  │  │  (Infinite Worlds)      │  │    │
│  │  └─────────────┘  └─────────────┘  └─────────────────────────┘  │    │
│  └─────────────────────────────────────────────────────────────────┘    │
│                                   │                                      │
│  ┌─────────────────────────────────────────────────────────────────┐    │
│  │                  Terrain & Geography Layer                       │    │
│  │  ┌───────────────┐  ┌───────────────┐  ┌─────────────────────┐  │    │
│  │  │   Terrain     │  │   Biome       │  │   Vegetation        │  │    │
│  │  │   Generator   │──│   System      │──│   System            │  │    │
│  │  │  (Heightmaps) │  │  (8 Biomes)   │  │  (Instanced)        │  │    │
│  │  └───────────────┘  └───────────────┘  └─────────────────────┘  │    │
│  └─────────────────────────────────────────────────────────────────┘    │
│                                   │                                      │
│  ┌─────────────────────────────────────────────────────────────────┐    │
│  │                  Atmosphere & Effects Layer                      │    │
│  │  ┌───────────────┐  ┌───────────────┐  ┌─────────────────────┐  │    │
│  │  │   Weather     │  │   Day/Night   │  │   Seasonal          │  │    │
│  │  │   System      │──│   Cycle       │──│   System            │  │    │
│  │  │  (11 States)  │  │  (Real-time)  │  │  (4 Seasons)        │  │    │
│  │  └───────────────┘  └───────────────┘  └─────────────────────┘  │    │
│  └─────────────────────────────────────────────────────────────────┘    │
│                                   │                                      │
│  ┌─────────────────────────────────────────────────────────────────┐    │
│  │                  Sacred Spaces Layer                             │    │
│  │  ┌───────────────┐  ┌───────────────┐  ┌─────────────────────┐  │    │
│  │  │   Template    │  │   Ancient     │  │   Sacred Geometry   │  │    │
│  │  │   Manager     │──│   Sites       │──│   Generator         │  │    │
│  │  │  (20+ Spaces) │  │  (Historical) │  │  (Procedural)       │  │    │
│  │  └───────────────┘  └───────────────┘  └─────────────────────┘  │    │
│  └─────────────────────────────────────────────────────────────────┘    │
│                                                                          │
└─────────────────────────────────────────────────────────────────────────┘
```

---

## World Management

### 1. World Loader

**Location**: `services/metaverse/src/world/WorldLoader.ts`

Dynamic streaming system with spatial partitioning for efficient world loading.

#### Features

| Feature                 | Description                                              |
| ----------------------- | -------------------------------------------------------- |
| **Spatial Grid**        | Configurable cell-based partitioning (default 100 units) |
| **Asset Streaming**     | Progressive loading with priority queue                  |
| **Dependency Tracking** | Asset dependency resolution                              |
| **Multi-Level Cache**   | LRU cache with 500MB default limit                       |
| **Concurrent Loading**  | Configurable max concurrent loads (default 6)            |
| **Zone Management**     | Dynamic loading/unloading based on player position       |

#### Configuration

```typescript
interface WorldLoaderConfig {
  gridCellSize: number; // Default: 100 units
  maxConcurrentLoads: number; // Default: 6
  cacheSize: number; // Default: 500MB
  prefetchDistance: number; // How far ahead to load
  unloadDistance: number; // When to unload zones
}
```

#### Usage

```typescript
import { WorldLoader } from '@/world/WorldLoader';

const loader = new WorldLoader({
  gridCellSize: 100,
  maxConcurrentLoads: 6,
  cacheSize: 500 * 1024 * 1024, // 500MB
});

// Register assets
loader.registerAsset('temple_model', {
  url: '/assets/temple.glb',
  type: 'mesh',
  dependencies: ['temple_texture', 'temple_material'],
});

// Load a zone
await loader.loadZone({ x: 0, y: 0 });

// Update based on player position
loader.updatePlayerPosition(playerPosition);

// Get loading stats
const stats = loader.getStats();
console.log(stats.totalAssets, stats.loadedAssets, stats.memoryUsage);
```

#### Loading Statistics

```typescript
interface LoaderStats {
  totalAssets: number;
  loadedAssets: number;
  pendingAssets: number;
  cacheHits: number;
  cacheMisses: number;
  activeZones: number;
  memoryUsage: number;
}
```

---

### 2. World Builder

**Location**: `services/metaverse/src/creator/WorldBuilder.ts`

Visual drag-and-drop 3D editor for environment creation.

#### Features

- **Project Management**: Create, load, save, delete projects
- **Multi-Selection**: Select and transform multiple objects
- **Transform Gizmos**: Translate, rotate, scale with snapping
- **Undo/Redo**: Unlimited history stack
- **Copy/Paste**: With duplication offset
- **Object Hierarchy**: Tree-based object organization
- **Grid Visualization**: Customizable grid settings
- **Camera Modes**: Orbit, pan, zoom, fly

#### Editor State

```typescript
interface EditorState {
  selectedObjects: string[];
  transformMode: 'translate' | 'rotate' | 'scale';
  snapEnabled: boolean;
  snapSize: number;
  gridVisible: boolean;
  gridSize: number;
  cameraMode: 'orbit' | 'pan' | 'zoom' | 'fly';
}
```

#### Project Structure

```typescript
interface WorldProject {
  id: string;
  name: string;
  description: string;
  objects: WorldObject[];
  settings: WorldSettings;
  metadata: {
    complexityScore: number;
    triangleCount: number;
    createdAt: Date;
    updatedAt: Date;
  };
}

interface WorldObject {
  id: string;
  type: 'mesh' | 'light' | 'audio' | 'trigger' | 'spawn';
  position: Vector3;
  rotation: Euler;
  scale: Vector3;
  parentId?: string;
  properties: Record<string, any>;
}
```

#### Usage

```typescript
import { WorldBuilder } from '@/creator/WorldBuilder';

const builder = new WorldBuilder();

// Create new project
const project = builder.createProject('Zen Garden');

// Add objects
const temple = builder.addObject({
  type: 'mesh',
  asset: 'temple_prefab',
  position: { x: 0, y: 0, z: 0 },
});

// Transform with snapping
builder.setSnapEnabled(true);
builder.setSnapSize(0.5);
builder.translateObject(temple.id, { x: 10, y: 0, z: 5 });

// Undo/Redo
builder.undo();
builder.redo();

// Save project
await builder.saveProject();
```

---

### 3. Procedural World Generator

**Location**: `services/metaverse/src/advanced/ProceduralWorldGenerator.ts`

Infinite world generation with seed-based determinism.

#### Features

| Feature                       | Description                                      |
| ----------------------------- | ------------------------------------------------ |
| **Infinite Exploration**      | Seed-based procedural generation                 |
| **Chunk Streaming**           | Dynamic loading/unloading based on view distance |
| **Multiple Noise Algorithms** | Perlin, Simplex, Worley/Cellular                 |
| **Biome Blending**            | Smooth transitions between biomes                |
| **Structure Placement**       | Temples, shrines, landmarks, caves               |
| **LRU Cache**                 | Configurable chunk cache                         |

#### Configuration

```typescript
interface ProceduralConfig {
  seed: number;
  chunkSize: number; // Default: 16 units
  viewDistance: number; // Default: 3 chunks
  cacheSize: number; // Default: 64 chunks
  noiseAlgorithm: 'perlin' | 'simplex' | 'worley';
  biomeScale: number; // Controls biome size
  structureDensity: number; // 0-1, structure spawn rate
}
```

#### Biome Types

| Biome     | Height Range | Temperature | Moisture | Features              |
| --------- | ------------ | ----------- | -------- | --------------------- |
| Plains    | Low          | Moderate    | Moderate | Grass, flowers        |
| Forest    | Low-Medium   | Cool-Warm   | High     | Dense trees           |
| Mountains | High         | Cold        | Low      | Rocks, snow caps      |
| Desert    | Low-Medium   | Hot         | Very Low | Sand, cacti           |
| Tundra    | Low          | Very Cold   | Low      | Snow, sparse shrubs   |
| Ocean     | Very Low     | Variable    | Maximum  | Water                 |
| Cave      | Underground  | Cool        | Variable | Crystals, stalactites |

#### Usage

```typescript
import { ProceduralWorldGenerator } from '@/advanced/ProceduralWorldGenerator';

const generator = new ProceduralWorldGenerator({
  seed: 12345,
  chunkSize: 16,
  viewDistance: 3,
});

// Generate chunk at position
const chunk = generator.generateChunk(chunkX, chunkZ);

// Update based on player position (loads/unloads chunks)
generator.update(playerPosition);

// Get statistics
const stats = generator.getStats();
console.log(stats.loadedChunks, stats.generatedStructures);
```

#### Chunk Structure

```typescript
interface Chunk {
  x: number;
  z: number;
  heightmap: Float32Array;
  biomeMap: Uint8Array;
  structures: Structure[];
  vegetation: VegetationInstance[];
  loaded: boolean;
  lastAccessed: number;
}
```

---

## Terrain & Geography

### 1. Terrain Generator

**Location**: `services/metaverse/src/creator/TerrainGenerator.ts`

Procedural terrain generation with heightmaps, erosion, and biome support.

#### Height Map Generation

```typescript
interface HeightmapConfig {
  width: number;
  height: number;
  scale: number;
  octaves: number; // Noise layers (default: 4)
  persistence: number; // Amplitude decay (default: 0.5)
  lacunarity: number; // Frequency increase (default: 2.0)
  seed: number;
}

// Generation algorithms
type HeightmapAlgorithm =
  | 'perlin' // Classic Perlin noise
  | 'diamond_square' // Fractal terrain
  | 'voronoi' // Cell-based
  | 'ridged'; // Ridged multifractal
```

#### Erosion Simulation

```typescript
interface ErosionConfig {
  iterations: number; // Simulation steps
  strength: number; // Erosion intensity (0-1)
  depositionRate: number; // Sediment deposit rate
  evaporationRate: number; // Water evaporation
  gravity: number; // Flow acceleration
}

// Apply erosion to heightmap
terrainGenerator.applyErosion(heightmap, {
  iterations: 50000,
  strength: 0.3,
});
```

#### Brush Types

```typescript
type BrushFalloff = 'linear' | 'smooth' | 'sharp';

interface TerrainBrush {
  radius: number;
  strength: number;
  falloff: BrushFalloff;
  operation: 'raise' | 'lower' | 'smooth' | 'flatten';
}
```

### 2. Biome System

8 distinct biomes with automatic placement based on height, temperature, and
moisture.

#### Biome Definitions

| Biome         | Temperature         | Precipitation         | Vegetation         |
| ------------- | ------------------- | --------------------- | ------------------ |
| **Desert**    | Hot (>30°C)         | Arid (<250mm)         | Cacti, succulents  |
| **Forest**    | Temperate (10-20°C) | Moderate (500-1500mm) | Oak, pine, fern    |
| **Mountain**  | Cold (<10°C)        | Variable              | Sparse alpine      |
| **Grassland** | Temperate           | Low-Moderate          | Grass, wildflowers |
| **Tundra**    | Very Cold (<0°C)    | Low                   | Moss, lichen       |
| **Volcanic**  | Extreme Hot         | N/A                   | Minimal            |
| **Wetland**   | Warm                | Very High             | Swamp vegetation   |
| **Alpine**    | Cold                | Moderate              | Rocky, sparse      |

#### Biome Configuration

```typescript
interface BiomeConfig {
  id: string;
  name: string;
  heightRange: [number, number]; // Min/max elevation
  temperatureRange: [number, number]; // Min/max temp
  moistureRange: [number, number]; // Min/max moisture
  vegetation: VegetationRule[];
  groundMaterial: MaterialConfig;
  ambientSound: string;
}
```

### 3. Vegetation System

Density-based procedural vegetation placement with instancing optimization.

#### Vegetation Rules

```typescript
interface VegetationRule {
  asset: string;
  density: number; // Plants per unit area
  heightRange: [number, number];
  moistureRange: [number, number];
  slopeRange: [number, number];
  scaleRange: [number, number];
  randomRotation: boolean;
}

// Example: Forest biome vegetation
const forestVegetation: VegetationRule[] = [
  {
    asset: 'oak_tree',
    density: 0.05,
    heightRange: [0, 0.5],
    moistureRange: [0.4, 1.0],
    slopeRange: [0, 0.3],
    scaleRange: [0.8, 1.2],
    randomRotation: true,
  },
  {
    asset: 'pine_tree',
    density: 0.08,
    heightRange: [0.3, 0.7],
    moistureRange: [0.3, 0.8],
    slopeRange: [0, 0.4],
    scaleRange: [0.9, 1.4],
    randomRotation: true,
  },
];
```

### 4. Water Features

```typescript
interface WaterFeature {
  type: 'lake' | 'river' | 'waterfall' | 'ocean';
  position: Vector3;
  size: Vector3;
  depth: number;
  flowDirection?: Vector3; // For rivers
  flowSpeed?: number;
  material: WaterMaterialConfig;
}

interface WaterMaterialConfig {
  color: Color;
  transparency: number;
  reflectivity: number;
  waveAmplitude: number;
  waveFrequency: number;
}
```

### 5. LOD System

Distance-based terrain detail reduction.

| Level         | Distance | Chunk Size | Resolution |
| ------------- | -------- | ---------- | ---------- |
| 0 (High)      | 0-100    | 32         | 128        |
| 1 (Medium)    | 100-300  | 64         | 64         |
| 2 (Low)       | 300-600  | 128        | 32         |
| 3 (Ultra Low) | 600+     | 256        | 16         |

---

## Atmosphere & Weather

### 1. Weather System

**Location**: `services/metaverse/src/environments/WeatherSystem.ts`

Dynamic weather simulation with consciousness impact for meditation.

#### Weather States (11 Types)

| State             | Precipitation | Visibility | Consciousness Effect        |
| ----------------- | ------------- | ---------- | --------------------------- |
| **Clear**         | None          | Excellent  | Focus +0.2, Energy +0.1     |
| **Cloudy**        | None          | Good       | Calm +0.1                   |
| **Partly Cloudy** | None          | Good       | Neutral                     |
| **Rain**          | Light         | Reduced    | Calm +0.2, Meditation +0.1  |
| **Heavy Rain**    | Heavy         | Poor       | Meditation +0.2             |
| **Snow**          | Light         | Reduced    | Peace +0.2                  |
| **Heavy Snow**    | Heavy         | Poor       | Meditation +0.3             |
| **Fog**           | None          | Very Poor  | Introspection +0.3          |
| **Mist**          | Light         | Reduced    | Mystery +0.2                |
| **Storm**         | Moderate      | Poor       | Energy -0.1, Challenge +0.2 |
| **Thunderstorm**  | Heavy         | Very Poor  | Energy +0.1, Awe +0.3       |

#### Weather Configuration

```typescript
interface WeatherConfig {
  initialState: WeatherState;
  transitionDuration: number; // Weather change time (ms)
  autoTransition: boolean; // Random weather changes
  transitionProbability: number; // Chance per interval
  seasonalAdjustment: boolean; // Season affects weather
}

interface WeatherEffects {
  particles: ParticleConfig; // Rain, snow, etc.
  fog: FogConfig;
  wind: WindConfig;
  lightning?: LightningConfig;
}
```

#### Usage

```typescript
import { WeatherSystem } from '@/environments/WeatherSystem';

const weather = new WeatherSystem({
  initialState: 'clear',
  autoTransition: true,
});

// Transition to new weather
weather.transitionTo('rain', 5000); // 5 second transition

// Get current effects
const effects = weather.getCurrentEffects();

// Get consciousness modifiers
const modifiers = weather.getConsciousnessModifiers();
console.log(modifiers.meditation, modifiers.focus, modifiers.energy);

// Update in game loop
weather.update(deltaTime);
```

### 2. Day/Night Cycle

Real-time simulation with astronomical accuracy.

#### Configuration

```typescript
interface DayNightConfig {
  timeScale: number; // Game seconds per real second (default: 60)
  startTime: number; // Initial hour (0-24)
  latitude: number; // For sun angle calculation
  autoProgress: boolean; // Time advances automatically
}
```

#### Time Periods

| Period        | Hours       | Sun Altitude  | Ambient Light |
| ------------- | ----------- | ------------- | ------------- |
| **Night**     | 00:00-05:00 | Below horizon | 0.1           |
| **Dawn**      | 05:00-07:00 | Rising        | 0.1-0.5       |
| **Morning**   | 07:00-11:00 | Low-Medium    | 0.5-0.9       |
| **Noon**      | 11:00-13:00 | High          | 1.0           |
| **Afternoon** | 13:00-17:00 | Medium-Low    | 0.9-0.6       |
| **Dusk**      | 17:00-19:00 | Setting       | 0.6-0.2       |
| **Evening**   | 19:00-24:00 | Below horizon | 0.2-0.1       |

#### Sky Color Gradients

```typescript
const skyColors = {
  dawn: {
    horizon: '#FF7F50', // Coral
    zenith: '#4169E1', // Royal Blue
    sun: '#FFD700', // Gold
  },
  day: {
    horizon: '#87CEEB', // Sky Blue
    zenith: '#1E90FF', // Dodger Blue
    sun: '#FFFACD', // Lemon Chiffon
  },
  dusk: {
    horizon: '#FF6347', // Tomato
    zenith: '#4B0082', // Indigo
    sun: '#FF8C00', // Dark Orange
  },
  night: {
    horizon: '#191970', // Midnight Blue
    zenith: '#000033', // Dark Navy
    moon: '#F0F0F0', // Off White
  },
};
```

### 3. Seasonal System

4 seasons affecting weather, lighting, and vegetation.

| Season     | Temperature Offset | Daylight Hours | Weather Bias |
| ---------- | ------------------ | -------------- | ------------ |
| **Spring** | +5°C               | 12-14          | Rain +20%    |
| **Summer** | +15°C              | 14-16          | Clear +30%   |
| **Autumn** | +5°C               | 10-12          | Cloudy +20%  |
| **Winter** | -10°C              | 8-10           | Snow +40%    |

#### Seasonal Effects

```typescript
interface SeasonalEffects {
  vegetationState: 'budding' | 'full' | 'changing' | 'bare';
  groundColor: Color;
  leafColor?: Color;
  particleEffects: string[]; // ['falling_leaves', 'snow', etc.]
}
```

---

## Sacred Spaces

### 1. Template Manager

**Location**: `services/metaverse/src/environments/TemplateManager.ts`

20+ pre-built sacred environments for meditation and spiritual practice.

#### Available Templates

| Category     | Templates                                                                                                    |
| ------------ | ------------------------------------------------------------------------------------------------------------ |
| **Eastern**  | Buddhist Temple, Hindu Temple, Japanese Shrine, Tibetan Monastery, Bamboo Forest Temple, Lotus Pond Pavilion |
| **Western**  | Gothic Cathedral, Celtic Stone Circle, Nordic Hall                                                           |
| **Ancient**  | Egyptian Temple, Greek Temple, Mayan Pyramid                                                                 |
| **Islamic**  | Ottoman Mosque                                                                                               |
| **Natural**  | Zen Garden, Forest Grove, Mountain Shrine, Desert Oasis, Cave Sanctuary                                      |
| **Ethereal** | Crystal Cave, Floating Sky Temple                                                                            |

#### Template Structure

```typescript
interface SacredSpaceTemplate {
  id: string;
  name: string;
  description: string;
  category: 'eastern' | 'western' | 'ancient' | 'natural' | 'ethereal';
  difficulty: 'beginner' | 'intermediate' | 'advanced';

  // Assets
  meshes: MeshAsset[];
  textures: TextureAsset[];
  materials: MaterialAsset[];
  sounds: SoundAsset[];
  particles: ParticleAsset[];

  // Configuration
  lighting: LightingPreset;
  soundscape: SoundscapeConfig;
  meditationZones: MeditationZone[];
  customProperties: Record<string, any>;
}
```

#### Lighting Presets (10 Types)

| Preset          | Ambient       | Directional   | Fog    | Use Case           |
| --------------- | ------------- | ------------- | ------ | ------------------ |
| **Dawn**        | Warm orange   | Low east      | Light  | Morning meditation |
| **Noon**        | Bright white  | High overhead | None   | Active practice    |
| **Dusk**        | Purple-orange | Low west      | Medium | Evening reflection |
| **Night**       | Deep blue     | None (moon)   | Heavy  | Night meditation   |
| **Moonlight**   | Silver-blue   | Low           | Light  | Lunar practice     |
| **Candlelight** | Warm amber    | Point lights  | None   | Indoor meditation  |
| **Sunrise**     | Pink-gold     | Rising        | Light  | Awakening          |
| **Sunset**      | Orange-red    | Setting       | Medium | Closing practice   |
| **Cloudy**      | Soft gray     | Diffuse       | Light  | Contemplation      |
| **Golden Hour** | Rich gold     | Low angle     | None   | Photography        |

#### Meditation Zones

```typescript
interface MeditationZone {
  id: string;
  name: string;
  position: Vector3;
  radius: number;
  type: 'sitting' | 'walking' | 'standing' | 'lying';
  capacity: number;
  benefits: MeditationBenefit[];
}

interface MeditationBenefit {
  type: 'mindfulness' | 'peace' | 'clarity' | 'focus' | 'energy' | 'healing';
  multiplier: number; // 0.5-2.0
}
```

#### Usage

```typescript
import { TemplateManager } from '@/environments/TemplateManager';

const templates = new TemplateManager();

// Get available templates
const all = templates.getAll();
const eastern = templates.getByCategory('eastern');

// Load a template
const zenGarden = await templates.load('zen_garden');

// Customize
zenGarden.setLighting('dawn');
zenGarden.addMeditationZone({
  position: { x: 0, y: 0, z: 0 },
  radius: 5,
  type: 'sitting',
  capacity: 10,
  benefits: [
    { type: 'peace', multiplier: 1.5 },
    { type: 'clarity', multiplier: 1.2 },
  ],
});

// Instantiate in scene
await zenGarden.instantiate(scene);
```

---

### 2. Ancient Sites

**Location**: `services/metaverse/src/environments/AncientSites.ts`

Historically-accurate reconstructions of sacred sites.

#### Available Sites

| Site              | Location | Era             | Historical Accuracy |
| ----------------- | -------- | --------------- | ------------------- |
| **Stonehenge**    | England  | 3000-2000 BCE   | 0.95                |
| **Giza Pyramids** | Egypt    | 2580-2560 BCE   | 0.98                |
| **Angkor Wat**    | Cambodia | 12th century    | 0.92                |
| **Machu Picchu**  | Peru     | 15th century    | 0.90                |
| **Petra**         | Jordan   | 4th century BCE | 0.88                |
| **Parthenon**     | Greece   | 5th century BCE | 0.94                |

#### Site Structure

```typescript
interface AncientSite {
  id: string;
  name: string;
  location: GeoLocation;
  era: string;
  historicalAccuracy: number; // 0-1

  // Physical elements
  structures: Structure[];
  inscriptions: Inscription[];
  altars: Altar[];

  // Interactive elements
  portals: Portal[];
  alignments: AstronomicalAlignment[];

  // Atmosphere
  lighting: LightingConfig;
  soundscape: Soundscape;
  particles: ParticleEffect[];

  // Meditation
  zones: MeditationZone[];
  benefits: SiteBenefit[];
}

interface Structure {
  type: 'stone' | 'chamber' | 'corridor' | 'altar' | 'column' | 'wall';
  mesh: string;
  position: Vector3;
  rotation: Euler;
  scale: Vector3;
  material: MaterialConfig;
}

interface AstronomicalAlignment {
  name: string;
  type: 'solstice' | 'equinox' | 'lunar';
  direction: Vector3;
  date: string; // MM-DD format
  visualEffect: string;
}
```

#### Usage

```typescript
import { AncientSites } from '@/environments/AncientSites';

const sites = new AncientSites();

// Load Stonehenge
const stonehenge = await sites.load('stonehenge');

// Access structures
const stones = stonehenge.getStructures('stone');
const altar = stonehenge.getAltar('central');

// Check astronomical alignments
const alignments = stonehenge.getAlignments();
const summerSolstice = alignments.find((a) => a.name === 'summer_solstice');

// Get meditation zones
const zones = stonehenge.getMeditationZones();
```

---

### 3. Sacred Geometry Generator

**Location**: `services/metaverse/src/environments/SacredGeometry.ts`

Procedural generation of sacred geometric patterns.

#### Pattern Types (7)

| Pattern             | Description                                                         | Complexity Range |
| ------------------- | ------------------------------------------------------------------- | ---------------- |
| **Mandala**         | Circular symmetrical patterns                                       | 1-10             |
| **Fractals**        | Self-similar patterns (Sierpinski, Mandelbrot, Julia, Koch, Dragon) | 1-8              |
| **Golden Spiral**   | Fibonacci-based spiral                                              | 1-6              |
| **Flower of Life**  | Overlapping circles pattern                                         | 1-5              |
| **Metatron's Cube** | 13-point sacred geometry                                            | 1-3              |
| **Sri Yantra**      | 9 interlocking triangles                                            | 1-4              |
| **Platonic Solids** | 5 regular polyhedra                                                 | 1-5              |

#### Configuration

```typescript
interface SacredGeometryConfig {
  pattern: PatternType;
  complexity: number; // 1-10
  size: number;
  animated: boolean;
  animationSpeed: number; // Rotation/pulsing speed
  material: {
    color: Color;
    emissive: Color;
    metalness: number;
    roughness: number;
    opacity: number;
  };
}
```

#### Platonic Solids

| Solid            | Faces | Vertices | Element |
| ---------------- | ----- | -------- | ------- |
| **Tetrahedron**  | 4     | 4        | Fire    |
| **Cube**         | 6     | 8        | Earth   |
| **Octahedron**   | 8     | 6        | Air     |
| **Dodecahedron** | 12    | 20       | Ether   |
| **Icosahedron**  | 20    | 12       | Water   |

#### Usage

```typescript
import { SacredGeometry } from '@/environments/SacredGeometry';

const generator = new SacredGeometry();

// Generate mandala
const mandala = generator.createMandala({
  rings: 8,
  symmetry: 12,
  petals: 6,
  complexity: 7,
  animated: true,
  material: {
    color: '#FFD700',
    emissive: '#FFA500',
    metalness: 0.3,
    roughness: 0.5,
    opacity: 0.9,
  },
});

// Generate Flower of Life
const flowerOfLife = generator.createFlowerOfLife({
  layers: 3,
  circleCount: 19,
  animated: true,
});

// Generate Platonic solid
const icosahedron = generator.createPlatonicSolid('icosahedron', {
  size: 2,
  animated: true,
  animationSpeed: 0.5,
});

// Add to scene
scene.add(mandala.mesh);
scene.add(flowerOfLife.mesh);
scene.add(icosahedron.mesh);

// Update in render loop
mandala.update(deltaTime);
```

---

## Portal Network

**Location**: `services/metaverse/src/environments/PortalNetwork.ts`

Inter-realm travel system connecting sacred spaces.

### Portal Types

| Type        | Description                    | Use Case              |
| ----------- | ------------------------------ | --------------------- |
| **One-Way** | Travel in one direction only   | Narrative progression |
| **Two-Way** | Bidirectional travel           | Standard navigation   |
| **Group**   | Multiple users travel together | Group sessions        |
| **Private** | User-specific access           | Personal spaces       |

### Activation Triggers

| Trigger         | Description               |
| --------------- | ------------------------- |
| **Proximity**   | Automatic when near       |
| **Interaction** | Requires user action      |
| **Timer**       | Activates on schedule     |
| **Quest**       | Requires quest completion |
| **Key Item**    | Requires specific item    |

### Visual Styles

```typescript
interface PortalVisuals {
  shape: 'circular' | 'rectangular' | 'archway';
  material: 'energy' | 'water' | 'fire' | 'stone' | 'crystal' | 'void';
  particles: {
    color: Color;
    density: number;
    animationSpeed: number;
  };
  transitionEffect:
    | 'fade'
    | 'spiral'
    | 'particle_vortex'
    | 'ripple'
    | 'dissolve'
    | 'warp';
}
```

### Configuration

```typescript
interface PortalConfig {
  id: string;
  name: string;
  type: PortalType;

  // Locations
  sourcePosition: Vector3;
  destinationRealm: string;
  destinationPosition: Vector3;

  // Activation
  trigger: ActivationTrigger;
  cooldown: number; // Seconds between uses
  requirements?: PortalRequirement[];

  // Visuals
  visuals: PortalVisuals;
  sounds: {
    ambient: string;
    activate: string;
    travel: string;
  };

  // Discovery
  discoverable: boolean;
  discoveryHint?: string;
}
```

### Usage

```typescript
import { PortalNetwork } from '@/environments/PortalNetwork';

const portals = new PortalNetwork();

// Register a portal
portals.register({
  id: 'zen_to_temple',
  name: 'Gateway to Temple',
  type: 'two_way',
  sourcePosition: { x: 0, y: 0, z: 10 },
  destinationRealm: 'buddhist_temple',
  destinationPosition: { x: 0, y: 0, z: -10 },
  trigger: 'proximity',
  cooldown: 5,
  visuals: {
    shape: 'archway',
    material: 'energy',
    particles: { color: '#00FFFF', density: 50, animationSpeed: 1 },
    transitionEffect: 'spiral',
  },
});

// Check if user can travel
const canTravel = portals.canTravel(userId, 'zen_to_temple');

// Execute travel
if (canTravel) {
  await portals.travel(userId, 'zen_to_temple');
}

// Find path between realms
const path = portals.findPath('zen_garden', 'tibetan_monastery');

// Get user's travel history
const history = portals.getTravelHistory(userId);

// Get discovery status
const discovered = portals.getDiscoveredPortals(userId);
```

---

## Performance Optimization

### Key Strategies

| Strategy                 | Description                     | Impact                   |
| ------------------------ | ------------------------------- | ------------------------ |
| **Spatial Partitioning** | Grid-based zone system          | Reduces per-frame checks |
| **LOD System**           | Distance-based detail reduction | Lower triangle count     |
| **Instancing**           | Batch rendering for vegetation  | Fewer draw calls         |
| **Culling**              | Frustum and occlusion culling   | Skip invisible objects   |
| **Asset Caching**        | LRU cache with memory limits    | Faster loading           |
| **Streaming**            | Progressive chunk loading       | Smooth exploration       |
| **Batching**             | Material-based batch groups     | Reduced state changes    |

### Default Configuration

| Parameter             | Default Value |
| --------------------- | ------------- |
| Max Concurrent Loads  | 6             |
| Cache Size            | 500MB         |
| Grid Cell Size        | 100 units     |
| Chunk Size            | 16 units      |
| View Distance         | 3 chunks      |
| Shadow Map Resolution | 2048px        |
| Target FPS            | 60            |

### Memory Management

```typescript
// Monitor memory usage
const stats = worldLoader.getStats();
if (stats.memoryUsage > 400 * 1024 * 1024) {
  // 400MB
  worldLoader.pruneCache(0.3); // Remove 30% oldest entries
}

// Force garbage collection on scene transition
worldLoader.clearCache();
renderer.dispose();
```

---

## Integration Examples

### Complete Environment Setup

```typescript
import { WorldLoader } from '@/world/WorldLoader';
import { WeatherSystem } from '@/environments/WeatherSystem';
import { TemplateManager } from '@/environments/TemplateManager';
import { PortalNetwork } from '@/environments/PortalNetwork';

// Initialize systems
const loader = new WorldLoader({ cacheSize: 500 * 1024 * 1024 });
const weather = new WeatherSystem({ autoTransition: true });
const templates = new TemplateManager();
const portals = new PortalNetwork();

// Load sacred space
const zenGarden = await templates.load('zen_garden');
await zenGarden.instantiate(scene);

// Setup weather
weather.transitionTo('partly_cloudy');

// Register portal to next area
portals.register({
  id: 'to_temple',
  destinationRealm: 'buddhist_temple',
  trigger: 'proximity',
  visuals: { shape: 'archway', material: 'energy' },
});

// Game loop
function update(deltaTime: number) {
  weather.update(deltaTime);
  loader.updatePlayerPosition(playerPosition);
  portals.update(deltaTime);
}
```

### Procedural World Exploration

```typescript
import { ProceduralWorldGenerator } from '@/advanced/ProceduralWorldGenerator';

const world = new ProceduralWorldGenerator({
  seed: Date.now(),
  chunkSize: 16,
  viewDistance: 4,
});

// Player exploration loop
function onPlayerMove(newPosition: Vector3) {
  world.update(newPosition);

  // Check for discovered structures
  const nearbyStructures = world.getNearbyStructures(newPosition, 100);
  for (const structure of nearbyStructures) {
    if (!player.hasDiscovered(structure.id)) {
      player.discover(structure);
      showDiscoveryNotification(structure);
    }
  }
}
```

---

## Best Practices

### Do's

- Use spatial partitioning for large environments
- Implement LOD for distant terrain and objects
- Cache frequently-used assets
- Use instancing for repeated objects (vegetation)
- Preload adjacent zones before player arrives
- Clean up resources when leaving areas
- Respect consciousness modifiers in meditation areas

### Don'ts

- Don't load entire world at once
- Don't use high-resolution textures for distant objects
- Don't skip culling for complex scenes
- Don't ignore memory limits
- Don't block main thread during loading
- Don't create portals without cooldowns (prevents abuse)

---

## Related Documentation

- [Rendering System](./rendering-system.md)
- [Asset Pipeline](./asset-pipeline.md)
- [Physics System](./physics-system.md)
- [Networking](./networking.md)

---

_Last Updated: January 2026_
