# Veilborn Chronicles Modding Guide

> _"The Weave has infinite threads. Why should we not add our own?"_ -- Unknown
> Creator

This guide explains how to create, package, and share custom content for
Veilborn Chronicles.

---

## Overview

Veilborn Chronicles supports extensive modding through:

1. **Custom Content Creation**: Cards, creatures, realms, campaigns
2. **Content Packs**: Bundled collections of related content
3. **Marketplace Integration**: Share and sell your creations
4. **Campaign Templates**: Reusable adventure frameworks
5. **Asset Generation**: AI-assisted art creation

---

## Content Types

### Supported Content

| Type                   | Description                         | Complexity |
| ---------------------- | ----------------------------------- | ---------- |
| **Card**               | Custom cards for the Deck of Echoes | Medium     |
| **Creature**           | Custom monsters and NPCs            | Medium     |
| **Realm**              | Custom worlds with regions          | High       |
| **Campaign Template**  | Complete adventure packages         | Very High  |
| **Character Portrait** | Custom character art                | Low        |

### Content Requirements

```typescript
type ContentType =
  | 'card'
  | 'creature'
  | 'realm'
  | 'campaign_template'
  | 'character_portrait';

interface ContentRequirements {
  card: {
    minFields: ['id', 'name', 'cardType', 'effects'];
    maxFileSize: '1MB';
    artRequired: false;
  };
  creature: {
    minFields: ['id', 'name', 'type', 'stats', 'abilities'];
    maxFileSize: '1MB';
    artRequired: false;
  };
  realm: {
    minFields: ['id', 'name', 'dominantBiome', 'properties'];
    maxFileSize: '10MB';
    artRequired: false;
  };
  campaign_template: {
    minFields: ['id', 'title', 'description', 'scenes'];
    maxFileSize: '50MB';
    artRequired: true;
  };
  character_portrait: {
    minFields: ['id', 'name', 'imageData'];
    maxFileSize: '5MB';
    artRequired: true;
  };
}
```

---

## Content Pack Structure

### Directory Layout

```
my-content-pack/
├── manifest.json           # Pack metadata
├── cards/
│   ├── index.json          # Card list
│   └── echo-cards/
│       ├── my-card-001.json
│       └── my-card-002.json
├── creatures/
│   ├── index.json
│   └── aberrations/
│       └── void-hunter.json
├── realms/
│   ├── index.json
│   └── shadowmere/
│       ├── realm.json
│       └── regions/
│           ├── dark-forest.json
│           └── void-shore.json
├── campaigns/
│   ├── index.json
│   └── into-the-void/
│       ├── campaign.json
│       └── scenes/
│           ├── scene-01.json
│           └── scene-02.json
├── assets/
│   ├── images/
│   │   ├── cards/
│   │   ├── creatures/
│   │   └── locations/
│   └── audio/
│       └── ambient/
└── README.md               # Pack documentation
```

### Manifest File

```json
{
  "id": "my-content-pack",
  "name": "My Content Pack",
  "version": "1.0.0",
  "author": {
    "id": "user-12345",
    "name": "Creator Name",
    "contact": "creator@example.com"
  },
  "description": "A collection of custom cards, creatures, and a new realm.",
  "tags": ["void", "horror", "advanced"],
  "compatibility": {
    "minVersion": "1.0.0",
    "maxVersion": "2.0.0"
  },
  "contents": {
    "cards": 15,
    "creatures": 8,
    "realms": 1,
    "campaigns": 1
  },
  "dependencies": [],
  "license": "CC-BY-NC-4.0",
  "createdAt": "2024-01-15T00:00:00Z",
  "updatedAt": "2024-01-20T00:00:00Z"
}
```

---

## JSON Formats

### Card Format

```json
{
  "id": "card-custom-void-slash",
  "cardId": "CUSTOM-001",
  "name": "Void Slash",
  "description": "Strike through the emptiness between moments.",
  "cardType": "echo",
  "rarity": "rare",
  "setId": "custom-void-set",
  "cost": {
    "resonance": 3,
    "veilPoints": 0
  },
  "effects": [
    {
      "id": "void-slash-main",
      "type": "damage",
      "trigger": "on_play",
      "target": "enemy",
      "value": 4,
      "description": "Deal 4 Void damage to target."
    },
    {
      "id": "void-slash-bonus",
      "type": "condition_apply",
      "trigger": "on_play",
      "target": "enemy",
      "description": "Target cannot use reactions until end of round.",
      "conditions": [
        {
          "type": "stat_check",
          "stat": "target_void_resonance",
          "operator": "<=",
          "value": 3,
          "source": "target"
        }
      ]
    }
  ],
  "faceDownEffects": [
    {
      "id": "void-slash-trap",
      "type": "counter",
      "trigger": "on_reveal",
      "description": "Counter target attack and deal 2 damage to attacker.",
      "conditions": [
        {
          "type": "stat_check",
          "stat": "incoming_damage",
          "operator": ">=",
          "value": 3,
          "source": "global"
        }
      ]
    }
  ],
  "requirements": {
    "requiredPath": null,
    "minLevel": 3
  },
  "keywords": ["void", "attack", "counter"],
  "flavorText": "The Void does not care when you strike. Only that you do.",
  "artUrl": "assets/images/cards/void-slash.png",
  "isActive": true,
  "echoStrength": 4,
  "echoElement": "void",
  "resonanceAffinity": "void"
}
```

### Creature Format

```json
{
  "id": "creature-void-hunter",
  "name": "Void Hunter",
  "description": "A predator from beyond the Veil that tracks its prey through dimensions.",
  "type": "aberration",
  "size": "large",
  "behavior": "predator",
  "challengeRating": 8,
  "stats": {
    "health": 90,
    "attack": 14,
    "defense": 12,
    "speed": 5
  },
  "resonance": {
    "clarity": 3,
    "flow": 4,
    "presence": 3,
    "root": 2,
    "void": 6
  },
  "abilities": [
    {
      "name": "Dimensional Strike",
      "description": "Teleport up to 4 hexes and make a melee attack.",
      "damage": 5,
      "cooldown": 2,
      "range": "4 hexes + melee"
    },
    {
      "name": "Void Sense",
      "description": "Detect all creatures within 10 hexes, even invisible ones."
    },
    {
      "name": "Reality Anchor",
      "description": "Prevent teleportation within 3 hexes of the hunter.",
      "cooldown": 4,
      "range": "3 hex aura"
    }
  ],
  "loot": [
    "Void Hunter Eye (rare component)",
    "Dimensional Claw x2",
    "4d20 gold"
  ],
  "habitat": ["void", "boundary_zones", "thin_places"],
  "lore": "Void Hunters are the apex predators of the spaces between realms...",
  "artUrl": "assets/images/creatures/void-hunter.png"
}
```

### Realm Format

```json
{
  "id": "realm-shadowmere",
  "name": "Shadowmere",
  "description": "A realm of perpetual twilight where shadows have substance.",
  "dominantBiome": "shadow",
  "secondaryBiomes": ["forest", "swamp"],
  "climate": "mystical",
  "properties": {
    "gravity": 0.95,
    "timeFlow": 0.8,
    "magicAffinity": 75,
    "veilIntensity": "strong",
    "elementalBalance": {
      "fire": 20,
      "water": 40,
      "earth": 30,
      "air": 35,
      "spirit": 80
    }
  },
  "portals": [
    {
      "id": "portal-shadow-gate",
      "name": "The Twilight Gate",
      "fromRealmId": "realm-aethoria",
      "toRealmId": "realm-shadowmere",
      "stability": "stable",
      "requirements": ["moonless night", "shadow affinity"],
      "description": "A doorway that only appears when no light touches it."
    }
  ],
  "regionIds": [
    "region-dark-forest",
    "region-void-shore",
    "region-shadow-city"
  ],
  "dangerLevel": 7,
  "secrets": [
    "The realm was once a paradise before the Sundering",
    "The Shadow Council controls more than they reveal"
  ]
}
```

### Campaign Template Format

```json
{
  "id": "campaign-into-the-void",
  "title": "Into the Void",
  "description": "A descent into the spaces between realms.",
  "thumbnail": "assets/images/campaigns/into-the-void-thumb.png",
  "author": {
    "id": "user-12345",
    "name": "Creator Name"
  },
  "playerCount": {
    "min": 3,
    "max": 5
  },
  "estimatedDuration": "12-16 hours",
  "difficulty": "advanced",
  "tags": ["void", "horror", "exploration"],
  "realm": "Shadowmere",
  "chapters": [
    {
      "id": "chapter-1",
      "title": "The Thinning",
      "description": "Strange events signal the weakening Veil.",
      "scenes": [
        {
          "id": "scene-1-1",
          "title": "Whispers in Ashhollow",
          "type": "roleplay",
          "description": "The players arrive in Ashhollow...",
          "objectives": ["Investigate the disturbances"],
          "npcs": ["npc-mayor-thorne", "npc-keeper-mirabel"],
          "locations": ["location-ashhollow-tavern"],
          "triggers": [
            {
              "condition": "investigation_complete",
              "action": "advance_to_scene_1_2"
            }
          ]
        }
      ]
    }
  ],
  "npcs": [
    {
      "id": "npc-mayor-thorne",
      "name": "Mayor Thorne",
      "role": "quest_giver",
      "description": "A worried official seeking help.",
      "stats": null,
      "dialogue": {
        "greeting": "Thank the Veil you've come...",
        "quest_offer": "We need your help...",
        "quest_complete": "You've saved us all."
      }
    }
  ],
  "rewards": {
    "experience": 5000,
    "items": ["Void Walker Cloak", "Shadowmere Token"],
    "unlocks": ["realm-shadowmere"]
  }
}
```

---

## API Integration

### Publishing Content

```typescript
import { MarketplaceService, ContentType } from '@veilborn/core';

const marketplace = new MarketplaceService();

// Create marketplace listing
const listing = await marketplace.createListing({
  sellerId: 'user-12345',
  sellerName: 'CreatorName',
  contentType: 'card' as ContentType,
  title: 'Void Slash',
  description: 'A powerful void attack card.',
  previewUrl: '/previews/void-slash.png',
  price: 0,
  currency: 'free',
  tags: ['void', 'attack', 'echo'],
});

// Upload content data
const content = await marketplace.uploadContent(listing.id, cardData);

// Submit for approval
await marketplace.submitForReview(listing.id);
```

### Searching Content

```typescript
// Search marketplace
const results = await marketplace.search({
  query: 'void',
  contentType: ['card', 'creature'],
  currency: ['free'],
  minRating: 4,
  sortBy: 'popular',
  page: 1,
  limit: 20,
});

// Get content details
const content = await marketplace.getContent(contentId);

// Download content
const data = await marketplace.downloadContent(contentId);
```

### Installing Content Packs

```typescript
import { ContentManager } from '@veilborn/core';

const contentManager = new ContentManager();

// Install from marketplace
await contentManager.installFromMarketplace(listingId);

// Install from local file
await contentManager.installFromFile('./my-content-pack.zip');

// List installed content
const installed = contentManager.listInstalled();

// Uninstall content
await contentManager.uninstall(packId);
```

---

## Sharing Campaigns

### Campaign Sharing Service

```typescript
import { CampaignSharingService } from '@veilborn/core';

const sharing = new CampaignSharingService();

// Create shared campaign
const campaign = sharing.createCampaign('user-12345', 'CreatorName', {
  title: 'Into the Void',
  description: 'A descent into darkness...',
  thumbnail: '/thumbnails/into-the-void.png',
  playerCount: { min: 3, max: 5 },
  estimatedDuration: '12-16 hours',
  difficulty: 'advanced',
  tags: ['void', 'horror'],
  realm: 'Shadowmere',
  isPublished: false,
});

// Publish campaign
sharing.updateCampaign(campaign.id, { isPublished: true });

// Search campaigns
const results = sharing.searchCampaigns({
  query: 'void',
  difficulty: ['advanced'],
  minRating: 4,
  sortBy: 'trending',
  page: 1,
  limit: 20,
});
```

### Character Gallery

```typescript
import { CharacterGalleryService } from '@veilborn/core';

const gallery = new CharacterGalleryService();

// Showcase character
const showcase = gallery.createShowcase({
  ownerId: 'user-12345',
  ownerName: 'PlayerName',
  name: 'Kira Shadowweave',
  title: 'Mistress of the Void',
  portraitUrl: '/portraits/kira.png',
  path: 'shadow',
  level: 12,
  description: 'A Veilborn who walks between worlds...',
  backstory: 'Born during a Veil storm...',
  achievements: ['Void Walker', 'Shadow Master'],
});

// Browse gallery
const characters = gallery.searchGallery({
  path: 'shadow',
  minLevel: 10,
  sortBy: 'popular',
  page: 1,
  limit: 20,
});
```

---

## Asset Generation

### Using the Asset Generator

```typescript
import {
  AssetGenerator,
  CreatureAppearance,
  CardVisuals,
} from '@veilborn/core';

const generator = new AssetGenerator();

// Generate creature art prompt
const creaturePrompt = generator.buildCreature({
  type: 'aberration',
  size: 'large',
  bodyForm: 'six-legged hunter',
  color: 'shifting purple and black',
  features: ['multiple eyes', 'phasing outline'],
  abilities: ['teleportation', 'void sense'],
  mood: 'predatory',
});

// Generate card art prompt
const cardPrompt = generator.buildCard({
  name: 'Void Slash',
  cardType: 'echo',
  element: 'void',
  rarity: 'rare',
  mood: 'aggressive',
  keywords: ['attack', 'void', 'dimensional'],
});

// Generate location art prompt
const locationPrompt = generator.buildLocation({
  name: 'The Shadow Citadel',
  biome: 'shadow',
  type: 'fortress',
  mood: 'ominous',
  features: ['dark spires', 'void portals', 'shadow guards'],
});
```

### Art Guidelines

| Content Type       | Recommended Size | Format  | Style          |
| ------------------ | ---------------- | ------- | -------------- |
| Card               | 750x1050         | PNG     | Illustrated    |
| Creature Token     | 512x512          | PNG     | Transparent BG |
| Creature Full      | 1024x1024        | PNG     | Detailed       |
| Location           | 1920x1080        | PNG/JPG | Scenic         |
| Character Portrait | 512x512          | PNG     | Bust shot      |
| Campaign Thumbnail | 640x360          | PNG/JPG | Scene          |

---

## Validation

### Content Validation

```typescript
import { ContentValidator } from '@veilborn/core';

const validator = new ContentValidator();

// Validate card
const cardValidation = validator.validateCard(cardData);
if (!cardValidation.valid) {
  console.error('Card errors:', cardValidation.errors);
  // e.g., "Missing required field: cardType"
  // e.g., "Invalid effect trigger: on_invalid"
}

// Validate creature
const creatureValidation = validator.validateCreature(creatureData);

// Validate realm
const realmValidation = validator.validateRealm(realmData);

// Validate content pack
const packValidation = validator.validatePack('./my-content-pack/');
console.log('Pack status:', packValidation.status);
console.log('Warnings:', packValidation.warnings);
```

### Balance Checking

```typescript
import { BalanceChecker } from '@veilborn/core';

const balance = new BalanceChecker();

// Check card balance
const cardBalance = balance.analyzeCard(cardData);
console.log('Power level:', cardBalance.powerLevel);
console.log('Suggested cost:', cardBalance.suggestedCost);
console.log('Balance issues:', cardBalance.issues);

// Check creature balance
const creatureBalance = balance.analyzeCreature(creatureData);
console.log('Suggested CR:', creatureBalance.suggestedCR);

// Check campaign balance
const campaignBalance = balance.analyzeCampaign(campaignData);
console.log('Difficulty curve:', campaignBalance.difficultyCurve);
console.log('Loot distribution:', campaignBalance.lootBalance);
```

