Solshine commited on
Commit
df566cb
·
verified ·
1 Parent(s): 510c797

Upload folder using huggingface_hub

Browse files
.claude/handoff.md ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Hyperspace Jam Lyria — Session Handoff (2026-03-23)
2
+
3
+ ## STATUS: Working locally, audio streaming confirmed, ready for user testing
4
+
5
+ ### What's Done
6
+ - Full architecture: Python backend (FastAPI) + modified frontend
7
+ - Lyria RealTime API integration verified and streaming 48kHz stereo PCM audio
8
+ - Qwen 3.5 0.8B gesture interpretation with conversation history (6-turn memory)
9
+ - Groove lock: music doesn't change when hands are still
10
+ - Two-tier change detection (gradual evolve vs dramatic direction change)
11
+ - HIGH hands = ethereal ambient, LOW hands = heavy nasty DnB
12
+ - Binary WebSocket frames for efficient PCM audio transfer (384KB/chunk, every 2s)
13
+ - DrumManager stubbed (Lyria handles all music)
14
+ - Tone.js replaced with minimal shim in game.js
15
+ - `.env` for local API key, `.gitignore` in place
16
+ - Comprehensive README with full architecture docs
17
+
18
+ ### What's NOT Done
19
+ - Private GitHub repo not yet created (still local copy at C:\Users\caleb\hyperspace-jam-lyria)
20
+ - Private HF Space not yet created
21
+ - No automated tests
22
+ - Lyria 10-minute session limit not handled (no auto-reconnect)
23
+ - HF Spaces deployment config (Dockerfile) not created
24
+ - No git commits yet
25
+ - Gemini review not requested (no PR yet)
26
+
27
+ ### To Resume Testing
28
+ ```bash
29
+ cd /c/Users/caleb/hyperspace-jam-lyria
30
+ source .venv/Scripts/activate
31
+ python -u backend/server.py
32
+ # Open http://localhost:8088
33
+ # Allow webcam, click to init audio, wave hands
34
+ ```
35
+
36
+ ### Key Files Modified from Original
37
+ - `MusicManager.js` — complete rewrite (Lyria WebSocket client + Web Audio PCM playback)
38
+ - `DrumManager.js` — complete rewrite (stub with Map-based interface)
39
+ - `game.js` — line 222: Tone.js import replaced with shim
40
+ - `index.html` — title updated
41
+ - `README.md` — complete rewrite
42
+ - `backend/` — all new (server.py, lyria_manager.py, gesture_interpreter.py, requirements.txt)
43
+ - `.env` — Gemini API key (gitignored)
44
+ - `.gitignore` — new
45
+ - `start.sh` — convenience launcher
46
+
47
+ ### Bugs Fixed During Session
48
+ 1. DrumManager `getActiveDrums()` returned plain object, game.js expected Map
49
+ 2. GEMINI_API_KEY not loading from .env — path resolution with `os.path.abspath(__file__)`
50
+ 3. `os.environ.setdefault` didn't override empty string
51
+ 4. Lyria context manager getting GC'd (connection closing instantly) — store `_ctx_manager` ref
52
+ 5. WebSocket `receive_text()` crashing on binary frames — use `websocket.receive()` dict
53
+ 6. Audio arriving as Blob not ArrayBuffer in browser — added Blob fallback handler
54
+ 7. Qwen 3.5 0.8B using all tokens on thinking — `think: False` in Ollama API
55
+
56
+ ### Architecture
57
+ ```
58
+ Browser (MediaPipe -> game.js -> MusicManager.js)
59
+ WebSocket (gesture JSON up, PCM binary down)
60
+ Python Backend (FastAPI)
61
+ -> Qwen 3.5 0.8B (Ollama, gesture->prompt, every 3s when hands move)
62
+ -> Lyria RealTime (google-genai SDK, streaming audio)
63
+ ```
.claude/vision-reference.md ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Hyperspace Jam — Vision Reference: Dynamic Geometric Shapes with Internal Hyperbolic Tessellation
2
+
3
+ ## Source
4
+ Instagram reel: https://www.instagram.com/reel/DTYN4uwCtuG/
5
+ Described by video analysis agent 2026-03-22.
6
+
7
+ ## Core Interaction Model
8
+
9
+ ### Dynamic Anchor Points
10
+ - **Pinch gesture** (thumb + index touching) = single anchor point
11
+ - **2 anchors** = line (two parallel lines connecting points)
12
+ - **3 anchors** = triangle
13
+ - **4 anchors** = quadrilateral
14
+ - System smoothly transitions between states as anchors are added/removed
15
+
16
+ ### Anchor Sources
17
+ - Thumb tip (landmark 4)
18
+ - Index tip (landmark 8)
19
+ - Middle tip (landmark 12)
20
+ - Pinch = thumb+index merged into one point
21
+ - Both hands can contribute anchors simultaneously
22
+
23
+ ### Shape Rendering (Layer 1: Wireframe)
24
+ - **Nodes**: Small hollow white squares with solid white dot center
25
+ - **Edges**: Crisp solid white lines connecting nodes
26
+ - **Z-depth**: Line thickness and node size scale inversely with distance from camera
27
+ - Close to camera = thick lines, large nodes
28
+ - Far from camera = thin lines, small nodes
29
+ - No physics/gravity — pure tension between tracked points
30
+
31
+ ## Internal Visualization (Layer 2: Hyperbolic Geometry)
32
+
33
+ ### When a closed shape forms (held > ~0.2s):
34
+ - Internal space fills with **Poincaré disk tessellation**
35
+ - Central focal point inside the shape
36
+ - Tessellating shapes get smaller and denser toward edges (hyperbolic compression)
37
+ - Pattern dynamically re-tessellates as shape morphs with finger movement
38
+
39
+ ### Shape-specific tessellations:
40
+ - **Line**: 1D hyperbolic waves and interference rings between parallel lines
41
+ - **Triangle**: Triangle-based Poincaré tessellation with central singularity
42
+ - **Quadrilateral**: Quad-based tiling (e.g., {4,5} non-Euclidean tiling)
43
+
44
+ ### Dynamic behavior:
45
+ - Pattern scales and re-tessellates in real-time as fingers move
46
+ - Stretching fingers = tessellation scales, colors intensify
47
+ - Collapsing shape = reverse singularity wink-out effect
48
+
49
+ ## Psychedelic Coloring (Layer 3: DMT-Chrome)
50
+
51
+ ### Color palette:
52
+ - Deep blues, electric purples, neon pinks, vibrant greens
53
+ - Iridescent shifting between colors (not static)
54
+ - Colors flow along curved non-Euclidean geometry toward focal point
55
+
56
+ ### Effects:
57
+ - Biological pulsation rhythm (edges flare brighter at peaks)
58
+ - Fractal particles drift from nodes during transitions
59
+ - Maximum stretch = most intense iridescence
60
+ - Close to camera = overwhelming magenta/turquoise flares
61
+
62
+ ## Audio Hooks
63
+ - Shape proximity to camera → distortion/low-pass filter
64
+ - Close = distorted/filtered, far = clear
65
+ - Pattern complexity peak synced with audio distortion peak
66
+ - Pulsation rhythm could sync with beat
67
+
68
+ ## Multiplayer Jam Session (3+ hands detected)
69
+
70
+ ### Core Concept
71
+ When MediaPipe detects more than 2 hands, the system enters **multiplayer jam mode**. Each player pair gets distinct musical roles that complement each other — not just duplicates.
72
+
73
+ ### Player Role Assignment
74
+ - **Player 1 (hands 0-1)**: Treble / Lead — higher octave range (C3-C6), brighter synth presets, faster arpeggio patterns
75
+ - **Player 2 (hands 2-3)**: Bass / Foundation — lower octave range (C1-C3), deeper presets (Acid Bass, sub-sine), slower patterns, heavier reverb
76
+ - Could also split as: melodic vs rhythmic, or arp vs pad
77
+
78
+ ### Musical Separation Strategy
79
+ - Each player pair routes through its own PolySynth instance with distinct preset
80
+ - Separate effects chains (Player 1: bright delay, Player 2: deep reverb)
81
+ - Octave offset so they naturally harmonize rather than clash
82
+ - Same scale (C Minor Pentatonic) but different registers = instant musical compatibility
83
+ - BPM is shared — both players lock to the same Transport clock
84
+
85
+ ### Visual Differentiation
86
+ - Player 1 mandala/geometry: cyan + magenta palette
87
+ - Player 2 mandala/geometry: gold + green palette
88
+ - Internal Poincaré tessellations use different {P,Q} tilings per player
89
+ - Inter-player geometry: lines connecting across players' hands create larger mandala structures
90
+
91
+ ### Detection Logic
92
+ - MediaPipe HandLandmarker already supports `numHands: 4`
93
+ - Hands 0-1 = Player 1, Hands 2-3 = Player 2
94
+ - If only 2 hands detected, single-player mode (current behavior)
95
+ - If 3-4 hands detected, split into two players automatically
96
+ - UI indicator shows "JAM SESSION" when multiplayer is active
97
+
98
+ ### Scaling Considerations
99
+ - 4 hands = 84 landmarks at 30fps — still performant
100
+ - Two separate PolySynth instances may need careful volume balancing
101
+ - Master bus limiter (-2dB) protects speakers regardless of player count
102
+
103
+ ## Implementation Priority for Hyperspace Jam
104
+ 1. Pinch detection → merge thumb+index into single anchor
105
+ 2. Dynamic shape state (line → triangle → quad) based on active anchors
106
+ 3. Internal Poincaré tessellation shader filling the shape geometry
107
+ 4. DMT-chrome iridescent color flow
108
+ 5. Z-depth line thickness + node size scaling
109
+ 6. Audio filter modulation from shape proximity
110
+ 7. Pulsation and particle effects
111
+ 8. **Multiplayer jam session** — detect 3-4 hands, split into treble+bass roles
.gitattributes CHANGED
@@ -33,3 +33,7 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ assets/demo.png filter=lfs diff=lfs merge=lfs -text
37
+ assets/kick.wav filter=lfs diff=lfs merge=lfs -text
38
+ assets/siteOGImage.webp filter=lfs diff=lfs merge=lfs -text
39
+ assets/snare.wav filter=lfs diff=lfs merge=lfs -text
DisplacementFilter.js ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export class DisplacementFilter {
2
+ constructor(rendererCanvas, videoElement) {
3
+ this.canvas = rendererCanvas;
4
+ this.video = videoElement;
5
+ this.enabled = true;
6
+ this.time = 0;
7
+
8
+ // Create SVG turbulence filter for real per-pixel displacement
9
+ this._createTurbulenceSVG();
10
+ }
11
+
12
+ _createTurbulenceSVG() {
13
+ // SVG filter = web equivalent of After Effects "Turbulent Displace"
14
+ var svgNS = 'http://www.w3.org/2000/svg';
15
+ this.svg = document.createElementNS(svgNS, 'svg');
16
+ this.svg.setAttribute('width', '0');
17
+ this.svg.setAttribute('height', '0');
18
+ this.svg.style.position = 'absolute';
19
+
20
+ var defs = document.createElementNS(svgNS, 'defs');
21
+
22
+ // Filter for the webcam video
23
+ var filter = document.createElementNS(svgNS, 'filter');
24
+ filter.setAttribute('id', 'turbulence-displace');
25
+ filter.setAttribute('x', '-10%');
26
+ filter.setAttribute('y', '-10%');
27
+ filter.setAttribute('width', '120%');
28
+ filter.setAttribute('height', '120%');
29
+
30
+ // feTurbulence = generates Perlin noise pattern
31
+ // "Evolution" = seed, animated over time
32
+ // "Amount" = scale parameter in feDisplacementMap
33
+ this.turbulence = document.createElementNS(svgNS, 'feTurbulence');
34
+ this.turbulence.setAttribute('type', 'fractalNoise');
35
+ this.turbulence.setAttribute('baseFrequency', '0.008 0.006'); // Size (lower = larger swirls)
36
+ this.turbulence.setAttribute('numOctaves', '3');
37
+ this.turbulence.setAttribute('seed', '0'); // Will animate this = "Evolution"
38
+ this.turbulence.setAttribute('result', 'noise');
39
+
40
+ // feDisplacementMap = displaces pixels based on the noise
41
+ this.displacement = document.createElementNS(svgNS, 'feDisplacementMap');
42
+ this.displacement.setAttribute('in', 'SourceGraphic');
43
+ this.displacement.setAttribute('in2', 'noise');
44
+ this.displacement.setAttribute('scale', '12'); // Amount — subtle but visible
45
+ this.displacement.setAttribute('xChannelSelector', 'R');
46
+ this.displacement.setAttribute('yChannelSelector', 'G');
47
+
48
+ filter.appendChild(this.turbulence);
49
+ filter.appendChild(this.displacement);
50
+ defs.appendChild(filter);
51
+
52
+ // Second filter for the Three.js canvas (slightly different params)
53
+ var filter2 = document.createElementNS(svgNS, 'filter');
54
+ filter2.setAttribute('id', 'turbulence-canvas');
55
+ filter2.setAttribute('x', '-10%');
56
+ filter2.setAttribute('y', '-10%');
57
+ filter2.setAttribute('width', '120%');
58
+ filter2.setAttribute('height', '120%');
59
+
60
+ this.turbulence2 = document.createElementNS(svgNS, 'feTurbulence');
61
+ this.turbulence2.setAttribute('type', 'fractalNoise');
62
+ this.turbulence2.setAttribute('baseFrequency', '0.005 0.004');
63
+ this.turbulence2.setAttribute('numOctaves', '2');
64
+ this.turbulence2.setAttribute('seed', '42');
65
+ this.turbulence2.setAttribute('result', 'noise');
66
+
67
+ this.displacement2 = document.createElementNS(svgNS, 'feDisplacementMap');
68
+ this.displacement2.setAttribute('in', 'SourceGraphic');
69
+ this.displacement2.setAttribute('in2', 'noise');
70
+ this.displacement2.setAttribute('scale', '8');
71
+ this.displacement2.setAttribute('xChannelSelector', 'R');
72
+ this.displacement2.setAttribute('yChannelSelector', 'G');
73
+
74
+ filter2.appendChild(this.turbulence2);
75
+ filter2.appendChild(this.displacement2);
76
+ defs.appendChild(filter2);
77
+
78
+ this.svg.appendChild(defs);
79
+ document.body.appendChild(this.svg);
80
+
81
+ // Apply filters
82
+ this.video.style.filter += ' url(#turbulence-displace)';
83
+ this.canvas.style.filter = 'url(#turbulence-canvas)';
84
+ }
85
+
86
+ toggle() {
87
+ this.enabled = !this.enabled;
88
+ if (!this.enabled) {
89
+ this.canvas.style.filter = '';
90
+ this.canvas.style.transform = '';
91
+ this.video.style.filter = '';
92
+ this.video.style.transform = 'scaleX(-1)';
93
+ } else {
94
+ this.video.style.filter = 'url(#turbulence-displace)';
95
+ this.canvas.style.filter = 'url(#turbulence-canvas)';
96
+ }
97
+ console.log('Turbulence displacement: ' + (this.enabled ? 'ON' : 'OFF'));
98
+ }
99
+
100
+ update(amplitude) {
101
+ if (!this.enabled) return;
102
+ this.time += 0.016;
103
+
104
+ // Throttle SVG DOM updates to ~10fps to prevent layout thrashing
105
+ this._frameCount = (this._frameCount || 0) + 1;
106
+ if (this._frameCount % 6 !== 0) return;
107
+
108
+ var amp = Math.max(0.15, amplitude || 0);
109
+
110
+ // Animate "Evolution" — change the noise seed over time
111
+ var seed = Math.floor(this.time * 1.5) % 1000;
112
+ this.turbulence.setAttribute('seed', String(seed));
113
+ this.turbulence2.setAttribute('seed', String(seed + 500));
114
+
115
+ // Animate "Offset Turbulence" — shift the noise pattern's base frequency
116
+ // Subtle variation creates the "breathing" organic feel
117
+ var freqX = 0.008 + Math.sin(this.time * 0.3) * 0.003;
118
+ var freqY = 0.006 + Math.cos(this.time * 0.25) * 0.002;
119
+ this.turbulence.setAttribute('baseFrequency', freqX + ' ' + freqY);
120
+
121
+ // Audio-reactive Amount — MAX STRENGTH displacement
122
+ var videoScale = 20 + amp * 30; // 20-50 range (always visible, big on audio)
123
+ var canvasScale = 14 + amp * 22; // 14-36 range
124
+ this.displacement.setAttribute('scale', String(videoScale));
125
+ this.displacement2.setAttribute('scale', String(canvasScale));
126
+
127
+ // Smoke/wave distortion — sinusoidal waves rippling the canvas
128
+ var breathScale = 1.0 + 0.01 * Math.sin(this.time * 0.7);
129
+ var waveSkewX = Math.sin(this.time * 0.4) * 0.8;
130
+ var waveSkewY = Math.cos(this.time * 0.35) * 0.5;
131
+ var waveX = Math.sin(this.time * 0.6) * 3;
132
+ var waveY = Math.cos(this.time * 0.5) * 2;
133
+
134
+ this.canvas.style.transform =
135
+ 'scale(' + breathScale + ') ' +
136
+ 'skew(' + waveSkewX + 'deg, ' + waveSkewY + 'deg) ' +
137
+ 'translate(' + waveX + 'px, ' + waveY + 'px)';
138
+ this.video.style.transform =
139
+ 'scaleX(-1) scale(' + breathScale + ') ' +
140
+ 'skew(' + (-waveSkewX * 0.6) + 'deg, ' + (-waveSkewY * 0.6) + 'deg) ' +
141
+ 'translate(' + (-waveX * 0.5) + 'px, ' + (-waveY * 0.5) + 'px)';
142
+ }
143
+
144
+ dispose() {
145
+ this.canvas.style.filter = '';
146
+ this.canvas.style.transform = '';
147
+ this.video.style.filter = '';
148
+ this.video.style.transform = 'scaleX(-1)';
149
+ if (this.svg && this.svg.parentNode) {
150
+ this.svg.parentNode.removeChild(this.svg);
151
+ }
152
+ }
153
+ }
DrumManager.js ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // DrumManager stub — Lyria handles all music generation including drums.
2
+ // These exports maintain compatibility with game.js references.
3
+
4
+ const defaultPattern = {
5
+ kick: [true,false,false,false,false,true,false,false,true,false,false,true,false,true,false,false],
6
+ snare: [false,false,false,false,true,false,false,false,false,false,false,false,true,false,false,false],
7
+ hihat: [false,true,false,true,false,true,false,true,false,true,false,true,false,true,false,true],
8
+ clap: [false,false,false,false,true,false,false,true,false,false,false,false,true,false,false,false],
9
+ };
10
+
11
+ const fingerToDrumMap = {
12
+ thumb: 'glitch',
13
+ index: null,
14
+ middle: 'kick',
15
+ ring: 'hihat',
16
+ pinky: 'clap',
17
+ };
18
+
19
+ let activeDrums = new Map();
20
+ let currentBeat = 0;
21
+
22
+ export function loadSamples() {}
23
+ export function startSequence() {}
24
+
25
+ export function updateActiveDrums(fingerStates) {
26
+ activeDrums = new Map();
27
+ if (fingerStates && typeof fingerStates === 'object') {
28
+ for (const [k, v] of Object.entries(fingerStates)) {
29
+ if (v) activeDrums.set(k, v);
30
+ }
31
+ }
32
+ }
33
+
34
+ export function getActiveDrums() {
35
+ return activeDrums;
36
+ }
37
+
38
+ export function getFingerToDrumMap() {
39
+ return fingerToDrumMap;
40
+ }
41
+
42
+ export function getCurrentBeat() {
43
+ return currentBeat;
44
+ }
45
+
46
+ export function getDrumPattern() {
47
+ return defaultPattern;
48
+ }
MandalaVisualizer.js ADDED
@@ -0,0 +1,248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import * as THREE from 'three';
2
+
3
+ const RING_SEGMENTS = 48;
4
+ const Z = 1.5;
5
+
6
+ function createReusableLine(color, opacity) {
7
+ const positions = new Float32Array(6);
8
+ const geom = new THREE.BufferGeometry();
9
+ geom.setAttribute('position', new THREE.BufferAttribute(positions, 3));
10
+ const mat = new THREE.LineBasicMaterial({ color, transparent: true, opacity, depthTest: false, linewidth: 1 });
11
+ const line = new THREE.Line(geom, mat);
12
+ line.visible = false;
13
+ return line;
14
+ }
15
+
16
+ function createReusableRing(segments, color, opacity) {
17
+ const positions = new Float32Array((segments + 1) * 3);
18
+ const geom = new THREE.BufferGeometry();
19
+ geom.setAttribute('position', new THREE.BufferAttribute(positions, 3));
20
+ const mat = new THREE.LineBasicMaterial({ color, transparent: true, opacity, depthTest: false });
21
+ const line = new THREE.Line(geom, mat);
22
+ line.visible = false;
23
+ return line;
24
+ }
25
+
26
+ // Pentagon is drawn as a single LineLoop-style line with 6 points (closed)
27
+ function createReusablePentagon(color, opacity) {
28
+ const positions = new Float32Array(18); // 6 points × 3
29
+ const geom = new THREE.BufferGeometry();
30
+ geom.setAttribute('position', new THREE.BufferAttribute(positions, 3));
31
+ const mat = new THREE.LineBasicMaterial({ color, transparent: true, opacity, depthTest: false });
32
+ const line = new THREE.Line(geom, mat);
33
+ line.visible = false;
34
+ return line;
35
+ }
36
+
37
+ // Pentagram star: 6 points (0,2,4,1,3,0)
38
+ function createReusableStar(color, opacity) {
39
+ const positions = new Float32Array(18); // 6 points × 3
40
+ const geom = new THREE.BufferGeometry();
41
+ geom.setAttribute('position', new THREE.BufferAttribute(positions, 3));
42
+ const mat = new THREE.LineBasicMaterial({ color, transparent: true, opacity, depthTest: false });
43
+ const line = new THREE.Line(geom, mat);
44
+ line.visible = false;
45
+ return line;
46
+ }
47
+
48
+ export class MandalaVisualizer {
49
+ constructor(scene) {
50
+ this.scene = scene;
51
+ this.group = new THREE.Group();
52
+ this.group.renderOrder = 2;
53
+ this.scene.add(this.group);
54
+ this.clock = new THREE.Clock();
55
+
56
+ this.fingertips = [4, 8, 12, 16, 20];
57
+ this.palmIndex = 9;
58
+
59
+ // Pre-allocate all geometry for 2 hands
60
+ this.hands = [];
61
+ for (let h = 0; h < 2; h++) {
62
+ const hand = {
63
+ pentagon: createReusablePentagon(0x00ffff, 0.7),
64
+ star: createReusableStar(0xff00ff, 0.6),
65
+ rays: [],
66
+ rings: [],
67
+ };
68
+ for (let i = 0; i < 5; i++) {
69
+ hand.rays.push(createReusableLine(0xffaa00, 0.7));
70
+ }
71
+ for (let r = 0; r < 3; r++) {
72
+ hand.rings.push(createReusableRing(RING_SEGMENTS, 0x00ffff, 0.35));
73
+ }
74
+ this.group.add(hand.pentagon);
75
+ this.group.add(hand.star);
76
+ hand.rays.forEach(l => this.group.add(l));
77
+ hand.rings.forEach(l => this.group.add(l));
78
+ this.hands.push(hand);
79
+ }
80
+
81
+ // Inter-hand: 5 bridge lines + 2 cross lines
82
+ this.bridges = [];
83
+ for (let i = 0; i < 5; i++) {
84
+ const line = createReusableLine(0xff00ff, 0.6);
85
+ this.bridges.push(line);
86
+ this.group.add(line);
87
+ }
88
+ this.crosses = [];
89
+ for (let i = 0; i < 2; i++) {
90
+ const line = createReusableLine(0xffaa00, 0.5);
91
+ this.crosses.push(line);
92
+ this.group.add(line);
93
+ }
94
+ }
95
+
96
+ update(handsData, canvasWidth, canvasHeight) {
97
+ // Hide everything
98
+ for (let h = 0; h < 2; h++) {
99
+ const hand = this.hands[h];
100
+ hand.pentagon.visible = false;
101
+ hand.star.visible = false;
102
+ for (let i = 0; i < 5; i++) hand.rays[i].visible = false;
103
+ for (let i = 0; i < 3; i++) hand.rings[i].visible = false;
104
+ }
105
+ for (let i = 0; i < 5; i++) this.bridges[i].visible = false;
106
+ for (let i = 0; i < 2; i++) this.crosses[i].visible = false;
107
+
108
+ if (!handsData || handsData.length === 0) return;
109
+
110
+ const time = this.clock.getElapsedTime();
111
+
112
+ for (let h = 0; h < handsData.length && h < 2; h++) {
113
+ const points3D = handsData[h];
114
+ if (!points3D || points3D.length < 21) continue;
115
+
116
+ const hand = this.hands[h];
117
+ const tips = this.fingertips.map(idx => points3D[idx]);
118
+ const palm = points3D[this.palmIndex];
119
+
120
+ const area = this._polygonArea(tips);
121
+ const areaFactor = Math.min(1, area / 40000);
122
+ const hue = 0.5 - areaFactor * 0.3;
123
+ const glowOpacity = 0.5 + areaFactor * 0.3;
124
+
125
+ // 1. Pentagon
126
+ const pentArr = hand.pentagon.geometry.attributes.position.array;
127
+ for (let i = 0; i < 5; i++) {
128
+ pentArr[i * 3] = tips[i].x;
129
+ pentArr[i * 3 + 1] = tips[i].y;
130
+ pentArr[i * 3 + 2] = Z;
131
+ }
132
+ pentArr[15] = tips[0].x;
133
+ pentArr[16] = tips[0].y;
134
+ pentArr[17] = Z;
135
+ hand.pentagon.geometry.attributes.position.needsUpdate = true;
136
+ hand.pentagon.material.color.setHSL(hue, 1.0, 0.5);
137
+ hand.pentagon.material.opacity = glowOpacity;
138
+ hand.pentagon.visible = true;
139
+
140
+ // 2. Pentagram star (order: 0,2,4,1,3,0)
141
+ const starOrder = [0, 2, 4, 1, 3, 0];
142
+ const starArr = hand.star.geometry.attributes.position.array;
143
+ for (let i = 0; i < 6; i++) {
144
+ const idx = starOrder[i];
145
+ starArr[i * 3] = tips[idx].x;
146
+ starArr[i * 3 + 1] = tips[idx].y;
147
+ starArr[i * 3 + 2] = Z;
148
+ }
149
+ hand.star.geometry.attributes.position.needsUpdate = true;
150
+ hand.star.material.opacity = glowOpacity * 0.8;
151
+ hand.star.visible = true;
152
+
153
+ // 3. Palm-to-tip rays
154
+ for (let i = 0; i < 5; i++) {
155
+ const arr = hand.rays[i].geometry.attributes.position.array;
156
+ arr[0] = palm.x; arr[1] = palm.y; arr[2] = Z;
157
+ arr[3] = tips[i].x; arr[4] = tips[i].y; arr[5] = Z;
158
+ hand.rays[i].geometry.attributes.position.needsUpdate = true;
159
+ hand.rays[i].visible = true;
160
+ }
161
+
162
+ // 4. Concentric rings
163
+ let avgDist = 0;
164
+ for (let i = 0; i < 5; i++) {
165
+ const dx = tips[i].x - palm.x;
166
+ const dy = tips[i].y - palm.y;
167
+ avgDist += Math.sqrt(dx * dx + dy * dy);
168
+ }
169
+ avgDist /= 5;
170
+
171
+ const ringRadii = [avgDist * 0.4, avgDist * 0.7, avgDist * 1.0];
172
+ for (let r = 0; r < 3; r++) {
173
+ const radius = ringRadii[r];
174
+ const arr = hand.rings[r].geometry.attributes.position.array;
175
+ for (let s = 0; s <= RING_SEGMENTS; s++) {
176
+ const angle = (s / RING_SEGMENTS) * Math.PI * 2 + time * (0.5 + r * 0.3);
177
+ arr[s * 3] = palm.x + Math.cos(angle) * radius;
178
+ arr[s * 3 + 1] = palm.y + Math.sin(angle) * radius;
179
+ arr[s * 3 + 2] = Z;
180
+ }
181
+ hand.rings[r].geometry.attributes.position.needsUpdate = true;
182
+ hand.rings[r].material.color.setHSL((hue + r * 0.15) % 1, 1.0, 0.5);
183
+ hand.rings[r].visible = true;
184
+ }
185
+ }
186
+
187
+ // 5 & 6. Inter-hand
188
+ if (handsData.length >= 2 && handsData[0] && handsData[1] && handsData[0].length >= 21 && handsData[1].length >= 21) {
189
+ const tips1 = this.fingertips.map(idx => handsData[0][idx]);
190
+ const tips2 = this.fingertips.map(idx => handsData[1][idx]);
191
+
192
+ for (let i = 0; i < 5; i++) {
193
+ const arr = this.bridges[i].geometry.attributes.position.array;
194
+ arr[0] = tips1[i].x; arr[1] = tips1[i].y; arr[2] = Z;
195
+ arr[3] = tips2[i].x; arr[4] = tips2[i].y; arr[5] = Z;
196
+ this.bridges[i].geometry.attributes.position.needsUpdate = true;
197
+ this.bridges[i].visible = true;
198
+ }
199
+
200
+ const crossPairs = [[tips1[0], tips2[4]], [tips1[4], tips2[0]]];
201
+ for (let c = 0; c < 2; c++) {
202
+ const arr = this.crosses[c].geometry.attributes.position.array;
203
+ arr[0] = crossPairs[c][0].x; arr[1] = crossPairs[c][0].y; arr[2] = Z;
204
+ arr[3] = crossPairs[c][1].x; arr[4] = crossPairs[c][1].y; arr[5] = Z;
205
+ this.crosses[c].geometry.attributes.position.needsUpdate = true;
206
+ this.crosses[c].visible = true;
207
+ }
208
+ }
209
+ }
210
+
211
+ _polygonArea(points) {
212
+ let area = 0;
213
+ const n = points.length;
214
+ for (let i = 0; i < n; i++) {
215
+ const j = (i + 1) % n;
216
+ area += points[i].x * points[j].y;
217
+ area -= points[j].x * points[i].y;
218
+ }
219
+ return Math.abs(area) / 2;
220
+ }
221
+
222
+ dispose() {
223
+ // Dispose all pre-allocated geometry and materials
224
+ for (const hand of this.hands) {
225
+ hand.pentagon.geometry.dispose();
226
+ hand.pentagon.material.dispose();
227
+ hand.star.geometry.dispose();
228
+ hand.star.material.dispose();
229
+ for (const ray of hand.rays) {
230
+ ray.geometry.dispose();
231
+ ray.material.dispose();
232
+ }
233
+ for (const ring of hand.rings) {
234
+ ring.geometry.dispose();
235
+ ring.material.dispose();
236
+ }
237
+ }
238
+ for (const bridge of this.bridges) {
239
+ bridge.geometry.dispose();
240
+ bridge.material.dispose();
241
+ }
242
+ for (const cross of this.crosses) {
243
+ cross.geometry.dispose();
244
+ cross.material.dispose();
245
+ }
246
+ this.scene.remove(this.group);
247
+ }
248
+ }
MusicManager.js ADDED
@@ -0,0 +1,330 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Lyria RealTime MusicManager — Drop-in replacement for Tone.js synth engine
2
+ // Sends gesture data to Python backend via WebSocket, receives PCM audio
3
+ export class MusicManager {
4
+ constructor() {
5
+ this.isStarted = false;
6
+ this._panicMuted = false;
7
+ this.analyser = null;
8
+
9
+ // Gesture state accumulator (sent to backend)
10
+ this._gestureState = {
11
+ handY: 0.5,
12
+ handSpread: 0.5,
13
+ wristAngle: 0.0,
14
+ volume: 0.5,
15
+ handVelocity: { x: 0, y: 0 },
16
+ fingerExtensions: {},
17
+ shapeActive: false,
18
+ shapeProximity: 0.5,
19
+ drumHandActive: false,
20
+ drumTempo: null,
21
+ muteDrums: false,
22
+ muteBass: false,
23
+ fistGesture: false,
24
+ };
25
+
26
+ // WebSocket to backend
27
+ this._ws = null;
28
+ this._wsReady = false;
29
+
30
+ // Audio playback via Web Audio API
31
+ this._audioCtx = null;
32
+ this._pcmQueue = [];
33
+ this._isPlaying = false;
34
+ this._nextPlayTime = 0;
35
+
36
+ // Analyser for visualizer compatibility
37
+ this._analyserNode = null;
38
+ this._analyserData = null;
39
+
40
+ // Throttle gesture sends (every 100ms)
41
+ this._lastSendTime = 0;
42
+ this._SEND_INTERVAL = 100;
43
+
44
+ // Compat: pad preset cycling
45
+ this.padPresets = [
46
+ { name: 'Ambient Sub' },
47
+ { name: 'Dub Growl' },
48
+ { name: 'Dream Wash' },
49
+ { name: 'Detuned Saw' },
50
+ { name: 'Warm Square' },
51
+ ];
52
+ this.currentSynthIndex = 0;
53
+
54
+ // Smoothing (compat with game.js references)
55
+ this._smoothDist = { thumb: 0, index: 0, middle: 0, ring: 0, pinky: 0 };
56
+ this._smoothDrumDist = { thumb: 0, index: 0, middle: 0, ring: 0, pinky: 0 };
57
+ this._SMOOTH_ALPHA = 0.3;
58
+ this._frameCount = 0;
59
+ this._prevExtensions = {};
60
+ this._prevDrumExtensions = { thumb: 0, index: 0, middle: 0, ring: 0, pinky: 0 };
61
+ this._drumFingerCooldowns = { thumb: 0, index: 0, middle: 0, ring: 0, pinky: 0 };
62
+ this.handVolumes = new Map();
63
+ this.fingerCooldowns = new Map();
64
+ this.percCooldown = 0;
65
+ this.padSynths = new Map();
66
+ this.activePatterns = this.padSynths;
67
+
68
+ this.scale = [
69
+ 'C1','Eb1','G1','Bb1','C2','Eb2','F2','G2','Bb2',
70
+ 'C3','Eb3','F3','G3','Bb3','C4','Eb4','F4','G4','Bb4','C5','Eb5','F5'
71
+ ];
72
+ }
73
+
74
+ async start() {
75
+ if (this.isStarted) return;
76
+
77
+ // Create AudioContext for PCM playback
78
+ this._audioCtx = new (window.AudioContext || window.webkitAudioContext)({
79
+ sampleRate: 48000
80
+ });
81
+
82
+ // Create analyser node for visualizer
83
+ this._analyserNode = this._audioCtx.createAnalyser();
84
+ this._analyserNode.fftSize = 2048;
85
+ this._analyserNode.connect(this._audioCtx.destination);
86
+ this._analyserData = new Float32Array(this._analyserNode.fftSize);
87
+
88
+ // Expose analyser in Tone.js-compatible format
89
+ this.analyser = {
90
+ getValue: () => {
91
+ this._analyserNode.getFloatTimeDomainData(this._analyserData);
92
+ return this._analyserData;
93
+ }
94
+ };
95
+
96
+ // Connect to backend WebSocket
97
+ const wsUrl = `ws://${window.location.host}/ws`;
98
+ this._ws = new WebSocket(wsUrl);
99
+
100
+ this._ws.onopen = () => {
101
+ console.log('[Lyria] WebSocket connected');
102
+ this._wsReady = true;
103
+ // Tell backend to start playing
104
+ this._ws.send(JSON.stringify({ type: 'play' }));
105
+ };
106
+
107
+ this._ws.binaryType = 'arraybuffer';
108
+
109
+ this._ws.onmessage = (event) => {
110
+ if (event.data instanceof ArrayBuffer) {
111
+ // Binary frame = raw PCM audio
112
+ this._handleAudioChunkBinary(event.data);
113
+ } else if (event.data instanceof Blob) {
114
+ // Some browsers send Blob even with binaryType='arraybuffer'
115
+ event.data.arrayBuffer().then(ab => this._handleAudioChunkBinary(ab));
116
+ } else if (typeof event.data === 'string') {
117
+ // Text frame = JSON control message
118
+ try {
119
+ const msg = JSON.parse(event.data);
120
+ if (msg.type === 'error') {
121
+ console.error('[Lyria] Backend error:', msg.message);
122
+ } else if (msg.type === 'connected') {
123
+ console.log('[Lyria] Backend session ready');
124
+ }
125
+ } catch (e) {
126
+ console.warn('[Lyria] Unparseable message:', event.data.substring(0, 50));
127
+ }
128
+ }
129
+ };
130
+
131
+ this._ws.onerror = (e) => {
132
+ console.error('[Lyria] WebSocket error:', e);
133
+ };
134
+
135
+ this._ws.onclose = () => {
136
+ console.log('[Lyria] WebSocket closed');
137
+ this._wsReady = false;
138
+ };
139
+
140
+ this.isStarted = true;
141
+ }
142
+
143
+ _handleAudioChunkBinary(arrayBuffer) {
144
+ if (!this._chunkCount) this._chunkCount = 0;
145
+ this._chunkCount++;
146
+ if (this._chunkCount <= 3) {
147
+ console.log(`[Lyria] Audio chunk ${this._chunkCount}: ${arrayBuffer.byteLength} bytes`);
148
+ }
149
+
150
+ // Convert 16-bit PCM to Float32 stereo directly from ArrayBuffer
151
+ const int16 = new Int16Array(arrayBuffer);
152
+ const numSamples = int16.length / 2; // stereo
153
+ const audioBuffer = this._audioCtx.createBuffer(2, numSamples, 48000);
154
+ const left = audioBuffer.getChannelData(0);
155
+ const right = audioBuffer.getChannelData(1);
156
+
157
+ for (let i = 0; i < numSamples; i++) {
158
+ left[i] = int16[i * 2] / 32768;
159
+ right[i] = int16[i * 2 + 1] / 32768;
160
+ }
161
+
162
+ // Schedule seamless playback
163
+ const now = this._audioCtx.currentTime;
164
+ const startTime = Math.max(now + 0.05, this._nextPlayTime);
165
+
166
+ const source = this._audioCtx.createBufferSource();
167
+ source.buffer = audioBuffer;
168
+ source.connect(this._analyserNode);
169
+ source.start(startTime);
170
+
171
+ this._nextPlayTime = startTime + audioBuffer.duration;
172
+ }
173
+
174
+ _sendGestureState() {
175
+ const now = performance.now();
176
+ if (!this._wsReady || now - this._lastSendTime < this._SEND_INTERVAL) return;
177
+ this._lastSendTime = now;
178
+
179
+ this._ws.send(JSON.stringify({
180
+ type: 'gesture',
181
+ data: this._gestureState
182
+ }));
183
+ }
184
+
185
+ // === Public API matching original MusicManager interface ===
186
+
187
+ startArpeggio(handId, note) {
188
+ // Track that a hand appeared, update base note
189
+ this._gestureState.handY = this.scale.indexOf(note) / (this.scale.length - 1);
190
+ if (!this._isPlaying && this._wsReady) {
191
+ this._ws.send(JSON.stringify({ type: 'play' }));
192
+ this._isPlaying = true;
193
+ }
194
+ }
195
+
196
+ stopArpeggio(handId) {
197
+ // Hand disappeared
198
+ }
199
+
200
+ updateGesture(handId, gestureData) {
201
+ if (!this.isStarted || this._panicMuted) return;
202
+
203
+ // Map gesture data to our state format
204
+ const rootNote = gestureData.rootNote || 'C3';
205
+ const noteIdx = this.scale.indexOf(rootNote);
206
+ this._gestureState.handY = noteIdx >= 0 ? noteIdx / (this.scale.length - 1) : 0.5;
207
+
208
+ this._gestureState.volume = gestureData.volume || 0;
209
+ this._gestureState.wristAngle = gestureData.wristAngle || 0;
210
+ this._gestureState.handSpread = gestureData.handSpread || 0;
211
+ this._gestureState.handVelocity = gestureData.handVelocity || { x: 0, y: 0 };
212
+ this._gestureState.fingerExtensions = gestureData.fingerExtensions || {};
213
+ this._gestureState.fistGesture = false;
214
+
215
+ this._sendGestureState();
216
+ }
217
+
218
+ updateDrumGesture(gestureData) {
219
+ if (!this.isStarted || this._panicMuted) return;
220
+
221
+ this._gestureState.drumHandActive = true;
222
+
223
+ // Average finger extension as tempo control
224
+ const ext = gestureData.fingerExtensions || {};
225
+ const vals = Object.values(ext).filter(v => typeof v === 'number');
226
+ if (vals.length > 0) {
227
+ this._gestureState.drumTempo = vals.reduce((a, b) => a + b, 0) / vals.length;
228
+ }
229
+
230
+ this._sendGestureState();
231
+ }
232
+
233
+ updateShapeBass(shapeData) {
234
+ if (!this.isStarted) return;
235
+ this._gestureState.shapeActive = true;
236
+ this._gestureState.shapeProximity = shapeData?.proximity || 0.5;
237
+ this._sendGestureState();
238
+ }
239
+
240
+ stopShapeBass() {
241
+ this._gestureState.shapeActive = false;
242
+ this._sendGestureState();
243
+ }
244
+
245
+ triggerFingerTouch(finger1, finger2) {
246
+ // Finger touches are sent as part of gesture state
247
+ // The Qwen model will interpret the overall gesture
248
+ }
249
+
250
+ cycleSynth() {
251
+ this.currentSynthIndex = (this.currentSynthIndex + 1) % this.padPresets.length;
252
+ this._gestureState.fistGesture = true;
253
+ this._sendGestureState();
254
+ console.log(`[Lyria] Preset: ${this.padPresets[this.currentSynthIndex].name}`);
255
+ }
256
+
257
+ panic() {
258
+ this._panicMuted = true;
259
+ if (this._wsReady) {
260
+ this._ws.send(JSON.stringify({ type: 'panic' }));
261
+ }
262
+ setTimeout(() => {
263
+ this._panicMuted = false;
264
+ if (this._wsReady) {
265
+ this._ws.send(JSON.stringify({ type: 'play' }));
266
+ }
267
+ }, 1000);
268
+ }
269
+
270
+ handLeft(handId) {
271
+ if (handId !== 0) {
272
+ this._gestureState.drumHandActive = false;
273
+ this._gestureState.drumTempo = null;
274
+ }
275
+ // Notify backend
276
+ if (this._wsReady) {
277
+ this._ws.send(JSON.stringify({ type: 'hands_lost' }));
278
+ }
279
+ }
280
+
281
+ // === Additional stubs for game.js compatibility ===
282
+
283
+ setProximityFilter(proximity) {
284
+ // Proximity affects brightness in the gesture state
285
+ this._gestureState.shapeProximity = proximity;
286
+ }
287
+
288
+ updateArpeggio(handId, note) {
289
+ const noteIdx = this.scale.indexOf(note);
290
+ this._gestureState.handY = noteIdx >= 0 ? noteIdx / (this.scale.length - 1) : 0.5;
291
+ }
292
+
293
+ updateArpeggioVolume(handId, volume) {
294
+ this._gestureState.volume = volume;
295
+ }
296
+
297
+ updateFingerExpression(data) {
298
+ // Finger expression data folded into gesture state via updateGesture
299
+ }
300
+
301
+ getAnalyser() {
302
+ return this.analyser;
303
+ }
304
+
305
+ ensureAudioActive() {
306
+ if (this._audioCtx && this._audioCtx.state === 'suspended') {
307
+ this._audioCtx.resume();
308
+ }
309
+ }
310
+
311
+ updateShapeAudio(shapeData) {
312
+ this.updateShapeBass(shapeData);
313
+ }
314
+
315
+ getAnalyserData() {
316
+ if (this.analyser) {
317
+ return this.analyser.getValue();
318
+ }
319
+ return new Float32Array(2048);
320
+ }
321
+
322
+ dispose() {
323
+ if (this._ws) {
324
+ this._ws.close();
325
+ }
326
+ if (this._audioCtx) {
327
+ this._audioCtx.close();
328
+ }
329
+ }
330
+ }
README.md CHANGED
@@ -1,10 +1,285 @@
1
  ---
