# D&D 4th Edition Virtual Tabletop Project Plan

## Overview
Interactive multiplayer D&D 4th Edition virtual tabletop with AI-generated character portraits using OpenAI's GPT Image model.

## Technology Stack

**Backend:**
- Node.js/Express with Socket.io for real-time communication
- MariaDB with mysql2 or mariadb npm package
- OpenAI API (GPT Image model) for character image generation

**Frontend:**
- React or Vue.js for reactive UI components
- Konva.js or Fabric.js for interactive maps/grids
- WebSockets via Socket.io for live updates

**Storage:**
- Local filesystem or cloud storage (AWS S3/Google Cloud) for images
- MariaDB for all application data

## Database Schema (MariaDB)

### Core Tables

```sql
-- Users and authentication
CREATE TABLE users (
    id INT PRIMARY KEY AUTO_INCREMENT,
    username VARCHAR(50) UNIQUE NOT NULL,
    email VARCHAR(100) UNIQUE NOT NULL,
    password_hash VARCHAR(255) NOT NULL,
    role ENUM('player', 'dm', 'admin') DEFAULT 'player',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- Campaigns (game sessions)
CREATE TABLE campaigns (
    id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(100) NOT NULL,
    dm_id INT NOT NULL,
    description TEXT,
    max_players INT DEFAULT 6,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (dm_id) REFERENCES users(id)
);

-- Campaign participants
CREATE TABLE campaign_users (
    id INT PRIMARY KEY AUTO_INCREMENT,
    campaign_id INT NOT NULL,
    user_id INT NOT NULL,
    joined_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (campaign_id) REFERENCES campaigns(id),
    FOREIGN KEY (user_id) REFERENCES users(id),
    UNIQUE KEY unique_campaign_user (campaign_id, user_id)
);

-- Characters with D&D 4e specific fields
CREATE TABLE characters (
    id INT PRIMARY KEY AUTO_INCREMENT,
    user_id INT NOT NULL,
    campaign_id INT NOT NULL,
    name VARCHAR(100) NOT NULL,
    
    -- Basic info
    race VARCHAR(50) NOT NULL,
    class VARCHAR(50) NOT NULL,
    level INT DEFAULT 1,
    experience_points INT DEFAULT 0,
    
    -- Ability scores
    strength INT NOT NULL,
    constitution INT NOT NULL,
    dexterity INT NOT NULL,
    intelligence INT NOT NULL,
    wisdom INT NOT NULL,
    charisma INT NOT NULL,
    
    -- Combat stats
    max_hit_points INT NOT NULL,
    current_hit_points INT NOT NULL,
    temporary_hit_points INT DEFAULT 0,
    armor_class INT NOT NULL,
    fortitude_defense INT NOT NULL,
    reflex_defense INT NOT NULL,
    will_defense INT NOT NULL,
    initiative_modifier INT NOT NULL,
    
    -- Character appearance for AI generation
    physical_description TEXT,
    personality_traits TEXT,
    
    -- Generated images
    portrait_url VARCHAR(500),
    token_url VARCHAR(500),
    image_prompt TEXT,
    image_generated_at TIMESTAMP,
    
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    
    FOREIGN KEY (user_id) REFERENCES users(id),
    FOREIGN KEY (campaign_id) REFERENCES campaigns(id)
);

-- Powers (At-Will, Encounter, Daily)
CREATE TABLE character_powers (
    id INT PRIMARY KEY AUTO_INCREMENT,
    character_id INT NOT NULL,
    name VARCHAR(100) NOT NULL,
    power_type ENUM('at-will', 'encounter', 'daily', 'utility') NOT NULL,
    power_source VARCHAR(50),
    action_type VARCHAR(50),
    range_type VARCHAR(50),
    description TEXT,
    used BOOLEAN DEFAULT FALSE, -- For encounter/daily powers
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (character_id) REFERENCES characters(id)
);

-- Maps and encounters
CREATE TABLE maps (
    id INT PRIMARY KEY AUTO_INCREMENT,
    campaign_id INT NOT NULL,
    name VARCHAR(100) NOT NULL,
    width INT NOT NULL, -- Grid width
    height INT NOT NULL, -- Grid height
    background_url VARCHAR(500),
    grid_size INT DEFAULT 30, -- Pixels per square
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (campaign_id) REFERENCES campaigns(id)
);

-- Tokens on maps
CREATE TABLE map_tokens (
    id INT PRIMARY KEY AUTO_INCREMENT,
    map_id INT NOT NULL,
    character_id INT,
    name VARCHAR(100), -- For NPCs/monsters
    token_url VARCHAR(500),
    x_position INT NOT NULL,
    y_position INT NOT NULL,
    size_category ENUM('tiny', 'small', 'medium', 'large', 'huge', 'gargantuan') DEFAULT 'medium',
    is_player_controlled BOOLEAN DEFAULT TRUE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (map_id) REFERENCES maps(id),
    FOREIGN KEY (character_id) REFERENCES characters(id)
);

-- Combat initiative tracking
CREATE TABLE initiative_order (
    id INT PRIMARY KEY AUTO_INCREMENT,
    campaign_id INT NOT NULL,
    character_id INT,
    npc_name VARCHAR(100),
    initiative_roll INT NOT NULL,
    is_player BOOLEAN DEFAULT TRUE,
    turn_order INT NOT NULL,
    has_acted BOOLEAN DEFAULT FALSE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (campaign_id) REFERENCES campaigns(id),
    FOREIGN KEY (character_id) REFERENCES characters(id)
);

-- Image generation tracking and cost management
CREATE TABLE image_generations (
    id INT PRIMARY KEY AUTO_INCREMENT,
    user_id INT NOT NULL,
    character_id INT,
    prompt TEXT NOT NULL,
    image_url VARCHAR(500) NOT NULL,
    model VARCHAR(50) DEFAULT 'gpt-image-1',
    image_size VARCHAR(20) DEFAULT '1024x1024',
    openai_cost DECIMAL(8,4) NOT NULL,
    generation_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (user_id) REFERENCES users(id),
    FOREIGN KEY (character_id) REFERENCES characters(id)
);

-- Chat messages
CREATE TABLE chat_messages (
    id INT PRIMARY KEY AUTO_INCREMENT,
    campaign_id INT NOT NULL,
    user_id INT NOT NULL,
    character_id INT,
    message TEXT NOT NULL,
    message_type ENUM('ic', 'ooc', 'system', 'dice') DEFAULT 'ooc', -- in-character, out-of-character, system, dice roll
    timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (campaign_id) REFERENCES campaigns(id),
    FOREIGN KEY (user_id) REFERENCES users(id),
    FOREIGN KEY (character_id) REFERENCES characters(id)
);

-- Dice roll history
CREATE TABLE dice_rolls (
    id INT PRIMARY KEY AUTO_INCREMENT,
    campaign_id INT NOT NULL,
    user_id INT NOT NULL,
    character_id INT,
    roll_expression VARCHAR(100) NOT NULL, -- e.g., "1d20+5"
    roll_result JSON NOT NULL, -- Detailed roll results
    total INT NOT NULL,
    roll_type VARCHAR(50), -- attack, damage, skill, etc.
    timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (campaign_id) REFERENCES campaigns(id),
    FOREIGN KEY (user_id) REFERENCES users(id),
    FOREIGN KEY (character_id) REFERENCES characters(id)
);
```

