# GDD: Room Prefab Framework

**System ID:** SYS-12  
**Design Order:** 11 of 33 (MVP tier)  
**Priority:** MVP — Feature Layer  
**Dependencies:** SYS-10 (Procedural Map Generator — defines what markers rooms need), SYS-14 (Item Database — RoomNode_SO schema)  
**Dependents:** SYS-11 (Prop System — uses prop slots from room prefabs), SYS-13 (Overtime Collapse — needs to identify sealable rooms)  
**Status:** Designed  

---

## 1. Purpose

The Room Prefab Framework is a set of **Unity Editor tools** that allow designers to author room modules for the Procedural Map Generator without touching code. It provides:

- Custom inspectors for `RoomNode_SO` assets with live validation
- Gizmo visualization for connectors, spawn slots, and room boundaries
- A `RoomValidator` that checks prefab correctness before it enters the generation pool
- Workflow for creating new rooms: scaffold → place geometry → mark connectors → validate → done

This system enforces the **Tools First** principle: a designer creates new room variety by duplicating a prefab, reshaping geometry, repositioning markers, filling out the SO, and pressing Validate. Zero code changes. The generator automatically discovers new rooms via `Resources.LoadAll<RoomNode_SO>()`.

---

## 2. Room Authoring Workflow

### 2.1 Step-by-Step

```
1. Duplicate an existing room prefab (or use the "Create Room" menu)
2. Reshape static geometry (walls, floor, ceiling) in Scene view
3. Position connector markers at openings (doorways, stairwells, vents)
4. Position spawn slot markers (loot, altar, runner spawn, incarnation, props)
5. Fill out the RoomNode_SO asset (dimensions, category, spawn rules)
6. Click "Validate Room" in the custom inspector
7. Fix any errors shown in the inspector
8. Save prefab → it's now in the generation pool
```

### 2.2 "Create Room" Menu Item

```
Menu: IStalk > Room Authoring > Create New Room
```

Creates:
- A new `RoomNode_SO` asset in `Assets/Resources/Items/Rooms/`
- A new room prefab in `Assets/Prefabs/Rooms/` with default structure:
  - Root GameObject (with `RoomInstance` component)
  - `Geometry/` child (empty — designer adds walls/floor here)
  - `Connectors/` child (pre-populated with 1 Left + 1 Right connector marker)
  - `SpawnSlots/` child (with 1 LootSlot marker)
  - `PropSlots/` child (empty — designer adds positions)
- Links the prefab to the SO's `roomPrefab` field automatically

---

## 3. Connector System

### 3.1 Connector Marker Component

```csharp
public class ConnectorMarker : MonoBehaviour
{
    public ConnectionTag direction;  // Up, Down, Left, Right
    public int size = 1;             // Opening width in grid units (1 = door, 2 = wide passage)
    
    // Automatically computed from position relative to room root
    public Vector3 LocalPosition => transform.localPosition;
}
```

### 3.2 Connector Placement Rules

| Rule | Validation Error |
|------|-----------------|
| Connectors must be at the edge of the room's bounding box | "Connector at interior position — must be on room boundary" |
| Direction must face outward from the room | "Connector_Left_0 faces Right — should face Left" |
| At least 2 connectors per room (entry + exit) | "Room has < 2 connectors — dead end rooms not allowed in MVP" |
| No two connectors at the same position | "Duplicate connector position detected" |
| Vertical connectors (Up/Down) must align with floor/ceiling | "Connector_Up_0 is not at ceiling height" |

### 3.3 Gizmo Visualization

In Scene view, connectors render as:
- **Green arrow** pointing in the connector's direction (outward)
- **Blue rectangle** showing the opening size (width × height)
- **Red X** if validation fails (with tooltip showing the error)
- **Yellow dotted line** connecting to compatible connectors on adjacent rooms (when multiple rooms are in scene for testing)

---

## 4. Spawn Slot System

### 4.1 Slot Types

| Slot Type | Tag | Gizmo | Component |
|-----------|-----|-------|-----------|
| Loot spawn | `LootSlot` | Gold diamond | `SpawnSlot` (type: Loot) |
| Altar position | `AltarSlot` | White pillar | `SpawnSlot` (type: Altar) |
| Runner spawn | `RunnerSpawn` | Green capsule | `SpawnSlot` (type: Runner) |
| Incarnation prop | `IncarnationSlot` | Purple eye | `SpawnSlot` (type: Incarnation) |
| Prop position | `PropSlot` | Grey cube | `SpawnSlot` (type: Prop) |

### 4.2 SpawnSlot Component

```csharp
public class SpawnSlot : MonoBehaviour
{
    public SpawnSlotType slotType;
    public bool isOccupied;  // Runtime only — used during generation
    
    // Optional constraints
    public float minDistanceFromConnector = 0.5f;  // Don't place loot in doorways
    public bool requiresFloor = true;  // Slot must be on a walkable surface
}

public enum SpawnSlotType { Loot, Altar, Runner, Incarnation, Prop }
```

### 4.3 Slot Validation Rules

| Rule | Error Message |
|------|--------------|
| LootSlot count must match `RoomNode_SO.lootSpawnSlots` | "SO says 3 loot slots but prefab has 2 LootSlot markers" |
| AltarSlot must exist if `isValidAltarLocation = true` | "SO marks room as altar-valid but no AltarSlot in prefab" |
| RunnerSpawn must exist if `isValidRunnerSpawn = true` | "SO marks room as spawn-valid but no RunnerSpawn in prefab" |
| IncarnationSlot count must match `incarnationPropSlots` | "SO says 2 incarnation slots but prefab has 1" |
| No slot may be inside a wall collider | "LootSlot_0 is inside a Wall-layer collider" |
| All slots must be within room bounds | "PropSlot_3 is outside room bounding box" |

---

## 5. Room Bounds and Grid Alignment

### 5.1 RoomBounds Component

```csharp
[RequireComponent(typeof(BoxCollider))]
public class RoomBounds : MonoBehaviour
{
    // The BoxCollider defines the room's physical extent
    // It MUST align to grid units (cellWidth × cellHeight from GlobalRules_SO)
    
    public Vector3Int GridSize => new Vector3Int(
        Mathf.RoundToInt(GetComponent<BoxCollider>().size.x / GlobalRules_SO.Instance.cellWidth),
        Mathf.RoundToInt(GetComponent<BoxCollider>().size.y / GlobalRules_SO.Instance.cellHeight),
        1  // Z is always 1 (2D side-view dollhouse)
    );
}
```

### 5.2 Grid Alignment Gizmo

The `RoomBounds` draws:
- **White wireframe box** showing the bounds
- **Grid overlay** showing cell divisions within the room
- **Snap indicators** — yellow highlight if bounds don't align to grid units (± 0.01m tolerance)

### 5.3 Validation

| Rule | Error |
|------|-------|
| Bounds must be a multiple of cellWidth horizontally | "Room width 5.3m is not a multiple of cellWidth (4.0m)" |
| Bounds must be a multiple of cellHeight vertically | "Room height 4.1m is not a multiple of cellHeight (3.0m)" |
| GridSize in SO must match computed GridSize from bounds | "SO gridSize (2,1,1) doesn't match computed (3,1,1)" |

---

## 6. Custom Inspector: RoomNode_SO

### 6.1 Inspector Layout

```
┌─────────────────────────────────────────────────┐
│ RoomNode_SO Inspector                            │
├─────────────────────────────────────────────────┤
│ [Identity]                                       │
│   Room ID: library                               │
│   Display Name: Grand Library                    │
│   Room Prefab: [drag prefab here]  [Select ▼]   │
│                                                  │
│ [Dimensions]                                     │
│   Grid Size: (2, 1, 1)    ← auto-computed from  │
│                              prefab RoomBounds   │
│                                                  │
│ [Connections]                                    │
│   ● Left (size 1)                               │
│   ● Right (size 1)                              │
│   ● Right (size 2) — wide passage               │
│   [Auto-Populate from Prefab]                    │
│                                                  │
│ [Spawn Rules]                                    │
│   Spawn Weight: [0.8] ████████░░                 │
│   Max Per Map: [0] (unlimited)                   │
│   Category: [LargeRoom ▼]                        │
│                                                  │
│ [Content Slots]                                  │
│   Loot Slots: 4  ← matches prefab marker count  │
│   Shrine Eligible: ☐                            │
│   Incarnation Slots: 1                          │
│   Valid Runner Spawn: ☐                         │
│   Valid Altar Location: ☑                       │
│                                                  │
│ [Validation]                                     │
│   ✅ Prefab assigned                            │
│   ✅ Grid alignment valid                       │
│   ✅ Connectors match (3 connectors)            │
│   ✅ Slot counts match                          │
│   ✅ All slots within bounds                    │
│   [▶ Validate Full]  [▶ Open Prefab]           │
└─────────────────────────────────────────────────┘
```

### 6.2 Auto-Populate Button

"Auto-Populate from Prefab" scans the linked prefab for:
- All `ConnectorMarker` components → fills `openConnections` list
- All `SpawnSlot` components → fills slot count fields
- `RoomBounds` component → fills `gridSize`

This means a designer can set up the prefab first, then click one button to sync the SO.