2
- title: Hyperspace Jam Lyria
3
- emoji: ⚡
4
- colorFrom: red
5
- colorTo: yellow
6
- sdk: docker
7
- pinned: false
 
8
  ---
9
 
10
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ license: mit
3
+ title: Hyperspace Jam — Lyria AI Edition
4
+ sdk: static
5
+ emoji: 🎹
6
+ colorFrom: purple
7
+ colorTo: blue
8
+ short_description: Hand-controlled AI music DJ with hyperbolic visuals
9
  ---
10
 
11
+ # Hyperspace Jam — Lyria AI Edition
12
+
13
+ **Hand-controlled AI music generation with hyperbolic geometry visuals.**
14
+
15
+ Wave your hands in front of a webcam to DJ real-time AI-generated music. Hand positions, finger spread, wrist angles, and movement speed are interpreted by a local Qwen 3.5 AI model into musical descriptions, which steer Google's Lyria RealTime API to generate a continuous stream of music that responds to your gestures.
16
+
17
+ > Forked from [Hyperspace Jam v2](https://github.com/SolshineCode/hyperspace-jam-v2) (original by [collidingScopes](https://github.com/collidingScopes/arpeggiator)). The original used Tone.js client-side synthesis — this version replaces all audio generation with AI-generated music via Lyria RealTime.
18
+
19
+ ---
20
+
21
+ ## How It Works
22
+
23
+ ```
24
+ Webcam → MediaPipe Hand Tracking → Gesture Data
25
+ ↓
26
+ ┌─────────┴──────────┐
27
+ │ Python Backend │
28
+ │ │
29
+ │ Qwen 3.5 (0.8B) │ ← Interprets gestures
30
+ │ via Ollama │ into musical text
31
+ │ ↓ │ descriptions
32
+ │ Lyria RealTime API │ ← Generates real-time
33
+ │ via Google GenAI │ 48kHz stereo audio
34
+ │ ↓ │
35
+ │ PCM audio stream │
36
+ └─────────┬──────────┘
37
+ ↓
38
+ Browser Web Audio API → Speakers
39
+ + Three.js hyperbolic geometry visuals
40
+ ```
41
+
42
+ ### Data Flow Detail
43
+
44
+ 1. **MediaPipe HandLandmarker** tracks 30 landmarks per hand at ~30fps in the browser
45
+ 2. **game.js** computes gesture features: hand height, finger spread, wrist angle, velocity, finger extensions, shape detection
46
+ 3. **MusicManager.js** sends gesture data to the Python backend via WebSocket every 100ms
47
+ 4. **Backend** does two things in parallel:
48
+ - **Direct parameter mapping**: Hand height → brightness, finger spread → density, wrist tilt → brightness modulation, drum hand → BPM (sent to Lyria every 500ms, only when hands move)
49
+ - **Qwen 3.5 prompt generation**: Every 3 seconds (only when gesture changes significantly), the gesture state is described in natural language and sent to Qwen 3.5 0.8B via Ollama, which outputs weighted musical text prompts
50
+ 5. **Lyria RealTime** receives the prompts + config and generates 2-second chunks of 48kHz stereo 16-bit PCM audio, streamed back via WebSocket
51
+ 6. **Browser** decodes PCM chunks and schedules seamless playback via Web Audio API AudioWorklet, with an AnalyserNode feeding the hyperbolic geometry visualizer
52
+
53
+ ---
54
+
55
+ ## Gesture Controls
56
+
57
+ ### Musical Mapping
58
+
59
+ | Gesture | Effect |
60
+ |---------|--------|
61
+ | **Hand height (Y position)** | HIGH = ethereal, ambient, floating pads / LOW = heavy, nasty, drippy drum & bass |
62
+ | **Finger spread** | WIDE = complex, dense, layered textures / NARROW = minimal, sparse, clean |
63
+ | **Wrist tilt** | Tilted = acid, filter sweep, tension, dissonance |
64
+ | **Movement speed** | FAST = aggressive, driving, intense / STILL = ambient, calm, sustained |
65
+ | **White square shape** (both hands) | Sub-bass drone, fat sawtooth rumble |
66
+ | **Drum hand** (2nd hand) | Rhythmic, percussive, breakbeats — finger extension controls BPM (60-200) |
67
+ | **Fist** | Cycles through preset mood labels |
68
+ | **Spacebar** | Panic stop (1 second mute) |
69
+
70
+ ### Groove Lock
71
+
72
+ When hands stay still, the music **stays in its groove** — no prompt changes are sent to Lyria. Small movements trigger gradual evolution ("keep the groove, shift subtly"). Large, dramatic movements trigger a direction change ("shift genre entirely").
73
+
74
+ ### Transition System
75
+
76
+ The Qwen model maintains conversation history (last 6 exchanges) to ensure smooth transitions. It builds on previous themes rather than jumping randomly between styles.
77
+
78
+ ---
79
+
80
+ ## Architecture
81
+
82
+ ### Frontend (Browser)
83
+
84
+ | File | Purpose |
85
+ |------|---------|
86
+ | `index.html` | Entry point, UI controls, import map for Three.js |
87
+ | `main.js` | Bootstraps the Game instance |
88
+ | `game.js` | MediaPipe hand tracking, gesture feature extraction, hand rendering, visualization orchestration. Tone.js replaced with a minimal shim. |
89
+ | `MusicManager.js` | **Lyria drop-in replacement** for original Tone.js synth engine. Sends gesture data to backend via WebSocket, receives PCM audio, plays via Web Audio API. Maintains full interface compatibility with game.js. |
90
+ | `DrumManager.js` | Stub module (Lyria generates all music including drums). Exports Map-based interface for game.js compatibility. |
91
+ | `WaveformVisualizer.js` | Poincare disk hyperbolic geometry shader, audio-reactive |
92
+ | `MandalaVisualizer.js` | Sacred geometry rendering with pre-allocated pools |
93
+ | `ShapeManager.js` | Pinch shape tracking between hands (white quadrilateral) |
94
+ | `ShapeTessellationShader.js` | GLSL hyperbolic tiling for shape fill |
95
+ | `DisplacementFilter.js` | SVG turbulence + smoke DOM-based warping |
96
+ | `styles.css` | Dark kiosk-style UI |
97
+
98
+ ### Backend (Python)
99
+
100
+ | File | Purpose |
101
+ |------|---------|
102
+ | `backend/server.py` | FastAPI + WebSocket server. Bridges frontend gestures to Lyria + Qwen. Serves frontend static files. Implements gesture dead-zone logic (only updates on significant movement) and distinguishes gradual vs dramatic changes. |
103
+ | `backend/lyria_manager.py` | Manages Lyria RealTime WebSocket session via `google-genai` SDK. Handles connect, play/pause/stop, prompt updates, config updates (brightness, density, BPM, mute toggles), context resets, and audio chunk streaming. |
104
+ | `backend/gesture_interpreter.py` | Translates gesture data into Lyria weighted prompts via Qwen 3.5 0.8B (Ollama). Maintains conversation history for smooth transitions. Falls back to rule-based prompt generation when Ollama is unavailable. |
105
+ | `backend/requirements.txt` | Python dependencies |
106
+
107
+ ### Key Technologies
108
+
109
+ | Technology | Role | Version/Model |
110
+ |-----------|------|---------------|
111
+ | **Google Lyria RealTime** | AI music generation (streaming) | `models/lyria-realtime-exp` via Gemini API v1alpha |
112
+ | **Qwen 3.5** | Gesture-to-prompt interpretation | `qwen3.5:0.8b` via Ollama (1GB, ~1s inference) |
113
+ | **MediaPipe** | Hand landmark detection | HandLandmarker v0.10.14 |
114
+ | **Three.js** | WebGL visualization | v0.161.0 |
115
+ | **FastAPI** | Backend WebSocket server | Latest |
116
+ | **Web Audio API** | PCM audio playback | Browser native |
117
+
118
+ ---
119
+
120
+ ## Setup
121
+
122
+ ### Prerequisites
123
+
124
+ - **Python 3.10+**
125
+ - **Ollama** running locally with `qwen3.5:0.8b` model
126
+ - **Google Gemini API key** with Lyria RealTime access
127
+ - **Modern browser** with webcam access (Chrome recommended)
128
+
129
+ ### Installation
130
+
131
+ ```bash
132
+ # Clone the repository
133
+ git clone https://github.com/SolshineCode/hyperspace-jam-lyria.git
134
+ cd hyperspace-jam-lyria
135
+
136
+ # Create and activate virtual environment
137
+ python -m venv .venv
138
+ source .venv/bin/activate # Linux/Mac
139
+ source .venv/Scripts/activate # Windows/Git Bash
140
+
141
+ # Install Python dependencies
142
+ pip install -r backend/requirements.txt
143
+
144
+ # Pull the Qwen model (if not already installed)
145
+ ollama pull qwen3.5:0.8b
146
+ ```
147
+
148
+ ### Configuration
149
+
150
+ **Local development**: Create a `.env` file in the project root:
151
+
152
+ ```
153
+ GEMINI_API_KEY=your-gemini-api-key-here
154
+ ```
155
+
156
+ **Hugging Face Spaces**: Add `GEMINI_API_KEY` as a Secret in the Space settings (Settings > Repository Secrets).
157
+
158
+ The `.env` file is in `.gitignore` and will not be committed.
159
+
160
+ ### Running
161
+
162
+ ```bash
163
+ # Make sure Ollama is running
164
+ ollama serve # (if not already running)
165
+
166
+ # Start the server
167
+ python -u backend/server.py
168
+
169
+ # Open in browser
170
+ # http://localhost:8088
171
+ ```
172
+
173
+ The server starts on port **8088** by default. It serves both the API (WebSocket at `/ws`) and the frontend static files.
174
+
175
+ ### Quick Start (one command)
176
+
177
+ ```bash
178
+ bash start.sh
179
+ ```
180
+
181
+ ---
182
+
183
+ ## Lyria RealTime API Details
184
+
185
+ ### Connection
186
+
187
+ - **Protocol**: WebSocket (persistent, bidirectional, low-latency)
188
+ - **Model**: `models/lyria-realtime-exp`
189
+ - **SDK**: `google-genai` with `api_version='v1alpha'`
190
+ - **Audio format**: Raw 16-bit PCM, 48kHz, stereo
191
+ - **Chunk size**: 384,000 bytes (2 seconds of audio)
192
+ - **First chunk latency**: ~3-4 seconds after `play()`
193
+ - **Session limit**: 10 minutes (auto-reconnect planned)
194
+
195
+ ### Controls Used
196
+
197
+ | Parameter | Range | Mapped From |
198
+ |-----------|-------|-------------|
199
+ | `weighted_prompts` | Text + weight (0.1-3.0) | Qwen 3.5 output from gesture interpretation |
200
+ | `brightness` | 0.0-1.0 | Hand height * wrist tilt factor |
201
+ | `density` | 0.0-1.0 | Finger spread * volume |
202
+ | `bpm` | 60-200 | Drum hand finger extension average (requires context reset) |
203
+ | `mute_drums` | bool | Gesture flag |
204
+ | `mute_bass` | bool | Gesture flag |
205
+ | `temperature` | 0.0-3.0 | Fixed at 1.1 (default) |
206
+ | `guidance` | 0.0-6.0 | Fixed at 4.0 (prompt adherence) |
207
+
208
+ ### Prompt Engineering
209
+
210
+ The Qwen model receives structured gesture descriptions like:
211
+
212
+ ```
213
+ Hand HIGH (0.8), fingers WIDE, wrist STRAIGHT, movement STILL.
214
+
215
+ Evolve gradually — keep the groove, shift subtly.
216
+ ```
217
+
218
+ And outputs weighted prompt JSON:
219
+
220
+ ```json
221
+ {
222
+ "prompts": [
223
+ {"text": "ethereal ambient floating pads celestial", "weight": 1.5},
224
+ {"text": "shimmering reverb atmosphere", "weight": 1.0}
225
+ ]
226
+ }
227
+ ```
228
+
229
+ The conversation history ensures coherent transitions between styles.
230
+
231
+ ---
232
+
233
+ ## Gesture Change Detection
234
+
235
+ The backend implements a two-tier change detection system:
236
+
237
+ ### Significant Change (triggers config update + Qwen prompt)
238
+ - Hand height moved > 0.12
239
+ - Finger spread changed > 0.15
240
+ - Wrist angle changed > 0.25
241
+ - Hand velocity > 0.25
242
+ - Shape (white square) toggled
243
+ - Drum hand toggled
244
+
245
+ ### Major Change (triggers Qwen "change direction" mode)
246
+ - Hand height moved > 0.3
247
+ - Finger spread changed > 0.35
248
+ - Hand velocity > 0.5
249
+ - Shape toggled
250
+
251
+ If neither threshold is met, **no updates are sent** — the music stays locked in its current groove.
252
+
253
+ ---
254
+
255
+ ## Deployment to Hugging Face Spaces
256
+
257
+ 1. Create a **private** Space on Hugging Face (SDK: Docker or Static)
258
+ 2. Add `GEMINI_API_KEY` as a Secret in Space settings
259
+ 3. Push the repository to the Space
260
+ 4. The backend will read the API key from environment variables
261
+
262
+ ---
263
+
264
+ ## Known Limitations
265
+
266
+ - **Lyria session limit**: 10 minutes max per session. Page refresh starts a new session.
267
+ - **Audio latency**: ~3-4 second initial latency for first chunk, then ~2 second chunks arrive smoothly. Not suitable for rhythm-game-level precision.
268
+ - **Qwen inference**: ~1-2 seconds per prompt generation on CPU with 0.8B model. Doesn't block audio streaming.
269
+ - **No vocals**: Lyria RealTime generates instrumental music only.
270
+ - **Experimental API**: Lyria RealTime is in `v1alpha` — API may change.
271
+
272
+ ---
273
+
274
+ ## Credits
275
+
276
+ - **Original Hyperspace Jam**: [collidingScopes](https://github.com/collidingScopes/arpeggiator) — hand tracking + Tone.js synth + hyperbolic visuals
277
+ - **Lyria RealTime**: [Google DeepMind](https://deepmind.google/models/lyria/lyria-realtime/) — real-time AI music generation
278
+ - **Qwen 3.5**: [Alibaba/Qwen](https://github.com/QwenLM/Qwen3) — small language model for gesture interpretation
279
+ - **MediaPipe**: [Google](https://mediapipe.dev/) — hand landmark detection
280
+ - **Three.js**: [mrdoob](https://threejs.org/) — WebGL rendering
281
+ - **Ollama**: [ollama.com](https://ollama.com/) — local LLM inference
282
+
283
+ ## License
284
+
285
+ MIT License
ShapeManager.js ADDED
@@ -0,0 +1,475 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import * as THREE from 'three';
2
+ import { createTessellationMaterial } from './ShapeTessellationShader.js';
3
+
4
+ export class ShapeManager {
5
+ constructor(scene) {
6
+ this.scene = scene;
7
+ this.group = new THREE.Group();
8
+ this.group.renderOrder = 1.5;
9
+ this.scene.add(this.group);
10
+
11
+ // Anchor tracking
12
+ this.anchors = [];
13
+ this.fadingAnchors = [];
14
+
15
+ // Internal tessellation
16
+ this.tessellationMesh = null;
17
+ this.tessellationMaterial = null;
18
+ this.shapeFormedTime = 0;
19
+ this.lastShapeType = 'none';
20
+ this.tessellationActive = false;
21
+
22
+ this.PINCH_THRESHOLD = 30; // pixels screen space
23
+ this.SMOOTH_FACTOR = 0.3;
24
+ this.FADE_DURATION = 150; // ms
25
+
26
+ // --- Pre-allocate node pool (6 nodes for active + 6 for fading) ---
27
+ this.nodePool = [];
28
+ for (let i = 0; i < 12; i++) {
29
+ const squareGeom = new THREE.PlaneGeometry(20, 20);
30
+ const squareMat = new THREE.MeshBasicMaterial({
31
+ color: 0xffffff,
32
+ transparent: true,
33
+ opacity: 1,
34
+ depthTest: false,
35
+ side: THREE.DoubleSide
36
+ });
37
+ const squareMesh = new THREE.Mesh(squareGeom, squareMat);
38
+ squareMesh.rotation.z = Math.PI / 4;
39
+ squareMesh.visible = false;
40
+
41
+ const dotGeom = new THREE.CircleGeometry(4, 16);
42
+ const dotMat = new THREE.MeshBasicMaterial({
43
+ color: 0xffffff,
44
+ transparent: true,
45
+ opacity: 1,
46
+ depthTest: false,
47
+ side: THREE.DoubleSide
48
+ });
49
+ const dotMesh = new THREE.Mesh(dotGeom, dotMat);
50
+ dotMesh.visible = false;
51
+
52
+ this.group.add(squareMesh);
53
+ this.group.add(dotMesh);
54
+ this.nodePool.push({ square: squareMesh, dot: dotMesh });
55
+ }
56
+
57
+ // --- Pre-allocate edge pool (12 edges) ---
58
+ this.edgePool = [];
59
+ for (let i = 0; i < 12; i++) {
60
+ const positions = new Float32Array(4 * 3); // 4 vertices × 3 coords
61
+ const indices = new Uint16Array([0, 1, 2, 0, 2, 3]);
62
+ const geom = new THREE.BufferGeometry();
63
+ geom.setAttribute('position', new THREE.BufferAttribute(positions, 3));
64
+ geom.setIndex(new THREE.BufferAttribute(indices, 1));
65
+
66
+ const mat = new THREE.MeshBasicMaterial({
67
+ color: 0xffffff,
68
+ transparent: true,
69
+ opacity: 1,
70
+ depthTest: false,
71
+ side: THREE.DoubleSide
72
+ });
73
+ const mesh = new THREE.Mesh(geom, mat);
74
+ mesh.visible = false;
75
+
76
+ this.group.add(mesh);
77
+ this.edgePool.push(mesh);
78
+ }
79
+ }
80
+
81
+ update(handsData, canvasWidth, canvasHeight) {
82
+ const now = performance.now();
83
+
84
+ // --- Hide all pooled meshes ---
85
+ for (const node of this.nodePool) {
86
+ node.square.visible = false;
87
+ node.dot.visible = false;
88
+ }
89
+ for (const edge of this.edgePool) {
90
+ edge.visible = false;
91
+ }
92
+
93
+ if (!handsData) handsData = [];
94
+
95
+ // --- Detect anchors from each hand ---
96
+ const rawAnchors = [];
97
+
98
+ for (let h = 0; h < handsData.length; h++) {
99
+ const points3D = handsData[h];
100
+ if (!points3D || points3D.length < 21) continue;
101
+
102
+ const thumbTip = points3D[4];
103
+ const indexTip = points3D[8];
104
+ const middleTip = points3D[12];
105
+ const middleDip = points3D[10]; // for extension check
106
+
107
+ // Compute average z across all landmarks for depth
108
+ let avgZ = 0;
109
+ for (let l = 0; l < 21; l++) {
110
+ avgZ += points3D[l].z;
111
+ }
112
+ avgZ /= 21;
113
+
114
+ // Distance between thumb and index
115
+ const dx = thumbTip.x - indexTip.x;
116
+ const dy = thumbTip.y - indexTip.y;
117
+ const thumbIndexDist = Math.sqrt(dx * dx + dy * dy);
118
+
119
+ // Check if middle finger is extended (tip significantly above dip in y)
120
+ const middleExtended = (middleDip.y - middleTip.y) > 15;
121
+
122
+ if (thumbIndexDist < this.PINCH_THRESHOLD) {
123
+ // PINCHING — thumb+index merge into 1 anchor at midpoint
124
+ rawAnchors.push({
125
+ position: new THREE.Vector3(
126
+ (thumbTip.x + indexTip.x) / 2,
127
+ (thumbTip.y + indexTip.y) / 2,
128
+ 0
129
+ ),
130
+ id: `h${h}_pinch`,
131
+ avgZ
132
+ });
133
+
134
+ // If middle finger extended while pinching, add it as a 2nd anchor
135
+ if (middleExtended) {
136
+ rawAnchors.push({
137
+ position: new THREE.Vector3(middleTip.x, middleTip.y, 0),
138
+ id: `h${h}_middle`,
139
+ avgZ
140
+ });
141
+ }
142
+ } else {
143
+ // NOT PINCHING — thumb and index are separate anchors
144
+ rawAnchors.push({
145
+ position: new THREE.Vector3(thumbTip.x, thumbTip.y, 0),
146
+ id: `h${h}_thumb`,
147
+ avgZ
148
+ });
149
+ rawAnchors.push({
150
+ position: new THREE.Vector3(indexTip.x, indexTip.y, 0),
151
+ id: `h${h}_index`,
152
+ avgZ
153
+ });
154
+
155
+ // If middle finger extended, add it too
156
+ if (middleExtended) {
157
+ rawAnchors.push({
158
+ position: new THREE.Vector3(middleTip.x, middleTip.y, 0),
159
+ id: `h${h}_middle`,
160
+ avgZ
161
+ });
162
+ }
163
+ }
164
+ }
165
+
166
+ // --- Match raw anchors to existing anchors by id ---
167
+ const matchedIds = new Set();
168
+ const newAnchors = [];
169
+
170
+ for (let r = 0; r < rawAnchors.length; r++) {
171
+ const raw = rawAnchors[r];
172
+ let found = false;
173
+
174
+ for (let a = 0; a < this.anchors.length; a++) {
175
+ if (matchedIds.has(this.anchors[a].id)) continue;
176
+ if (this.anchors[a].id === raw.id) {
177
+ // Update existing anchor with smoothing
178
+ const anchor = this.anchors[a];
179
+ anchor.smoothed.x += (raw.position.x - anchor.smoothed.x) * this.SMOOTH_FACTOR;
180
+ anchor.smoothed.y += (raw.position.y - anchor.smoothed.y) * this.SMOOTH_FACTOR;
181
+ anchor.depthScale = this._computeDepthScale(raw.avgZ);
182
+ anchor.avgZ = raw.avgZ;
183
+ newAnchors.push(anchor);
184
+ matchedIds.add(anchor.id);
185
+ found = true;
186
+ break;
187
+ }
188
+ }
189
+
190
+ if (!found) {
191
+ // New anchor — birth it
192
+ newAnchors.push({
193
+ smoothed: raw.position.clone(),
194
+ id: raw.id,
195
+ birthTime: now,
196
+ depthScale: this._computeDepthScale(raw.avgZ),
197
+ avgZ: raw.avgZ
198
+ });
199
+ }
200
+ }
201
+
202
+ // Anchors that disappeared — move to fading
203
+ for (let a = 0; a < this.anchors.length; a++) {
204
+ if (!matchedIds.has(this.anchors[a].id)) {
205
+ const dying = this.anchors[a];
206
+ dying.fadeStartTime = now;
207
+ this.fadingAnchors.push(dying);
208
+ }
209
+ }
210
+
211
+ this.anchors = newAnchors;
212
+
213
+ // --- Update fading anchors, remove expired ---
214
+ this.fadingAnchors = this.fadingAnchors.filter(fa => (now - fa.fadeStartTime) < this.FADE_DURATION);
215
+
216
+ // --- Determine shape type ---
217
+ const activeCount = this.anchors.length;
218
+ let shapeType = 'none';
219
+ if (activeCount === 2) shapeType = 'line';
220
+ else if (activeCount === 3) shapeType = 'triangle';
221
+ else if (activeCount >= 4) shapeType = 'quad';
222
+
223
+ // --- Render active anchor nodes (using pool) ---
224
+ let nodeIdx = 0;
225
+ for (let i = 0; i < this.anchors.length && nodeIdx < this.nodePool.length; i++, nodeIdx++) {
226
+ const anc = this.anchors[i];
227
+ const age = now - anc.birthTime;
228
+ const fadeIn = Math.min(1, age / this.FADE_DURATION);
229
+ const scale = anc.depthScale;
230
+ const node = this.nodePool[nodeIdx];
231
+
232
+ node.square.visible = true;
233
+ node.square.position.set(anc.smoothed.x, anc.smoothed.y, 3);
234
+ node.square.scale.set(scale, scale, 1);
235
+ node.square.material.opacity = fadeIn;
236
+
237
+ node.dot.visible = true;
238
+ node.dot.position.set(anc.smoothed.x, anc.smoothed.y, 3.01);
239
+ node.dot.scale.set(scale, scale, 1);
240
+ node.dot.material.opacity = fadeIn;
241
+ }
242
+
243
+ // --- Render fading anchor nodes (using pool) ---
244
+ for (let i = 0; i < this.fadingAnchors.length && nodeIdx < this.nodePool.length; i++, nodeIdx++) {
245
+ const fa = this.fadingAnchors[i];
246
+ const fadeOut = 1 - Math.min(1, (now - fa.fadeStartTime) / this.FADE_DURATION);
247
+ const scale = fa.depthScale;
248
+ const node = this.nodePool[nodeIdx];
249
+
250
+ node.square.visible = true;
251
+ node.square.position.set(fa.smoothed.x, fa.smoothed.y, 3);
252
+ node.square.scale.set(scale, scale, 1);
253
+ node.square.material.opacity = fadeOut;
254
+
255
+ node.dot.visible = true;
256
+ node.dot.position.set(fa.smoothed.x, fa.smoothed.y, 3.01);
257
+ node.dot.scale.set(scale, scale, 1);
258
+ node.dot.material.opacity = fadeOut;
259
+ }
260
+
261
+ // --- Render edges (using pool) ---
262
+ if (shapeType !== 'none') {
263
+ this._drawEdges(shapeType, now);
264
+ }
265
+
266
+ // --- Internal tessellation for closed shapes ---
267
+ if (shapeType === 'triangle' || shapeType === 'quad') {
268
+ if (shapeType !== this.lastShapeType) {
269
+ this.shapeFormedTime = now;
270
+ this.lastShapeType = shapeType;
271
+ this.tessellationActive = false;
272
+ }
273
+
274
+ if (!this.tessellationActive && (now - this.shapeFormedTime) > 200) {
275
+ this.tessellationActive = true;
276
+ this._createTessellationMesh(canvasWidth, canvasHeight);
277
+ }
278
+
279
+ if (this.tessellationActive && this.tessellationMaterial) {
280
+ this.tessellationMaterial.uniforms.u_time.value = now * 0.001;
281
+ this.tessellationMaterial.uniforms.u_vertexCount.value = (shapeType === 'triangle') ? 3 : 4;
282
+ this.tessellationMaterial.uniforms.u_resolution.value.set(canvasWidth, canvasHeight);
283
+
284
+ for (let v = 0; v < 4; v++) {
285
+ if (v < this.anchors.length) {
286
+ this.tessellationMaterial.uniforms.u_vertices.value[v].set(
287
+ this.anchors[v].smoothed.x / (canvasWidth / 2),
288
+ this.anchors[v].smoothed.y / (canvasHeight / 2)
289
+ );
290
+ }
291
+ }
292
+ }
293
+ } else {
294
+ if (this.tessellationActive) {
295
+ this._removeTessellationMesh();
296
+ this.tessellationActive = false;
297
+ }
298
+ this.lastShapeType = shapeType;
299
+ }
300
+ }
301
+
302
+ _computeDepthScale(avgZ) {
303
+ // Map z from [-0.2, 0] to [3.0, 0.5] (DRAMATIC range)
304
+ const t = Math.max(0, Math.min(1, (avgZ - (-0.2)) / (0 - (-0.2))));
305
+ return 3.0 + t * (0.5 - 3.0); // lerp from 3.0 (close) to 0.5 (far)
306
+ }
307
+
308
+ _drawEdges(shapeType, now) {
309
+ const z = 3;
310
+ const anchors = this.anchors;
311
+
312
+ // Compute min opacity from birth fades
313
+ let minOpacity = 1;
314
+ for (let i = 0; i < anchors.length; i++) {
315
+ const age = now - anchors[i].birthTime;
316
+ const fade = Math.min(1, age / this.FADE_DURATION);
317
+ if (fade < minOpacity) minOpacity = fade;
318
+ }
319
+
320
+ // Average depth scale for edge width
321
+ let avgDepthScale = 0;
322
+ for (let i = 0; i < anchors.length; i++) {
323
+ avgDepthScale += anchors[i].depthScale;
324
+ }
325
+ avgDepthScale /= anchors.length;
326
+
327
+ const edgeWidth = 4 * avgDepthScale;
328
+
329
+ // Build edge pairs
330
+ const edges = [];
331
+ if (shapeType === 'line') {
332
+ // Two parallel lines offset ±3px perpendicular
333
+ const a = anchors[0].smoothed;
334
+ const b = anchors[1].smoothed;
335
+ const dx = b.x - a.x;
336
+ const dy = b.y - a.y;
337
+ const len = Math.sqrt(dx * dx + dy * dy);
338
+ if (len < 0.001) return;
339
+ const nx = -dy / len * 3;
340
+ const ny = dx / len * 3;
341
+
342
+ edges.push([
343
+ new THREE.Vector3(a.x + nx, a.y + ny, z),
344
+ new THREE.Vector3(b.x + nx, b.y + ny, z)
345
+ ]);
346
+ edges.push([
347
+ new THREE.Vector3(a.x - nx, a.y - ny, z),
348
+ new THREE.Vector3(b.x - nx, b.y - ny, z)
349
+ ]);
350
+ } else if (shapeType === 'triangle') {
351
+ for (let i = 0; i < 3; i++) {
352
+ const j = (i + 1) % 3;
353
+ edges.push([
354
+ new THREE.Vector3(anchors[i].smoothed.x, anchors[i].smoothed.y, z),
355
+ new THREE.Vector3(anchors[j].smoothed.x, anchors[j].smoothed.y, z)
356
+ ]);
357
+ }
358
+ } else if (shapeType === 'quad') {
359
+ const count = Math.min(anchors.length, 4);
360
+ for (let i = 0; i < count; i++) {
361
+ const j = (i + 1) % count;
362
+ edges.push([
363
+ new THREE.Vector3(anchors[i].smoothed.x, anchors[i].smoothed.y, z),
364
+ new THREE.Vector3(anchors[j].smoothed.x, anchors[j].smoothed.y, z)
365
+ ]);
366
+ }
367
+ }
368
+
369
+ // Render each edge by updating pre-allocated buffer geometry
370
+ for (let e = 0; e < edges.length && e < this.edgePool.length; e++) {
371
+ const pA = edges[e][0];
372
+ const pB = edges[e][1];
373
+
374
+ const dx = pB.x - pA.x;
375
+ const dy = pB.y - pA.y;
376
+ const len = Math.sqrt(dx * dx + dy * dy);
377
+ if (len < 0.001) continue;
378
+
379
+ // Perpendicular direction for width
380
+ const nx = -dy / len * (edgeWidth / 2);
381
+ const ny = dx / len * (edgeWidth / 2);
382
+
383
+ const mesh = this.edgePool[e];
384
+ const posAttr = mesh.geometry.getAttribute('position');
385
+ const arr = posAttr.array;
386
+
387
+ // 4 vertices forming a thin rectangle
388
+ arr[0] = pA.x + nx; arr[1] = pA.y + ny; arr[2] = z;
389
+ arr[3] = pA.x - nx; arr[4] = pA.y - ny; arr[5] = z;
390
+ arr[6] = pB.x - nx; arr[7] = pB.y - ny; arr[8] = z;
391
+ arr[9] = pB.x + nx; arr[10] = pB.y + ny; arr[11] = z;
392
+
393
+ posAttr.needsUpdate = true;
394
+ mesh.material.opacity = minOpacity;
395
+ mesh.visible = true;
396
+ }
397
+ }
398
+
399
+ getShapeState() {
400
+ const count = this.anchors.length;
401
+ let type = 'none';
402
+ if (count === 2) type = 'line';
403
+ else if (count === 3) type = 'triangle';
404
+ else if (count >= 4) type = 'quad';
405
+
406
+ const anchorPositions = this.anchors.map(a => a.smoothed.clone());
407
+ return { type, anchors: anchorPositions };
408
+ }
409
+
410
+ getAnchors() {
411
+ return this.anchors.map(a => a.smoothed.clone());
412
+ }
413
+
414
+ getAverageDepth() {
415
+ if (this.anchors.length === 0) return 0;
416
+ let sum = 0;
417
+ for (let i = 0; i < this.anchors.length; i++) {
418
+ sum += this.anchors[i].avgZ;
419
+ }
420
+ return sum / this.anchors.length;
421
+ }
422
+
423
+ getShapeArea() {
424
+ if (this.anchors.length < 3) return 0;
425
+ const points = this.anchors.map(a => a.smoothed);
426
+ let area = 0;
427
+ const n = points.length;
428
+ for (let i = 0; i < n; i++) {
429
+ const j = (i + 1) % n;
430
+ area += points[i].x * points[j].y;
431
+ area -= points[j].x * points[i].y;
432
+ }
433
+ area = Math.abs(area) / 2;
434
+ return Math.min(1, area / 200000);
435
+ }
436
+
437
+ _createTessellationMesh(canvasWidth, canvasHeight) {
438
+ this._removeTessellationMesh();
439
+ this.tessellationMaterial = createTessellationMaterial();
440
+ this.tessellationMaterial.uniforms.u_resolution.value.set(canvasWidth, canvasHeight);
441
+ const geom = new THREE.PlaneGeometry(2, 2);
442
+ this.tessellationMesh = new THREE.Mesh(geom, this.tessellationMaterial);
443
+ this.tessellationMesh.renderOrder = 1.3;
444
+ this.scene.add(this.tessellationMesh);
445
+ }
446
+
447
+ _removeTessellationMesh() {
448
+ if (this.tessellationMesh) {
449
+ this.scene.remove(this.tessellationMesh);
450
+ this.tessellationMesh.geometry.dispose();
451
+ this.tessellationMaterial.dispose();
452
+ this.tessellationMesh = null;
453
+ this.tessellationMaterial = null;
454
+ }
455
+ }
456
+
457
+ dispose() {
458
+ this._removeTessellationMesh();
459
+ // Dispose all pooled geometries and materials
460
+ for (const node of this.nodePool) {
461
+ node.square.geometry.dispose();
462
+ node.square.material.dispose();
463
+ node.dot.geometry.dispose();
464
+ node.dot.material.dispose();
465
+ }
466
+ for (const edge of this.edgePool) {
467
+ edge.geometry.dispose();
468
+ edge.material.dispose();
469
+ }
470
+ while (this.group.children.length) {
471
+ this.group.remove(this.group.children[0]);
472
+ }
473
+ this.scene.remove(this.group);
474
+ }
475
+ }
ShapeTessellationShader.js ADDED
@@ -0,0 +1,231 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import * as THREE from 'three';
2
+
3
+ export const tessVertexShader = `
4
+ void main() {
5
+ gl_Position = vec4(position.xy, 0.0, 1.0);
6
+ }
7
+ `;
8
+
9
+ export const tessFragmentShader = `
10
+ precision highp float;
11
+
12
+ uniform float u_time;
13
+ uniform vec2 u_vertices[4];
14
+ uniform int u_vertexCount;
15
+ uniform float u_amplitude;
16
+ uniform vec2 u_resolution;
17
+
18
+ // --- Complex arithmetic (from WaveformVisualizer) ---
19
+ vec2 cmul(vec2 a, vec2 b) {
20
+ return vec2(a.x * b.x - a.y * b.y, a.x * b.y + a.y * b.x);
21
+ }
22
+
23
+ vec2 cdiv(vec2 a, vec2 b) {
24
+ float d = dot(b, b);
25
+ return vec2(dot(a, b), a.y * b.x - a.x * b.y) / d;
26
+ }
27
+
28
+ vec2 conj(vec2 z) {
29
+ return vec2(z.x, -z.y);
30
+ }
31
+
32
+ vec2 mobius(vec2 z, vec2 a) {
33
+ return cdiv(z - a, vec2(1.0, 0.0) - cmul(conj(a), z));
34
+ }
35
+
36
+ float hdist(vec2 z) {
37
+ float r = length(z);
38
+ if (r >= 1.0) return 10.0;
39
+ return log((1.0 + r) / (1.0 - r));
40
+ }
41
+
42
+ vec2 rot(vec2 p, float a) {
43
+ float c = cos(a), s = sin(a);
44
+ return vec2(c * p.x - s * p.y, s * p.x + c * p.y);
45
+ }
46
+
47
+ // --- HSV to RGB ---
48
+ vec3 hsv2rgb(vec3 c) {
49
+ vec4 K = vec4(1.0, 2.0/3.0, 1.0/3.0, 3.0);
50
+ vec3 p = abs(fract(c.xxx + K.xyz) * 6.0 - K.www);
51
+ return c.z * mix(K.xxx, clamp(p - K.xxx, 0.0, 1.0), c.y);
52
+ }
53
+
54
+ // --- Polygon winding number test ---
55
+ float crossZ(vec2 a, vec2 b) {
56
+ return a.x * b.y - a.y * b.x;
57
+ }
58
+
59
+ bool insidePolygon(vec2 p, int count) {
60
+ int winding = 0;
61
+ for (int i = 0; i < 4; i++) {
62
+ if (i >= count) break;
63
+ int j = i + 1;
64
+ if (j >= count) j = 0;
65
+ vec2 vi = u_vertices[i];
66
+ vec2 vj = u_vertices[j];
67
+ if (vi.y <= p.y) {
68
+ if (vj.y > p.y) {
69
+ if (crossZ(vj - vi, p - vi) > 0.0) winding++;
70
+ }
71
+ } else {
72
+ if (vj.y <= p.y) {
73
+ if (crossZ(vj - vi, p - vi) < 0.0) winding--;
74
+ }
75
+ }
76
+ }
77
+ return winding != 0;
78
+ }
79
+
80
+ // --- Map point inside polygon to unit disk ---
81
+ vec2 mapToDisk(vec2 p, int count) {
82
+ // Compute ctr
83
+ vec2 ctr = vec2(0.0);
84
+ for (int i = 0; i < 4; i++) {
85
+ if (i >= count) break;
86
+ ctr += u_vertices[i];
87
+ }
88
+ ctr /= float(count);
89
+
90
+ // Find max distance from ctr to any vertex
91
+ float maxDist = 0.0;
92
+ for (int i = 0; i < 4; i++) {
93
+ if (i >= count) break;
94
+ float d = length(u_vertices[i] - ctr);
95
+ if (d > maxDist) maxDist = d;
96
+ }
97
+
98
+ // Normalize: ctr -> origin, scale so vertices sit near disk edge
99
+ vec2 offset = (p - ctr) / max(maxDist, 0.001);
100
+
101
+ // Clamp to disk
102
+ float r = length(offset);
103
+ if (r > 0.98) offset = normalize(offset) * 0.98;
104
+
105
+ return offset;
106
+ }
107
+
108
+ void main() {
109
+ // Convert fragment coords to normalized [-1,1] using resolution
110
+ vec2 ndc = (gl_FragCoord.xy / u_resolution) * 2.0 - 1.0;
111
+
112
+ // Polygon clip
113
+ int count = u_vertexCount;
114
+ if (!insidePolygon(ndc, count)) {
115
+ discard;
116
+ }
117
+
118
+ // Map to unit disk
119
+ vec2 diskPos = mapToDisk(ndc, count);
120
+
121
+ float r = length(diskPos);
122
+ if (r >= 1.0) {
123
+ discard;
124
+ }
125
+
126
+ // Audio-reactive rotation
127
+ float rotSpeed = 0.12 + 0.08 * u_amplitude;
128
+ vec2 uv = rot(diskPos, u_time * rotSpeed);
129
+
130
+ // Breathing scale
131
+ float breathe = 1.0 + 0.1 * u_amplitude;
132
+ uv *= breathe;
133
+
134
+ if (length(uv) >= 1.0) {
135
+ discard;
136
+ }
137
+
138
+ // --- {7,3} Poincare tessellation (from WaveformVisualizer) ---
139
+ float n = 7.0;
140
+ float angleStep = 6.283185 / n;
141
+
142
+ float coshR = cos(3.14159265 / 3.0) / sin(3.14159265 / n);
143
+ float sinhR = sqrt(coshR * coshR - 1.0);
144
+ float tr = sinhR / (coshR + 1.0);
145
+
146
+ vec2 z = uv;
147
+ float iter = 0.0;
148
+
149
+ for (int i = 0; i < 20; i++) {
150
+ float ang = atan(z.y, z.x);
151
+ float sector = floor(ang / angleStep + 0.5) * angleStep;
152
+
153
+ z = rot(z, -sector);
154
+ iter += abs(sector) > 0.01 ? 1.0 : 0.0;
155
+
156
+ vec2 center = vec2(tr, 0.0);
157
+ vec2 w = mobius(z, center);
158
+
159
+ if (length(w) >= length(z) - 0.0001) break;
160
+ z = w;
161
+ iter += 1.0;
162
+ }
163
+
164
+ float d = hdist(z);
165
+
166
+ // --- DMT-Chrome coloring ---
167
+ // Pulsation: biological rhythm ~3 second cycle
168
+ float pulsation = 0.5 + 0.5 * sin(u_time * 2.094); // 2*pi/3 ≈ 2.094 for ~3s cycle
169
+
170
+ // Hue flows along geometry toward center
171
+ float hueFlow = sin(iter * 0.3 + u_time * 0.1);
172
+ // Map to: deep blue(0.6) -> purple(0.75) -> pink(0.85) -> green(0.3)
173
+ float hue;
174
+ if (hueFlow > 0.33) {
175
+ hue = mix(0.6, 0.75, (hueFlow - 0.33) / 0.67); // blue -> purple
176
+ } else if (hueFlow > -0.33) {
177
+ hue = mix(0.75, 0.85, (0.33 - hueFlow) / 0.66); // purple -> pink
178
+ } else {
179
+ hue = mix(0.85, 1.3, (-0.33 - hueFlow) / 0.67); // pink -> green (via 1.0+)
180
+ }
181
+ hue = fract(hue);
182
+
183
+ float sat = 0.9;
184
+ float val = 0.7 + 0.3 * pulsation;
185
+
186
+ vec3 color = hsv2rgb(vec3(hue, sat, val));
187
+
188
+ // Edge flare: internal tile edges glow brighter at pulsation peaks
189
+ float edgeLine = 1.0 - smoothstep(0.0, 0.05, abs(fract(d * 1.5) - 0.5) - 0.42);
190
+ color += vec3(0.3, 0.2, 0.4) * edgeLine * pulsation;
191
+
192
+ // Sector pattern for extra geometry detail
193
+ float ang = atan(z.y, z.x);
194
+ float sectorPattern = smoothstep(0.02, 0.05, abs(sin(ang * n * 0.5)));
195
+ color *= 0.75 + 0.25 * sectorPattern;
196
+
197
+ // Audio boost
198
+ color *= 0.9 + 0.3 * u_amplitude;
199
+
200
+ // Disk edge fade
201
+ float diskEdge = smoothstep(0.98, 0.85, r);
202
+ color *= diskEdge;
203
+
204
+ color = min(color, vec3(1.0));
205
+
206
+ gl_FragColor = vec4(color, 0.8);
207
+ }
208
+ `;
209
+
210
+ export function createTessellationMaterial() {
211
+ return new THREE.ShaderMaterial({
212
+ uniforms: {
213
+ u_time: { value: 0 },
214
+ u_vertices: { value: [
215
+ new THREE.Vector2(),
216
+ new THREE.Vector2(),
217
+ new THREE.Vector2(),
218
+ new THREE.Vector2()
219
+ ]},
220
+ u_vertexCount: { value: 3 },
221
+ u_amplitude: { value: 0 },
222
+ u_resolution: { value: new THREE.Vector2(1, 1) }
223
+ },
224
+ vertexShader: tessVertexShader,
225
+ fragmentShader: tessFragmentShader,
226
+ transparent: true,
227
+ depthWrite: false,
228
+ depthTest: false,
229
+ side: THREE.DoubleSide
230
+ });
231
+ }
WaveformVisualizer.js ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import * as THREE from 'three';
2
+
3
+ const vertexShader = `
4
+ void main() {
5
+ gl_Position = vec4(position.xy, 0.0, 1.0);
6
+ }
7
+ `;
8
+
9
+ const fragmentShader = `
10
+ precision highp float;
11
+
12
+ uniform float u_time;
13
+ uniform float u_amplitude;
14
+ uniform vec2 u_resolution;
15
+ uniform vec3 u_color;
16
+ uniform float u_breathe;
17
+
18
+ vec2 cmul(vec2 a, vec2 b) {
19
+ return vec2(a.x * b.x - a.y * b.y, a.x * b.y + a.y * b.x);
20
+ }
21
+
22
+ vec2 cdiv(vec2 a, vec2 b) {
23
+ float d = dot(b, b);
24
+ return vec2(dot(a, b), a.y * b.x - a.x * b.y) / d;
25
+ }
26
+
27
+ vec2 conj(vec2 z) {
28
+ return vec2(z.x, -z.y);
29
+ }
30
+
31
+ vec2 mobius(vec2 z, vec2 a) {
32
+ return cdiv(z - a, vec2(1.0, 0.0) - cmul(conj(a), z));
33
+ }
34
+
35
+ float hdist(vec2 z) {
36
+ float r = length(z);
37
+ if (r >= 1.0) return 10.0;
38
+ return log((1.0 + r) / (1.0 - r));
39
+ }
40
+
41
+ vec2 rot(vec2 p, float a) {
42
+ float c = cos(a), s = sin(a);
43
+ return vec2(c * p.x - s * p.y, s * p.x + c * p.y);
44
+ }
45
+
46
+ void main() {
47
+ vec2 uv = (gl_FragCoord.xy - 0.5 * u_resolution) / min(u_resolution.x, u_resolution.y);
48
+
49
+ // Texture breathing: subtle scale pulsation independent of audio
50
+ uv *= 1.0 + 0.05 * (u_breathe - 0.5);
51
+
52
+ float breathe = 1.0 + 0.15 * u_amplitude;
53
+ uv *= 1.1 * breathe;
54
+
55
+ float r = length(uv);
56
+
57
+ if (r >= 1.0) {
58
+ gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);
59
+ return;
60
+ }
61
+
62
+ float rotSpeed = 0.08 + 0.05 * u_amplitude;
63
+ uv = rot(uv, u_time * rotSpeed);
64
+
65
+ float n = 7.0;
66
+ float angleStep = 6.283185 / n;
67
+
68
+ float coshR = cos(3.14159265 / 3.0) / sin(3.14159265 / n);
69
+ float sinhR = sqrt(coshR * coshR - 1.0);
70
+ float tr = sinhR / (coshR + 1.0);
71
+
72
+ vec2 z = uv;
73
+ float iter = 0.0;
74
+
75
+ for (int i = 0; i < 40; i++) {
76
+ float ang = atan(z.y, z.x);
77
+ float sector = floor(ang / angleStep + 0.5) * angleStep;
78
+
79
+ z = rot(z, -sector);
80
+ iter += abs(sector) > 0.01 ? 1.0 : 0.0;
81
+
82
+ vec2 center = vec2(tr, 0.0);
83
+ vec2 w = mobius(z, center);
84
+
85
+ if (length(w) >= length(z) - 0.0001) break;
86
+ z = w;
87
+ iter += 1.0;
88
+ }
89
+
90
+ float d = hdist(z);
91
+
92
+ // Color palette: deep purples, teals, magentas — psychedelic but dark
93
+ float t = mod(iter * 0.1 + u_time * 0.02, 1.0);
94
+ vec3 col1 = vec3(0.03, 0.01, 0.08); // deep purple-black
95
+ vec3 col2 = vec3(0.02, 0.10, 0.15); // dark teal
96
+ vec3 col3 = vec3(0.12, 0.02, 0.10); // dark magenta
97
+
98
+ vec3 color = mix(col1, col2, sin(iter * 0.7 + u_time * 0.1) * 0.5 + 0.5);
99
+ color = mix(color, col3, sin(iter * 1.1 - u_time * 0.15) * 0.5 + 0.5);
100
+
101
+ // Breathe-modulated saturation
102
+ float sat = 0.85 + 0.15 * u_breathe;
103
+ color *= sat;
104
+
105
+ // Tint toward the hand-gesture color
106
+ float satBoost = 0.3 + 0.2 * u_amplitude;
107
+ color = mix(color, u_color * 0.15, satBoost * 0.3);
108
+
109
+ // Edge highlights with glow from amplitude
110
+ float edgeThreshold = (0.04 - 0.02 * u_amplitude) * (1.0 + 0.3 * u_breathe);
111
+ float edgeLine = 1.0 - smoothstep(0.0, edgeThreshold, abs(fract(d * 1.5) - 0.5) - 0.45);
112
+ color += vec3(0.06, 0.08, 0.14) * edgeLine * (1.0 + u_amplitude);
113
+
114
+ // Sector pattern
115
+ float ang = atan(z.y, z.x);
116
+ float sectorPattern = smoothstep(0.02, 0.04, abs(sin(ang * n * 0.5)));
117
+ color *= 0.7 + 0.3 * sectorPattern;
118
+
119
+ // Audio reactive brightness
120
+ color *= 0.8 + 0.25 * u_amplitude;
121
+
122
+ // Disk edge fade
123
+ float diskEdge = smoothstep(0.98, 0.92, r);
124
+ color *= diskEdge;
125
+
126
+ color = min(color, vec3(1.0));
127
+
128
+ gl_FragColor = vec4(color, 0.45);
129
+ }
130
+ `;
131
+
132
+ export class WaveformVisualizer {
133
+ constructor(scene, analyser, canvasWidth, canvasHeight) {
134
+ this.scene = scene;
135
+ this.analyser = analyser;
136
+ this.mesh = null;
137
+ this.clock = new THREE.Clock();
138
+ this.currentColor = new THREE.Color('#7B4394');
139
+ this.targetColor = new THREE.Color('#7B4394');
140
+
141
+ this.uniforms = {
142
+ u_time: { value: 0.0 },
143
+ u_amplitude: { value: 0.0 },
144
+ u_resolution: { value: new THREE.Vector2(canvasWidth, canvasHeight) },
145
+ u_color: { value: this.currentColor },
146
+ u_breathe: { value: 0 }
147
+ };
148
+
149
+ this._createVisualizer();
150
+ }
151
+
152
+ _createVisualizer() {
153
+ const geometry = new THREE.PlaneGeometry(2, 2);
154
+ const material = new THREE.ShaderMaterial({
155
+ uniforms: this.uniforms,
156
+ vertexShader: vertexShader,
157
+ fragmentShader: fragmentShader,
158
+ transparent: true,
159
+ depthWrite: false,
160
+ depthTest: false
161
+ });
162
+
163
+ this.mesh = new THREE.Mesh(geometry, material);
164
+ this.mesh.renderOrder = -1;
165
+ this.mesh.frustumCulled = false;
166
+ this.scene.add(this.mesh);
167
+ }
168
+
169
+ update() {
170
+ if (!this.analyser || !this.mesh) return;
171
+
172
+ // Interpolate color
173
+ this.currentColor.lerp(this.targetColor, 0.05);
174
+
175
+ // Update time
176
+ this.uniforms.u_time.value = this.clock.getElapsedTime();
177
+
178
+ // Compute RMS amplitude from analyser
179
+ var waveformData = this.analyser.getValue();
180
+ var sum = 0;
181
+ for (var i = 0; i < waveformData.length; i++) {
182
+ sum += waveformData[i] * waveformData[i];
183
+ }
184
+ var amplitude = Math.sqrt(sum / waveformData.length);
185
+ this.uniforms.u_amplitude.value = amplitude;
186
+ this.lastAmplitude = amplitude;
187
+
188
+ var breathe = 0.5 + 0.5 * Math.sin(this.uniforms.u_time.value * 2.094); // ~3 second cycle
189
+ this.uniforms.u_breathe.value = breathe;
190
+ }
191
+
192
+ updateColor(newColor) {
193
+ this.targetColor.set(newColor);
194
+ }
195
+
196
+ updatePosition(canvasWidth, canvasHeight) {
197
+ this.uniforms.u_resolution.value.set(canvasWidth, canvasHeight);
198
+ }
199
+
200
+ dispose() {
201
+ if (this.mesh) {
202
+ this.scene.remove(this.mesh);
203
+ if (this.mesh.geometry) this.mesh.geometry.dispose();
204
+ if (this.mesh.material) this.mesh.material.dispose();
205
+ }
206
+ }
207
+ }
assets/clap.wav ADDED
Binary file (93.3 kB). View file
 
assets/demo.png ADDED

Git LFS Details

  • SHA256: a87d6ba857ed9ebc414fd4ff6ca445f7d234379672571661acc57e4f55dba881
  • Pointer size: 132 Bytes
  • Size of remote file: 2.42 MB
assets/hihat.wav ADDED
Binary file (35.6 kB). View file
 
assets/kick.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0f6aca362d354edda241a23ebd0721b3a6d3a75009a983920b9bd6ff5d551065
3
+ size 344364
assets/siteOGImage.webp ADDED

Git LFS Details

  • SHA256: 37381d0b03a61163ea089e8701b42d39d3a5cc7d756173a1ef9a8cecac6fad0a
  • Pointer size: 131 Bytes
  • Size of remote file: 154 kB
assets/snare.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8972ccc2d9cc63130ca95e4c55819dc7b27041ac6ac35bb8f362ba2c25e5a4c6
3
+ size 176478
backend/gesture_interpreter.py ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Gesture Interpreter — uses a tiny local Qwen 3.5 model (via Ollama) to translate
3
+ hand tracking state into musical text descriptions for Lyria RealTime prompts.
4
+
5
+ Maintains conversation history for smooth transitions and groove continuity.
6
+ """
7
+
8
+ import json
9
+ import httpx
10
+
11
+ OLLAMA_URL = "http://localhost:11434/api/chat"
12
+ MODEL_NAME = "qwen3.5:0.8b"
13
+
14
+ SYSTEM_PROMPT = """You are a live music DJ AI directing a real-time AI music generator.
15
+ You receive hand gesture descriptions from a performer and output JSON to control the music.
16
+
17
+ CRITICAL RULES:
18
+ - Output ONLY valid JSON, no other text
19
+ - Format: {"prompts":[{"text":"description","weight":1.0}]}
20
+ - Use 1-4 prompts, weights 0.1-3.0
21
+ - Keep descriptions under 10 words each
22
+ - Use synth/EDM instrument terminology
23
+
24
+ GESTURE MAPPING:
25
+ - HIGH hands = ethereal, ambient, atmospheric, shimmering pads, celestial, dreamy reverb, floating synths
26
+ - LOW hands = heavy nasty drippy drum and bass, deep reese bass, amen breaks, dark wobble, filthy sub
27
+ - MIDDLE hands = blend of both worlds, melodic electronic, progressive
28
+ - WIDE fingers = complex, layered, dense arpeggios, busy textures
29
+ - NARROW fingers = minimal, sparse, clean, simple
30
+ - FAST movement = aggressive, driving, energetic, intense, harder drops
31
+ - STILL/SLOW = ambient, floating, dreamy, calm, sustained
32
+ - WRIST TILT = acid, filter sweep, tension, dissonance, warped
33
+ - SHAPE ACTIVE = massive sub-bass drone, fat sawtooth, rumbling foundation
34
+ - DRUM HAND = rhythmic, percussive, breakbeats, driving beat
35
+
36
+ TRANSITION RULES:
37
+ - When told to "evolve gradually", keep the core genre and shift ONE element
38
+ - When told to "change direction", you may shift genre entirely
39
+ - Always maintain musical coherence between turns
40
+ - Build on what came before — don't jump randomly"""
41
+
42
+ # Few-shot examples for the conversation
43
+ SEED_EXAMPLES = [
44
+ {"role": "user", "content": "Hand HIGH (0.8), fingers WIDE, wrist STRAIGHT, movement STILL.\n\nEvolve gradually — keep the groove, shift subtly."},
45
+ {"role": "assistant", "content": '{"prompts":[{"text":"ethereal ambient floating pads celestial","weight":1.5},{"text":"shimmering reverb atmosphere","weight":1.0}]}'},
46
+ {"role": "user", "content": "Hand LOW (0.2), fingers MEDIUM, wrist TILTED LEFT, movement FAST.\n\nChange direction — the performer made a dramatic gesture shift."},
47
+ {"role": "assistant", "content": '{"prompts":[{"text":"heavy nasty drum and bass reese","weight":2.0},{"text":"filthy wobble sub-bass dark","weight":1.5},{"text":"acid filter sweep tension","weight":1.0}]}'},
48
+ ]
49
+
50
+
51
+ class GestureInterpreter:
52
+ def __init__(self, ollama_url: str = OLLAMA_URL, model: str = MODEL_NAME):
53
+ self.ollama_url = ollama_url
54
+ self.model = model
55
+ self.client = httpx.AsyncClient(timeout=10.0)
56
+ self._fallback_mode = False
57
+ # Conversation history for smooth transitions (keep last 4 exchanges)
58
+ self._history = list(SEED_EXAMPLES)
59
+ self._max_history = 12 # 6 user/assistant pairs
60
+
61
+ async def interpret(self, gesture_data: dict, force_new_direction: bool = False) -> list[dict] | None:
62
+ """Convert gesture data to Lyria weighted prompts via Qwen with history."""
63
+ description = self._build_description(gesture_data)
64
+
65
+ # Add transition instruction
66
+ if force_new_direction:
67
+ description += "\n\nChange direction — the performer made a dramatic gesture shift."
68
+ else:
69
+ description += "\n\nEvolve gradually — keep the groove, shift subtly."
70
+
71
+ if self._fallback_mode:
72
+ return self._rule_based_prompts(gesture_data)
73
+
74
+ try:
75
+ # Build messages with history
76
+ messages = [{"role": "system", "content": SYSTEM_PROMPT}]
77
+ messages.extend(self._history)
78
+ messages.append({"role": "user", "content": description})
79
+
80
+ response = await self.client.post(
81
+ self.ollama_url,
82
+ json={
83
+ "model": self.model,
84
+ "messages": messages,
85
+ "stream": False,
86
+ "think": False,
87
+ "options": {
88
+ "temperature": 0.7,
89
+ "num_predict": 200,
90
+ }
91
+ }
92
+ )
93
+ response.raise_for_status()
94
+ result = response.json()
95
+ text = result.get("message", {}).get("content", "").strip()
96
+
97
+ # Strip markdown fences if present
98
+ if text.startswith("```"):
99
+ text = text.split("\n", 1)[1] if "\n" in text else text[3:]
100
+ if text.endswith("```"):
101
+ text = text[:-3]
102
+ text = text.strip()
103
+
104
+ parsed = json.loads(text)
105
+ prompts = parsed.get("prompts", [])
106
+ if prompts:
107
+ # Update conversation history
108
+ self._history.append({"role": "user", "content": description})
109
+ self._history.append({"role": "assistant", "content": text})
110
+ # Trim history to max size
111
+ while len(self._history) > self._max_history:
112
+ self._history.pop(0)
113
+ self._history.pop(0) # remove in pairs
114
+ return prompts
115
+
116
+ except httpx.ConnectError:
117
+ print("Ollama not available, switching to rule-based fallback")
118
+ self._fallback_mode = True
119
+ return self._rule_based_prompts(gesture_data)
120
+ except Exception as e:
121
+ print(f"Qwen interpretation error: {e}")
122
+ return self._rule_based_prompts(gesture_data)
123
+
124
+ return None
125
+
126
+ def _build_description(self, g: dict) -> str:
127
+ """Build a concise description of gesture state for the LLM."""
128
+ parts = []
129
+
130
+ hand_y = g.get("handY", 0.5)
131
+ if hand_y > 0.7:
132
+ parts.append(f"Hand HIGH ({hand_y:.1f})")
133
+ elif hand_y < 0.3:
134
+ parts.append(f"Hand LOW ({hand_y:.1f})")
135
+ else:
136
+ parts.append(f"Hand MIDDLE ({hand_y:.1f})")
137
+
138
+ spread = g.get("handSpread", 0.5)
139
+ if spread > 0.6:
140
+ parts.append("fingers WIDE")
141
+ elif spread < 0.3:
142
+ parts.append("fingers NARROW")
143
+ else:
144
+ parts.append("fingers MEDIUM")
145
+
146
+ wrist = g.get("wristAngle", 0.0)
147
+ if abs(wrist) > 0.4:
148
+ parts.append(f"wrist TILTED {'RIGHT' if wrist > 0 else 'LEFT'}")
149
+ else:
150
+ parts.append("wrist STRAIGHT")
151
+
152
+ vel = g.get("handVelocity", {})
153
+ speed = (vel.get("x", 0)**2 + vel.get("y", 0)**2) ** 0.5
154
+ if speed > 0.3:
155
+ parts.append("movement FAST")
156
+ elif speed > 0.1:
157
+ parts.append("movement MODERATE")
158
+ else:
159
+ parts.append("movement STILL")
160
+
161
+ if g.get("shapeActive"):
162
+ parts.append("SHAPE ACTIVE (bass drone)")
163
+
164
+ if g.get("drumHandActive"):
165
+ parts.append("DRUM HAND active")
166
+
167
+ return ", ".join(parts) + "."
168
+
169
+ def _rule_based_prompts(self, g: dict) -> list[dict]:
170
+ """Fallback: generate prompts from rules when Ollama is unavailable."""
171
+ prompts = []
172
+ hand_y = g.get("handY", 0.5)
173
+ spread = g.get("handSpread", 0.5)
174
+ wrist = abs(g.get("wristAngle", 0.0))
175
+
176
+ if hand_y > 0.7:
177
+ prompts.append({"text": "ethereal ambient floating pads celestial", "weight": 1.5})
178
+ elif hand_y < 0.3:
179
+ prompts.append({"text": "heavy nasty drippy drum and bass reese", "weight": 2.0})
180
+ elif hand_y < 0.45:
181
+ prompts.append({"text": "dark progressive electronic deep bass", "weight": 1.2})
182
+ else:
183
+ prompts.append({"text": "psychedelic melodic electronic", "weight": 1.0})
184
+
185
+ if spread > 0.6:
186
+ prompts.append({"text": "complex layered arpeggios dense textures", "weight": 1.0})
187
+ elif spread < 0.3:
188
+ prompts.append({"text": "minimal sparse atmospheric", "weight": 0.8})
189
+
190
+ if wrist > 0.4:
191
+ prompts.append({"text": "acid squelch filter sweep tension", "weight": wrist * 2})
192
+
193
+ if g.get("shapeActive"):
194
+ prompts.append({"text": "fat sub-bass drone sawtooth rumble", "weight": 1.5})
195
+
196
+ if g.get("drumHandActive"):
197
+ prompts.append({"text": "driving percussion rhythm", "weight": 1.0})
198
+
199
+ return prompts if prompts else [{"text": "ambient electronic soundscape", "weight": 1.0}]
backend/lyria_manager.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Lyria RealTime API session manager.
3
+
4
+ Maintains a persistent WebSocket connection to Google's Lyria RealTime model
5
+ and exposes methods to update prompts, config, and receive audio chunks.
6
+ """
7
+
8
+ import asyncio
9
+ from google import genai
10
+ from google.genai import types
11
+
12
+
13
+ class LyriaManager:
14
+ def __init__(self, api_key: str):
15
+ self.client = genai.Client(
16
+ api_key=api_key,
17
+ http_options={"api_version": "v1alpha"}
18
+ )
19
+ self.session = None
20
+ self._ctx_manager = None
21
+ self._playing = False
22
+ self._current_bpm = None
23
+
24
+ async def connect(self):
25
+ """Connect to Lyria RealTime and start playing."""
26
+ self._ctx_manager = self.client.aio.live.music.connect(
27
+ model="models/lyria-realtime-exp"
28
+ )
29
+ self.session = await self._ctx_manager.__aenter__()
30
+ print("[Lyria] Session connected")
31
+
32
+ # Set initial config
33
+ await self.session.set_weighted_prompts(
34
+ prompts=[
35
+ types.WeightedPrompt(text="psychedelic ambient electronic", weight=1.0),
36
+ types.WeightedPrompt(text="ethereal synthesizer pads", weight=0.5),
37
+ ]
38
+ )
39
+ await self.session.set_music_generation_config(
40
+ config=types.LiveMusicGenerationConfig(
41
+ bpm=120,
42
+ temperature=1.1,
43
+ guidance=4.0,
44
+ )
45
+ )
46
+
47
+ # Start playing immediately
48
+ await self.session.play()
49
+ self._playing = True
50
+ print("[Lyria] Playing started")
51
+
52
+ async def play(self):
53
+ if self.session and not self._playing:
54
+ await self.session.play()
55
+ self._playing = True
56
+
57
+ async def pause(self):
58
+ if self.session and self._playing:
59
+ await self.session.pause()
60
+ self._playing = False
61
+
62
+ async def stop(self):
63
+ if self.session:
64
+ try:
65
+ await self.session.pause()
66
+ except Exception:
67
+ pass
68
+ self._playing = False
69
+
70
+ async def disconnect(self):
71
+ if self._ctx_manager:
72
+ try:
73
+ await self._ctx_manager.__aexit__(None, None, None)
74
+ except Exception as e:
75
+ print(f"[Lyria] Disconnect error: {e}")
76
+ self._ctx_manager = None
77
+ self.session = None
78
+ self._playing = False
79
+ print("[Lyria] Disconnected")
80
+
81
+ async def update_prompts(self, prompts: list[dict]):
82
+ """Update weighted prompts. prompts = [{"text": "...", "weight": 1.0}, ...]"""
83
+ if not self.session:
84
+ return
85
+ weighted = [
86
+ types.WeightedPrompt(text=p["text"], weight=p.get("weight", 1.0))
87
+ for p in prompts
88
+ ]
89
+ try:
90
+ await self.session.set_weighted_prompts(prompts=weighted)
91
+ print(f"[Lyria] Prompts updated: {[p['text'][:30] for p in prompts]}")
92
+ except Exception as e:
93
+ print(f"[Lyria] Prompt update error: {e}")
94
+
95
+ async def update_config(self, config: dict):
96
+ """Update Lyria generation config from mapped gesture parameters."""
97
+ if not self.session:
98
+ return
99
+
100
+ kwargs = {}
101
+ if "brightness" in config:
102
+ kwargs["brightness"] = config["brightness"]
103
+ if "density" in config:
104
+ kwargs["density"] = config["density"]
105
+ if "temperature" in config:
106
+ kwargs["temperature"] = config["temperature"]
107
+
108
+ needs_reset = False
109
+ if "bpm" in config and config["bpm"] != self._current_bpm:
110
+ kwargs["bpm"] = config["bpm"]
111
+ self._current_bpm = config["bpm"]
112
+ needs_reset = True
113
+
114
+ if kwargs:
115
+ try:
116
+ await self.session.set_music_generation_config(
117
+ config=types.LiveMusicGenerationConfig(**kwargs)
118
+ )
119
+ except Exception as e:
120
+ print(f"[Lyria] Config update error: {e}")
121
+
122
+ if needs_reset:
123
+ try:
124
+ await self.session.reset_context()
125
+ except Exception as e:
126
+ print(f"[Lyria] Context reset error: {e}")
127
+
128
+ # Handle mute toggles
129
+ mute_kwargs = {}
130
+ if "mute_drums" in config:
131
+ mute_kwargs["mute_drums"] = config["mute_drums"]
132
+ if "mute_bass" in config:
133
+ mute_kwargs["mute_bass"] = config["mute_bass"]
134
+ if mute_kwargs:
135
+ try:
136
+ await self.session.set_music_generation_config(
137
+ config=types.LiveMusicGenerationConfig(**mute_kwargs)
138
+ )
139
+ except Exception as e:
140
+ print(f"[Lyria] Mute update error: {e}")
141
+
142
+ async def receive_audio(self):
143
+ """Async generator yielding raw PCM audio bytes from Lyria."""
144
+ if not self.session:
145
+ print("[Lyria] No session for audio receive")
146
+ return
147
+ print("[Lyria] Starting audio receive loop")
148
+ try:
149
+ async for message in self.session.receive():
150
+ if hasattr(message, 'server_content') and message.server_content:
151
+ sc = message.server_content
152
+ if hasattr(sc, 'audio_chunks') and sc.audio_chunks:
153
+ for chunk in sc.audio_chunks:
154
+ yield chunk.data
155
+ await asyncio.sleep(1e-6)
156
+ except asyncio.CancelledError:
157
+ print("[Lyria] Audio receive cancelled")
158
+ return
159
+ except Exception as e:
160
+ print(f"[Lyria] Receive error: {e}")
backend/requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ fastapi>=0.115.0
2
+ uvicorn>=0.34.0
3
+ websockets>=13.0
4
+ google-genai>=1.0.0
5
+ httpx>=0.27.0
backend/server.py ADDED
@@ -0,0 +1,236 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Hyperspace Jam — Lyria RealTime Backend
3
+
4
+ Bridges hand-tracking gesture data from the browser to:
5
+ 1. A tiny local Qwen model (via Ollama) for gesture → musical prompt interpretation
6
+ 2. Google Lyria RealTime API for real-time music generation
7
+ 3. Streams PCM audio back to the browser
8
+ """
9
+
10
+ import asyncio
11
+ import json
12
+ import os
13
+ import time
14
+ import base64
15
+
16
+ # Load .env file
17
+ env_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), ".env")
18
+ if os.path.exists(env_path):
19
+ with open(env_path) as f:
20
+ for line in f:
21
+ line = line.strip()
22
+ if line and not line.startswith("#") and "=" in line:
23
+ k, v = line.split("=", 1)
24
+ if not os.environ.get(k.strip()):
25
+ os.environ[k.strip()] = v.strip()
26
+
27
+ from fastapi import FastAPI, WebSocket, WebSocketDisconnect
28
+ from fastapi.staticfiles import StaticFiles
29
+ from fastapi.responses import FileResponse
30
+
31
+ from lyria_manager import LyriaManager
32
+ from gesture_interpreter import GestureInterpreter
33
+
34
+ app = FastAPI()
35
+
36
+ # Serve frontend static files
37
+ FRONTEND_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
38
+
39
+
40
+ @app.websocket("/ws")
41
+ async def websocket_endpoint(websocket: WebSocket):
42
+ await websocket.accept()
43
+
44
+ gemini_key = os.environ.get("GEMINI_API_KEY", "")
45
+ if not gemini_key:
46
+ await websocket.send_json({"type": "error", "message": "GEMINI_API_KEY not set"})
47
+ await websocket.close()
48
+ return
49
+
50
+ interpreter = GestureInterpreter()
51
+ lyria = LyriaManager(gemini_key)
52
+
53
+ # Start Lyria session
54
+ try:
55
+ await lyria.connect()
56
+ except Exception as e:
57
+ await websocket.send_json({"type": "error", "message": f"Lyria connection failed: {e}"})
58
+ await websocket.close()
59
+ return
60
+
61
+ await websocket.send_json({"type": "connected"})
62
+
63
+ # Task to forward Lyria audio to the browser as binary frames
64
+ async def audio_forwarder():
65
+ chunk_count = 0
66
+ try:
67
+ async for audio_chunk in lyria.receive_audio():
68
+ # Send raw PCM as binary WebSocket frame (much more efficient than base64)
69
+ await websocket.send_bytes(audio_chunk)
70
+ chunk_count += 1
71
+ if chunk_count <= 3 or chunk_count % 10 == 0:
72
+ print(f"[Audio] Sent chunk {chunk_count}: {len(audio_chunk)} bytes")
73
+ except asyncio.CancelledError:
74
+ pass
75
+ except Exception as e:
76
+ print(f"Audio forwarder error: {e}")
77
+
78
+ forwarder_task = asyncio.create_task(audio_forwarder())
79
+
80
+ # Accumulate gesture state — only update when hands move significantly
81
+ last_qwen_time = 0
82
+ QWEN_INTERVAL = 3.0 # seconds between Qwen prompt updates
83
+ current_gesture_state = {}
84
+ prev_gesture_state = {}
85
+ last_config_update = 0
86
+ CONFIG_THROTTLE = 0.5 # only update Lyria config every 500ms
87
+
88
+ def _gesture_changed_significantly(prev, curr):
89
+ """Check if hands moved enough to warrant a music change."""
90
+ if not prev:
91
+ return True
92
+ # Check hand height change
93
+ dy = abs(curr.get("handY", 0.5) - prev.get("handY", 0.5))
94
+ # Check spread change
95
+ ds = abs(curr.get("handSpread", 0.5) - prev.get("handSpread", 0.5))
96
+ # Check wrist angle change
97
+ dw = abs(curr.get("wristAngle", 0) - prev.get("wristAngle", 0))
98
+ # Check velocity (any fast movement is significant)
99
+ vel = curr.get("handVelocity", {})
100
+ speed = (vel.get("x", 0)**2 + vel.get("y", 0)**2) ** 0.5
101
+ # Shape toggle is always significant
102
+ shape_changed = curr.get("shapeActive") != prev.get("shapeActive")
103
+ # Drum hand toggle is significant
104
+ drum_changed = curr.get("drumHandActive") != prev.get("drumHandActive")
105
+
106
+ return (dy > 0.12 or ds > 0.15 or dw > 0.25 or
107
+ speed > 0.25 or shape_changed or drum_changed)
108
+
109
+ def _major_gesture_change(prev, curr):
110
+ """Check for dramatic movement that should break the groove."""
111
+ if not prev:
112
+ return True
113
+ dy = abs(curr.get("handY", 0.5) - prev.get("handY", 0.5))
114
+ ds = abs(curr.get("handSpread", 0.5) - prev.get("handSpread", 0.5))
115
+ vel = curr.get("handVelocity", {})
116
+ speed = (vel.get("x", 0)**2 + vel.get("y", 0)**2) ** 0.5
117
+ shape_changed = curr.get("shapeActive") != prev.get("shapeActive")
118
+ return dy > 0.3 or ds > 0.35 or speed > 0.5 or shape_changed
119
+
120
+ try:
121
+ while True:
122
+ message = await websocket.receive()
123
+ if "text" in message:
124
+ raw = message["text"]
125
+ elif "bytes" in message:
126
+ continue
127
+ else:
128
+ break
129
+ msg = json.loads(raw)
130
+
131
+ if msg["type"] == "gesture":
132
+ gesture_data = msg["data"]
133
+ current_gesture_state = gesture_data
134
+
135
+ # Throttle Lyria config updates — only when movement is significant
136
+ now = time.time()
137
+ if (now - last_config_update >= CONFIG_THROTTLE and
138
+ _gesture_changed_significantly(prev_gesture_state, gesture_data)):
139
+ lyria_config = _map_gesture_to_lyria_config(gesture_data)
140
+ await lyria.update_config(lyria_config)
141
+ last_config_update = now
142
+
143
+ # Ask Qwen for prompts — only when enough time passed AND hands moved
144
+ if now - last_qwen_time >= QWEN_INTERVAL:
145
+ is_major = _major_gesture_change(prev_gesture_state, gesture_data)
146
+ changed = _gesture_changed_significantly(prev_gesture_state, gesture_data)
147
+ if changed:
148
+ last_qwen_time = now
149
+ prompt_text = await interpreter.interpret(
150
+ gesture_data, force_new_direction=is_major
151
+ )
152
+ if prompt_text:
153
+ await lyria.update_prompts(prompt_text)
154
+ prev_gesture_state = gesture_data.copy()
155
+
156
+ elif msg["type"] == "play":
157
+ await lyria.play()
158
+
159
+ elif msg["type"] == "pause":
160
+ await lyria.pause()
161
+
162
+ elif msg["type"] == "panic":
163
+ await lyria.stop()
164
+
165
+ elif msg["type"] == "hands_lost":
166
+ # All hands gone — fade out
167
+ await lyria.update_config({"density": 0.05, "brightness": 0.2})
168
+
169
+ except WebSocketDisconnect:
170
+ pass
171
+ except Exception as e:
172
+ print(f"WebSocket error: {e}")
173
+ finally:
174
+ forwarder_task.cancel()
175
+ await lyria.disconnect()
176
+
177
+
178
+ def _map_gesture_to_lyria_config(gesture_data: dict) -> dict:
179
+ """Map raw hand tracking numbers directly to Lyria RealTime parameters."""
180
+ config = {}
181
+
182
+ # Hand height (0=bottom, 1=top) → brightness
183
+ hand_y = gesture_data.get("handY", 0.5)
184
+ config["brightness"] = max(0.0, min(1.0, hand_y))
185
+
186
+ # Hand spread (fingers wide) → density
187
+ spread = gesture_data.get("handSpread", 0.5)
188
+ config["density"] = max(0.0, min(1.0, spread))
189
+
190
+ # Wrist angle (-1 to 1) → shift brightness darker when tilted
191
+ wrist = gesture_data.get("wristAngle", 0.0)
192
+ tilt_factor = 1.0 - abs(wrist) * 0.4
193
+ config["brightness"] *= tilt_factor
194
+
195
+ # Drum hand finger tempo → BPM mapping (only if drum hand present)
196
+ drum_tempo = gesture_data.get("drumTempo")
197
+ if drum_tempo is not None:
198
+ bpm = int(60 + drum_tempo * 140) # 60-200 range
199
+ config["bpm"] = max(60, min(200, bpm))
200
+
201
+ # Volume/pinch → density modulation
202
+ volume = gesture_data.get("volume", 0.5)
203
+ config["density"] = max(0.0, min(1.0, config["density"] * (0.3 + volume * 0.7)))
204
+
205
+ # Mute controls based on finger states
206
+ config["mute_drums"] = gesture_data.get("muteDrums", False)
207
+ config["mute_bass"] = gesture_data.get("muteBass", False)
208
+
209
+ return config
210
+
211
+
212
+ # Serve frontend
213
+ app.mount("/assets", StaticFiles(directory=os.path.join(FRONTEND_DIR, "assets")), name="assets")
214
+
215
+
216
+ @app.get("/{path:path}")
217
+ async def serve_frontend(path: str):
218
+ if not path or path == "/":
219
+ path = "index.html"
220
+ file_path = os.path.join(FRONTEND_DIR, path)
221
+ if os.path.isfile(file_path):
222
+ # Determine content type
223
+ ct = "application/octet-stream"
224
+ if path.endswith(".html"):
225
+ ct = "text/html"
226
+ elif path.endswith(".js"):
227
+ ct = "application/javascript"
228
+ elif path.endswith(".css"):
229
+ ct = "text/css"
230
+ return FileResponse(file_path, media_type=ct)
231
+ return FileResponse(os.path.join(FRONTEND_DIR, "index.html"))
232
+
233
+
234
+ if __name__ == "__main__":
235
+ import uvicorn
236
+ uvicorn.run(app, host="0.0.0.0", port=8088)
game.js ADDED
@@ -0,0 +1,1717 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ function _array_like_to_array(arr, len) {
2
+ if (len == null || len > arr.length) len = arr.length;
3
+ for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
4
+ return arr2;
5
+ }
6
+ function _array_with_holes(arr) {
7
+ if (Array.isArray(arr)) return arr;
8
+ }
9
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
10
+ try {
11
+ var info = gen[key](arg);
12
+ var value = info.value;
13
+ } catch (error) {
14
+ reject(error);
15
+ return;
16
+ }
17
+ if (info.done) {
18
+ resolve(value);
19
+ } else {
20
+ Promise.resolve(value).then(_next, _throw);
21
+ }
22
+ }
23
+ function _async_to_generator(fn) {
24
+ return function() {
25
+ var self = this, args = arguments;
26
+ return new Promise(function(resolve, reject) {
27
+ var gen = fn.apply(self, args);
28
+ function _next(value) {
29
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
30
+ }
31
+ function _throw(err) {
32
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
33
+ }
34
+ _next(undefined);
35
+ });
36
+ };
37
+ }
38
+ function _class_call_check(instance, Constructor) {
39
+ if (!(instance instanceof Constructor)) {
40
+ throw new TypeError("Cannot call a class as a function");
41
+ }
42
+ }
43
+ function _defineProperties(target, props) {
44
+ for(var i = 0; i < props.length; i++){
45
+ var descriptor = props[i];
46
+ descriptor.enumerable = descriptor.enumerable || false;
47
+ descriptor.configurable = true;
48
+ if ("value" in descriptor) descriptor.writable = true;
49
+ Object.defineProperty(target, descriptor.key, descriptor);
50
+ }
51
+ }
52
+ function _create_class(Constructor, protoProps, staticProps) {
53
+ if (protoProps) _defineProperties(Constructor.prototype, protoProps);
54
+ if (staticProps) _defineProperties(Constructor, staticProps);
55
+ return Constructor;
56
+ }
57
+ function _define_property(obj, key, value) {
58
+ if (key in obj) {
59
+ Object.defineProperty(obj, key, {
60
+ value: value,
61
+ enumerable: true,
62
+ configurable: true,
63
+ writable: true
64
+ });
65
+ } else {
66
+ obj[key] = value;
67
+ }
68
+ return obj;
69
+ }
70
+ function _iterable_to_array_limit(arr, i) {
71
+ var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
72
+ if (_i == null) return;
73
+ var _arr = [];
74
+ var _n = true;
75
+ var _d = false;
76
+ var _s, _e;
77
+ try {
78
+ for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
79
+ _arr.push(_s.value);
80
+ if (i && _arr.length === i) break;
81
+ }
82
+ } catch (err) {
83
+ _d = true;
84
+ _e = err;
85
+ } finally{
86
+ try {
87
+ if (!_n && _i["return"] != null) _i["return"]();
88
+ } finally{
89
+ if (_d) throw _e;
90
+ }
91
+ }
92
+ return _arr;
93
+ }
94
+ function _non_iterable_rest() {
95
+ throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
96
+ }
97
+ function _object_spread(target) {
98
+ for(var i = 1; i < arguments.length; i++){
99
+ var source = arguments[i] != null ? arguments[i] : {};
100
+ var ownKeys = Object.keys(source);
101
+ if (typeof Object.getOwnPropertySymbols === "function") {
102
+ ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
103
+ return Object.getOwnPropertyDescriptor(source, sym).enumerable;
104
+ }));
105
+ }
106
+ ownKeys.forEach(function(key) {
107
+ _define_property(target, key, source[key]);
108
+ });
109
+ }
110
+ return target;
111
+ }
112
+ function _sliced_to_array(arr, i) {
113
+ return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
114
+ }
115
+ function _unsupported_iterable_to_array(o, minLen) {
116
+ if (!o) return;
117
+ if (typeof o === "string") return _array_like_to_array(o, minLen);
118
+ var n = Object.prototype.toString.call(o).slice(8, -1);
119
+ if (n === "Object" && o.constructor) n = o.constructor.name;
120
+ if (n === "Map" || n === "Set") return Array.from(n);
121
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
122
+ }
123
+ function _ts_generator(thisArg, body) {
124
+ var f, y, t, g, _ = {
125
+ label: 0,
126
+ sent: function() {
127
+ if (t[0] & 1) throw t[1];
128
+ return t[1];
129
+ },
130
+ trys: [],
131
+ ops: []
132
+ };
133
+ return g = {
134
+ next: verb(0),
135
+ "throw": verb(1),
136
+ "return": verb(2)
137
+ }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
138
+ return this;
139
+ }), g;
140
+ function verb(n) {
141
+ return function(v) {
142
+ return step([
143
+ n,
144
+ v
145
+ ]);
146
+ };
147
+ }
148
+ function step(op) {
149
+ if (f) throw new TypeError("Generator is already executing.");
150
+ while(_)try {
151
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
152
+ if (y = 0, t) op = [
153
+ op[0] & 2,
154
+ t.value
155
+ ];
156
+ switch(op[0]){
157
+ case 0:
158
+ case 1:
159
+ t = op;
160
+ break;
161
+ case 4:
162
+ _.label++;
163
+ return {
164
+ value: op[1],
165
+ done: false
166
+ };
167
+ case 5:
168
+ _.label++;
169
+ y = op[1];
170
+ op = [
171
+ 0
172
+ ];
173
+ continue;
174
+ case 7:
175
+ op = _.ops.pop();
176
+ _.trys.pop();
177
+ continue;
178
+ default:
179
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
180
+ _ = 0;
181
+ continue;
182
+ }
183
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
184
+ _.label = op[1];
185
+ break;
186
+ }
187
+ if (op[0] === 6 && _.label < t[1]) {
188
+ _.label = t[1];
189
+ t = op;
190
+ break;
191
+ }
192
+ if (t && _.label < t[2]) {
193
+ _.label = t[2];
194
+ _.ops.push(op);
195
+ break;
196
+ }
197
+ if (t[2]) _.ops.pop();
198
+ _.trys.pop();
199
+ continue;
200
+ }
201
+ op = body.call(thisArg, _);
202
+ } catch (e) {
203
+ op = [
204
+ 6,
205
+ e
206
+ ];
207
+ y = 0;
208
+ } finally{
209
+ f = t = 0;
210
+ }
211
+ if (op[0] & 5) throw op[1];
212
+ return {
213
+ value: op[0] ? op[1] : void 0,
214
+ done: true
215
+ };
216
+ }
217
+ }
218
+ import * as THREE from 'three';
219
+ import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js'; // Import GLTFLoader
220
+ import { HandLandmarker, FilesetResolver } from 'https://esm.sh/@mediapipe/tasks-vision@0.10.14';
221
+ import { MusicManager } from './MusicManager.js'; // Import the MusicManager
222
+ // Tone.js shim — Lyria version doesn't use Tone directly
223
+ const Tone = {
224
+ now: () => 0,
225
+ start: async () => {},
226
+ context: { resume: async () => {} },
227
+ Transport: { progress: 0, bpm: { value: 120 }, start: () => {}, stop: () => {} }
228
+ };
229
+ import * as drumManager from './DrumManager.js'; // Import the new drum manager module
230
+ import { WaveformVisualizer } from './WaveformVisualizer.js'; // Import the new waveform visualizer
231
+ import { MandalaVisualizer } from './MandalaVisualizer.js';
232
+ import { ShapeManager } from './ShapeManager.js';
233
+ import { DisplacementFilter } from './DisplacementFilter.js';
234
+ export var Game = /*#__PURE__*/ function() {
235
+ "use strict";
236
+ function Game(renderDiv) {
237
+ var _this = this;
238
+ _class_call_check(this, Game);
239
+ this.renderDiv = renderDiv;
240
+ this.scene = null;
241
+ this.camera = null;
242
+ this.renderer = null;
243
+ this.videoElement = null;
244
+ this.handLandmarker = null;
245
+ this.lastVideoTime = -1;
246
+ this.hands = []; // Stores data about detected hands (landmarks, anchor position, line group)
247
+ this.handLineMaterial = null; // Material for hand lines
248
+ this.fingertipMaterialHand1 = null; // Material for first hand's fingertip circles (blue)
249
+ this.fingertipMaterialHand2 = null; // Material for second hand's fingertip circles (green)
250
+ this.fingertipLandmarkIndices = [
251
+ 0,
252
+ 4,
253
+ 8,
254
+ 12,
255
+ 16,
256
+ 20
257
+ ]; // WRIST + TIP landmarks
258
+ this.handConnections = null; // Landmark connection definitions
259
+ // this.handCollisionRadius = 30; // Conceptual radius for hand collision, was 25 (sphere radius) - Not needed for template
260
+ this.gameState = 'loading'; // loading, ready, tracking, error
261
+ this.gameOverText = null; // Will be repurposed or simplified
262
+ this.clock = new THREE.Clock();
263
+ this.musicManager = new MusicManager(); // Create an instance of MusicManager
264
+ this.waveformVisualizer = null; // To be initialized
265
+ // this.drumManager = new DrumManager(); // DrumManager is now a static module, no instance needed
266
+ this.lastLandmarkPositions = [
267
+ [],
268
+ []
269
+ ]; // Store last known smoothed positions for each hand's landmarks
270
+ this.smoothingFactor = 0.4; // Alpha for exponential smoothing (0 < alpha <= 1). Smaller = more smoothing.
271
+ this.loadedModels = {}; // To store loaded models if any (e.g. a generic hand model in future)
272
+ this.beatIndicators = []; // Array to hold the 16 beat indicator meshes
273
+ this.beatIndicatorMaterials = []; // Array to hold the base material for each indicator
274
+ this.beatIndicatorColors = {
275
+ kick: new THREE.Color("#D72828"),
276
+ snare: new THREE.Color("#F36E2F"),
277
+ clap: new THREE.Color("#7B4394"),
278
+ hihat: new THREE.Color("#84C34E"),
279
+ off: new THREE.Color("#ffffff") // Off state remains white
280
+ };
281
+ this.beatIndicatorGroup = null; // Group to hold all indicators for easy repositioning
282
+ this.labelColors = {
283
+ evaPurple: {
284
+ r: 123,
285
+ g: 67,
286
+ b: 148,
287
+ a: 0.9
288
+ },
289
+ evaGreen: {
290
+ r: 132,
291
+ g: 195,
292
+ b: 78,
293
+ a: 0.9
294
+ },
295
+ evaOrange: {
296
+ r: 243,
297
+ g: 110,
298
+ b: 47,
299
+ a: 0.9
300
+ },
301
+ evaRed: {
302
+ r: 215,
303
+ g: 40,
304
+ b: 40,
305
+ a: 0.9
306
+ },
307
+ white: {
308
+ r: 255,
309
+ g: 255,
310
+ b: 255,
311
+ a: 1.0
312
+ },
313
+ black: {
314
+ r: 0,
315
+ g: 0,
316
+ b: 0,
317
+ a: 1.0
318
+ }
319
+ };
320
+ this.waveformColors = [
321
+ new THREE.Color("#7B4394"),
322
+ new THREE.Color("#84C34E"),
323
+ new THREE.Color("#F36E2F"),
324
+ new THREE.Color("#D72828"),
325
+ new THREE.Color("#66ffff")
326
+ ];
327
+ // Initialize asynchronously
328
+ this._init().catch(function(error) {
329
+ console.error("Initialization failed:", error);
330
+ _this._showError("Initialization failed. Check console.");
331
+ });
332
+ }
333
+ _create_class(Game, [
334
+ {
335
+ key: "_init",
336
+ value: function _init() {
337
+ var _this = this;
338
+ return _async_to_generator(function() {
339
+ return _ts_generator(this, function(_state) {
340
+ switch(_state.label){
341
+ case 0:
342
+ _this._setupDOM(); // Sets up basic DOM, including speech bubble container
343
+ _this._setupThree();
344
+ return [
345
+ 4,
346
+ _this._loadAssets()
347
+ ];
348
+ case 1:
349
+ _state.sent(); // Add asset loading step
350
+ return [
351
+ 4,
352
+ _this._setupHandTracking()
353
+ ];
354
+ case 2:
355
+ _state.sent(); // This needs to complete before we can proceed
356
+ // Ensure webcam is playing before starting game logic dependent on it
357
+ return [
358
+ 4,
359
+ _this.videoElement.play()
360
+ ];
361
+ case 3:
362
+ _state.sent();
363
+ window.addEventListener('resize', _this._onResize.bind(_this));
364
+ _this._startGame(); // Start the game directly
365
+ _this._setupEventListeners(); // Set up interaction listeners
366
+ _this._animate(); // Start the animation loop (it will check state)
367
+ return [
368
+ 2
369
+ ];
370
+ }
371
+ });
372
+ })();
373
+ }
374
+ },
375
+ {
376
+ key: "_setupDOM",
377
+ value: function _setupDOM() {
378
+ this.renderDiv.style.position = 'relative';
379
+ this.renderDiv.style.width = '100vw'; // Use viewport units for fullscreen
380
+ this.renderDiv.style.height = '100vh';
381
+ this.renderDiv.style.overflow = 'hidden';
382
+ this.renderDiv.style.background = '#111'; // Fallback background
383
+ this.videoElement = document.createElement('video');
384
+ this.videoElement.style.position = 'absolute';
385
+ this.videoElement.style.top = '0';
386
+ this.videoElement.style.left = '0';
387
+ this.videoElement.style.width = '100%';
388
+ this.videoElement.style.height = '100%';
389
+ this.videoElement.style.objectFit = 'cover';
390
+ this.videoElement.style.transform = 'scaleX(-1)'; // Mirror view for intuitive control
391
+ this.videoElement.style.filter = 'saturate(1.8) contrast(1.2) hue-rotate(0deg)';
392
+ this.videoElement.autoplay = true;
393
+ this.videoElement.muted = true; // Mute video to avoid feedback loops if audio was captured
394
+ this.videoElement.playsInline = true;
395
+ this.videoElement.style.zIndex = '0'; // Ensure video is behind THREE canvas
396
+ this.renderDiv.appendChild(this.videoElement);
397
+ // Psychedelic hue rotation — MAX STRENGTH
398
+ var hueAngle = 0;
399
+ var videoEl = this.videoElement;
400
+ setInterval(function() {
401
+ hueAngle = (hueAngle + 3) % 360;
402
+ var sat = 3.5 + Math.sin(hueAngle * 0.04) * 1.5;
403
+ var bright = 1.2 + Math.sin(hueAngle * 0.025) * 0.3;
404
+ var cont = 1.4 + Math.sin(hueAngle * 0.03) * 0.2;
405
+ videoEl.style.filter = 'saturate(' + sat + ') contrast(' + cont + ') brightness(' + bright + ') hue-rotate(' + hueAngle + 'deg) url(#turbulence-displace)';
406
+ }, 25);
407
+ // Container for Status text (formerly Game Over) and restart hint
408
+ this.gameOverContainer = document.createElement('div');
409
+ this.gameOverContainer.style.position = 'absolute';
410
+ this.gameOverContainer.style.top = '50%';
411
+ this.gameOverContainer.style.left = '50%';
412
+ this.gameOverContainer.style.transform = 'translate(-50%, -50%)';
413
+ this.gameOverContainer.style.zIndex = '10';
414
+ this.gameOverContainer.style.display = 'none'; // Hidden initially
415
+ this.gameOverContainer.style.pointerEvents = 'none'; // Don't block clicks
416
+ this.gameOverContainer.style.textAlign = 'center'; // Center text elements within
417
+ this.gameOverContainer.style.color = 'white'; // Default color, can be changed by _showError
418
+ this.gameOverContainer.style.textShadow = '2px 2px 4px black';
419
+ this.gameOverContainer.style.fontFamily = '"Arial Black", Gadget, sans-serif';
420
+ // Main Status Text (formerly Game Over Text)
421
+ this.gameOverText = document.createElement('div'); // Will be 'gameOverText' internally
422
+ this.gameOverText.innerText = 'STATUS'; // Generic placeholder
423
+ this.gameOverText.style.fontSize = 'clamp(36px, 10vw, 72px)'; // Responsive font size
424
+ this.gameOverText.style.fontWeight = 'bold';
425
+ this.gameOverText.style.marginBottom = '10px'; // Space below main text
426
+ this.gameOverContainer.appendChild(this.gameOverText);
427
+ // Restart Hint Text (may or may not be shown depending on context)
428
+ this.restartHintText = document.createElement('div');
429
+ this.restartHintText.innerText = '(click to restart tracking)';
430
+ this.restartHintText.style.fontSize = 'clamp(16px, 3vw, 24px)';
431
+ this.restartHintText.style.fontWeight = 'normal';
432
+ this.restartHintText.style.opacity = '0.8'; // Slightly faded
433
+ this.gameOverContainer.appendChild(this.restartHintText);
434
+ this.renderDiv.appendChild(this.gameOverContainer);
435
+ // ScoreDisplay removed
436
+ // Watermelon (Center Emoji Marker) setup removed
437
+ // Chad Image Marker setup removed
438
+ }
439
+ },
440
+ {
441
+ key: "_setupThree",
442
+ value: function _setupThree() {
443
+ var width = this.renderDiv.clientWidth;
444
+ var height = this.renderDiv.clientHeight;
445
+ this.scene = new THREE.Scene();
446
+ // Using OrthographicCamera for a 2D-like overlay effect
447
+ this.camera = new THREE.OrthographicCamera(width / -2, width / 2, height / 2, height / -2, 1, 1000);
448
+ this.camera.position.z = 100; // Position along Z doesn't change scale in Ortho
449
+ this.renderer = new THREE.WebGLRenderer({
450
+ alpha: true,
451
+ antialias: true
452
+ });
453
+ this.renderer.setSize(width, height);
454
+ this.renderer.setPixelRatio(window.devicePixelRatio);
455
+ this.renderer.domElement.style.position = 'absolute';
456
+ this.renderer.domElement.style.top = '0';
457
+ this.renderer.domElement.style.left = '0';
458
+ this.renderer.domElement.style.zIndex = '1'; // Canvas on top of video
459
+ this.renderer.domElement.style.mixBlendMode = 'screen';
460
+ // No CSS filters — they cause compositing lag
461
+ this.renderDiv.appendChild(this.renderer.domElement);
462
+ this.displacementFilter = new DisplacementFilter(this.renderer.domElement, this.videoElement);
463
+ var gameRef = this;
464
+ window.addEventListener('keydown', function(e) {
465
+ if (e.code === 'KeyD') {
466
+ if (gameRef.displacementFilter) gameRef.displacementFilter.toggle();
467
+ }
468
+ if (e.code === 'Space') {
469
+ e.preventDefault();
470
+ if (gameRef.musicManager && gameRef.musicManager.panic) {
471
+ gameRef.musicManager.panic();
472
+ }
473
+ }
474
+ });
475
+ var ambientLight = new THREE.AmbientLight(0xffffff, 0.7);
476
+ this.scene.add(ambientLight);
477
+ var directionalLight = new THREE.DirectionalLight(0xffffff, 0.9);
478
+ directionalLight.position.set(0, 0, 100); // Pointing from behind camera
479
+ this.scene.add(directionalLight);
480
+ // Setup hand visualization (palm circles removed, lines will be added later)
481
+ this._multiplayerEnabled = false;
482
+ this._maxHands = 2;
483
+ for(var i = 0; i < 4; i++){
484
+ var lineGroup = new THREE.Group();
485
+ lineGroup.visible = false;
486
+ this.scene.add(lineGroup);
487
+ this.hands.push({
488
+ landmarks: null,
489
+ anchorPos: new THREE.Vector3(),
490
+ lineGroup: lineGroup,
491
+ isFist: false // Track if the hand is currently in a fist
492
+ });
493
+ }
494
+ this.handLineMaterial = new THREE.LineBasicMaterial({
495
+ color: 0xff00ff,
496
+ linewidth: 8
497
+ });
498
+ this.fingertipMaterialHand1 = new THREE.MeshBasicMaterial({
499
+ color: 0x00ffff,
500
+ side: THREE.DoubleSide
501
+ }); // Neon Cyan
502
+ this.fingertipMaterialHand2 = new THREE.MeshBasicMaterial({
503
+ color: 0xffffff,
504
+ side: THREE.DoubleSide
505
+ }); // White
506
+ // Define connections for MediaPipe hand landmarks
507
+ // See: https://developers.google.com/mediapipe/solutions/vision/hand_landmarker#hand_landmarks
508
+ this.handConnections = [
509
+ // Thumb
510
+ [
511
+ 0,
512
+ 1
513
+ ],
514
+ [
515
+ 1,
516
+ 2
517
+ ],
518
+ [
519
+ 2,
520
+ 3
521
+ ],
522
+ [
523
+ 3,
524
+ 4
525
+ ],
526
+ // Index finger
527
+ [
528
+ 0,
529
+ 5
530
+ ],
531
+ [
532
+ 5,
533
+ 6
534
+ ],
535
+ [
536
+ 6,
537
+ 7
538
+ ],
539
+ [
540
+ 7,
541
+ 8
542
+ ],
543
+ // Middle finger
544
+ [
545
+ 0,
546
+ 9
547
+ ],
548
+ [
549
+ 9,
550
+ 10
551
+ ],
552
+ [
553
+ 10,
554
+ 11
555
+ ],
556
+ [
557
+ 11,
558
+ 12
559
+ ],
560
+ // Ring finger
561
+ [
562
+ 0,
563
+ 13
564
+ ],
565
+ [
566
+ 13,
567
+ 14
568
+ ],
569
+ [
570
+ 14,
571
+ 15
572
+ ],
573
+ [
574
+ 15,
575
+ 16
576
+ ],
577
+ // Pinky
578
+ [
579
+ 0,
580
+ 17
581
+ ],
582
+ [
583
+ 17,
584
+ 18
585
+ ],
586
+ [
587
+ 18,
588
+ 19
589
+ ],
590
+ [
591
+ 19,
592
+ 20
593
+ ],
594
+ // Palm
595
+ [
596
+ 5,
597
+ 9
598
+ ],
599
+ [
600
+ 9,
601
+ 13
602
+ ],
603
+ [
604
+ 13,
605
+ 17
606
+ ] // Connect base of fingers
607
+ ];
608
+ // Particle resources removed
609
+ // Ground line removed
610
+ // --- Beat Indicator ---
611
+ this.beatIndicatorGroup = new THREE.Group();
612
+ this.scene.add(this.beatIndicatorGroup);
613
+ this._setupBeatIndicatorMaterials(); // Create materials based on drum pattern
614
+ var indicatorSize = 20;
615
+ var indicatorGeometry = new THREE.PlaneGeometry(indicatorSize, indicatorSize);
616
+ for(var i1 = 0; i1 < 16; i1++){
617
+ // Use the pre-calculated material for this beat index
618
+ var indicator = new THREE.Mesh(indicatorGeometry, this.beatIndicatorMaterials[i1]);
619
+ this.beatIndicatorGroup.add(indicator);
620
+ this.beatIndicators.push(indicator);
621
+ }
622
+ this._positionBeatIndicators(); // Position them right after creation
623
+ }
624
+ },
625
+ {
626
+ key: "_loadAssets",
627
+ value: function _loadAssets() {
628
+ var _this = this;
629
+ return _async_to_generator(function() {
630
+ var error;
631
+ return _ts_generator(this, function(_state) {
632
+ switch(_state.label){
633
+ case 0:
634
+ console.log("Loading assets...");
635
+ _state.label = 1;
636
+ case 1:
637
+ _state.trys.push([
638
+ 1,
639
+ 3,
640
+ ,
641
+ 4
642
+ ]);
643
+ // Ghost Textures loading removed
644
+ // Ghost GLTF Model loading removed (was already commented out)
645
+ return [
646
+ 4,
647
+ drumManager.loadSamples()
648
+ ];
649
+ case 2:
650
+ _state.sent(); // Load drum sounds
651
+ console.log("No game-specific assets to load for template.");
652
+ return [
653
+ 3,
654
+ 4
655
+ ];
656
+ case 3:
657
+ error = _state.sent();
658
+ console.error("Error loading assets:", error);
659
+ _this._showError("Failed to load assets."); // Generic message
660
+ throw error; // Stop initialization
661
+ case 4:
662
+ return [
663
+ 2
664
+ ];
665
+ }
666
+ });
667
+ })();
668
+ }
669
+ },
670
+ {
671
+ key: "_setupHandTracking",
672
+ value: function _setupHandTracking() {
673
+ var _this = this;
674
+ return _async_to_generator(function() {
675
+ var vision, stream, error;
676
+ return _ts_generator(this, function(_state) {
677
+ switch(_state.label){
678
+ case 0:
679
+ _state.trys.push([
680
+ 0,
681
+ 4,
682
+ ,
683
+ 5
684
+ ]);
685
+ console.log("Setting up Hand Tracking...");
686
+ return [
687
+ 4,
688
+ FilesetResolver.forVisionTasks('https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@0.10.14/wasm')
689
+ ];
690
+ case 1:
691
+ vision = _state.sent();
692
+ return [
693
+ 4,
694
+ HandLandmarker.createFromOptions(vision, {
695
+ baseOptions: {
696
+ modelAssetPath: "https://storage.googleapis.com/mediapipe-models/hand_landmarker/hand_landmarker/float16/1/hand_landmarker.task",
697
+ delegate: 'GPU'
698
+ },
699
+ numHands: 2,
700
+ runningMode: 'VIDEO'
701
+ })
702
+ ];
703
+ case 2:
704
+ _this.handLandmarker = _state.sent();
705
+ console.log("HandLandmarker created.");
706
+ console.log("Requesting webcam access...");
707
+ return [
708
+ 4,
709
+ navigator.mediaDevices.getUserMedia({
710
+ video: {
711
+ facingMode: 'user',
712
+ width: {
713
+ ideal: 640
714
+ },
715
+ height: {
716
+ ideal: 480
717
+ }
718
+ },
719
+ audio: false
720
+ })
721
+ ];
722
+ case 3:
723
+ stream = _state.sent();
724
+ _this.videoElement.srcObject = stream;
725
+ console.log("Webcam stream obtained.");
726
+ // Wait for video metadata to load to ensure dimensions are available
727
+ return [
728
+ 2,
729
+ new Promise(function(resolve) {
730
+ _this.videoElement.onloadedmetadata = function() {
731
+ console.log("Webcam metadata loaded.");
732
+ // Adjust video size slightly after metadata is loaded if needed, but CSS handles most
733
+ _this.videoElement.style.width = _this.renderDiv.clientWidth + 'px';
734
+ _this.videoElement.style.height = _this.renderDiv.clientHeight + 'px';
735
+ resolve();
736
+ };
737
+ })
738
+ ];
739
+ case 4:
740
+ error = _state.sent();
741
+ console.error('Error setting up Hand Tracking or Webcam:', error);
742
+ _this._showError("Webcam/Hand Tracking Error: ".concat(error.message, ". Please allow camera access."));
743
+ throw error; // Re-throw to stop initialization
744
+ case 5:
745
+ return [
746
+ 2
747
+ ];
748
+ }
749
+ });
750
+ })();
751
+ }
752
+ },
753
+ {
754
+ // _startSpawning, _scheduleNextSpawn, _stopSpawning, _spawnGhost methods removed.
755
+ key: "_updateHands",
756
+ value: function _updateHands() {
757
+ var _this = this;
758
+ if (!this.handLandmarker || !this.videoElement.srcObject || this.videoElement.readyState < 2 || this.videoElement.videoWidth === 0) return;
759
+ var videoTime = this.videoElement.currentTime;
760
+ if (videoTime > this.lastVideoTime) {
761
+ this.lastVideoTime = videoTime;
762
+ try {
763
+ var _this1, _loop = function(i) {
764
+ var hand = _this1.hands[i];
765
+ var wasVisible = hand.landmarks !== null;
766
+ if (results.landmarks && results.landmarks[i]) {
767
+ var currentRawLandmarks = results.landmarks[i];
768
+ if (!_this1.lastLandmarkPositions[i] || _this1.lastLandmarkPositions[i].length !== currentRawLandmarks.length) {
769
+ _this1.lastLandmarkPositions[i] = currentRawLandmarks.map(function(lm) {
770
+ return _object_spread({}, lm);
771
+ });
772
+ }
773
+ var smoothedLandmarks = currentRawLandmarks.map(function(lm, lmIndex) {
774
+ var prevLm = _this.lastLandmarkPositions[i][lmIndex];
775
+ return {
776
+ x: _this.smoothingFactor * lm.x + (1 - _this.smoothingFactor) * prevLm.x,
777
+ y: _this.smoothingFactor * lm.y + (1 - _this.smoothingFactor) * prevLm.y,
778
+ z: _this.smoothingFactor * lm.z + (1 - _this.smoothingFactor) * prevLm.z
779
+ };
780
+ });
781
+ _this1.lastLandmarkPositions[i] = smoothedLandmarks.map(function(lm) {
782
+ return _object_spread({}, lm);
783
+ });
784
+ hand.landmarks = smoothedLandmarks;
785
+ var palm = smoothedLandmarks[9]; // MIDDLE_FINGER_MCP
786
+ var lmOriginalX = palm.x * videoParams.videoNaturalWidth;
787
+ var lmOriginalY = palm.y * videoParams.videoNaturalHeight;
788
+ var normX_visible = (lmOriginalX - videoParams.offsetX) / videoParams.visibleWidth;
789
+ var normY_visible = (lmOriginalY - videoParams.offsetY) / videoParams.visibleHeight;
790
+ var handX = (1 - normX_visible) * canvasWidth - canvasWidth / 2;
791
+ var handY = (1 - normY_visible) * canvasHeight - canvasHeight / 2;
792
+ hand.anchorPos.set(handX, handY, 1);
793
+ // Multi-player routing: hands 0,1 = player 0; hands 2,3 = player 1
794
+ var maxHandIdx = _this1._multiplayerEnabled ? 4 : 2;
795
+ var playerIndex = Math.floor(i / 2);
796
+ var isSynthHand = (i % 2 === 0);
797
+ var isDrumHand = (i % 2 === 1);
798
+ if (i >= maxHandIdx) {
799
+ // Hand not active in current mode
800
+ } else if (isSynthHand) {
801
+ // --- Music & Gesture Control ---
802
+ var isFistNow = _this1._isFist(smoothedLandmarks);
803
+ if (isFistNow && !hand.isFist) {
804
+ // Fist gesture was just made
805
+ _this1.musicManager.cycleSynth();
806
+ _this1.musicManager.stopArpeggio(i); // Stop any old arpeggio
807
+ }
808
+ hand.isFist = isFistNow;
809
+ var noteIndex = Math.floor((1 - normY_visible) * scale.length);
810
+ var note = scale[Math.max(0, Math.min(scale.length - 1, noteIndex))];
811
+ if (_this1.waveformVisualizer) {
812
+ var colorIndex = noteIndex % _this1.waveformColors.length;
813
+ var newColor = _this1.waveformColors[colorIndex];
814
+ _this1.waveformVisualizer.updateColor(newColor);
815
+ }
816
+ var thumbTip = smoothedLandmarks[4];
817
+ var indexTip = smoothedLandmarks[8];
818
+ var dx = thumbTip.x - indexTip.x;
819
+ var dy = thumbTip.y - indexTip.y;
820
+ var distance = Math.sqrt(dx * dx + dy * dy);
821
+ // Normalize by hand size so volume works at any camera distance
822
+ var wristPt = smoothedLandmarks[0];
823
+ var middleMcp = smoothedLandmarks[9];
824
+ var palmDx = wristPt.x - middleMcp.x;
825
+ var palmDy = wristPt.y - middleMcp.y;
826
+ var palmSize = Math.sqrt(palmDx * palmDx + palmDy * palmDy) || 0.01;
827
+ var normalizedDist = distance / palmSize;
828
+ var velocity = Math.max(0.05, Math.min(1.0, normalizedDist * 1.5));
829
+ // Proximity = how close the hand is to camera
830
+ // Use apparent palm size as proxy (bigger = closer)
831
+ // palmSize is in normalized coords (0-1), typical range 0.03 (far) to 0.2 (close)
832
+ var proximity = Math.max(0, Math.min(1, (palmSize - 0.03) / 0.12));
833
+ if (_this1.musicManager.setProximityFilter) {
834
+ _this1.musicManager.setProximityFilter(proximity);
835
+ }
836
+ _this1._updateHandLines(i, smoothedLandmarks, videoParams, canvasWidth, canvasHeight, {
837
+ note: note,
838
+ velocity: velocity,
839
+ isFist: isFistNow
840
+ });
841
+ if (!isFistNow) {
842
+ // Start/Restart arpeggio if the hand just appeared OR if it just opened from a fist.
843
+ var arpeggioIsActive = _this1.musicManager.activePatterns.has(i);
844
+ if (!wasVisible || !arpeggioIsActive) {
845
+ _this1.musicManager.startArpeggio(i, note, playerIndex);
846
+ } else {
847
+ _this1.musicManager.updateArpeggio(i, note);
848
+ }
849
+ _this1.musicManager.updateArpeggioVolume(i, velocity);
850
+ // --- Finger Distance-from-Palm Controls ---
851
+ // Each finger's Euclidean distance from palm center, normalized by palm size
852
+ var wrist = smoothedLandmarks[0];
853
+ var palmCenter = smoothedLandmarks[9]; // middle finger MCP = palm center
854
+ var palmDist = Math.sqrt(Math.pow(wrist.x - palmCenter.x, 2) + Math.pow(wrist.y - palmCenter.y, 2)) || 0.05;
855
+ // Fingertip landmarks: thumb=4, index=8, middle=12, ring=16, pinky=20
856
+ var fingerTips = {
857
+ thumb: smoothedLandmarks[4],
858
+ index: smoothedLandmarks[8],
859
+ middle: smoothedLandmarks[12],
860
+ ring: smoothedLandmarks[16],
861
+ pinky: smoothedLandmarks[20]
862
+ };
863
+ var fingerDistances = {};
864
+ for (var fname in fingerTips) {
865
+ var tip = fingerTips[fname];
866
+ var fdx = tip.x - palmCenter.x;
867
+ var fdy = tip.y - palmCenter.y;
868
+ var fdist = Math.sqrt(fdx * fdx + fdy * fdy);
869
+ // Normalize: 0 = touching palm, 1 = fully extended (~ 2x palm size)
870
+ fingerDistances[fname] = Math.max(0, Math.min(1, fdist / (palmDist * 2)));
871
+ }
872
+ // --- Finger-touch detection: play unique sound when fingertips collide ---
873
+ var touchThreshold = palmDist * 0.35; // fingers within ~35% of palm size = touching
874
+ var fNames = ['thumb', 'index', 'middle', 'ring', 'pinky'];
875
+ if (!_this1._fingerTouchState) _this1._fingerTouchState = {};
876
+ for (var fi = 0; fi < fNames.length; fi++) {
877
+ for (var fj = fi + 1; fj < fNames.length; fj++) {
878
+ var fa = fingerTips[fNames[fi]];
879
+ var fb = fingerTips[fNames[fj]];
880
+ var tdx = fa.x - fb.x;
881
+ var tdy = fa.y - fb.y;
882
+ var tdist = Math.sqrt(tdx * tdx + tdy * tdy);
883
+ var pairKey = fNames[fi] + '-' + fNames[fj];
884
+ var wasTouching = _this1._fingerTouchState[pairKey] || false;
885
+ var isTouching = tdist < touchThreshold;
886
+ if (isTouching && !wasTouching) {
887
+ // Fingers just came together — trigger touch sound
888
+ if (_this1.musicManager.triggerFingerTouch) {
889
+ _this1.musicManager.triggerFingerTouch(fNames[fi], fNames[fj]);
890
+ }
891
+ }
892
+ _this1._fingerTouchState[pairKey] = isTouching;
893
+ }
894
+ }
895
+ // Also keep legacy extension values for compatibility
896
+ var palmSize = palmDist;
897
+ var middleTip = smoothedLandmarks[12];
898
+ var middlePip = smoothedLandmarks[10];
899
+ var ringTip = smoothedLandmarks[16];
900
+ var ringPip = smoothedLandmarks[14];
901
+ var pinkyTip = smoothedLandmarks[20];
902
+ var pinkyPip = smoothedLandmarks[18];
903
+ var middleExt = Math.max(0, Math.min(1, (middlePip.y - middleTip.y) / palmSize));
904
+ var ringExt = Math.max(0, Math.min(1, (ringPip.y - ringTip.y) / palmSize));
905
+ var pinkyExt = Math.max(0, Math.min(1, (pinkyPip.y - pinkyTip.y) / palmSize));
906
+ var indexExt = Math.max(0, Math.min(1, (smoothedLandmarks[6].y - smoothedLandmarks[8].y) / palmSize));
907
+ // Hand spread: average distance between adjacent fingertips / palm size
908
+ var tips = [smoothedLandmarks[4], smoothedLandmarks[8], middleTip, ringTip, pinkyTip];
909
+ var spreadSum = 0;
910
+ for (var t = 0; t < tips.length - 1; t++) {
911
+ var sdx = tips[t].x - tips[t+1].x;
912
+ var sdy = tips[t].y - tips[t+1].y;
913
+ spreadSum += Math.sqrt(sdx*sdx + sdy*sdy);
914
+ }
915
+ var handSpread = Math.max(0, Math.min(1, (spreadSum / 4) / (palmSize * 2)));
916
+ _this1.musicManager.updateFingerExpression({
917
+ fingerDistances: fingerDistances,
918
+ middleFinger: middleExt,
919
+ ringFinger: ringExt,
920
+ pinkyFinger: pinkyExt,
921
+ handSpread: handSpread
922
+ });
923
+ // --- Gesture-Driven Music ---
924
+ var fingerStates = {
925
+ thumb: fingerDistances.thumb > 0.3,
926
+ index: indexExt > 0.3,
927
+ middle: middleExt > 0.3,
928
+ ring: ringExt > 0.3,
929
+ pinky: pinkyExt > 0.3
930
+ };
931
+ // Track previous states and compute velocities
932
+ if (!_this1._prevFingerStates) _this1._prevFingerStates = {};
933
+ if (!_this1._prevHandPos) _this1._prevHandPos = {};
934
+ if (!_this1._prevFingerDistances) _this1._prevFingerDistances = {};
935
+ var prevFS = _this1._prevFingerStates[i] || { thumb: false, index: false, middle: false, ring: false, pinky: false };
936
+ var prevHP = _this1._prevHandPos[i] || { x: hand.anchorPos.x, y: hand.anchorPos.y };
937
+ var prevFD = _this1._prevFingerDistances[i] || { thumb: 0, index: 0, middle: 0, ring: 0, pinky: 0 };
938
+ var handVelX = hand.anchorPos.x - prevHP.x;
939
+ var handVelY = hand.anchorPos.y - prevHP.y;
940
+ // Wrist angle: angle of wrist→palm vector vs vertical
941
+ // 0 = hand pointing straight up, 1 = tilted fully right, -1 = fully left
942
+ var wristToMcp_dx = palmCenter.x - wrist.x;
943
+ var wristToMcp_dy = palmCenter.y - wrist.y;
944
+ var wristAngleRad = Math.atan2(wristToMcp_dx, -wristToMcp_dy); // 0=up, +π/2=right
945
+ var wristAngle = Math.max(-1, Math.min(1, wristAngleRad / (Math.PI / 2))); // normalize to -1..1
946
+ _this1.musicManager.updateGesture(i, {
947
+ fingerStates: fingerStates,
948
+ prevFingerStates: prevFS,
949
+ fingerDistances: fingerDistances,
950
+ prevFingerDistances: prevFD,
951
+ fingerExtensions: {
952
+ thumb: fingerDistances.thumb,
953
+ index: indexExt,
954
+ middle: middleExt,
955
+ ring: ringExt,
956
+ pinky: pinkyExt
957
+ },
958
+ handVelocity: { x: handVelX, y: handVelY },
959
+ handSpread: handSpread,
960
+ wristAngle: wristAngle,
961
+ rootNote: note,
962
+ volume: velocity
963
+ });
964
+ _this1._prevFingerStates[i] = fingerStates;
965
+ _this1._prevHandPos[i] = { x: hand.anchorPos.x, y: hand.anchorPos.y };
966
+ _this1._prevFingerDistances[i] = Object.assign({}, fingerDistances);
967
+ } else {
968
+ // If it is a fist, make sure the arpeggio is stopped
969
+ _this1.musicManager.stopArpeggio(i);
970
+ }
971
+ } else if (isDrumHand) {
972
+ var fingerStates = _this1._getFingerStates(smoothedLandmarks);
973
+ if (playerIndex === 0) drumManager.updateActiveDrums(fingerStates);
974
+ _this1._updateHandLines(i, smoothedLandmarks, videoParams, canvasWidth, canvasHeight, {
975
+ fingerStates: fingerStates
976
+ });
977
+ // Per-finger drum sounds via updateDrumGesture
978
+ var drumWrist = smoothedLandmarks[0];
979
+ var drumPalmCenter = smoothedLandmarks[9];
980
+ var drumPalmDist = Math.sqrt(Math.pow(drumWrist.x - drumPalmCenter.x, 2) + Math.pow(drumWrist.y - drumPalmCenter.y, 2)) || 0.05;
981
+ var drumFingerTips = {
982
+ thumb: smoothedLandmarks[4],
983
+ index: smoothedLandmarks[8],
984
+ middle: smoothedLandmarks[12],
985
+ ring: smoothedLandmarks[16],
986
+ pinky: smoothedLandmarks[20]
987
+ };
988
+ var drumFingerDistances = {};
989
+ for (var dfname in drumFingerTips) {
990
+ var dtip = drumFingerTips[dfname];
991
+ var dfdx = dtip.x - drumPalmCenter.x;
992
+ var dfdy = dtip.y - drumPalmCenter.y;
993
+ var dfdist = Math.sqrt(dfdx * dfdx + dfdy * dfdy);
994
+ drumFingerDistances[dfname] = Math.max(0, Math.min(1, dfdist / (drumPalmDist * 2)));
995
+ }
996
+ // Drum hand finger-touch detection
997
+ var drumTouchThreshold = drumPalmDist * 0.35;
998
+ var dFNames = ['thumb', 'index', 'middle', 'ring', 'pinky'];
999
+ if (!_this1._drumFingerTouchState) _this1._drumFingerTouchState = {};
1000
+ for (var dfi = 0; dfi < dFNames.length; dfi++) {
1001
+ for (var dfj = dfi + 1; dfj < dFNames.length; dfj++) {
1002
+ var dfa = drumFingerTips[dFNames[dfi]];
1003
+ var dfb = drumFingerTips[dFNames[dfj]];
1004
+ var dtdx = dfa.x - dfb.x;
1005
+ var dtdy = dfa.y - dfb.y;
1006
+ var dtdist = Math.sqrt(dtdx * dtdx + dtdy * dtdy);
1007
+ var dpairKey = 'drum-' + dFNames[dfi] + '-' + dFNames[dfj];
1008
+ var dwasTouching = _this1._drumFingerTouchState[dpairKey] || false;
1009
+ var disTouching = dtdist < drumTouchThreshold;
1010
+ if (disTouching && !dwasTouching) {
1011
+ if (_this1.musicManager.triggerFingerTouch) {
1012
+ _this1.musicManager.triggerFingerTouch(dFNames[dfi], dFNames[dfj]);
1013
+ }
1014
+ }
1015
+ _this1._drumFingerTouchState[dpairKey] = disTouching;
1016
+ }
1017
+ }
1018
+ // Drum hand wrist angle
1019
+ var drumWristToMcp_dx = drumPalmCenter.x - drumWrist.x;
1020
+ var drumWristToMcp_dy = drumPalmCenter.y - drumWrist.y;
1021
+ var drumWristAngleRad = Math.atan2(drumWristToMcp_dx, -drumWristToMcp_dy);
1022
+ var drumWristAngle = Math.max(-1, Math.min(1, drumWristAngleRad / (Math.PI / 2)));
1023
+ if (_this1.musicManager.updateDrumGesture) {
1024
+ _this1.musicManager.updateDrumGesture({
1025
+ fingerStates: fingerStates,
1026
+ fingerDistances: drumFingerDistances,
1027
+ fingerExtensions: {
1028
+ thumb: drumFingerDistances.thumb,
1029
+ index: drumFingerDistances.index,
1030
+ middle: drumFingerDistances.middle,
1031
+ ring: drumFingerDistances.ring,
1032
+ pinky: drumFingerDistances.pinky
1033
+ },
1034
+ wristAngle: drumWristAngle
1035
+ });
1036
+ }
1037
+ }
1038
+ hand.lineGroup.visible = true;
1039
+ } else {
1040
+ if (wasVisible) {
1041
+ if (i === 0) {
1042
+ _this1.musicManager.stopArpeggio(i);
1043
+ // Kill sub-bass and plucks when music hand leaves
1044
+ if (_this1.musicManager.subBass) {
1045
+ try { _this1.musicManager.subBass.triggerRelease(Tone.now()); } catch(e) {}
1046
+ }
1047
+ if (_this1.musicManager.pluckSynth) {
1048
+ try { _this1.musicManager.pluckSynth.releaseAll(Tone.now()); } catch(e) {}
1049
+ }
1050
+ } else if (i % 2 === 1) {
1051
+ if (Math.floor(i / 2) === 0) drumManager.updateActiveDrums({});
1052
+ }
1053
+ }
1054
+ hand.landmarks = null;
1055
+ if (hand.lineGroup) hand.lineGroup.visible = false;
1056
+ }
1057
+ };
1058
+ var results = this.handLandmarker.detectForVideo(this.videoElement, performance.now());
1059
+ var videoParams = this._getVisibleVideoParameters();
1060
+ if (!videoParams) return;
1061
+ var canvasWidth = this.renderDiv.clientWidth;
1062
+ var canvasHeight = this.renderDiv.clientHeight;
1063
+ // C Minor Pentatonic Scale
1064
+ // Extended C Minor Pentatonic: SUPER bassy at bottom, modest highs at top
1065
+ // Bottom of screen (hands low) = deep sub-bass
1066
+ // Top of screen (hands high) = higher pitched but not extreme
1067
+ var scale = [
1068
+ 'C1', 'Eb1', 'G1', 'Bb1',
1069
+ 'C2', 'Eb2', 'F2', 'G2', 'Bb2',
1070
+ 'C3', 'Eb3', 'F3', 'G3', 'Bb3',
1071
+ 'C4', 'Eb4', 'F4', 'G4', 'Bb4',
1072
+ 'C5', 'Eb5', 'F5'
1073
+ ];
1074
+ var handLimit = this._multiplayerEnabled ? this.hands.length : 2;
1075
+ for(var i = 0; i < handLimit; i++)_this1 = this, _loop(i);
1076
+ } catch (error) {
1077
+ console.error("Error during hand detection:", error);
1078
+ }
1079
+ }
1080
+ }
1081
+ },
1082
+ {
1083
+ key: "_getVisibleVideoParameters",
1084
+ value: function _getVisibleVideoParameters() {
1085
+ if (!this.videoElement || this.videoElement.videoWidth === 0 || this.videoElement.videoHeight === 0) {
1086
+ return null;
1087
+ }
1088
+ var vNatW = this.videoElement.videoWidth;
1089
+ var vNatH = this.videoElement.videoHeight;
1090
+ var rW = this.renderDiv.clientWidth;
1091
+ var rH = this.renderDiv.clientHeight;
1092
+ if (vNatW === 0 || vNatH === 0 || rW === 0 || rH === 0) return null;
1093
+ var videoAR = vNatW / vNatH;
1094
+ var renderDivAR = rW / rH;
1095
+ var finalVideoPixelX, finalVideoPixelY;
1096
+ var visibleVideoPixelWidth, visibleVideoPixelHeight;
1097
+ if (videoAR > renderDivAR) {
1098
+ // Video is wider than renderDiv, scaled to fit renderDiv height, cropped horizontally.
1099
+ var scale = rH / vNatH; // Scale factor based on height.
1100
+ var scaledVideoWidth = vNatW * scale; // Width of video if scaled to fit renderDiv height.
1101
+ // Total original video pixels cropped horizontally (from both sides combined).
1102
+ var totalCroppedPixelsX = (scaledVideoWidth - rW) / scale;
1103
+ finalVideoPixelX = totalCroppedPixelsX / 2; // Pixels cropped from the left of original video.
1104
+ finalVideoPixelY = 0; // No vertical cropping.
1105
+ visibleVideoPixelWidth = vNatW - totalCroppedPixelsX; // Width of the visible part in original video pixels.
1106
+ visibleVideoPixelHeight = vNatH; // Full height is visible.
1107
+ } else {
1108
+ // Video is taller than renderDiv (or same AR), scaled to fit renderDiv width, cropped vertically.
1109
+ var scale1 = rW / vNatW; // Scale factor based on width.
1110
+ var scaledVideoHeight = vNatH * scale1; // Height of video if scaled to fit renderDiv width.
1111
+ // Total original video pixels cropped vertically (from top and bottom combined).
1112
+ var totalCroppedPixelsY = (scaledVideoHeight - rH) / scale1;
1113
+ finalVideoPixelX = 0; // No horizontal cropping.
1114
+ finalVideoPixelY = totalCroppedPixelsY / 2; // Pixels cropped from the top of original video.
1115
+ visibleVideoPixelWidth = vNatW; // Full width is visible.
1116
+ visibleVideoPixelHeight = vNatH - totalCroppedPixelsY; // Height of the visible part in original video pixels.
1117
+ }
1118
+ // Safety check for degenerate cases (e.g., extreme aspect ratios leading to zero visible dimension)
1119
+ if (visibleVideoPixelWidth <= 0 || visibleVideoPixelHeight <= 0) {
1120
+ // Fallback or log error, this shouldn't happen in normal scenarios
1121
+ console.warn("Calculated visible video dimension is zero or negative.", {
1122
+ visibleVideoPixelWidth: visibleVideoPixelWidth,
1123
+ visibleVideoPixelHeight: visibleVideoPixelHeight
1124
+ });
1125
+ return {
1126
+ offsetX: 0,
1127
+ offsetY: 0,
1128
+ visibleWidth: vNatW,
1129
+ visibleHeight: vNatH,
1130
+ videoNaturalWidth: vNatW,
1131
+ videoNaturalHeight: vNatH
1132
+ };
1133
+ }
1134
+ return {
1135
+ offsetX: finalVideoPixelX,
1136
+ offsetY: finalVideoPixelY,
1137
+ visibleWidth: visibleVideoPixelWidth,
1138
+ visibleHeight: visibleVideoPixelHeight,
1139
+ videoNaturalWidth: vNatW,
1140
+ videoNaturalHeight: vNatH
1141
+ };
1142
+ }
1143
+ },
1144
+ {
1145
+ // _updateGhosts method removed.
1146
+ key: "_showStatusScreen",
1147
+ value: function _showStatusScreen(message) {
1148
+ var color = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 'white', showRestartHint = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : false;
1149
+ this.gameOverContainer.style.display = 'block';
1150
+ this.gameOverText.innerText = message;
1151
+ this.gameOverText.style.color = color;
1152
+ this.restartHintText.style.display = showRestartHint ? 'block' : 'none';
1153
+ // No spawning to stop for template
1154
+ }
1155
+ },
1156
+ {
1157
+ key: "_showError",
1158
+ value: function _showError(message) {
1159
+ this.gameOverContainer.style.display = 'block';
1160
+ this.gameOverText.innerText = "ERROR: ".concat(message);
1161
+ this.gameOverText.style.color = 'orange';
1162
+ this.restartHintText.style.display = 'true'; // Show restart hint on error
1163
+ this.gameState = 'error';
1164
+ // No spawning to stop
1165
+ this.hands.forEach(function(hand) {
1166
+ if (hand.lineGroup) hand.lineGroup.visible = false;
1167
+ });
1168
+ // if (this.startButton) this.startButton.style.display = 'none'; // No longer exists
1169
+ }
1170
+ },
1171
+ {
1172
+ key: "_startGame",
1173
+ value: function _startGame() {
1174
+ var _this = this;
1175
+ console.log("Starting tracking...");
1176
+ // This is now called automatically, so no need to check gameState
1177
+ this.musicManager.start().then(function() {
1178
+ drumManager.startSequence(); // Start drums *after* audio context is ready.
1179
+ // Setup the waveform visualizer after the music manager is ready
1180
+ var analyser = _this.musicManager.getAnalyser();
1181
+ if (analyser) {
1182
+ _this.waveformVisualizer = new WaveformVisualizer(_this.scene, analyser, _this.renderDiv.clientWidth, _this.renderDiv.clientHeight);
1183
+ }
1184
+ _this.mandalaVisualizer = new MandalaVisualizer(_this.scene);
1185
+ _this.shapeManager = new ShapeManager(_this.scene);
1186
+ });
1187
+ this.gameState = 'tracking'; // Changed from 'playing'
1188
+ this.lastVideoTime = -1;
1189
+ this.clock.start();
1190
+ // Removed display of score, castle, chad
1191
+ // Removed _startSpawning()
1192
+ }
1193
+ },
1194
+ {
1195
+ key: "_restartGame",
1196
+ value: function _restartGame() {
1197
+ console.log("Restarting tracking...");
1198
+ this.gameOverContainer.style.display = 'none';
1199
+ this.hands.forEach(function(hand) {
1200
+ if (hand.lineGroup) {
1201
+ hand.lineGroup.visible = false;
1202
+ }
1203
+ });
1204
+ // Ghost removal removed
1205
+ // Score reset removed
1206
+ // Visibility of game elements removed
1207
+ this.gameState = 'tracking'; // Changed from 'playing'
1208
+ this.lastVideoTime = -1;
1209
+ this.clock.start();
1210
+ // Removed _startSpawning()
1211
+ }
1212
+ },
1213
+ {
1214
+ // _updateScoreDisplay method removed.
1215
+ key: "_onResize",
1216
+ value: function _onResize() {
1217
+ var width = this.renderDiv.clientWidth;
1218
+ var height = this.renderDiv.clientHeight;
1219
+ // Update camera perspective
1220
+ this.camera.left = width / -2;
1221
+ this.camera.right = width / 2;
1222
+ this.camera.top = height / 2;
1223
+ this.camera.bottom = height / -2;
1224
+ this.camera.updateProjectionMatrix();
1225
+ // Update renderer size
1226
+ this.renderer.setSize(width, height);
1227
+ // Update video element size
1228
+ this.videoElement.style.width = width + 'px';
1229
+ this.videoElement.style.height = height + 'px';
1230
+ // Watermelon, Chad, GroundLine updates removed.
1231
+ this._positionBeatIndicators();
1232
+ if (this.waveformVisualizer) {
1233
+ this.waveformVisualizer.updatePosition(width, height);
1234
+ }
1235
+ }
1236
+ },
1237
+ {
1238
+ key: "_positionBeatIndicators",
1239
+ value: function _positionBeatIndicators() {
1240
+ var width = this.renderDiv.clientWidth;
1241
+ var height = this.renderDiv.clientHeight;
1242
+ var totalWidth = width * 0.8; // Occupy 80% of screen width to match the waveform
1243
+ var spacing = totalWidth / 16;
1244
+ var startX = -totalWidth / 2 + spacing / 2;
1245
+ var yPos = -height / 2 + 150; // Positioned a bit higher from the bottom
1246
+ this.beatIndicators.forEach(function(indicator, i) {
1247
+ indicator.position.set(startX + i * spacing, yPos, 1);
1248
+ });
1249
+ }
1250
+ },
1251
+ {
1252
+ key: "_setupBeatIndicatorMaterials",
1253
+ value: function _setupBeatIndicatorMaterials() {
1254
+ // All indicators start as 'off' (white)
1255
+ for(var i = 0; i < 16; i++){
1256
+ // We just need one material definition now and will copy it.
1257
+ this.beatIndicatorMaterials[i] = new THREE.MeshBasicMaterial({
1258
+ color: this.beatIndicatorColors.off,
1259
+ transparent: true,
1260
+ opacity: 0.5
1261
+ });
1262
+ }
1263
+ }
1264
+ },
1265
+ {
1266
+ key: "_createTextSprite",
1267
+ value: function _createTextSprite(message, parameters) {
1268
+ parameters = parameters || {};
1269
+ var fontface = parameters.fontface || 'Arial';
1270
+ var fontsize = parameters.fontsize || 24;
1271
+ // borderColor is no longer needed
1272
+ var backgroundColor = parameters.backgroundColor || {
1273
+ r: 255,
1274
+ g: 255,
1275
+ b: 255,
1276
+ a: 0.8
1277
+ };
1278
+ var textColor = parameters.textColor || {
1279
+ r: 0,
1280
+ g: 0,
1281
+ b: 0,
1282
+ a: 1.0
1283
+ };
1284
+ var canvas = document.createElement('canvas');
1285
+ var context = canvas.getContext('2d');
1286
+ context.font = "Bold ".concat(fontsize, "px ").concat(fontface);
1287
+ // get size data (height depends only on font size)
1288
+ var metrics = context.measureText(message);
1289
+ var textWidth = metrics.width;
1290
+ var padding = 10;
1291
+ var canvasWidth = textWidth + padding * 2;
1292
+ var canvasHeight = fontsize * 1.4 + padding;
1293
+ canvas.width = canvasWidth;
1294
+ canvas.height = canvasHeight;
1295
+ // Font needs to be re-applied after resizing canvas
1296
+ context.font = "Bold ".concat(fontsize, "px ").concat(fontface);
1297
+ // background color
1298
+ context.fillStyle = "rgba(".concat(backgroundColor.r, ",").concat(backgroundColor.g, ",").concat(backgroundColor.b, ",").concat(backgroundColor.a, ")");
1299
+ context.fillRect(0, 0, canvasWidth, canvasHeight);
1300
+ // text color and position
1301
+ context.fillStyle = "rgba(".concat(textColor.r, ", ").concat(textColor.g, ", ").concat(textColor.b, ", 1.0)");
1302
+ context.textAlign = 'center';
1303
+ context.textBaseline = 'middle';
1304
+ context.fillText(message, canvasWidth / 2, canvasHeight / 2);
1305
+ // canvas contents will be used for a texture
1306
+ var texture = new THREE.CanvasTexture(canvas);
1307
+ texture.needsUpdate = true;
1308
+ var spriteMaterial = new THREE.SpriteMaterial({
1309
+ map: texture
1310
+ });
1311
+ var sprite = new THREE.Sprite(spriteMaterial);
1312
+ sprite.scale.set(canvas.width, canvas.height, 1.0);
1313
+ return sprite;
1314
+ }
1315
+ },
1316
+ {
1317
+ key: "_getFingerStates",
1318
+ value: function _getFingerStates(landmarks) {
1319
+ // Landmark indices for fingertips
1320
+ var fingertips = {
1321
+ index: 8,
1322
+ middle: 12,
1323
+ ring: 16,
1324
+ pinky: 20
1325
+ };
1326
+ // Stricter check using the joint below the tip (PIP joint) to avoid false positives.
1327
+ var fingerJointsBelowTip = {
1328
+ index: 6,
1329
+ middle: 10,
1330
+ ring: 14,
1331
+ pinky: 18
1332
+ };
1333
+ var states = {};
1334
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
1335
+ try {
1336
+ for(var _iterator = Object.entries(fingertips)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
1337
+ var _step_value = _sliced_to_array(_step.value, 2), finger = _step_value[0], tipIndex = _step_value[1];
1338
+ var jointIndex = fingerJointsBelowTip[finger];
1339
+ if (landmarks[tipIndex] && landmarks[jointIndex]) {
1340
+ // A finger is "up" if its tip is higher than the joint just below it.
1341
+ states[finger] = landmarks[tipIndex].y < landmarks[jointIndex].y;
1342
+ } else {
1343
+ states[finger] = false;
1344
+ }
1345
+ }
1346
+ } catch (err) {
1347
+ _didIteratorError = true;
1348
+ _iteratorError = err;
1349
+ } finally{
1350
+ try {
1351
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
1352
+ _iterator.return();
1353
+ }
1354
+ } finally{
1355
+ if (_didIteratorError) {
1356
+ throw _iteratorError;
1357
+ }
1358
+ }
1359
+ }
1360
+ return states;
1361
+ }
1362
+ },
1363
+ {
1364
+ key: "_isFist",
1365
+ value: function _isFist(landmarks) {
1366
+ if (!landmarks || landmarks.length < 21) return false;
1367
+ // Use the middle finger's MCP joint as a proxy for the palm center
1368
+ var palmCenter = landmarks[9];
1369
+ var fingertipsIndices = [
1370
+ 4,
1371
+ 8,
1372
+ 12,
1373
+ 16,
1374
+ 20
1375
+ ]; // Thumb, Index, Middle, Ring, Pinky
1376
+ // Threshold for normalized landmark distance. If fingertips are further than this from palm, it's not a fist.
1377
+ // This value may need tuning. A smaller value makes the fist detection stricter.
1378
+ var fistThreshold = 0.1;
1379
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
1380
+ try {
1381
+ for(var _iterator = fingertipsIndices[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
1382
+ var tipIndex = _step.value;
1383
+ var tip = landmarks[tipIndex];
1384
+ var dx = tip.x - palmCenter.x;
1385
+ var dy = tip.y - palmCenter.y;
1386
+ var distance = Math.sqrt(dx * dx + dy * dy);
1387
+ if (distance > fistThreshold) {
1388
+ return false; // At least one finger is open
1389
+ }
1390
+ }
1391
+ } catch (err) {
1392
+ _didIteratorError = true;
1393
+ _iteratorError = err;
1394
+ } finally{
1395
+ try {
1396
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
1397
+ _iterator.return();
1398
+ }
1399
+ } finally{
1400
+ if (_didIteratorError) {
1401
+ throw _iteratorError;
1402
+ }
1403
+ }
1404
+ }
1405
+ return true; // All fingertips are close to the palm
1406
+ }
1407
+ },
1408
+ {
1409
+ key: "_updateHandLines",
1410
+ value: function _updateHandLines(handIndex, landmarks, videoParams, canvasWidth, canvasHeight, controlData) {
1411
+ var _this = this;
1412
+ var hand = this.hands[handIndex];
1413
+ var lineGroup = hand.lineGroup;
1414
+ // Clean up previous frame's objects
1415
+ while(lineGroup.children.length){
1416
+ var child = lineGroup.children[0];
1417
+ lineGroup.remove(child);
1418
+ if (child.geometry) child.geometry.dispose();
1419
+ if (child.material) {
1420
+ // For sprites, we need to dispose the texture map as well
1421
+ if (child.material.map) child.material.map.dispose();
1422
+ child.material.dispose();
1423
+ }
1424
+ }
1425
+ if (!landmarks || landmarks.length === 0 || !videoParams) {
1426
+ lineGroup.visible = false;
1427
+ return;
1428
+ }
1429
+ var points3D = landmarks.map(function(lm) {
1430
+ var lmOriginalX = lm.x * videoParams.videoNaturalWidth;
1431
+ var lmOriginalY = lm.y * videoParams.videoNaturalHeight;
1432
+ var normX_visible = (lmOriginalX - videoParams.offsetX) / videoParams.visibleWidth;
1433
+ var normY_visible = (lmOriginalY - videoParams.offsetY) / videoParams.visibleHeight;
1434
+ normX_visible = Math.max(0, Math.min(1, normX_visible));
1435
+ normY_visible = Math.max(0, Math.min(1, normY_visible));
1436
+ var x = (1 - normX_visible) * canvasWidth - canvasWidth / 2;
1437
+ var y = (1 - normY_visible) * canvasHeight - canvasHeight / 2;
1438
+ return new THREE.Vector3(x, y, 1.1); // Z for fingertip circles
1439
+ });
1440
+ hand.points3D = points3D;
1441
+ // --- Draw Skeleton Lines ---
1442
+ var lineZ = 1;
1443
+ this.handConnections.forEach(function(conn) {
1444
+ var p1 = points3D[conn[0]];
1445
+ var p2 = points3D[conn[1]];
1446
+ if (p1 && p2) {
1447
+ var lineP1 = p1.clone().setZ(lineZ);
1448
+ var lineP2 = p2.clone().setZ(lineZ);
1449
+ var geometry = new THREE.BufferGeometry().setFromPoints([
1450
+ lineP1,
1451
+ lineP2
1452
+ ]);
1453
+ var line = new THREE.Line(geometry, _this.handLineMaterial);
1454
+ lineGroup.add(line);
1455
+ }
1456
+ });
1457
+ // --- Draw Fingertip & Wrist Circles ---
1458
+ var fingertipRadius = 12, wristRadius = 16, circleSegments = 12;
1459
+ this.fingertipLandmarkIndices.forEach(function(index) {
1460
+ var landmarkPosition = points3D[index];
1461
+ if (landmarkPosition) {
1462
+ var radius = index === 0 ? wristRadius : fingertipRadius;
1463
+ var circleGeometry = new THREE.CircleGeometry(radius, circleSegments);
1464
+ var material = handIndex === 0 ? _this.fingertipMaterialHand1 : _this.fingertipMaterialHand2;
1465
+ var landmarkCircle = new THREE.Mesh(circleGeometry, material);
1466
+ landmarkCircle.position.copy(landmarkPosition);
1467
+ lineGroup.add(landmarkCircle);
1468
+ }
1469
+ });
1470
+ // --- Draw Thumb-to-Index line and Labels ---
1471
+ var thumbPos = points3D[4];
1472
+ var indexPos = points3D[8];
1473
+ var wristPos = points3D[0];
1474
+ if (wristPos) {
1475
+ // Labels depend on which hand it is
1476
+ if (handIndex === 0 && thumbPos && indexPos) {
1477
+ // Connecting line
1478
+ var lineGeom = new THREE.BufferGeometry().setFromPoints([
1479
+ thumbPos,
1480
+ indexPos
1481
+ ]);
1482
+ var line = new THREE.Line(lineGeom, new THREE.LineBasicMaterial({
1483
+ color: 0xffffff,
1484
+ linewidth: 3
1485
+ }));
1486
+ lineGroup.add(line);
1487
+ // Volume and Pitch labels
1488
+ var note = controlData.note, velocity = controlData.velocity, isFist = controlData.isFist;
1489
+ var presetNames = ['HYPNOTIC SUB', 'ACID GROWL', 'TRANCE WASH'];
1490
+ if (isFist) {
1491
+ var fistLabel = this._createTextSprite(presetNames[this.musicManager.currentSynthIndex] || 'SYNTH', {
1492
+ fontsize: 22,
1493
+ backgroundColor: this.labelColors.evaPurple,
1494
+ textColor: this.labelColors.evaGreen
1495
+ });
1496
+ fistLabel.position.set(wristPos.x, wristPos.y + 60, 2);
1497
+ lineGroup.add(fistLabel);
1498
+ } else {
1499
+ // Volume label between thumb and index
1500
+ var midPoint = new THREE.Vector3().lerpVectors(thumbPos, indexPos, 0.5);
1501
+ var volumeLabel = this._createTextSprite("VOL ".concat(Math.round(velocity * 100), "%"), {
1502
+ fontsize: 16,
1503
+ backgroundColor: this.labelColors.evaOrange,
1504
+ textColor: this.labelColors.white
1505
+ });
1506
+ volumeLabel.position.set(midPoint.x, midPoint.y - 20, 2);
1507
+ lineGroup.add(volumeLabel);
1508
+ // Pitch label above wrist
1509
+ var pitchLabel = this._createTextSprite(note, {
1510
+ fontsize: 20,
1511
+ backgroundColor: this.labelColors.evaGreen,
1512
+ textColor: this.labelColors.black
1513
+ });
1514
+ pitchLabel.position.set(wristPos.x, wristPos.y + 50, 2);
1515
+ lineGroup.add(pitchLabel);
1516
+ // Finger labels at each fingertip
1517
+ var fingerLabels = [
1518
+ { idx: 12, text: 'ROOT', color: this.labelColors.evaGreen },
1519
+ { idx: 16, text: 'BEAT', color: this.labelColors.evaOrange },
1520
+ { idx: 20, text: 'ZAP', color: this.labelColors.evaRed }
1521
+ ];
1522
+ for (var fl = 0; fl < fingerLabels.length; fl++) {
1523
+ var fp = points3D[fingerLabels[fl].idx];
1524
+ if (fp) {
1525
+ var fLabel = this._createTextSprite(fingerLabels[fl].text, {
1526
+ fontsize: 12,
1527
+ backgroundColor: fingerLabels[fl].color,
1528
+ textColor: this.labelColors.white
1529
+ });
1530
+ fLabel.position.set(fp.x, fp.y + 25, 2);
1531
+ lineGroup.add(fLabel);
1532
+ }
1533
+ }
1534
+ }
1535
+ } else if (handIndex === 1) {
1536
+ var fingerStates = controlData.fingerStates;
1537
+ // Per-finger drum labels at each fingertip
1538
+ var drumFingers = [
1539
+ { idx: 12, finger: 'middle', drum: 'KICK' },
1540
+ { idx: 16, finger: 'ring', drum: 'HIHAT' },
1541
+ { idx: 20, finger: 'pinky', drum: 'CLAP' }
1542
+ ];
1543
+ for (var df = 0; df < drumFingers.length; df++) {
1544
+ var dfp = points3D[drumFingers[df].idx];
1545
+ if (dfp) {
1546
+ var isActive = fingerStates[drumFingers[df].finger];
1547
+ var dLabel = this._createTextSprite(drumFingers[df].drum, {
1548
+ fontsize: 12,
1549
+ backgroundColor: isActive ? this.labelColors.evaGreen : this.labelColors.evaRed,
1550
+ textColor: this.labelColors.white
1551
+ });
1552
+ dLabel.position.set(dfp.x, dfp.y + 25, 2);
1553
+ lineGroup.add(dLabel);
1554
+ }
1555
+ }
1556
+ // Drum status at wrist
1557
+ var activeDrums = Object.entries(fingerStates).filter(function(param) {
1558
+ var _param = _sliced_to_array(param, 2), _ = _param[0], isUp = _param[1];
1559
+ return isUp;
1560
+ }).map(function(param) {
1561
+ var _param = _sliced_to_array(param, 2), finger = _param[0], _ = _param[1];
1562
+ return drumManager.getFingerToDrumMap()[finger];
1563
+ }).join(' ');
1564
+ var drumLabel = this._createTextSprite(activeDrums || 'DRUMS', {
1565
+ fontsize: 16,
1566
+ backgroundColor: this.labelColors.evaRed,
1567
+ textColor: this.labelColors.white
1568
+ });
1569
+ drumLabel.position.set(wristPos.x, wristPos.y + 50, 2);
1570
+ lineGroup.add(drumLabel);
1571
+ }
1572
+ }
1573
+ lineGroup.visible = true;
1574
+ }
1575
+ },
1576
+ {
1577
+ key: "_animate",
1578
+ value: function _animate() {
1579
+ requestAnimationFrame(this._animate.bind(this));
1580
+ if (this.gameState === 'tracking') {
1581
+ // Periodically check AudioContext hasn't been suspended by browser
1582
+ if (!this._lastAudioCheck) this._lastAudioCheck = 0;
1583
+ var now = performance.now();
1584
+ if (now - this._lastAudioCheck > 10000) {
1585
+ this._lastAudioCheck = now;
1586
+ this.musicManager.ensureAudioActive();
1587
+ }
1588
+ var deltaTime = this.clock.getDelta();
1589
+ this._updateHands();
1590
+ this._updateBeatIndicator();
1591
+ if (this.waveformVisualizer) {
1592
+ this.waveformVisualizer.update();
1593
+ }
1594
+ if (this.mandalaVisualizer) {
1595
+ var mandalaHands = this.hands.map(function(h) { return h.points3D || null; }).filter(Boolean);
1596
+ this.mandalaVisualizer.update(mandalaHands, 0, 0);
1597
+ }
1598
+ if (this.shapeManager) {
1599
+ var shapeHands = this.hands.map(function(h) { return h.points3D || null; }).filter(Boolean);
1600
+ var cw = this.renderDiv.clientWidth;
1601
+ var ch = this.renderDiv.clientHeight;
1602
+ this.shapeManager.update(shapeHands, cw, ch);
1603
+ // Pipe shape data to audio — depth modulates bass
1604
+ if (this.musicManager.updateShapeAudio) {
1605
+ var shapeState = this.shapeManager.getShapeState();
1606
+ var shapeDepth = this.shapeManager.getAverageDepth();
1607
+ var shapeArea = this.shapeManager.getShapeArea();
1608
+ this.musicManager.updateShapeAudio({
1609
+ type: shapeState.type,
1610
+ depth: shapeDepth,
1611
+ area: shapeArea,
1612
+ anchorCount: shapeState.anchors.length
1613
+ });
1614
+ }
1615
+ }
1616
+ if (this.displacementFilter) {
1617
+ var dispAmplitude = this.waveformVisualizer ? (this.waveformVisualizer.lastAmplitude || 0) : 0;
1618
+ this.displacementFilter.update(dispAmplitude, []);
1619
+ }
1620
+ // Simple line color pulse (lightweight)
1621
+ var pulseAmp = this.waveformVisualizer ? (this.waveformVisualizer.lastAmplitude || 0) : 0;
1622
+ var brightness = 0.7 + Math.min(0.3, pulseAmp * 2);
1623
+ if (this.handLineMaterial) {
1624
+ this.handLineMaterial.color.setHSL(0.83, 1.0, brightness); // bright magenta pulse
1625
+ }
1626
+ }
1627
+ this.renderer.render(this.scene, this.camera);
1628
+ }
1629
+ },
1630
+ {
1631
+ key: "_updateBeatIndicator",
1632
+ value: function _updateBeatIndicator() {
1633
+ var _this = this;
1634
+ var currentBeat = drumManager.getCurrentBeat();
1635
+ var progress = Tone.Transport.progress;
1636
+ var beatProgress = progress * 16 % 1;
1637
+ var pulse = 1.5 + 0.5 * Math.cos(beatProgress * Math.PI * 2);
1638
+ var activeDrums = drumManager.getActiveDrums();
1639
+ var drumPattern = drumManager.getDrumPattern();
1640
+ var drumPriority = [
1641
+ 'kick',
1642
+ 'snare',
1643
+ 'clap',
1644
+ 'hihat'
1645
+ ];
1646
+ this.beatIndicators.forEach(function(indicator, i) {
1647
+ // Determine the color for this step based on active drums
1648
+ var stepColor = _this.beatIndicatorColors.off;
1649
+ var isHit = false;
1650
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
1651
+ try {
1652
+ for(var _iterator = drumPriority[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
1653
+ var drum = _step.value;
1654
+ if (activeDrums.has(drum) && drumPattern[drum][i]) {
1655
+ stepColor = _this.beatIndicatorColors[drum];
1656
+ isHit = true;
1657
+ break;
1658
+ }
1659
+ }
1660
+ } catch (err) {
1661
+ _didIteratorError = true;
1662
+ _iteratorError = err;
1663
+ } finally{
1664
+ try {
1665
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
1666
+ _iterator.return();
1667
+ }
1668
+ } finally{
1669
+ if (_didIteratorError) {
1670
+ throw _iteratorError;
1671
+ }
1672
+ }
1673
+ }
1674
+ indicator.material.color.set(stepColor);
1675
+ indicator.material.opacity = isHit ? 0.9 : 0.5;
1676
+ // Apply pulse only to the current beat marker
1677
+ if (i === currentBeat) {
1678
+ indicator.scale.set(pulse, pulse, 1);
1679
+ } else {
1680
+ indicator.scale.set(1, 1, 1);
1681
+ }
1682
+ });
1683
+ }
1684
+ },
1685
+ {
1686
+ key: "_setupEventListeners",
1687
+ value: function _setupEventListeners() {
1688
+ var _this = this;
1689
+ // Add click listener for resuming audio context and potentially restarting on error
1690
+ this.renderDiv.addEventListener('click', function() {
1691
+ _this.musicManager.start(); // Resume audio context on any click
1692
+ if (_this.gameState === 'error') {
1693
+ _this._restartGame();
1694
+ }
1695
+ });
1696
+ // Multiplayer toggle — recreates HandLandmarker with correct numHands
1697
+ window._toggleMultiplayer = function() {
1698
+ _this._multiplayerEnabled = !_this._multiplayerEnabled;
1699
+ var statusEl = document.getElementById('mp-status');
1700
+ if (statusEl) {
1701
+ statusEl.textContent = _this._multiplayerEnabled ? 'ON' : 'OFF';
1702
+ statusEl.className = _this._multiplayerEnabled ? 'mp-on' : 'mp-off';
1703
+ }
1704
+ var newNumHands = _this._multiplayerEnabled ? 4 : 2;
1705
+ // Recreate landmarker with new hand count
1706
+ if (_this.handLandmarker && _this.handLandmarker.setOptions) {
1707
+ _this.handLandmarker.setOptions({ numHands: newNumHands });
1708
+ }
1709
+ console.log('Multiplayer: ' + (_this._multiplayerEnabled ? 'ON (4 hands)' : 'OFF (2 hands)'));
1710
+ };
1711
+
1712
+ console.log('Game event listeners set up.');
1713
+ }
1714
+ }
1715
+ ]);
1716
+ return Game;
1717
+ }();
index.html ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html>
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>Hyperspace Jam — Lyria AI</title>
7
+ <link rel="stylesheet" href="styles.css">
8
+
9
+ <!-- Primary Meta Tags -->
10
+ <meta name="title" content="Hyperspace Jam — Hand-controlled psychedelic synth with hyperbolic geometry">
11
+ <meta name="description" content="Hyperspace Jam — Hand-controlled psychedelic synth with hyperbolic geometry">
12
+
13
+ <!-- Open Graph / Facebook -->
14
+ <meta property="og:type" content="website">
15
+ <meta property="og:title" content="Hyperspace Jam — Hand-controlled psychedelic synth with hyperbolic geometry">
16
+ <meta property="og:description" content="Hyperspace Jam — Hand-controlled psychedelic synth with hyperbolic geometry">
17
+
18
+ <!-- Twitter -->
19
+ <meta property="twitter:card" content="summary_large_image">
20
+ <meta property="twitter:title" content="Hyperspace Jam — Hand-controlled psychedelic synth with hyperbolic geometry">
21
+ <meta property="twitter:description" content="Hyperspace Jam — Hand-controlled psychedelic synth with hyperbolic geometry">
22
+
23
+ <script type="importmap">
24
+ {
25
+ "imports": {
26
+ "three": "https://esm.sh/three@0.161.0?dev",
27
+ "three/": "https://esm.sh/three@0.161.0&dev/"
28
+ }
29
+ }
30
+ </script>
31
+ </head>
32
+ <body style="width: 100%; height: 100%; overflow: hidden; margin: 0;">
33
+ <div id="renderDiv" style="width: 100%; height: 100%; margin: 0;">
34
+
35
+ <div id="corner-controls">
36
+ <div id="multiplayer-toggle" onclick="window._toggleMultiplayer && window._toggleMultiplayer()">
37
+ <span class="mp-label">MULTI</span>
38
+ <span id="mp-status" class="mp-off">OFF</span>
39
+ </div>
40
+ <div id="legend-toggle" onclick="document.getElementById('controls-hint').classList.toggle('hidden')">
41
+ <span class="toggle-icon">?</span>
42
+ <span class="toggle-title">Hyperspace Jam</span>
43
+ </div>
44
+ </div>
45
+
46
+ <div id="controls-hint" class="hidden">
47
+ <div class="hint-title">HYPERSPACE JAM</div>
48
+ <div class="hint-grid">
49
+ <span class="hint-icon">↕️</span><span class="hint-desc">Hand high = bright · Hand low = DEEP bass</span>
50
+ <span class="hint-icon">👌</span><span class="hint-desc">Pinch thumb+index = volume</span>
51
+ <span class="hint-icon">🖐️</span><span class="hint-desc">Extend fingers = play chord notes</span>
52
+ <span class="hint-icon">✊</span><span class="hint-desc">Make fist = cycle synth sound</span>
53
+ <span class="hint-icon">🤲</span><span class="hint-desc">Tilt wrist = filter sweep + detune</span>
54
+ <span class="hint-icon">🤚</span><span class="hint-desc">2nd hand = kick · hihat · clap (distance = tempo)</span>
55
+ <span class="hint-icon">📏</span><span class="hint-desc">Spread fingers wide = wobble bass</span>
56
+ <span class="hint-icon">👆</span><span class="hint-desc">Touch fingertips together = sparkle sounds</span>
57
+ </div>
58
+ <div class="hint-fade">spacebar = panic stop · D = toggle displacement</div>
59
+ </div>
60
+
61
+ </div>
62
+ <div id="attract-mode">
63
+ <div id="attract-text">STEP UP TO JAM</div>
64
+ <div id="attract-sub">wave your hands to make music</div>
65
+ </div>
66
+ <script type="module" src="main.js"></script>
67
+ </body>
68
+ </html>
main.js ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { Game } from './game.js';
2
+ // Get the render target div
3
+ var renderDiv = document.getElementById('renderDiv');
4
+ // Check if renderDiv exists
5
+ if (!renderDiv) {
6
+ console.error('Fatal Error: renderDiv element not found.');
7
+ } else {
8
+ // Initialize the game with the render target
9
+ var game = new Game(renderDiv);
10
+ // The game now initializes and starts automatically from its constructor.
11
+ }
start.sh ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Hyperspace Jam — Lyria AI Edition
3
+ # Start the backend server which also serves the frontend
4
+
5
+ cd "$(dirname "$0")"
6
+
7
+ # Check for GEMINI_API_KEY
8
+ if [ -z "$GEMINI_API_KEY" ]; then
9
+ echo "ERROR: Set GEMINI_API_KEY environment variable first"
10
+ echo " export GEMINI_API_KEY=your-key-here"
11
+ exit 1
12
+ fi
13
+
14
+ # Check Ollama is running
15
+ if ! curl -s http://localhost:11434/api/tags > /dev/null 2>&1; then
16
+ echo "WARNING: Ollama not detected at localhost:11434"
17
+ echo " The system will use rule-based fallback for gesture interpretation."
18
+ echo " For AI-powered interpretation, start Ollama and pull qwen3:0.6b:"
19
+ echo " ollama serve"
20
+ echo " ollama pull qwen3:0.6b"
21
+ fi
22
+
23
+ # Create venv if needed
24
+ if [ ! -d ".venv" ]; then
25
+ echo "Creating virtual environment..."
26
+ python -m venv .venv
27
+ fi
28
+
29
+ source .venv/bin/activate 2>/dev/null || source .venv/Scripts/activate
30
+
31
+ pip install -q -r backend/requirements.txt
32
+
33
+ echo ""
34
+ echo "=== Hyperspace Jam — Lyria AI Edition ==="
35
+ echo "Open http://localhost:8000 in your browser"
36
+ echo ""
37
+
38
+ python backend/server.py
styles.css ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ * { margin: 0; padding: 0; box-sizing: border-box; }
2
+
3
+ html, body {
4
+ width: 100%;
5
+ height: 100%;
6
+ overflow: hidden;
7
+ background: #000;
8
+ font-family: 'Inter', 'Segoe UI', system-ui, -apple-system, sans-serif;
9
+ color: #fff;
10
+ }
11
+
12
+ #renderDiv {
13
+ width: 100%;
14
+ height: 100%;
15
+ position: relative;
16
+ }
17
+
18
+ /* --- Corner controls container --- */
19
+ #corner-controls {
20
+ position: absolute;
21
+ bottom: 16px;
22
+ right: 16px;
23
+ display: flex;
24
+ flex-direction: column;
25
+ align-items: flex-end;
26
+ gap: 8px;
27
+ z-index: 210;
28
+ }
29
+
30
+ /* --- Multiplayer toggle --- */
31
+ #multiplayer-toggle {
32
+ display: flex;
33
+ align-items: center;
34
+ gap: 6px;
35
+ padding: 4px 10px;
36
+ background: rgba(0, 0, 0, 0.5);
37
+ backdrop-filter: blur(6px);
38
+ border: 1px solid rgba(255, 255, 255, 0.12);
39
+ border-radius: 14px;
40
+ cursor: pointer;
41
+ user-select: none;
42
+ transition: background 0.2s;
43
+ }
44
+
45
+ #multiplayer-toggle:hover {
46
+ background: rgba(0, 0, 0, 0.7);
47
+ border-color: rgba(255, 200, 0, 0.3);
48
+ }
49
+
50
+ .mp-label {
51
+ font-size: 9px;
52
+ letter-spacing: 1.5px;
53
+ color: rgba(255, 255, 255, 0.4);
54
+ font-weight: 600;
55
+ }
56
+
57
+ .mp-off {
58
+ font-size: 9px;
59
+ color: rgba(255, 100, 100, 0.7);
60
+ font-weight: 700;
61
+ }
62
+
63
+ .mp-on {
64
+ font-size: 9px;
65
+ color: rgba(100, 255, 100, 0.9);
66
+ font-weight: 700;
67
+ }
68
+
69
+ /* --- Legend toggle button (always visible) --- */
70
+ #legend-toggle {
71
+ display: flex;
72
+ align-items: center;
73
+ gap: 8px;
74
+ padding: 6px 12px;
75
+ background: rgba(0, 0, 0, 0.5);
76
+ backdrop-filter: blur(6px);
77
+ -webkit-backdrop-filter: blur(6px);
78
+ border: 1px solid rgba(255, 255, 255, 0.12);
79
+ border-radius: 20px;
80
+ cursor: pointer;
81
+ transition: background 0.2s;
82
+ user-select: none;
83
+ }
84
+
85
+ #legend-toggle:hover {
86
+ background: rgba(0, 0, 0, 0.7);
87
+ border-color: rgba(0, 255, 255, 0.3);
88
+ }
89
+
90
+ .toggle-icon {
91
+ display: flex;
92
+ align-items: center;
93
+ justify-content: center;
94
+ width: 20px;
95
+ height: 20px;
96
+ border-radius: 50%;
97
+ background: rgba(0, 255, 255, 0.2);
98
+ color: rgba(0, 255, 255, 0.9);
99
+ font-size: 12px;
100
+ font-weight: 700;
101
+ line-height: 1;
102
+ }
103
+
104
+ .toggle-title {
105
+ font-size: 11px;
106
+ letter-spacing: 1.5px;
107
+ color: rgba(255, 255, 255, 0.5);
108
+ font-weight: 400;
109
+ font-style: italic;
110
+ }
111
+
112
+ /* --- Controls hint overlay --- */
113
+ #controls-hint {
114
+ position: absolute;
115
+ bottom: 20px;
116
+ left: 50%;
117
+ transform: translateX(-50%);
118
+ padding: 12px 20px;
119
+ background: rgba(0, 0, 0, 0.65);
120
+ backdrop-filter: blur(8px);
121
+ -webkit-backdrop-filter: blur(8px);
122
+ border: 1px solid rgba(255, 255, 255, 0.1);
123
+ border-radius: 12px;
124
+ z-index: 200;
125
+ max-width: 420px;
126
+ width: 90%;
127
+ transition: opacity 0.5s;
128
+ }
129
+
130
+ #controls-hint.hidden {
131
+ opacity: 0;
132
+ pointer-events: none;
133
+ }
134
+
135
+ .hint-title {
136
+ text-align: center;
137
+ font-size: 11px;
138
+ letter-spacing: 4px;
139
+ color: rgba(0, 255, 255, 0.7);
140
+ margin-bottom: 10px;
141
+ font-weight: 600;
142
+ }
143
+
144
+ .hint-grid {
145
+ display: grid;
146
+ grid-template-columns: 28px 1fr;
147
+ gap: 4px 8px;
148
+ font-size: 12px;
149
+ line-height: 1.6;
150
+ }
151
+
152
+ .hint-icon {
153
+ text-align: center;
154
+ font-size: 14px;
155
+ }
156
+
157
+ .hint-desc {
158
+ color: rgba(255, 255, 255, 0.75);
159
+ font-size: 11px;
160
+ }
161
+
162
+ .hint-fade {
163
+ text-align: center;
164
+ font-size: 9px;
165
+ color: rgba(255, 255, 255, 0.3);
166
+ margin-top: 8px;
167
+ letter-spacing: 2px;
168
+ text-transform: uppercase;
169
+ }
170
+
171
+ /* --- Attract mode overlay --- */
172
+ #attract-mode {
173
+ position: fixed;
174
+ inset: 0;
175
+ display: flex;
176
+ flex-direction: column;
177
+ align-items: center;
178
+ justify-content: center;
179
+ z-index: 300;
180
+ pointer-events: none;
181
+ opacity: 0;
182
+ transition: opacity 0.5s;
183
+ }
184
+
185
+ #attract-mode.visible {
186
+ opacity: 1;
187
+ }
188
+
189
+ #attract-text {
190
+ font-size: clamp(28px, 7vw, 60px);
191
+ color: #fff;
192
+ text-shadow: 0 0 15px rgba(0, 255, 255, 0.5), 0 0 30px rgba(255, 0, 255, 0.3);
193
+ letter-spacing: 6px;
194
+ font-weight: 300;
195
+ animation: pulse 2.5s ease-in-out infinite;
196
+ }
197
+
198
+ #attract-sub {
199
+ font-size: clamp(11px, 2.5vw, 18px);
200
+ color: rgba(255, 255, 255, 0.5);
201
+ margin-top: 16px;
202
+ letter-spacing: 3px;
203
+ font-weight: 300;
204
+ }
205
+
206
+ @keyframes pulse {
207
+ 0%, 100% { opacity: 0.3; transform: scale(1); }
208
+ 50% { opacity: 1; transform: scale(1.01); }
209
+ }