---

## Best Practices

### Content Design

1. **Consistency**: Match the Veilborn aesthetic and tone
2. **Balance**: Test content against official equivalents
3. **Clarity**: Write clear, unambiguous descriptions
4. **Completeness**: Include all required fields
5. **Documentation**: Explain custom mechanics

### Naming Conventions

```typescript
// IDs: lowercase with hyphens
const cardId = 'card-custom-void-slash';
const creatureId = 'creature-void-hunter';
const realmId = 'realm-shadowmere';

// Display names: Title Case
const cardName = 'Void Slash';
const creatureName = 'Void Hunter';
const realmName = 'Shadowmere';

// File names: lowercase with hyphens
// cards/void-slash.json
// creatures/void-hunter.json
// realms/shadowmere/realm.json
```

### Version Compatibility

```json
{
  "compatibility": {
    "minVersion": "1.0.0",
    "maxVersion": "2.0.0",
    "testedVersions": ["1.0.0", "1.1.0", "1.2.0"],
    "breakingChanges": {
      "2.0.0": "Effect trigger syntax changed"
    }
  }
}
```

### Testing Checklist

- [ ] All required fields present
- [ ] IDs are unique within pack
- [ ] References resolve correctly
- [ ] Balance is appropriate
- [ ] Art assets load correctly
- [ ] No copyright violations
- [ ] Tested in actual gameplay
- [ ] Documentation complete

---

## Moderation Guidelines

### Content Requirements

All marketplace content must:

1. **Be Original**: No copying from other games/media
2. **Be Appropriate**: No explicit or offensive content
3. **Be Functional**: Actually work when installed
4. **Be Balanced**: Not game-breaking
5. **Have Clear Licensing**: State usage rights

### Prohibited Content

- Copyrighted characters/settings without permission
- Explicit sexual content
- Hate speech or discriminatory content
- Malicious code or exploits
- Content designed to crash/break the game

### Review Process

```typescript
// Content goes through review before publishing
interface ContentReview {
  status: 'pending' | 'approved' | 'rejected' | 'revision_required';
  reviewerId?: string;
  reviewDate?: string;
  feedback?: string;
  issues?: string[];
}
```

---

## Troubleshooting

### Common Issues

| Issue                  | Cause                | Solution                          |
| ---------------------- | -------------------- | --------------------------------- |
| Content not loading    | Invalid JSON         | Validate JSON syntax              |
| Effects not triggering | Wrong trigger type   | Check trigger spelling            |
| Art not displaying     | Wrong path           | Use relative paths from pack root |
| Balance warnings       | Stats too high/low   | Adjust to match CR guidelines     |
| Import fails           | Missing dependencies | Check manifest dependencies       |

### Debug Mode

```typescript
import { ContentManager } from '@veilborn/core';

const manager = new ContentManager({ debug: true });

// Enable verbose logging
manager.setLogLevel('verbose');

// Validate with detailed output
const result = manager.validateWithDetails('./my-pack/');
console.log('Validation trace:', result.trace);
```

---

## Quick Reference

### File Extensions

```
.json     - Data files (cards, creatures, realms)
.png      - Image assets (transparent background preferred)
.jpg      - Scene images (locations, thumbnails)
.ogg      - Audio files (ambient, music)
.md       - Documentation
```

### Required Fields by Type

```
Card:     id, name, cardType, cost, effects
Creature: id, name, type, size, challengeRating, stats
Realm:    id, name, dominantBiome, properties
Campaign: id, title, description, chapters, scenes
```

### Marketplace Categories

```
free       - No cost
veilcoins  - In-game currency
premium    - Real money purchase
```

---

_For card creation, see [Card Creation Guide](01-card-creation-guide.md)_ _For
creature creation, see [Creature Creation Guide](02-creature-creation-guide.md)_
_For realm building, see [Realm Building Guide](03-realm-building-guide.md)_
