Skip to content

About

Interactive alternative history simulator — explore how small historical changes ripple through 1000 years using AI-powered timeline generation.

Topics

Resources

Contributing

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

banner

Next.js TypeScript Tailwind CSS Framer Motion shadcn/ui License

Issues Stars Forks

What if a single flutter changed the course of history?
Pick a moment. Change it. Watch 1,000 years unfold.

Live Demo

About

"Does the flap of a butterfly's wings in Brazil set off a tornado in Texas?" — Edward Lorenz, 1972

The Butterfly Effect is an interactive web application that merges Chaos Theory, Alternative History, and Generative AI into a cinematic experience. Users choose a historical turning point, and the AI engine simulates how that tiny change ripples across centuries — generating unique timelines, world states, and concept art along the way.


Features

🎯 3-Step Wizard

Simple, guided flow:

  1. The Ripple — Choose an era, location, and a small change
  2. The Magnitude — Set how widely the change spreads (Secret / Limited / Public)
  3. The Time Leap — Watch AI generate the alternate timeline

🤖 AI Timeline Engine

  • LLM generates 4 branching checkpoints spanning 800+ years
  • Each checkpoint includes achievements, crises, world state, and geography
  • AI-generated concept art for the final era
  • Smart retry + fallback for reliable responses

🌐 Interactive Visualization

  • Animated branching timeline with Framer Motion
  • Expandable checkpoint cards with rich detail
  • Responsive design — works on mobile and desktop

🛡️ Battle-Tested Engineering

  • Resilient JSON parser — repairs truncated LLM responses
  • Hydration-safe particles — deterministic SSR (no Math.random())
  • Graceful degradation — smart fallback checkpoints if AI fails
  • Request normalization — missing fields auto-filled

Quick Start

git clone https://github.com/modarresi1913/the-butterfly-effect.git
cd the-butterfly-effect
npm install
cp .env.example .env.local
npm run dev

Open http://localhost:3000 — or try the live demo at butterfly0.space-z.ai

⚙️ Production Build
npm run build
npm start
📦 Tech Stack Details
Layer Technology Role
Framework Next.js 16 App Router, SSR, API Routes
Language TypeScript 5 Type safety
Styling Tailwind CSS 4 Utility-first CSS
UI Kit shadcn/ui Accessible, composable components
Animation Framer Motion 11 Page transitions, timeline animation
AI z-ai-web-dev-sdk LLM completions + image generation
Icons Lucide Consistent icon system

How It Works

  ┌──────────────┐       ┌──────────────┐       ┌──────────────┐       ┌──────────────┐
  │              │       │              │       │              │       │              │
  │  THE RIPPLE  │──────▶│ THE MAGNITUDE│──────▶│ THE TIME LEAP│──────▶│  TIMELINE    │
  │              │       │              │       │              │       │  RESULTS     │
  │  Era         │       │  Secret      │       │  AI generates│       │              │
  │  Location    │       │  Limited     │       │  4 epochs    │       │  Checkpoint 1│
  │  Change      │       │  Public      │       │  + art       │       │  Checkpoint 2│
  │              │       │              │       │              │       │  Checkpoint 3│
  └──────────────┘       └──────────────┘       └──────────────┘       │  Checkpoint 4│
                                                                          │  + AI Art   │
                                                                          └──────────────┘

Checkpoint Data Model

Each AI-generated checkpoint contains:

interface Checkpoint {
  year: string;           // "500 BC", "+200 years"
  era_label: string;      // "The Printing Dawn"
  achievements: string[]; // ["Mass book production", "..."]
  crises: string[];       // ["Resistance from priests"]
  world_state: string;    // "Persia became the knowledge center..."
  geography: string;      // "The Achaemenid Empire expanded..."
  image_prompt: string;   // Visual description for AI art generation
}

Project Structure

the-butterfly-effect/
├── src/
│   ├── app/
│   │   ├── api/simulate/
│   │   │   └── route.ts          # 🧠 AI simulation endpoint
│   │   ├── globals.css            # 🎨 Dark sci-fi theme + animations
│   │   ├── layout.tsx             # 📐 Root layout (LTR, metadata)
│   │   └── page.tsx               # 🦋 Main app (wizard + timeline)
│   └── components/
│       └── ui/                    # shadcn/ui primitives
├── .github/                       # CI, issue templates, PR template
├── .env.example                   # Environment variables template
├── CONTRIBUTING.md                # Contribution guidelines
├── LICENSE                        # MIT
└── README.md                      # You are here 📍

Technical Deep Dives

🛡️ Resilient JSON Parsing

AI models frequently truncate their JSON output. This project implements a multi-layer repair strategy:

  1. Strip markdown fences — Removes json ... wrappers
  2. Fix trailing commas — Cleans {a: 1,} → {a: 1}
  3. Detect unclosed strings — Finds the last unclosed quote and removes the incomplete key-value pair
  4. Auto-close brackets — Counts open/close braces and appends missing closers
  5. Validate structure — Ensures all required fields exist before rendering

This reduces LLM response failures from ~40% to near-zero.

💧 Hydration-Safe Particle Field

Next.js SSR requires server and client markup to match. Using Math.random() in components causes hydration mismatches because the server generates different values than the client.

Solution: Deterministic positioning via modular arithmetic:

// Instead of Math.random()
const x = ((i * 37 + 13) % 97) * 1.03;
const y = ((i * 53 + 7) % 89) * 1.14;

This produces visually random-looking distributions that are identical on server and client.

🔄 Smart Retry + Fallback
Attempt 1: LLM call → parse → validate  ✅/❌
Attempt 2: LLM call → parse → validate  ✅/❌
Fallback:  Hand-crafted checkpoints    ✅

The system makes 2 attempts with the LLM. If both fail (truncation, invalid format, timeout), it falls back to pre-written thematic checkpoints so the user always gets a result.


Roadmap

  • Shareable timeline links
  • Multiple branching paths (user chooses at each checkpoint)
  • Historical comparison mode (real vs. alternate)
  • Export as PDF / image
  • Community timeline gallery
  • Mobile app (React Native)

Contributing

Contributions, issues, and feature requests are welcome!

  1. Read CONTRIBUTING.md
  2. Fork the repository
  3. Create a feature branch
  4. Open a Pull Request

footer

Built with 🦋 by modarresi1913
If you like this project, consider giving it a ⭐!

About

Interactive alternative history simulator — explore how small historical changes ripple through 1000 years using AI-powered timeline generation.

Topics

Resources

Contributing

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages