Creative Web Algorithm v3.0
Transform STATE A → STATE B while preserving valid behavior, proving each significant change, and delivering a production-grade experience. Never begin by editing.
Operating Contract (Inviolable)
Observe before modifying. Map the entire runtime before touching a single line.
Never patch unknown runtimes, exported snapshots, iframes, or minified bundles until execution model is fully mapped.
Component decisions only: Keep, Refactor, Replace, Remove, or mark Unknown. Never remove without evidence.
Strict separation: RENDERING ≠ UI ≠ ANIMATION ≠ STATE ≠ ASSETS ≠ PERFORMANCE_POLICY. Each layer has its own module, its own tests, its own lifecycle.
Never claim a feature exists until it has been run and tested in a real browser. Console + Network + Performance tabs required.
Prefer reversible incremental migrations over rewrites. Every change must be rollbackable in ≤1 commit.
If the format prevents reliable development, extract/reconstruct the runtime first. Stop, diagnose, rebuild the foundation before continuing.
One owned render loop. One state machine. One source of truth for scene state. No orphaned RAF handles, no duplicate loops.
Memory is a first-class concern. Every GPU resource, every listener, every timer must have an explicit disposal path.
Accessibility is non-negotiable. Every visual effect must have a reduced-motion fallback and keyboard/screen-reader equivalent.
Phase 0 — OBSERVE (Zero Modifications)
Goal: Produce a complete Architecture Map before writing any code.
Scan Checklist
Category
What to inspect
Tool
Entry points
HTML, JS modules, CSS entry, config files
grep, find
Dependencies
npm packages, CDN imports, dynamic imports
package.json, import statements
DOM structure
Element tree, canvas elements, iframes
DevTools, document.querySelectorAll
CSS architecture
Custom properties, animations, layout system
grep for @keyframes, :root
JS modules
Export/import graph, state management, store patterns
AST analysis
Canvas/WebGL
WebGL context, shader programs, render targets, framebuffers
WEBGL_debug_renderer_info
Shaders
Vertex/fragment source, uniform locations, texture bindings
File scan
Assets
Images, fonts, audio, video, models, with sizes and formats
File scan, ls -lh
Loading/boot
Sequence order, preloaders, skeleton screens, lazy loading
Code trace
Iframes
Embedded content, cross-origin, postMessage channels
DOM scan
CSP
Content-Security-Policy headers, nonce/hashes, restrictions
Network tab
Timers/promises
setInterval, setTimeout, Promise chains, microtasks
Code scan
External resources
APIs, CDNs, fonts, analytics, tracking
Network tab
Event listeners
Mouse, touch, scroll, keyboard, resize, custom events
Code scan, DevTools
Performance
FPS, frame time, memory, layout thrashing
Performance tab
Network
Requests, waterfalls, caching, compression
Network tab
Output: Architecture Map
# Architecture Map — [Project Name]
## Entry Points
- [ ] Primary: [file] → [initialization sequence]
- [ ] Secondary: [file] → [purpose]
## Module Graph
- [module A] imports [B, C]
- [module B] exports [X, Y]
- [module C] depends on [D, E]
## State Management
- [ ] Single source of truth: [store/context/prop]
- [ ] Derived state: [computed values]
- [ ] Side effects: [saga/epic/effect]
## Render Architecture
- [ ] Primary renderer: [Three.js/Canvas2D/WebGL]
- [ ] Secondary renderers: [overlays, post-processing]
- [ ] Render loop ownership: [which module]
## Asset Pipeline
- [ ] Loading strategy: [lazy/eager/prefetch]
- [ ] Cache policy: [memory/disk/None]
- [ ] Fallback assets: [low-res/progressive]
## Performance Profile
- [ ] Current FPS: [target/described]
- [ ] Memory budget: [bytes]
- [ ] Frame budget: [ms]
- [ ] Bundle size: [KB]
## Known Issues
- [ ] [Issue description, evidence, impact]
Dependency Graph (ASCII)
[Entry] → [Renderer] → [Scene] → [Camera]
↓ ↓
[PostFX] [Lights]
↓ ↓
[UI Layer] ← [State Store]
↓
[Animation] → [Assets]
Phase 1 — CLASSIFY
Goal: Create a Component Decision Map with evidence for every component.
Decision Categories
Category
Criteria
Action
KEEP
Functional, valuable, no structural issues
Leave untouched
REFACTOR
Valuable but structurally unsafe, hard to extend, or technically debt
Rewrite internals, preserve API
REPLACE
Unsuitable for target state with concrete evidence
Swap implementation, preserve interface
REMOVE
Redundant, broken, harmful with evidence
Delete + add migration note
UNKNOWN
Insufficient evidence to classify
Investigate → reclassify → act
Decision Record Format
## Component Decision Map
### [Component Name]
- **Location:** [file:line]
- **Current state:** [working/broken/debt]
- **Evidence:** [test results, performance metrics, bug reports]
- **Decision:** KEEP / REFACTOR / REPLACE / REMOVE / UNKNOWN
- **Rationale:** [why this decision]
- **Risk if wrong:** [what breaks]
- **Reversibility:** [how to undo]
### [Next Component]
...
Evidence Requirements
Performance data: FPS benchmarks, memory snapshots, frame timing
Functional tests: Unit tests passing/failing, integration test results
User feedback: Bug reports, support tickets, analytics data
Code quality: Cyclomatic complexity, bundle impact, coupling metrics
Phase 2 — DETECT FAILURE MODES
Goal: For every issue, record CAUSE → EFFECT → FIX. Fix causes, not symptoms.
Failure Mode Catalog
Failure Mode
CAUSE
EFFECT
FIX
Infinite/duplicated loops
RAF not cancelled, recursive setTimeout, missing break condition
CPU spike, battery drain, tab crash
Cancel RAF on unmount, use useEffect cleanup, add requestID tracking
Duplicate listeners
Event added in render without cleanup, closure scoping bug
Memory leak, double-fire, exponential growth
Use AbortController, removeEventListener, single subscription pattern
Blocking initialization
Synchronous asset load, blocking script, large bundle parse
White screen >3s, TTI degradation
Code splitting, lazy import, skeleton screen, streaming
Failed promises
Missing .catch(), unhandled rejection, race condition
Silent failure, zombie state
Always .catch(), use Promise.allSettled, add error boundaries
Missing assets
Broken URL, wrong path, CORS restriction
Fallback broken, layout shift
Verify paths, use onError handlers, preload critical assets
Broken imports
Circular dependency, missing module, wrong export
Runtime error, blank page
Fix import paths, use eslint import/no-cycle, tree-shake
iframe/CSP conflicts
CSP blocks inline scripts, iframe sandbox restrictions
Content blocked, security errors
Adjust CSP headers, use sandbox attribute carefully
Memory leaks
Orphaned listeners, unclosed connections, retained references
Gradual slowdown, OOM crash
WeakRef for caches, explicit dispose, DevTools memory profiling
Excessive DPR
devicePixelRatio > 2 on high-DPI screens
GPU memory spike, frame drops
Cap DPR at Math.min(window.devicePixelRatio, 2)
Reflow/repaint cost
Layout thrashing, forced synchronous layouts
Jank, >16ms frame time
Batch DOM reads/writes, use transform/opacity only, will-change
Runaway particles
Unbounded particle count, no max cap, no culling
GPU overload, FPS collapse to <10
Cap count, use LOD, frustum culling, GPU instancing
Orphaned GPU resources
Disposed but not freed textures, unreleased framebuffers
VRAM leak, context lost
Track all GPU handles, explicit dispose() on unmount
Shader compilation stalls
Many shaders compiled in one frame, large programs
Frame drop, jank
Precompile during loading, use THREE.ShaderMaterial warmup
Network waterfall
Sequential dependencies, unoptimized loading
Long TTI, slow perceived performance
Parallelize, prefetch, use HTTP/2+ push, CDN
Failure Mode Report
## Failure Mode Analysis
### F-001: [Title]
- **Severity:** Critical / High / Medium / Low
- **CAUSE:** [root cause]
- **EFFECT:** [observable impact]
- **FIX:** [specific solution]
- **Evidence:** [data proving this]
- **Prevention:** [how to avoid in future]
Phase 3 — DEFINE TARGET ARCHITECTURE
Goal: Create a maintainable, scalable structure with strict layer separation.
Canonical Directory Structure
project/
├── src/
│ ├── scene/ # Scene graph, objects, entities
│ │ ├── index.ts
│ │ ├── Camera.ts # Camera management, transitions
│ │ ├── Lights.ts # Lighting system
│ │ ├── Objects/ # Reusable 3D objects
│ │ │ ├── Indexed.ts # Pre-registered geometries
│ │ │ └── Materials/ # Material definitions
│ │ └── Environment/ # Sky, fog, post-processing
│ ├── renderer/ # Renderer configuration, context
│ │ ├── index.ts
│ │ ├── WebGLContext.ts # Context creation, loss handling
│ │ └── PostFX/ # Bloom, SSAO, chromatic, etc.
│ ├── shaders/ # GLSL source code
│ │ ├── common.glsl
│ │ ├── vertex/
│ │ └── fragment/
│ ├── effects/ # Visual effects pipeline
│ │ ├── LiquidGlass.ts
│ │ ├── Chromatic.ts
│ │ ├── Haze.ts
│ │ └── Particles.ts
│ ├── animation/ # Animation system
│ │ ├── Animator.ts # Main animation controller
│ │ ├── Tweens.ts # Easing functions
│ │ └── Timeline.ts # Sequenced animations
│ ├── ui/ # HTML/CSS overlay layer
│ │ ├── components/
│ │ ├── styles/
│ │ └── state/ # UI state (separate from scene state)
│ ├── assets/ # Static assets, textures, models
│ │ ├── textures/
│ │ ├── models/
│ │ └── audio/
│ ├── state/ # Single source of truth for scene state
│ │ ├── Store.ts # Centralized state management
│ │ └── selectors.ts # Derived state
│ ├── utils/ # Shared utilities
│ │ ├── math.ts
│ │ ├── geometry.ts
│ │ └── helpers.ts
│ └── main.ts # Entry point, boot sequence
├── tests/
│ ├── unit/
│ ├── integration/
│ └── visual/
├── public/
│ └── index.html
├── package.json
├── tsconfig.json
├── vite.config.ts
└── README.md
Architecture Rules
RENDERING ≠ UI ≠ ANIMATION ≠ STATE ≠ ASSETS ≠ PERFORMANCE — Each module owns its domain, never crosses boundaries without explicit interfaces.
Single source of truth — Scene state lives in state/Store.ts. UI state lives in ui/state/. Never duplicate.
Renderer is agnostic — renderer/ knows nothing about scene content. Scene provides geometries; renderer draws them.
Animation is parameterized — All motion derives from time, delta, velocity, damping, easing. Never hardcode frame counts.
Assets are lazy — Load on demand. Preload only critical path (<100KB).
Effects are composable — PostFX pipeline is a chain. Add/remove without affecting core render.
Cleanup is mandatory — Every module exports dispose(). Call it on unmount/context loss.
Phase 4 — BUILD THE VISUAL SYSTEM
Goal: Create a layered scene graph with explicit depth, parallax, and motion policy.
Scene Graph Layers (Front to Back)
┌─────────────────────────────────┐
│ UI LAYER │ ← HTML/CSS overlay, interactive controls
│ ───────────────────────────── │
│ INTERACTION LAYER │ ← Raycasting, pointer events, hover
│ ───────────────────────────── │
│ PARTICLES LAYER │ ← Atmospheric particles, ambient
│ ───────────────────────────── │
│ SUBJECT LAYER │ ← Main 3D object, hero geometry
│ ───────────────────────────── │
│ LIGHTING LAYER │ → Reflections, shadows, glow
│ ───────────────────────────── │
│ ENVIRONMENT LAYER │ → Sky, fog, ground, skybox
│ ───────────────────────────── │
│ DEPTH LAYERS │ → Parallax planes, background depth
│ ───────────────────────────── │
│ ATMOSPHERE LAYER │ → Haze, fog, volumetric light
│ ───────────────────────────── │
│ BACKGROUND LAYER │ → Solid color, gradient, gradient
└─────────────────────────────────┘
Layer Configuration
Each layer has explicit properties:
interface LayerConfig {
name: string;
depth: number; // 0.0 (back) to 1.0 (front)
parallaxCoefficient: number; // 0.0 (static) to 1.0 (follows pointer)
motionPolicy: 'static' | 'parallax' | 'animated' | 'interactive';
opacity: number; // 0.0 to 1.0
visible: boolean;
quality: 'high' | 'medium' | 'low';
}
Parameterized Inputs
Route these same inputs to ALL visual layers:
time — clock.getElapsedTime() — drives all animations
pointer — mouse.x, mouse.y — drives parallax, hover, interaction
viewport — window.innerWidth/innerHeight — drives resolution, scale
scroll — window.scrollY — drives depth, reveals, transitions
delta — clock.getDelta() — drives frame-rate-independent motion
Anti-pattern: Applying arbitrary transforms to every element and calling it "3D". Every transform must serve a visual purpose documented in the layer config.
Phase 5 — BUILD THE MATERIAL SYSTEM SELECTIVELY
Goal: Choose materials hierarchically. Every effect must earn its place.
Material Hierarchy
Primary (One Dominant Effect):
Choose ONE primary visual identity:
Liquid Glass: MeshPhysicalMaterial with transmission: 0.85, thickness: 0.5, ior: 1.5, clearcoat: 1.0, roughness: 0.05. Creates refractive, reflective surfaces.
Liquid Metal: MeshPhysicalMaterial with metalness: 1.0, roughness: 0.0, color: [theme], envMapIntensity: 2.0. Creates mirror-like metallic surfaces.
Ethereal: MeshStandardMaterial with emissive, transparent, opacity: 0.3, wireframe: true. Creates ghostly, sci-fi surfaces.
Neon Glow: MeshBasicMaterial with emissive, emissiveIntensity: 2.0, transparent: true, opacity: 0.8. Creates glowing, holographic surfaces.
Secondary (Supporting Effects):
Reflection/Refraction: Environment maps, cubeCamera, refractionRatio
Fresnel: FresnelMaterial or custom shader with dot(normal, viewDir)
Displacement: displacementMap, displacementScale, vertex displacement
Chromatic: Custom shader with RGB channel offset based on view angle
Atmospheric (Global Effects):
Bloom: UnrealBloomPass — strength 0.5-1.5, radius 0.4, threshold 0.85
Light Scatter: LensFlare, sprite glow, AdditiveBlending
Haze: FogExp2 or custom depth-based fog
RGB Shift: Custom post-process shader with chromatic aberration offset
Material Decision Rules
Never use a generated still image to cover or replace an existing animated canvas unless explicitly requested by the user.
Remove effects that do not improve composition. If a bloom pass doesn't add visual value, remove it. If a chromatic effect distracts from the subject, kill it.
One primary effect. Supporting effects only earn their place if they enhance the primary without competing.
Performance budget: Primary material <2 shader compiles. Total post-processing <3 passes.
Liquid Glass Implementation Template
// Fragment shader for liquid glass
uniform float uTime;
uniform float uTransmission;
uniform vec3 uColor;
uniform float uIOR;
void main() {
vec3 viewDir = normalize(vViewPosition);
vec3 normal = normalize(vNormal);
// Fresnel for edge glow
float fresnel = pow(1.0 - dot(viewDir, normal), 3.0);
// Transmission for refraction
vec3 refracted = texture2D(uTransmissionMap, vUv).rgb;
vec3 transmitted = mix(uColor, refracted, uTransmission);
// Edge glow
vec3 edgeGlow = vec3(0.0, 0.9, 0.97) * fresnel * 0.5;
gl_FragColor = vec4(transmitted + edgeGlow, 0.85 + fresnel * 0.15);
}
Phase 6 — BUILD DETERMINISTIC MOTION
Goal: All motion derives from parameterized inputs. Never hardcoded values.
Motion Parameter System
interface MotionParams {
velocity: number; // Base speed (units/sec)
acceleration: number; // Rate of change of velocity
damping: number; // Friction/decay (0-1)
easing: 'linear' | 'easeIn' | 'easeOut' | 'easeInOut' | 'elastic' | 'bounce';
depth: number; // Z-depth parallax coefficient
amplitude: number; // Max displacement
frequency: number; // Oscillations per second
phase: number; // Time offset
}
Routing Protocol
All inputs MUST route to ALL relevant transforms:
[time] → camera.transform, layer.transform, shader.uniforms, lighting.position, particle.velocity, UI.transition
[pointer] → camera.position (parallax), layer.parallax, object.rotation (follow)
[scroll] → camera.position (depth), layer.opacity (reveal), object.scale (approach)
[viewport] → renderer.dpr, camera.aspect, object.scale (responsive)
Animation Loop Contract
// ONE owned loop per renderer
class AnimationLoop {
private rafId: number | null = null;
private lastTime = 0;
start() {
const tick = (timestamp: number) => {
const delta = timestamp - this.lastTime;
this.lastTime = timestamp;
this.update(delta, timestamp);
this.rafId = requestAnimationFrame(tick);
};
this.rafId = requestAnimationFrame(tick);
}
stop() {
if (this.rafId !== null) {
cancelAnimationFrame(this.rafId);
this.rafId = null;
}
}
private update(delta: number, timestamp: number) {
// Route delta to ALL systems:
this.scene.update(delta);
this.ui.update(delta);
this.particles.update(delta);
this.camera.update(delta);
}
dispose() {
this.stop();
// Clean up all listeners, observers, GPU resources
}
}
Rules:
Use requestAnimationFrame only through this ONE owned loop.
Never create additional setTimeout, setInterval, or secondary RAF loops.
Always provide dispose() that cleans up listeners, RAF handles, observers, and GPU resources.
Use clock.getDelta() for frame-rate-independent motion. Never assume 60fps.
Phase 7 — ENFORCE PERFORMANCE
Goal: Adaptive quality with explicit budgets and mobile-specific states.
Quality Tiers
enum Quality { HIGH = 'high', MEDIUM = 'medium', LOW = 'low' }
interface QualityConfig {
dpr: number; // 2, 1.5, 1
resolution: number; // 1, 0.75, 0.5
particleCount: number; // 10000, 5000, 1000
shadowMap: { size: number, enabled: boolean }; // 2048/1024/512
postProcessing: { bloom: boolean, ssao: boolean, chromatic: boolean };
animationFrequency: number; // 60, 30, 15 fps cap
textureSize: number; // 1024, 512, 256
geometryDetail: number; // high/medium/low segment counts
}
Quality Selection Logic
function selectQuality(): Quality {
const cores = navigator.hardwareConcurrency || 2;
const memory = (navigator as any).deviceMemory || 4;
const dpr = Math.min(window.devicePixelRatio, 2);
const isMobile = /Mobi|Android/i.test(navigator.userAgent);
const fps = getBaselineFPS(); // Measure initial FPS
if (isMobile || cores < 4 || memory < 4 || fps < 30) return Quality.LOW;
if (cores < 8 || memory < 8 || dpr > 1.5 || fps < 45) return Quality.MEDIUM;
return Quality.HIGH;
}
Degradation Cascade (Priority Order)
When performance degrades, reduce in this order:
Atmospheric effects first — bloom, haze, fog
Particles second — reduce count, simplify shader
Shader resolution third — lower texture sizes, fewer segments
Preserve the primary composition — the hero object must remain visible and coherent
Performance Budgets
Metric
HIGH
MEDIUM
LOW
Budget
Target FPS
60
45
30
≥30
Frame Time
≤16ms
≤22ms
≤33ms
<33ms
Draw Calls
<100
<50
<25
<50
Triangles
<500k
<200k
<50k
<200k
Textures
10MB
5MB
2MB
<10MB
Bundle
500KB
300KB
150KB
<500KB
GPU Memory
<500MB
<250MB
<100MB
<500MB
Mobile State
Mobile is a distinct lower-cost rendering state , not merely a scaled desktop:
Different geometry LODs (not just scaled down)
Different particle systems (points vs. sprites)
Different post-processing pipeline (no bloom on mobile)
Touch-optimized interaction (no hover-dependent UI)
Reduced shadow quality (no real-time shadows on LOW)
Phase 8 — REAL LOADING STATE MACHINE
Goal: Explicit, deterministic loading with no arbitrary timeouts.
State Machine
┌─────────────┐
│ BOOT │ ← Entry point, initialize globals
└──────┬──────┘
↓
┌──────────────┐
│INITIALIZING │ ← Setup modules, validate dependencies
└──────┬───────┘
↓
┌─────────────────┐
│LOADING_ASSETS │ ← Load textures, models, audio, fonts
│(with progress) │ ← Report progress to UI
└──────┬──────────┘
↓
┌───────────────────────┐
│INITIALIZING_RENDERER │ ← Create WebGL context, compile shaders
└──────┬────────────────┘
↓
┌────────────┐
│ READY │ ← All assets loaded, renderer initialized
└──────┬─────┘
↓
┌────────────┐
│ ENTERING │ ← First render, transition in
└──────┬─────┘
↓
┌────────────┐
│ ACTIVE │ ← Full interactive experience
└────┬───────┘
↓ (from any state)
┌─────────────────┐
│RECOVERABLE_ERROR│ ← Asset failed, context lost, etc.
└──────┬──────────┘
↓
┌────────────┐
│ FALLBACK │ ← Graceful degradation, cached content, error UI
└──────┬─────┘
↓ (user action / retry)
┌────────────┐
│ ACTIVE │ ← Retry successful
└────────────┘
SPECIAL: ENTERING → ACTIVE (skip, if no transition needed)
State Implementation
class LoadingStateMachine {
state: State = 'BOOT';
progress: number = 0;
errors: Error[] = [];
async transition(to: State) {
const valid = this.allowedTransitions[this.state];
if (!valid.includes(to)) throw new Error(`Invalid transition: ${this.state} → ${to}`);
this.state = to;
this.onStateChange(to);
}
async loadAssets(urls: string[], onProgress: (p: number) => void) {
await this.transition('LOADING_ASSETS');
const results = await Promise.allSettled(
urls.map(url => fetch(url).then(r => r.blob()))
);
// Handle partial failures gracefully
const successes = results.filter(r => r.status === 'fulfilled');
const failures = results.filter(r => r.status === 'rejected');
if (failures.length > 0 && successes.length === 0) {
await this.transition('RECOVERABLE_ERROR');
}
this.progress = successes.length / urls.length;
}
// skip is ALWAYS safe and idempotent
skip() {
this.transition('ACTIVE'); // or FALLBACK if assets not loaded
}
}
Rules
Advance on actual asset/renderer readiness , never an arbitrary timeout
Display actionable errors — "Failed to load texture X. Retry?" not "Error 404"
Skip is always safe and idempotent — calling skip twice does nothing bad
Enter → Active can skip if assets are cached (service worker)
Any state → Recoverable Error → Fallback → Active for error recovery
Phase 9 — VERIFY AFTER EVERY SIGNIFICANT CHANGE
Goal: Run the full verification matrix. Never stack unverified patches.
Verification Matrix
BUILD ──────────────────────────────
→ tsc --noEmit (or equivalent)
→ Rollup/Vite build succeeds
→ No TypeScript errors
→ No bundler warnings
RUN ────────────────────────────────
→ Opens in browser without errors
→ No console errors (0 critical)
→ No console warnings (0 new)
→ Network tab: all assets load (200 OK)
→ FPS ≥ target (≥30 minimum)
INSPECT CONSOLE ────────────────────
→ Zero errors
→ Zero warnings from our code
→ No deprecated API usage
→ No CORS violations
→ No CSP violations
TEST INTERACTION ───────────────────
→ Click/hover/touch all interactive elements
→ All event handlers fire correctly
→ No duplicate listener warnings
→ Scroll works without jank
TEST BOOT ──────────────────────────
→ Fresh load: BOOT → INITIALIZING → LOADING → RENDERER → READY → ENTERING → ACTIVE
→ Progress bar updates correctly
→ Skip button works from any state
→ Error state triggers correctly on failed asset
TEST SKIP ──────────────────────────
→ Skip from BOOT: works, shows fallback
→ Skip from LOADING_ASSETS: works, shows cached content
→ Skip from INITIALIZING_RENDERER: works, shows static content
→ Skip is idempotent: calling twice = calling once
TEST RESIZE ────────────────────────
→ Window resize: camera aspect updates
→ DPR change: renderer resize triggered
→ Mobile rotate: layout adapts
→ No layout shift (CLS < 0.1)
TEST MOBILE ────────────────────────
→ Touch events work
→ Quality = LOW selected automatically
→ Reduced motion respects prefers-reduced-motion
→ No hover-dependent UI visible
→ Touch target sizes ≥ 44px
TEST PERFORMANCE ───────────────────
→ Performance tab: no long tasks (>50ms)
→ Memory: no leak over 5 min session
→ GPU: no context lost events
→ Frame time: consistent (no spikes)
VISUAL QA ──────────────────────────
→ All layers render in correct order
→ Colors match design specification
→ Typography is legible at all sizes
→ Animations are smooth (60fps target)
→ No visual artifacts, flickering, or tearing
On Failure Protocol
Roll back the last change (git checkout or revert)
Identify the exact cause (not the symptom — trace back)
Modify ONE thing (never multiple changes at once)
Test again (full verification matrix)
Only then proceed to next change
Anti-pattern: Stacking unverified patches. If something breaks, revert and debug one change at a time.
Phase 10 — FINAL ACCEPTANCE
Goal: All success criteria met. "The page loads" is not success.
Acceptance Checklist
Functional: All features work as specified. No bugs. All states handled.
Visually coherent: Design is consistent, colors match, typography is unified.
Performant: All performance budgets met. FPS ≥ target. No jank.
Responsive: Works on desktop, tablet, mobile. Layout adapts correctly.
Accessible: Keyboard navigable, screen-reader friendly, prefers-reduced-motion respected, ARIA labels present.
Maintainable: Clean architecture, documented code, modular structure, tests pass.
Demonstrated through verification loop: All phases 9 tests pass.
Final Deliverable Package
1. Source code (all files, clean, commented)
2. Architecture notes (Architecture Map, Decision Map)
3. Performance report (FPS, memory, frame time metrics)
4. Test results (verification matrix status)
5. Documentation (README, setup instructions, API docs)
6. Assets manifest (all files, sizes, formats)
7. Deployment guide (build commands, hosting config)
Required First Response for Existing Projects
Before writing ANY code, return ONLY:
Architecture Map (Phase 0 output)
Component Decision Map (Phase 1 output)
Failure Modes (CAUSE → EFFECT → FIX from Phase 2)
Target Architecture (Phase 3 output — directory structure)
Implementation Sequence (ordered list of tasks, phase by phase)
Risks (what could go wrong, mitigation strategies)
Then wait for explicit authorization unless the user has already authorized implementation.
Anti-Patterns Catalog (Never Do These)
Anti-Pattern
Why It's Bad
Correct Approach
Using generated still image to replace working canvas
Static content can't respond to interaction
Keep canvas animated, overlay image only as fallback
requestAnimationFrame in multiple modules
Frame conflicts, race conditions, double renders
ONE owned loop, all modules subscribe to it
Hardcoded animation frames (for (let i=0; i<60; i++))
Tied to 60fps, breaks on slow devices
Use clock.getDelta() with parameterized time
Applying transforms to every element calling it "3D"
Visual noise, no depth, no purpose
Only transform elements that serve a visual layer purpose
Removing unknown components without evidence
Destroys potentially valuable code
Mark UNKNOWN, investigate, then decide
setTimeout(() => { render() }, 1000) for loading
Arbitrary, not tied to actual readiness
Use state machine with real asset progress
Memory leaks from unclosed GPU resources
Progressive slowdown, eventual crash
Explicit dispose() on every GPU handle
Ignoring prefers-reduced-motion
Accessibility violation, motion sickness
Always provide reduced-motion fallback
Scaling desktop to mobile (just CSS transform)
Poor touch targets, unreadable UI
Distinct mobile rendering state with LOD
Stacking unverified patches
Hard to debug, cascading failures
One change, verify, then next
Debugging Strategies
Common Issues and Solutions
Canvas is black / white:
Check WebGL context: canvas.getContext('webgl2') — if null, browser doesn't support WebGL2
Check shader compilation: renderer.debug.checkShaderErrors = true
Check scene graph: scene.children.length > 0 — empty scene renders black
Check camera position: camera must be outside the near plane and facing objects
FPS drops suddenly:
Check particle count: scene.children.filter(c => c.isPoints).length
Check shadow map: renderer.shadowMap.enabled — disable if not needed
Check draw calls: renderer.info.render.calls — >100 is suspicious
Check geometry: geometry.attributes.position.count — high vertex counts kill FPS
Memory growing:
Take heap snapshot before and after interaction
Check renderer.info.memory.geometries, textures, programs
Look for detached DOM elements (DevTools Memory panel)
Check for orphaned event listeners (no cleanup on unmount)
Context lost:
Listen: canvas.addEventListener('webglcontextlost', handler)
Save state, stop all loops
Attempt restore: canvas.addEventListener('webglcontextrestored', handler)
Rebuild scene from state snapshot, not from scratch
Shader not compiling:
renderer.debug.checkShaderErrors = true
Check uniform locations: gl.getUniformLocation(program, name) — null means not found
Check attribute locations: same pattern
Verify GLSL version matches renderer (GLSL 300 es for WebGL2)
Tooling Recommendations
Category
Tool
Purpose
Build
Vite
Fast bundling, HMR, TypeScript
Testing
Vitest
Unit/integration tests, fast
Linting
ESLint + TypeScript
Catch errors pre-runtime
Formatting
Prettier
Consistent code style
3D Debug
Three.js Studio / React Three Fiber
Visual scene inspection
Profiling
Chrome DevTools Performance + Memory
FPS, frame time, memory
Network
Chrome DevTools Network
Asset loading, waterfalls
Type Checking
tsc --noEmit
Static analysis
Bundle Analysis
vite build --mode analyze
Bundle size, tree-shaking
Code Templates
Minimal Three.js Scene (Foundation)
import * as THREE from "three";
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: false });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
document.body.appendChild(renderer.domElement);
const clock = new THREE.Clock();
const controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
const animate = () => {
const delta = clock.getDelta();
const time = clock.getElapsedTime();
controls.update();
renderer.render(scene, camera);
requestAnimationFrame(animate);
};
animate();
// Cleanup
window.addEventListener('beforeunload', () => {
renderer.dispose();
controls.dispose();
});
Loading State Machine (Implementation)
const STATES = ['BOOT', 'INITIALIZING', 'LOADING_ASSETS', 'INITIALIZING_RENDERER', 'READY', 'ENTERING', 'ACTIVE', 'RECOVERABLE_ERROR', 'FALLBACK'];
const ALLOWED = {
BOOT: ['INITIALIZING'],
INITIALIZING: ['LOADING_ASSETS', 'RECOVERABLE_ERROR'],
LOADING_ASSETS: ['INITIALIZING_RENDERER', 'RECOVERABLE_ERROR'],
INITIALIZING_RENDERER: ['READY', 'RECOVERABLE_ERROR'],
READY: ['ENTERING'],
ENTERING: ['ACTIVE', 'FALLBACK'],
ACTIVE: ['RECOVERABLE_ERROR'],
RECOVERABLE_ERROR: ['FALLBACK'],
FALLBACK: ['ACTIVE'],
};
class StateMachine {
constructor() { this.state = 'BOOT'; }
async transition(to) {
if (!ALLOWED[this.state]?.includes(to)) throw new Error(`Invalid: ${this.state} → ${to}`);
this.state = to;
this.onEnter(to);
}
}
Quality Adaptation Pattern
function getConfig() {
const isMobile = /Mobi|Android/i.test(navigator.userAgent);
const cores = navigator.hardwareConcurrency || 2;
const quality = isMobile || cores < 4 ? 'LOW' : cores < 8 ? 'MEDIUM' : 'HIGH';
return QUALITY_PRESETS[quality];
}
Compact Checklist
Version History
v3.0 — Added: Quality tiers with budgets, mobile distinct state, accessibility requirements, anti-patterns catalog, debugging strategies, tooling recommendations, code templates, performance budgets table, material hierarchy, error recovery paths, version history
v2.0 — Added: Liquid glass/metal material system, deterministic motion parameters, loading state machine implementation
v1.0 — Original: Observe → Classify → Detect → Architecture → Visual → Material → Motion → Performance → Loading → Verify → Accept
1 --- 2 name: creative-web-algorithm 3 description: >- 4 Build or refactor premium creative-web experiences from an existing codebase using an observe-first execution algorithm. Use for HTML/CSS/JS/WebGL landing pages, SaaS interfaces, parallax, image-to-motion, liquid glass/metal, chromatic effects, canvas scenes, boot state machines, and performance-sensitive interactive frontends. Triggers: "make this page 3D", "add WebGL", "creative landing page", "liquid glass UI", "Three.js scene", "interactive canvas", "parallax website", "SaaS hero section", "webGL portfolio", "shader effects", "particle system web", "chromatic aberration", "motion design web", "boot state machine", "creative web algorithm". 5 metadata: 6 source: https://skillmd.com/skills/belentani7/creative-web-algorithm 7 --- 8 9 # Creative Web Algorithm v3.0 10 11 Transform **STATE A → STATE B** while preserving valid behavior, proving each significant change, and delivering a production-grade experience. Never begin by editing. 12 13 ## Operating Contract (Inviolable) 14 15 1. **Observe before modifying.** Map the entire runtime before touching a single line. 16 2. **Never patch unknown runtimes, exported snapshots, iframes, or minified bundles** until execution model is fully mapped. 17 3. **Component decisions only:** Keep, Refactor, Replace, Remove, or mark Unknown. Never remove without evidence. 18 4. **Strict separation:** `RENDERING ≠ UI ≠ ANIMATION ≠ STATE ≠ ASSETS ≠ PERFORMANCE_POLICY`. Each layer has its own module, its own tests, its own lifecycle. 19 5. **Never claim a feature exists until it has been run and tested** in a real browser. Console + Network + Performance tabs required. 20 6. **Prefer reversible incremental migrations over rewrites.** Every change must be rollbackable in ≤1 commit. 21 7. **If the format prevents reliable development, extract/reconstruct the runtime first.** Stop, diagnose, rebuild the foundation before continuing. 22 8. **One owned render loop. One state machine. One source of truth for scene state.** No orphaned RAF handles, no duplicate loops. 23 9. **Memory is a first-class concern.** Every GPU resource, every listener, every timer must have an explicit disposal path. 24 10. **Accessibility is non-negotiable.** Every visual effect must have a reduced-motion fallback and keyboard/screen-reader equivalent. 25 26 --- 27 28 ## Phase 0 — OBSERVE (Zero Modifications) 29 30 **Goal:** Produce a complete Architecture Map before writing any code. 31 32 ### Scan Checklist 33 34 | Category | What to inspect | Tool | 35 |----------|----------------|------| 36 | **Entry points** | HTML, JS modules, CSS entry, config files | `grep`, `find` | 37 | **Dependencies** | npm packages, CDN imports, dynamic imports | `package.json`, `import` statements | 38 | **DOM structure** | Element tree, canvas elements, iframes | DevTools, `document.querySelectorAll` | 39 | **CSS architecture** | Custom properties, animations, layout system | `grep` for `@keyframes`, `:root` | 40 | **JS modules** | Export/import graph, state management, store patterns | AST analysis | 41 | **Canvas/WebGL** | WebGL context, shader programs, render targets, framebuffers | `WEBGL_debug_renderer_info` | 42 | **Shaders** | Vertex/fragment source, uniform locations, texture bindings | File scan | 43 | **Assets** | Images, fonts, audio, video, models, with sizes and formats | File scan, `ls -lh` | 44 | **Loading/boot** | Sequence order, preloaders, skeleton screens, lazy loading | Code trace | 45 | **Iframes** | Embedded content, cross-origin, postMessage channels | DOM scan | 46 | **CSP** | Content-Security-Policy headers, nonce/hashes, restrictions | Network tab | 47 | **Timers/promises** | setInterval, setTimeout, Promise chains, microtasks | Code scan | 48 | **External resources** | APIs, CDNs, fonts, analytics, tracking | Network tab | 49 | **Event listeners** | Mouse, touch, scroll, keyboard, resize, custom events | Code scan, DevTools | 50 | **Performance** | FPS, frame time, memory, layout thrashing | Performance tab | 51 | **Network** | Requests, waterfalls, caching, compression | Network tab | 52 53 ### Output: Architecture Map 54 55 ```markdown 56 # Architecture Map — [Project Name] 57 58 ## Entry Points 59 - [ ] Primary: [file] → [initialization sequence] 60 - [ ] Secondary: [file] → [purpose] 61 62 ## Module Graph 63 - [module A] imports [B, C] 64 - [module B] exports [X, Y] 65 - [module C] depends on [D, E] 66 67 ## State Management 68 - [ ] Single source of truth: [store/context/prop] 69 - [ ] Derived state: [computed values] 70 - [ ] Side effects: [saga/epic/effect] 71 72 ## Render Architecture 73 - [ ] Primary renderer: [Three.js/Canvas2D/WebGL] 74 - [ ] Secondary renderers: [overlays, post-processing] 75 - [ ] Render loop ownership: [which module] 76 77 ## Asset Pipeline 78 - [ ] Loading strategy: [lazy/eager/prefetch] 79 - [ ] Cache policy: [memory/disk/None] 80 - [ ] Fallback assets: [low-res/progressive] 81 82 ## Performance Profile 83 - [ ] Current FPS: [target/described] 84 - [ ] Memory budget: [bytes] 85 - [ ] Frame budget: [ms] 86 - [ ] Bundle size: [KB] 87 88 ## Known Issues 89 - [ ] [Issue description, evidence, impact] 90 ``` 91 92 ### Dependency Graph (ASCII) 93 ``` 94 [Entry] → [Renderer] → [Scene] → [Camera] 95 ↓ ↓ 96 [PostFX] [Lights] 97 ↓ ↓ 98 [UI Layer] ← [State Store] 99 ↓ 100 [Animation] → [Assets] 101 ``` 102 103 --- 104 105 ## Phase 1 — CLASSIFY 106 107 **Goal:** Create a Component Decision Map with evidence for every component. 108 109 ### Decision Categories 110 111 | Category | Criteria | Action | 112 |----------|----------|--------| 113 | **KEEP** | Functional, valuable, no structural issues | Leave untouched | 114 | **REFACTOR** | Valuable but structurally unsafe, hard to extend, or technically debt | Rewrite internals, preserve API | 115 | **REPLACE** | Unsuitable for target state with concrete evidence | Swap implementation, preserve interface | 116 | **REMOVE** | Redundant, broken, harmful with evidence | Delete + add migration note | 117 | **UNKNOWN** | Insufficient evidence to classify | Investigate → reclassify → act | 118 119 ### Decision Record Format 120 ```markdown 121 ## Component Decision Map 122 123 ### [Component Name] 124 - **Location:** [file:line] 125 - **Current state:** [working/broken/debt] 126 - **Evidence:** [test results, performance metrics, bug reports] 127 - **Decision:** KEEP / REFACTOR / REPLACE / REMOVE / UNKNOWN 128 - **Rationale:** [why this decision] 129 - **Risk if wrong:** [what breaks] 130 - **Reversibility:** [how to undo] 131 132 ### [Next Component] 133 ... 134 ``` 135 136 ### Evidence Requirements 137 - **Performance data:** FPS benchmarks, memory snapshots, frame timing 138 - **Functional tests:** Unit tests passing/failing, integration test results 139 - **User feedback:** Bug reports, support tickets, analytics data 140 - **Code quality:** Cyclomatic complexity, bundle impact, coupling metrics 141 142 --- 143 144 ## Phase 2 — DETECT FAILURE MODES 145 146 **Goal:** For every issue, record `CAUSE → EFFECT → FIX`. Fix causes, not symptoms. 147 148 ### Failure Mode Catalog 149 150 | Failure Mode | CAUSE | EFFECT | FIX | 151 |-------------|-------|--------|-----| 152 | **Infinite/duplicated loops** | RAF not cancelled, recursive setTimeout, missing break condition | CPU spike, battery drain, tab crash | Cancel RAF on unmount, use `useEffect` cleanup, add `requestID` tracking | 153 | **Duplicate listeners** | Event added in render without cleanup, closure scoping bug | Memory leak, double-fire, exponential growth | Use `AbortController`, `removeEventListener`, single subscription pattern | 154 | **Blocking initialization** | Synchronous asset load, blocking script, large bundle parse | White screen >3s, TTI degradation | Code splitting, lazy import, skeleton screen, streaming | 155 | **Failed promises** | Missing `.catch()`, unhandled rejection, race condition | Silent failure, zombie state | Always `.catch()`, use `Promise.allSettled`, add error boundaries | 156 | **Missing assets** | Broken URL, wrong path, CORS restriction | Fallback broken, layout shift | Verify paths, use `onError` handlers, preload critical assets | 157 | **Broken imports** | Circular dependency, missing module, wrong export | Runtime error, blank page | Fix import paths, use `eslint import/no-cycle`, tree-shake | 158 | **iframe/CSP conflicts** | CSP blocks inline scripts, iframe sandbox restrictions | Content blocked, security errors | Adjust CSP headers, use `sandbox` attribute carefully | 159 | **Memory leaks** | Orphaned listeners, unclosed connections, retained references | Gradual slowdown, OOM crash | `WeakRef` for caches, explicit dispose, DevTools memory profiling | 160 | **Excessive DPR** | `devicePixelRatio > 2` on high-DPI screens | GPU memory spike, frame drops | Cap DPR at `Math.min(window.devicePixelRatio, 2)` | 161 | **Reflow/repaint cost** | Layout thrashing, forced synchronous layouts | Jank, >16ms frame time | Batch DOM reads/writes, use `transform`/`opacity` only, `will-change` | 162 | **Runaway particles** | Unbounded particle count, no max cap, no culling | GPU overload, FPS collapse to <10 | Cap count, use LOD, frustum culling, GPU instancing | 163 | **Orphaned GPU resources** | Disposed but not freed textures, unreleased framebuffers | VRAM leak, context lost | Track all GPU handles, explicit `dispose()` on unmount | 164 | **Shader compilation stalls** | Many shaders compiled in one frame, large programs | Frame drop, jank | Precompile during loading, use `THREE.ShaderMaterial` warmup | 165 | **Network waterfall** | Sequential dependencies, unoptimized loading | Long TTI, slow perceived performance | Parallelize, prefetch, use HTTP/2+ push, CDN | 166 167 ### Failure Mode Report 168 ```markdown 169 ## Failure Mode Analysis 170 171 ### F-001: [Title] 172 - **Severity:** Critical / High / Medium / Low 173 - **CAUSE:** [root cause] 174 - **EFFECT:** [observable impact] 175 - **FIX:** [specific solution] 176 - **Evidence:** [data proving this] 177 - **Prevention:** [how to avoid in future] 178 ``` 179 180 --- 181 182 ## Phase 3 — DEFINE TARGET ARCHITECTURE 183 184 **Goal:** Create a maintainable, scalable structure with strict layer separation. 185 186 ### Canonical Directory Structure 187 ```text 188 project/ 189 ├── src/ 190 │ ├── scene/ # Scene graph, objects, entities 191 │ │ ├── index.ts 192 │ │ ├── Camera.ts # Camera management, transitions 193 │ │ ├── Lights.ts # Lighting system 194 │ │ ├── Objects/ # Reusable 3D objects 195 │ │ │ ├── Indexed.ts # Pre-registered geometries 196 │ │ │ └── Materials/ # Material definitions 197 │ │ └── Environment/ # Sky, fog, post-processing 198 │ ├── renderer/ # Renderer configuration, context 199 │ │ ├── index.ts 200 │ │ ├── WebGLContext.ts # Context creation, loss handling 201 │ │ └── PostFX/ # Bloom, SSAO, chromatic, etc. 202 │ ├── shaders/ # GLSL source code 203 │ │ ├── common.glsl 204 │ │ ├── vertex/ 205 │ │ └── fragment/ 206 │ ├── effects/ # Visual effects pipeline 207 │ │ ├── LiquidGlass.ts 208 │ │ ├── Chromatic.ts 209 │ │ ├── Haze.ts 210 │ │ └── Particles.ts 211 │ ├── animation/ # Animation system 212 │ │ ├── Animator.ts # Main animation controller 213 │ │ ├── Tweens.ts # Easing functions 214 │ │ └── Timeline.ts # Sequenced animations 215 │ ├── ui/ # HTML/CSS overlay layer 216 │ │ ├── components/ 217 │ │ ├── styles/ 218 │ │ └── state/ # UI state (separate from scene state) 219 │ ├── assets/ # Static assets, textures, models 220 │ │ ├── textures/ 221 │ │ ├── models/ 222 │ │ └── audio/ 223 │ ├── state/ # Single source of truth for scene state 224 │ │ ├── Store.ts # Centralized state management 225 │ │ └── selectors.ts # Derived state 226 │ ├── utils/ # Shared utilities 227 │ │ ├── math.ts 228 │ │ ├── geometry.ts 229 │ │ └── helpers.ts 230 │ └── main.ts # Entry point, boot sequence 231 ├── tests/ 232 │ ├── unit/ 233 │ ├── integration/ 234 │ └── visual/ 235 ├── public/ 236 │ └── index.html 237 ├── package.json 238 ├── tsconfig.json 239 ├── vite.config.ts 240 └── README.md 241 ``` 242 243 ### Architecture Rules 244 245 1. **`RENDERING ≠ UI ≠ ANIMATION ≠ STATE ≠ ASSETS ≠ PERFORMANCE`** — Each module owns its domain, never crosses boundaries without explicit interfaces. 246 2. **Single source of truth** — Scene state lives in `state/Store.ts`. UI state lives in `ui/state/`. Never duplicate. 247 3. **Renderer is agnostic** — `renderer/` knows nothing about scene content. Scene provides geometries; renderer draws them. 248 4. **Animation is parameterized** — All motion derives from `time`, `delta`, `velocity`, `damping`, `easing`. Never hardcode frame counts. 249 5. **Assets are lazy** — Load on demand. Preload only critical path (<100KB). 250 6. **Effects are composable** — PostFX pipeline is a chain. Add/remove without affecting core render. 251 7. **Cleanup is mandatory** — Every module exports `dispose()`. Call it on unmount/context loss. 252 253 --- 254 255 ## Phase 4 — BUILD THE VISUAL SYSTEM 256 257 **Goal:** Create a layered scene graph with explicit depth, parallax, and motion policy. 258 259 ### Scene Graph Layers (Front to Back) 260 ``` 261 ┌─────────────────────────────────┐ 262 │ UI LAYER │ ← HTML/CSS overlay, interactive controls 263 │ ───────────────────────────── │ 264 │ INTERACTION LAYER │ ← Raycasting, pointer events, hover 265 │ ───────────────────────────── │ 266 │ PARTICLES LAYER │ ← Atmospheric particles, ambient 267 │ ───────────────────────────── │ 268 │ SUBJECT LAYER │ ← Main 3D object, hero geometry 269 │ ───────────────────────────── │ 270 │ LIGHTING LAYER │ → Reflections, shadows, glow 271 │ ───────────────────────────── │ 272 │ ENVIRONMENT LAYER │ → Sky, fog, ground, skybox 273 │ ───────────────────────────── │ 274 │ DEPTH LAYERS │ → Parallax planes, background depth 275 │ ───────────────────────────── │ 276 │ ATMOSPHERE LAYER │ → Haze, fog, volumetric light 277 │ ───────────────────────────── │ 278 │ BACKGROUND LAYER │ → Solid color, gradient, gradient 279 └─────────────────────────────────┘ 280 ``` 281 282 ### Layer Configuration 283 Each layer has explicit properties: 284 ```typescript 285 interface LayerConfig { 286 name: string; 287 depth: number; // 0.0 (back) to 1.0 (front) 288 parallaxCoefficient: number; // 0.0 (static) to 1.0 (follows pointer) 289 motionPolicy: 'static' | 'parallax' | 'animated' | 'interactive'; 290 opacity: number; // 0.0 to 1.0 291 visible: boolean; 292 quality: 'high' | 'medium' | 'low'; 293 } 294 ``` 295 296 ### Parameterized Inputs 297 Route these same inputs to ALL visual layers: 298 - `time` — `clock.getElapsedTime()` — drives all animations 299 - `pointer` — `mouse.x, mouse.y` — drives parallax, hover, interaction 300 - `viewport` — `window.innerWidth/innerHeight` — drives resolution, scale 301 - `scroll` — `window.scrollY` — drives depth, reveals, transitions 302 - `delta` — `clock.getDelta()` — drives frame-rate-independent motion 303 304 **Anti-pattern:** Applying arbitrary transforms to every element and calling it "3D". Every transform must serve a visual purpose documented in the layer config. 305 306 --- 307 308 ## Phase 5 — BUILD THE MATERIAL SYSTEM SELECTIVELY 309 310 **Goal:** Choose materials hierarchically. Every effect must earn its place. 311 312 ### Material Hierarchy 313 314 **Primary (One Dominant Effect):** 315 Choose ONE primary visual identity: 316 - **Liquid Glass:** `MeshPhysicalMaterial` with `transmission: 0.85`, `thickness: 0.5`, `ior: 1.5`, `clearcoat: 1.0`, `roughness: 0.05`. Creates refractive, reflective surfaces. 317 - **Liquid Metal:** `MeshPhysicalMaterial` with `metalness: 1.0`, `roughness: 0.0`, `color: [theme]`, `envMapIntensity: 2.0`. Creates mirror-like metallic surfaces. 318 - **Ethereal:** `MeshStandardMaterial` with `emissive`, `transparent`, `opacity: 0.3`, `wireframe: true`. Creates ghostly, sci-fi surfaces. 319 - **Neon Glow:** `MeshBasicMaterial` with `emissive`, `emissiveIntensity: 2.0`, `transparent: true`, `opacity: 0.8`. Creates glowing, holographic surfaces. 320 321 **Secondary (Supporting Effects):** 322 - **Reflection/Refraction:** Environment maps, `cubeCamera`, `refractionRatio` 323 - **Fresnel:** `FresnelMaterial` or custom shader with `dot(normal, viewDir)` 324 - **Displacement:** `displacementMap`, `displacementScale`, vertex displacement 325 - **Chromatic:** Custom shader with RGB channel offset based on view angle 326 327 **Atmospheric (Global Effects):** 328 - **Bloom:** `UnrealBloomPass` — strength 0.5-1.5, radius 0.4, threshold 0.85 329 - **Light Scatter:** `LensFlare`, `sprite` glow, `AdditiveBlending` 330 - **Haze:** `FogExp2` or custom depth-based fog 331 - **RGB Shift:** Custom post-process shader with chromatic aberration offset 332 333 ### Material Decision Rules 334 1. **Never use a generated still image to cover or replace an existing animated canvas** unless explicitly requested by the user. 335 2. **Remove effects that do not improve composition.** If a bloom pass doesn't add visual value, remove it. If a chromatic effect distracts from the subject, kill it. 336 3. **One primary effect.** Supporting effects only earn their place if they enhance the primary without competing. 337 4. **Performance budget:** Primary material <2 shader compiles. Total post-processing <3 passes. 338 339 ### Liquid Glass Implementation Template 340 ```glsl 341 // Fragment shader for liquid glass 342 uniform float uTime; 343 uniform float uTransmission; 344 uniform vec3 uColor; 345 uniform float uIOR; 346 347 void main() { 348 vec3 viewDir = normalize(vViewPosition); 349 vec3 normal = normalize(vNormal); 350 351 // Fresnel for edge glow 352 float fresnel = pow(1.0 - dot(viewDir, normal), 3.0); 353 354 // Transmission for refraction 355 vec3 refracted = texture2D(uTransmissionMap, vUv).rgb; 356 vec3 transmitted = mix(uColor, refracted, uTransmission); 357 358 // Edge glow 359 vec3 edgeGlow = vec3(0.0, 0.9, 0.97) * fresnel * 0.5; 360 361 gl_FragColor = vec4(transmitted + edgeGlow, 0.85 + fresnel * 0.15); 362 } 363 ``` 364 365 --- 366 367 ## Phase 6 — BUILD DETERMINISTIC MOTION 368 369 **Goal:** All motion derives from parameterized inputs. Never hardcoded values. 370 371 ### Motion Parameter System 372 ```typescript 373 interface MotionParams { 374 velocity: number; // Base speed (units/sec) 375 acceleration: number; // Rate of change of velocity 376 damping: number; // Friction/decay (0-1) 377 easing: 'linear' | 'easeIn' | 'easeOut' | 'easeInOut' | 'elastic' | 'bounce'; 378 depth: number; // Z-depth parallax coefficient 379 amplitude: number; // Max displacement 380 frequency: number; // Oscillations per second 381 phase: number; // Time offset 382 } 383 ``` 384 385 ### Routing Protocol 386 All inputs MUST route to ALL relevant transforms: 387 ``` 388 [time] → camera.transform, layer.transform, shader.uniforms, lighting.position, particle.velocity, UI.transition 389 [pointer] → camera.position (parallax), layer.parallax, object.rotation (follow) 390 [scroll] → camera.position (depth), layer.opacity (reveal), object.scale (approach) 391 [viewport] → renderer.dpr, camera.aspect, object.scale (responsive) 392 ``` 393 394 ### Animation Loop Contract 395 ```typescript 396 // ONE owned loop per renderer 397 class AnimationLoop { 398 private rafId: number | null = null; 399 private lastTime = 0; 400 401 start() { 402 const tick = (timestamp: number) => { 403 const delta = timestamp - this.lastTime; 404 this.lastTime = timestamp; 405 this.update(delta, timestamp); 406 this.rafId = requestAnimationFrame(tick); 407 }; 408 this.rafId = requestAnimationFrame(tick); 409 } 410 411 stop() { 412 if (this.rafId !== null) { 413 cancelAnimationFrame(this.rafId); 414 this.rafId = null; 415 } 416 } 417 418 private update(delta: number, timestamp: number) { 419 // Route delta to ALL systems: 420 this.scene.update(delta); 421 this.ui.update(delta); 422 this.particles.update(delta); 423 this.camera.update(delta); 424 } 425 426 dispose() { 427 this.stop(); 428 // Clean up all listeners, observers, GPU resources 429 } 430 } 431 ``` 432 433 **Rules:** 434 - Use `requestAnimationFrame` only through this ONE owned loop. 435 - Never create additional `setTimeout`, `setInterval`, or secondary RAF loops. 436 - Always provide `dispose()` that cleans up listeners, RAF handles, observers, and GPU resources. 437 - Use `clock.getDelta()` for frame-rate-independent motion. Never assume 60fps. 438 439 --- 440 441 ## Phase 7 — ENFORCE PERFORMANCE 442 443 **Goal:** Adaptive quality with explicit budgets and mobile-specific states. 444 445 ### Quality Tiers 446 ```typescript 447 enum Quality { HIGH = 'high', MEDIUM = 'medium', LOW = 'low' } 448 449 interface QualityConfig { 450 dpr: number; // 2, 1.5, 1 451 resolution: number; // 1, 0.75, 0.5 452 particleCount: number; // 10000, 5000, 1000 453 shadowMap: { size: number, enabled: boolean }; // 2048/1024/512 454 postProcessing: { bloom: boolean, ssao: boolean, chromatic: boolean }; 455 animationFrequency: number; // 60, 30, 15 fps cap 456 textureSize: number; // 1024, 512, 256 457 geometryDetail: number; // high/medium/low segment counts 458 } 459 ``` 460 461 ### Quality Selection Logic 462 ```typescript 463 function selectQuality(): Quality { 464 const cores = navigator.hardwareConcurrency || 2; 465 const memory = (navigator as any).deviceMemory || 4; 466 const dpr = Math.min(window.devicePixelRatio, 2); 467 const isMobile = /Mobi|Android/i.test(navigator.userAgent); 468 const fps = getBaselineFPS(); // Measure initial FPS 469 470 if (isMobile || cores < 4 || memory < 4 || fps < 30) return Quality.LOW; 471 if (cores < 8 || memory < 8 || dpr > 1.5 || fps < 45) return Quality.MEDIUM; 472 return Quality.HIGH; 473 } 474 ``` 475 476 ### Degradation Cascade (Priority Order) 477 When performance degrades, reduce in this order: 478 1. **Atmospheric effects first** — bloom, haze, fog 479 2. **Particles second** — reduce count, simplify shader 480 3. **Shader resolution third** — lower texture sizes, fewer segments 481 4. **Preserve the primary composition** — the hero object must remain visible and coherent 482 483 ### Performance Budgets 484 | Metric | HIGH | MEDIUM | LOW | Budget | 485 |--------|------|--------|-----|--------| 486 | Target FPS | 60 | 45 | 30 | ≥30 | 487 | Frame Time | ≤16ms | ≤22ms | ≤33ms | <33ms | 488 | Draw Calls | <100 | <50 | <25 | <50 | 489 | Triangles | <500k | <200k | <50k | <200k | 490 | Textures | 10MB | 5MB | 2MB | <10MB | 491 | Bundle | 500KB | 300KB | 150KB | <500KB | 492 | GPU Memory | <500MB | <250MB | <100MB | <500MB | 493 494 ### Mobile State 495 Mobile is a **distinct lower-cost rendering state**, not merely a scaled desktop: 496 - Different geometry LODs (not just scaled down) 497 - Different particle systems (points vs. sprites) 498 - Different post-processing pipeline (no bloom on mobile) 499 - Touch-optimized interaction (no hover-dependent UI) 500 - Reduced shadow quality (no real-time shadows on LOW) 501 502 --- 503 504 ## Phase 8 — REAL LOADING STATE MACHINE 505 506 **Goal:** Explicit, deterministic loading with no arbitrary timeouts. 507 508 ### State Machine 509 ``` 510 ┌─────────────┐ 511 │ BOOT │ ← Entry point, initialize globals 512 └──────┬──────┘ 513 ↓ 514 ┌──────────────┐ 515 │INITIALIZING │ ← Setup modules, validate dependencies 516 └──────┬───────┘ 517 ↓ 518 ┌─────────────────┐ 519 │LOADING_ASSETS │ ← Load textures, models, audio, fonts 520 │(with progress) │ ← Report progress to UI 521 └──────┬──────────┘ 522 ↓ 523 ┌───────────────────────┐ 524 │INITIALIZING_RENDERER │ ← Create WebGL context, compile shaders 525 └──────┬────────────────┘ 526 ↓ 527 ┌────────────┐ 528 │ READY │ ← All assets loaded, renderer initialized 529 └──────┬─────┘ 530 ↓ 531 ┌────────────┐ 532 │ ENTERING │ ← First render, transition in 533 └──────┬─────┘ 534 ↓ 535 ┌────────────┐ 536 │ ACTIVE │ ← Full interactive experience 537 └────┬───────┘ 538 ↓ (from any state) 539 ┌─────────────────┐ 540 │RECOVERABLE_ERROR│ ← Asset failed, context lost, etc. 541 └──────┬──────────┘ 542 ↓ 543 ┌────────────┐ 544 │ FALLBACK │ ← Graceful degradation, cached content, error UI 545 └──────┬─────┘ 546 ↓ (user action / retry) 547 ┌────────────┐ 548 │ ACTIVE │ ← Retry successful 549 └────────────┘ 550 551 SPECIAL: ENTERING → ACTIVE (skip, if no transition needed) 552 ``` 553 554 ### State Implementation 555 ```typescript 556 class LoadingStateMachine { 557 state: State = 'BOOT'; 558 progress: number = 0; 559 errors: Error[] = []; 560 561 async transition(to: State) { 562 const valid = this.allowedTransitions[this.state]; 563 if (!valid.includes(to)) throw new Error(`Invalid transition: ${this.state} → ${to}`); 564 this.state = to; 565 this.onStateChange(to); 566 } 567 568 async loadAssets(urls: string[], onProgress: (p: number) => void) { 569 await this.transition('LOADING_ASSETS'); 570 const results = await Promise.allSettled( 571 urls.map(url => fetch(url).then(r => r.blob())) 572 ); 573 // Handle partial failures gracefully 574 const successes = results.filter(r => r.status === 'fulfilled'); 575 const failures = results.filter(r => r.status === 'rejected'); 576 if (failures.length > 0 && successes.length === 0) { 577 await this.transition('RECOVERABLE_ERROR'); 578 } 579 this.progress = successes.length / urls.length; 580 } 581 582 // skip is ALWAYS safe and idempotent 583 skip() { 584 this.transition('ACTIVE'); // or FALLBACK if assets not loaded 585 } 586 } 587 ``` 588 589 ### Rules 590 - **Advance on actual asset/renderer readiness**, never an arbitrary timeout 591 - **Display actionable errors** — "Failed to load texture X. Retry?" not "Error 404" 592 - **Skip is always safe and idempotent** — calling skip twice does nothing bad 593 - **Enter → Active can skip** if assets are cached (service worker) 594 - **Any state → Recoverable Error → Fallback → Active** for error recovery 595 596 --- 597 598 ## Phase 9 — VERIFY AFTER EVERY SIGNIFICANT CHANGE 599 600 **Goal:** Run the full verification matrix. Never stack unverified patches. 601 602 ### Verification Matrix 603 ``` 604 BUILD ────────────────────────────── 605 → tsc --noEmit (or equivalent) 606 → Rollup/Vite build succeeds 607 → No TypeScript errors 608 → No bundler warnings 609 610 RUN ──────────────────────────────── 611 → Opens in browser without errors 612 → No console errors (0 critical) 613 → No console warnings (0 new) 614 → Network tab: all assets load (200 OK) 615 → FPS ≥ target (≥30 minimum) 616 617 INSPECT CONSOLE ──────────────────── 618 → Zero errors 619 → Zero warnings from our code 620 → No deprecated API usage 621 → No CORS violations 622 → No CSP violations 623 624 TEST INTERACTION ─────────────────── 625 → Click/hover/touch all interactive elements 626 → All event handlers fire correctly 627 → No duplicate listener warnings 628 → Scroll works without jank 629 630 TEST BOOT ────────────────────────── 631 → Fresh load: BOOT → INITIALIZING → LOADING → RENDERER → READY → ENTERING → ACTIVE 632 → Progress bar updates correctly 633 → Skip button works from any state 634 → Error state triggers correctly on failed asset 635 636 TEST SKIP ────────────────────────── 637 → Skip from BOOT: works, shows fallback 638 → Skip from LOADING_ASSETS: works, shows cached content 639 → Skip from INITIALIZING_RENDERER: works, shows static content 640 → Skip is idempotent: calling twice = calling once 641 642 TEST RESIZE ──────────────────────── 643 → Window resize: camera aspect updates 644 → DPR change: renderer resize triggered 645 → Mobile rotate: layout adapts 646 → No layout shift (CLS < 0.1) 647 648 TEST MOBILE ──────────────────────── 649 → Touch events work 650 → Quality = LOW selected automatically 651 → Reduced motion respects prefers-reduced-motion 652 → No hover-dependent UI visible 653 → Touch target sizes ≥ 44px 654 655 TEST PERFORMANCE ─────────────────── 656 → Performance tab: no long tasks (>50ms) 657 → Memory: no leak over 5 min session 658 → GPU: no context lost events 659 → Frame time: consistent (no spikes) 660 661 VISUAL QA ────────────────────────── 662 → All layers render in correct order 663 → Colors match design specification 664 → Typography is legible at all sizes 665 → Animations are smooth (60fps target) 666 → No visual artifacts, flickering, or tearing 667 ``` 668 669 ### On Failure Protocol 670 1. **Roll back the last change** (`git checkout` or revert) 671 2. **Identify the exact cause** (not the symptom — trace back) 672 3. **Modify ONE thing** (never multiple changes at once) 673 4. **Test again** (full verification matrix) 674 5. **Only then proceed** to next change 675 676 **Anti-pattern:** Stacking unverified patches. If something breaks, revert and debug one change at a time. 677 678 --- 679 680 ## Phase 10 — FINAL ACCEPTANCE 681 682 **Goal:** All success criteria met. "The page loads" is not success. 683 684 ### Acceptance Checklist 685 - [ ] **Functional:** All features work as specified. No bugs. All states handled. 686 - [ ] **Visually coherent:** Design is consistent, colors match, typography is unified. 687 - [ ] **Performant:** All performance budgets met. FPS ≥ target. No jank. 688 - [ ] **Responsive:** Works on desktop, tablet, mobile. Layout adapts correctly. 689 - [ ] **Accessible:** Keyboard navigable, screen-reader friendly, `prefers-reduced-motion` respected, ARIA labels present. 690 - [ ] **Maintainable:** Clean architecture, documented code, modular structure, tests pass. 691 - [ ] **Demonstrated through verification loop:** All phases 9 tests pass. 692 693 ### Final Deliverable Package 694 ``` 695 1. Source code (all files, clean, commented) 696 2. Architecture notes (Architecture Map, Decision Map) 697 3. Performance report (FPS, memory, frame time metrics) 698 4. Test results (verification matrix status) 699 5. Documentation (README, setup instructions, API docs) 700 6. Assets manifest (all files, sizes, formats) 701 7. Deployment guide (build commands, hosting config) 702 ``` 703 704 --- 705 706 ## Required First Response for Existing Projects 707 708 **Before writing ANY code, return ONLY:** 709 710 1. **Architecture Map** (Phase 0 output) 711 2. **Component Decision Map** (Phase 1 output) 712 3. **Failure Modes** (`CAUSE → EFFECT → FIX` from Phase 2) 713 4. **Target Architecture** (Phase 3 output — directory structure) 714 5. **Implementation Sequence** (ordered list of tasks, phase by phase) 715 6. **Risks** (what could go wrong, mitigation strategies) 716 717 **Then wait for explicit authorization unless the user has already authorized implementation.** 718 719 --- 720 721 ## Anti-Patterns Catalog (Never Do These) 722 723 | Anti-Pattern | Why It's Bad | Correct Approach | 724 |-------------|-------------|-----------------| 725 | Using `generated still image` to replace working canvas | Static content can't respond to interaction | Keep canvas animated, overlay image only as fallback | 726 | `requestAnimationFrame` in multiple modules | Frame conflicts, race conditions, double renders | ONE owned loop, all modules subscribe to it | 727 | Hardcoded animation frames (`for (let i=0; i<60; i++)`) | Tied to 60fps, breaks on slow devices | Use `clock.getDelta()` with parameterized time | 728 | Applying transforms to every element calling it "3D" | Visual noise, no depth, no purpose | Only transform elements that serve a visual layer purpose | 729 | Removing unknown components without evidence | Destroys potentially valuable code | Mark UNKNOWN, investigate, then decide | 730 | `setTimeout(() => { render() }, 1000)` for loading | Arbitrary, not tied to actual readiness | Use state machine with real asset progress | 731 | Memory leaks from unclosed GPU resources | Progressive slowdown, eventual crash | Explicit `dispose()` on every GPU handle | 732 | Ignoring `prefers-reduced-motion` | Accessibility violation, motion sickness | Always provide reduced-motion fallback | 733 | Scaling desktop to mobile (just CSS transform) | Poor touch targets, unreadable UI | Distinct mobile rendering state with LOD | 734 | Stacking unverified patches | Hard to debug, cascading failures | One change, verify, then next | 735 736 --- 737 738 ## Debugging Strategies 739 740 ### Common Issues and Solutions 741 742 **Canvas is black / white:** 743 1. Check WebGL context: `canvas.getContext('webgl2')` — if null, browser doesn't support WebGL2 744 2. Check shader compilation: `renderer.debug.checkShaderErrors = true` 745 3. Check scene graph: `scene.children.length > 0` — empty scene renders black 746 4. Check camera position: camera must be outside the near plane and facing objects 747 748 **FPS drops suddenly:** 749 1. Check particle count: `scene.children.filter(c => c.isPoints).length` 750 2. Check shadow map: `renderer.shadowMap.enabled` — disable if not needed 751 3. Check draw calls: `renderer.info.render.calls` — >100 is suspicious 752 4. Check geometry: `geometry.attributes.position.count` — high vertex counts kill FPS 753 754 **Memory growing:** 755 1. Take heap snapshot before and after interaction 756 2. Check `renderer.info.memory.geometries`, `textures`, `programs` 757 3. Look for detached DOM elements (DevTools Memory panel) 758 4. Check for orphaned event listeners (no cleanup on unmount) 759 760 **Context lost:** 761 1. Listen: `canvas.addEventListener('webglcontextlost', handler)` 762 2. Save state, stop all loops 763 3. Attempt restore: `canvas.addEventListener('webglcontextrestored', handler)` 764 4. Rebuild scene from state snapshot, not from scratch 765 766 **Shader not compiling:** 767 1. `renderer.debug.checkShaderErrors = true` 768 2. Check uniform locations: `gl.getUniformLocation(program, name)` — null means not found 769 3. Check attribute locations: same pattern 770 4. Verify GLSL version matches renderer (GLSL 300 es for WebGL2) 771 772 --- 773 774 ## Tooling Recommendations 775 776 | Category | Tool | Purpose | 777 |----------|------|---------| 778 | **Build** | Vite | Fast bundling, HMR, TypeScript | 779 | **Testing** | Vitest | Unit/integration tests, fast | 780 | **Linting** | ESLint + TypeScript | Catch errors pre-runtime | 781 | **Formatting** | Prettier | Consistent code style | 782 | **3D Debug** | Three.js Studio / React Three Fiber | Visual scene inspection | 783 | **Profiling** | Chrome DevTools Performance + Memory | FPS, frame time, memory | 784 | **Network** | Chrome DevTools Network | Asset loading, waterfalls | 785 | **Type Checking** | `tsc --noEmit` | Static analysis | 786 | **Bundle Analysis** | `vite build --mode analyze` | Bundle size, tree-shaking | 787 788 --- 789 790 ## Code Templates 791 792 ### Minimal Three.js Scene (Foundation) 793 ```javascript 794 import * as THREE from "three"; 795 796 const scene = new THREE.Scene(); 797 const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000); 798 const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: false }); 799 renderer.setSize(window.innerWidth, window.innerHeight); 800 renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)); 801 document.body.appendChild(renderer.domElement); 802 803 const clock = new THREE.Clock(); 804 const controls = new OrbitControls(camera, renderer.domElement); 805 controls.enableDamping = true; 806 807 const animate = () => { 808 const delta = clock.getDelta(); 809 const time = clock.getElapsedTime(); 810 controls.update(); 811 renderer.render(scene, camera); 812 requestAnimationFrame(animate); 813 }; 814 animate(); 815 816 // Cleanup 817 window.addEventListener('beforeunload', () => { 818 renderer.dispose(); 819 controls.dispose(); 820 }); 821 ``` 822 823 ### Loading State Machine (Implementation) 824 ```javascript 825 const STATES = ['BOOT', 'INITIALIZING', 'LOADING_ASSETS', 'INITIALIZING_RENDERER', 'READY', 'ENTERING', 'ACTIVE', 'RECOVERABLE_ERROR', 'FALLBACK']; 826 const ALLOWED = { 827 BOOT: ['INITIALIZING'], 828 INITIALIZING: ['LOADING_ASSETS', 'RECOVERABLE_ERROR'], 829 LOADING_ASSETS: ['INITIALIZING_RENDERER', 'RECOVERABLE_ERROR'], 830 INITIALIZING_RENDERER: ['READY', 'RECOVERABLE_ERROR'], 831 READY: ['ENTERING'], 832 ENTERING: ['ACTIVE', 'FALLBACK'], 833 ACTIVE: ['RECOVERABLE_ERROR'], 834 RECOVERABLE_ERROR: ['FALLBACK'], 835 FALLBACK: ['ACTIVE'], 836 }; 837 838 class StateMachine { 839 constructor() { this.state = 'BOOT'; } 840 async transition(to) { 841 if (!ALLOWED[this.state]?.includes(to)) throw new Error(`Invalid: ${this.state} → ${to}`); 842 this.state = to; 843 this.onEnter(to); 844 } 845 } 846 ``` 847 848 ### Quality Adaptation Pattern 849 ```javascript 850 function getConfig() { 851 const isMobile = /Mobi|Android/i.test(navigator.userAgent); 852 const cores = navigator.hardwareConcurrency || 2; 853 const quality = isMobile || cores < 4 ? 'LOW' : cores < 8 ? 'MEDIUM' : 'HIGH'; 854 return QUALITY_PRESETS[quality]; 855 } 856 ``` 857 858 --- 859 860 ## Compact Checklist 861 862 - [ ] **Observe before modify** — Architecture Map complete 863 - [ ] **Extract runtime** if snapshot/iframe/CSP prevents reliable work 864 - [ ] **One renderer loop, one state machine, explicit cleanup** — No orphaned resources 865 - [ ] **No static hero replacing working motion** — Everything animated or has purpose 866 - [ ] **One primary visual effect; supporting effects earn their place** — Material hierarchy respected 867 - [ ] **Adaptive quality and mobile state** — Not just scaled desktop 868 - [ ] **Boot/skip/error/resize/mobile tested** — Full verification matrix 869 - [ ] **Console and performance checked** — Zero errors, FPS on target 870 - [ ] **Accessible** — reduced-motion, keyboard, ARIA 871 - [ ] **Deliver source plus architecture notes when useful** — Documentation complete 872 873 --- 874 875 ## Version History 876 877 - **v3.0** — Added: Quality tiers with budgets, mobile distinct state, accessibility requirements, anti-patterns catalog, debugging strategies, tooling recommendations, code templates, performance budgets table, material hierarchy, error recovery paths, version history 878 - **v2.0** — Added: Liquid glass/metal material system, deterministic motion parameters, loading state machine implementation 879 - **v1.0** — Original: Observe → Classify → Detect → Architecture → Visual → Material → Motion → Performance → Loading → Verify → Accept