---

## 7. RoomValidator (Editor Tool)

### 7.1 Single Room Validation

```
Menu: IStalk > Room Authoring > Validate Selected Room
Shortcut: Ctrl+Shift+V (when RoomNode_SO or room prefab is selected)
```

Runs all checks from Sections 3.2, 4.3, 5.3 above. Outputs:
- ✅ Pass messages in green
- ⚠️ Warnings in yellow (non-blocking recommendations)
- ❌ Errors in red (room will NOT enter generation pool until fixed)

### 7.2 Batch Validation (All Rooms)

```
Menu: IStalk > Room Authoring > Validate All Rooms
```

Runs validation on every `RoomNode_SO` in `Resources/Items/Rooms/`. Outputs a summary:

```
Room Validation Report
──────────────────────
Total rooms: 12
  ✅ Valid: 10
  ⚠️ Warnings: 1 (corridor_narrow — only 1 loot slot, consider adding more)
  ❌ Errors: 1 (kitchen_large — SO gridSize mismatch)
```

### 7.3 Generation Test

```
Menu: IStalk > Room Authoring > Test Generation (Editor)
```

Runs the map generator algorithm in Edit mode (no Play mode needed):
- Generates 10 layouts with random seeds
- Reports success/failure rate
- Reports average room count, floor count, connectivity
- Highlights any room that was never selected across 10 runs (spawn weight too low?)
- Does NOT instantiate prefabs (pure data pass for speed)

---

## 8. Starter Room Set (MVP)

The MVP needs a minimum room variety to produce interesting layouts:

| Room ID | Category | Grid Size | Connectors | Loot Slots | Notes |
|---------|----------|-----------|-----------|-----------|-------|
| `foyer` | StartingArea | 3×1 | L, R | 0 | Runner spawn. Full cover. No loot. |
| `corridor_straight` | Corridor | 2×1 | L, R | 1 | Connector tissue. Minimal cover. |
| `corridor_t` | Corridor | 2×2 | L, R, U | 1 | T-junction. Creates branching. |
| `stairwell` | Corridor | 1×2 | U(top), D(bottom) | 0 | Vertical connection between floors. |
| `room_small` | SmallRoom | 1×1 | L or R (1) | 2 | Tight room, lots of cover. |
| `room_medium` | SmallRoom | 2×1 | L, R | 3 | Standard living space. |
| `room_large` | LargeRoom | 3×1 | L, R, R(wide) | 4 | Open space. Eye has clear sightlines. |
| `kitchen` | SmallRoom | 2×1 | L, R | 2 | Counter cover. Fragile props (dishes). |
| `library` | LargeRoom | 2×2 | L, R, U | 4 | Tall bookshelves block LoS vertically. |
| `balcony` | SmallRoom | 1×1 | L | 1 | Dead-end risk. High loot value. |

**10 rooms minimum for MVP generation.** The generator can produce variety from 10 rooms due to randomized placement order and content population.

---

## 9. Acceptance Criteria

- [ ] "Create Room" menu item scaffolds a valid prefab + SO pair in one click
- [ ] Connector gizmos render in Scene view with correct color coding
- [ ] "Auto-Populate from Prefab" syncs SO fields from prefab markers
- [ ] "Validate Room" catches all error cases from Sections 3-5
- [ ] "Validate All Rooms" batch-runs on the full room pool
- [ ] "Test Generation" runs 10 seeds in Editor without Play mode
- [ ] A designer can create a new room from scratch without modifying any .cs files
- [ ] Invalid rooms (❌ errors) are excluded from the generation pool at runtime
- [ ] All gizmos respect Scene view visibility toggles
- [ ] Custom inspector shows live validation status

---

## 10. Relationship to Other Systems

| System | Relationship |
|--------|-------------|
| **SYS-10 Procedural Map Generator** | Consumes room prefabs and SOs authored with these tools |
| **SYS-14 Item Database** | Defines `RoomNode_SO` schema; ItemDatabase discovers rooms at runtime |
| **SYS-11 Prop System** | PropSlot markers define where props spawn within rooms |
| **SYS-05 Geometric LoS** | Room wall geometry and prop placement directly affect LoS blocking |

---

## 11. Future Extensions (Alpha+)

- **Room prefab variant system** — same room SO, multiple visual themes (industrial, gothic, domestic)
- **Prop placement rules** — density slider per room, cover vs. fragile ratio controls
- **Connection compatibility tags** — "only connect kitchen to corridor, never directly to stairwell"
- **Room thumbnail preview** — auto-generated isometric thumbnails shown in inspector
- **Live preview in Scene view** — drag RoomNode_SOs onto a grid to test arrangements manually