## OpenAI GPT Image Integration

### API Configuration
- **Model**: gpt-image-1
- **Cost**: ~$0.02 per 1024x1024 HD image
- **Quality**: HD images with consistent D&D fantasy art style
- **Speed**: Faster generation than DALL-E 3

### Character Image Generation System

```javascript
const generateCharacterImage = async (characterData) => {
  const basePrompt = `D&D 4th edition fantasy art portrait of a ${characterData.race} ${characterData.class}`;
  const detailPrompt = characterData.physical_description 
    ? `, ${characterData.physical_description}` 
    : '';
  const stylePrompt = `, detailed character art, heroic fantasy style, high quality`;
  
  const fullPrompt = basePrompt + detailPrompt + stylePrompt;
  
  const response = await openai.images.generate({
    model: "gpt-image-1",
    prompt: fullPrompt,
    n: 1,
    size: "1024x1024",
    style: "natural",
    quality: "hd"
  });
  
  return response.data[0].url;
};
```

### Prompt Engineering Templates

**Race-Specific Features:**
- Dragonborn: "with [color] scales and draconic features"
- Tiefling: "with horns and infernal heritage features"
- Eladrin: "with ethereal fey beauty and pointed ears"

**Class-Themed Elements:**
- Paladin: "in gleaming plate armor with holy symbol"
- Rogue: "in dark leather armor with daggers"
- Wizard: "in robes with arcane implements"

**4e-Specific Styling:**
- "D&D 4th edition character art style"
- "heroic fantasy, detailed character portrait"
- "professional fantasy game art"

## Core Features

### 1. D&D 4th Edition Specific Features
- **Character Creation**: All 4e races, classes, and build options
- **Power Management**: At-Will, Encounter, Daily, and Utility powers
- **Action Economy**: Standard, Move, Minor, and Free actions
- **Grid-Based Combat**: 5-foot squares with tactical positioning
- **Status Effects**: All 4e conditions (dazed, stunned, etc.)
- **Skill Challenges**: Structured 4e skill challenge system

### 2. Character Image Generation
- AI-generated portraits based on character descriptions
- Automatic token creation from portraits
- Multiple image variants and regeneration options
- Cost tracking and usage quotas
- Template prompts for consistent art style

### 3. Real-time Multiplayer Features
- **Map Synchronization**: Live token movement updates
- **Turn Management**: Initiative tracking and turn order
- **Dice Rolling**: Shared rolls with 4e-specific modifiers
- **Chat System**: In-character/out-of-character messaging
- **Power Usage**: Real-time power availability updates

### 4. DM Tools
- **Map Management**: Upload backgrounds, set grid overlays
- **Fog of War**: Dynamic vision and lighting
- **NPC/Monster Management**: Stat blocks and initiative
- **Encounter Builder**: Balance encounters using 4e math
- **Campaign Notes**: Shared handouts and references

### 5. Combat System
- **Initiative Tracker**: Automatic turn order management
- **Action Tracking**: Monitor actions taken each turn
- **Condition Management**: Apply and track status effects
- **Damage Tracking**: Hit points, temporary HP, healing surges
- **Power Recovery**: Encounter/daily power refresh

## Implementation Phases

### Phase 1: Foundation (Weeks 1-2)
- MariaDB database setup with core schema
- User authentication and session management
- Basic campaign creation and user management
- Project structure and development environment

### Phase 2: Character System (Weeks 3-4)
- Character creation with 4e races and classes
- Ability score generation and calculation
- Power system implementation
- Character sheet interface

### Phase 3: AI Integration (Weeks 5-6)
- OpenAI API integration with GPT Image
- Character image generation system
- Image storage and management
- Prompt engineering and templates

### Phase 4: Maps and Combat (Weeks 7-8)
- Grid-based map system with Konva.js
- Token placement and movement
- Initiative tracking system
- Basic combat mechanics

### Phase 5: Real-time Features (Weeks 9-10)
- Socket.io integration for live updates
- Real-time token movement
- Shared dice rolling system
- Chat system implementation

### Phase 6: Advanced Features (Weeks 11-12)
- Fog of war and dynamic lighting
- Power usage tracking and recovery
- Status effect management
- Mobile responsiveness

### Phase 7: Polish and Testing (Weeks 13-14)
- Performance optimization
- Bug fixes and stability improvements
- User testing and feedback integration
- Documentation and deployment

## Cost Management

### OpenAI Usage
- GPT Image: ~$0.02 per 1024x1024 image
- Recommended quotas: 10-15 images per character
- Monthly budget estimation: $5-20 per active user
- Rate limiting: 5 images per hour per user

### Usage Tracking
- Monitor API costs per user
- Implement generation limits
- Optional premium tiers for unlimited generation
- Cache generated images to avoid regeneration

## Technical Considerations

### Performance
- Image caching and CDN for generated portraits
- Database indexing for quick character/campaign lookups
- WebSocket connection pooling for large campaigns
- Lazy loading for maps and character data

### Security
- JWT authentication with refresh tokens
- Rate limiting on API endpoints
- Input validation and sanitization
- Secure image upload and storage

### Scalability
- Horizontal scaling with load balancers
- Database read replicas for heavy queries
- Redis for session management and caching
- Container deployment with Docker

## Future Enhancements

### Advanced AI Features
- AI-powered NPC dialogue generation
- Automatic encounter balancing suggestions
- Quest and story generation assistance
- Voice-to-text for accessibility

### Enhanced Gameplay
- 3D dice physics simulation
- Animated spell effects
- Background music and sound effects
- Integration with D&D Beyond or similar APIs

### Community Features
- Public campaign browsing
- Character template sharing
- Custom content creation tools
- Achievement and progression systems

## Getting Started

1. Set up development environment with Node.js and MariaDB
2. Initialize project with package.json and dependencies
3. Create database schema using provided SQL
4. Set up OpenAI API credentials and test image generation
5. Build basic authentication and user management
6. Begin character creation system implementation

This plan provides a comprehensive roadmap for building a full-featured D&D 4th Edition virtual tabletop with AI-generated character portraits.