Arothurk commited on
Commit
0306d8f
·
verified ·
1 Parent(s): da6a751

Upload 14 files

Browse files
matrix-vision_0/.env.local ADDED
@@ -0,0 +1 @@
 
 
1
+ GEMINI_API_KEY=PLACEHOLDER_API_KEY
matrix-vision_0/.gitignore ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Logs
2
+ logs
3
+ *.log
4
+ npm-debug.log*
5
+ yarn-debug.log*
6
+ yarn-error.log*
7
+ pnpm-debug.log*
8
+ lerna-debug.log*
9
+
10
+ node_modules
11
+ dist
12
+ dist-ssr
13
+ *.local
14
+
15
+ # Editor directories and files
16
+ .vscode/*
17
+ !.vscode/extensions.json
18
+ .idea
19
+ .DS_Store
20
+ *.suo
21
+ *.ntvs*
22
+ *.njsproj
23
+ *.sln
24
+ *.sw?
matrix-vision_0/App.tsx ADDED
@@ -0,0 +1,372 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React, { useState, useEffect, useRef } from 'react';
2
+ import { RefreshCw, Monitor, Eye, Zap, AlertTriangle, FlipHorizontal, ShieldCheck, ShieldAlert, Wifi, WifiOff, Power } from 'lucide-react';
3
+ import MatrixCanvas from './components/MatrixCanvas';
4
+ import TerminalOutput from './components/TerminalOutput';
5
+ import { decodeMatrixImage, checkAIConnection } from './gemini';
6
+ import { AppState, CameraDevice } from './types';
7
+
8
+ const App: React.FC = () => {
9
+ const [stream, setStream] = useState<MediaStream | null>(null);
10
+ const [devices, setDevices] = useState<CameraDevice[]>([]);
11
+ const [currentDeviceId, setCurrentDeviceId] = useState<string>('');
12
+ const [appState, setAppState] = useState<AppState>(AppState.IDLE);
13
+ const [captureTrigger, setCaptureTrigger] = useState(0);
14
+ const [terminalLogs, setTerminalLogs] = useState<string[]>(["System initialized...", "Booting Matrix interface..."]);
15
+ const [showTerminal, setShowTerminal] = useState(true);
16
+ const [density, setDensity] = useState(12);
17
+ const [isMirrored, setIsMirrored] = useState(false); // Default false
18
+
19
+ // Status Indicators
20
+ const [aiConnected, setAiConnected] = useState(false);
21
+ const [cameraStatus, setCameraStatus] = useState<'PENDING' | 'ACTIVE' | 'ERROR' | 'DENIED'>('PENDING');
22
+
23
+ const initializedRef = useRef(false);
24
+
25
+ // 1. Deployment Self-Check & AI Initialization
26
+ useEffect(() => {
27
+ // HTTPS Check
28
+ if (window.location.protocol !== 'https:' && window.location.hostname !== 'localhost') {
29
+ const msg = "Security Warning: Camera access requires a secure HTTPS connection.";
30
+ console.warn(msg);
31
+ setTerminalLogs(prev => [...prev, "CRITICAL: INSECURE CONNECTION (HTTP).", "Camera access may be blocked."]);
32
+ }
33
+
34
+ // AI Configuration Check
35
+ // We check this but do NOT block camera initialization
36
+ const isAIReady = checkAIConnection();
37
+ setAiConnected(isAIReady);
38
+ if (isAIReady) {
39
+ setTerminalLogs(prev => [...prev, "Neural Network interface connected.", "Uplink established successfully."]);
40
+ } else {
41
+ setTerminalLogs(prev => [...prev, "WARN: API_KEY not found.", "Running in offline perception mode."]);
42
+ }
43
+ }, []);
44
+
45
+ // 2. Camera Initialization Logic
46
+ const initializeCamera = async () => {
47
+ setCameraStatus('PENDING');
48
+ setAppState(AppState.IDLE);
49
+
50
+ // Browser Capability Check
51
+ if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
52
+ setTerminalLogs(prev => [...prev, "CRITICAL ERROR: Camera API unavailable."]);
53
+ setAppState(AppState.ERROR);
54
+ setCameraStatus('ERROR');
55
+ return;
56
+ }
57
+
58
+ try {
59
+ setTerminalLogs(prev => [...prev, "Initializing visual sensors..."]);
60
+
61
+ // Request Permission - Explicitly asking for 'user' (Front Camera) as requested
62
+ const initialStream = await navigator.mediaDevices.getUserMedia({
63
+ video: {
64
+ facingMode: 'user'
65
+ }
66
+ });
67
+
68
+ // Enumerate Devices to find others if needed
69
+ const allDevices = await navigator.mediaDevices.enumerateDevices();
70
+ const videoDevices = allDevices
71
+ .filter(d => d.kind === 'videoinput')
72
+ .map(d => ({
73
+ deviceId: d.deviceId,
74
+ label: d.label || `Device ${d.deviceId.slice(0, 5)}...`
75
+ }));
76
+
77
+ // Stop initial stream to switch to the tracked one
78
+ initialStream.getTracks().forEach(track => track.stop());
79
+
80
+ setDevices(videoDevices);
81
+
82
+ if (videoDevices.length > 0) {
83
+ setTerminalLogs(prev => [...prev, "Visual sensors detected.", `${videoDevices.length} devices online.`]);
84
+
85
+ // Use the first available device, which usually matches the 'user' request if valid
86
+ const targetDeviceId = videoDevices[0].deviceId;
87
+ setCurrentDeviceId(targetDeviceId);
88
+ setCameraStatus('ACTIVE');
89
+ } else {
90
+ setTerminalLogs(prev => [...prev, "ERROR: No visual sensors found."]);
91
+ setAppState(AppState.ERROR);
92
+ setCameraStatus('ERROR');
93
+ }
94
+ } catch (err: any) {
95
+ console.error("Camera Init Error:", err);
96
+
97
+ let errorMsg = "ERROR: Sensor access failed.";
98
+ let status: 'ERROR' | 'DENIED' = 'ERROR';
99
+
100
+ if (err.name === 'NotAllowedError' || err.name === 'PermissionDeniedError') {
101
+ // Specific user request for this error message
102
+ errorMsg = "Matrix 提示:请允许摄像头访问以接入母体";
103
+ status = 'DENIED';
104
+ // Alert for mobile users who might miss the terminal log
105
+ alert(errorMsg);
106
+ } else if (err.name === 'NotFoundError') {
107
+ errorMsg = "ERROR: Visual input device not found.";
108
+ } else if (err.name === 'NotReadableError') {
109
+ errorMsg = "ERROR: Visual input occupied by another process.";
110
+ }
111
+
112
+ setTerminalLogs(prev => [...prev, errorMsg]);
113
+ setAppState(AppState.ERROR);
114
+ setCameraStatus(status);
115
+ }
116
+ };
117
+
118
+ // Run init on mount - Independent of AI check
119
+ useEffect(() => {
120
+ if (initializedRef.current) return;
121
+ initializedRef.current = true;
122
+ initializeCamera();
123
+ }, []);
124
+
125
+ // 3. Stream Handling
126
+ useEffect(() => {
127
+ if (!currentDeviceId) return;
128
+
129
+ const startStream = async () => {
130
+ if (stream) {
131
+ stream.getTracks().forEach(track => track.stop());
132
+ }
133
+
134
+ try {
135
+ const constraints = {
136
+ video: {
137
+ deviceId: { exact: currentDeviceId },
138
+ width: { ideal: 1280 },
139
+ height: { ideal: 720 },
140
+ frameRate: { ideal: 30 }
141
+ }
142
+ };
143
+
144
+ const newStream = await navigator.mediaDevices.getUserMedia(constraints);
145
+
146
+ setStream(newStream);
147
+ setAppState(AppState.STREAMING);
148
+ setCameraStatus('ACTIVE');
149
+ setTerminalLogs(prev => [...prev, "Visual feed established."]);
150
+ } catch (err: any) {
151
+ console.warn("Stream connection failed, retrying loose...", err);
152
+ // Fallback
153
+ try {
154
+ const looseStream = await navigator.mediaDevices.getUserMedia({
155
+ video: { deviceId: currentDeviceId }
156
+ });
157
+ setStream(looseStream);
158
+ setAppState(AppState.STREAMING);
159
+ setCameraStatus('ACTIVE');
160
+ } catch (retryErr) {
161
+ setAppState(AppState.ERROR);
162
+ setCameraStatus('ERROR');
163
+ setTerminalLogs(prev => [...prev, "CRITICAL: Signal lost."]);
164
+ }
165
+ }
166
+ };
167
+
168
+ startStream();
169
+ return () => {};
170
+ // eslint-disable-next-line react-hooks/exhaustive-deps
171
+ }, [currentDeviceId]);
172
+
173
+ const handleSwitchCamera = () => {
174
+ if (devices.length <= 1) return;
175
+ const currentIndex = devices.findIndex(d => d.deviceId === currentDeviceId);
176
+ const nextIndex = (currentIndex + 1) % devices.length;
177
+ if (devices[nextIndex]) {
178
+ setTerminalLogs(prev => [...prev, `Switching to sensor ${nextIndex + 1}...`]);
179
+ setCurrentDeviceId(devices[nextIndex].deviceId);
180
+ }
181
+ };
182
+
183
+ const handleCapture = () => {
184
+ if (!aiConnected) {
185
+ setTerminalLogs(prev => [...prev, "CMD ERROR: AI Config Missing.", "Please check API_KEY."]);
186
+ return;
187
+ }
188
+ setCaptureTrigger(prev => prev + 1);
189
+ setAppState(AppState.ANALYZING);
190
+ setShowTerminal(true);
191
+ setTerminalLogs(prev => [...prev, "Capturing frame...", "Uploading to Construct..."]);
192
+ };
193
+
194
+ const retryConnection = () => {
195
+ setTerminalLogs(prev => [...prev, "Re-initializing sensor subsystem..."]);
196
+ initializeCamera();
197
+ };
198
+
199
+ const onFrameCaptured = async (dataUrl: string) => {
200
+ try {
201
+ const result = await decodeMatrixImage(dataUrl);
202
+ if (result === "CONFIG_MISSING") {
203
+ setTerminalLogs(prev => [...prev, ">> ERROR: API_KEY NOT CONFIGURED."]);
204
+ } else {
205
+ setTerminalLogs(prev => [...prev, `>> ANALYSIS COMPLETE:`, result]);
206
+ }
207
+ } catch (e) {
208
+ setTerminalLogs(prev => [...prev, ">> ANALYSIS FAILED: Signal corrupted."]);
209
+ } finally {
210
+ setAppState(AppState.STREAMING);
211
+ }
212
+ };
213
+
214
+ const toggleDensity = () => {
215
+ setDensity(prev => prev === 12 ? 8 : (prev === 8 ? 16 : 12));
216
+ setTerminalLogs(prev => [...prev, `Grid density adjusted.`]);
217
+ };
218
+
219
+ const toggleMirror = () => {
220
+ setIsMirrored(prev => !prev);
221
+ setTerminalLogs(prev => [...prev, `Mirror mode: ${!isMirrored}`]);
222
+ };
223
+
224
+ return (
225
+ <div className="relative w-screen h-screen bg-black text-green-500 overflow-hidden flex flex-col">
226
+ {/* Main Viewport */}
227
+ <div className="flex-1 relative z-0">
228
+ {appState === AppState.ERROR || cameraStatus === 'ERROR' || cameraStatus === 'DENIED' ? (
229
+ <div className="flex flex-col items-center justify-center h-full space-y-6 px-4 text-center z-20 relative bg-black/80 backdrop-blur-sm">
230
+ <AlertTriangle size={64} className="animate-pulse text-red-500" />
231
+ <div className="space-y-2">
232
+ <p className="text-xl font-mono text-red-500 font-bold">SIGNAL LOST / ACCESS DENIED</p>
233
+ <p className="text-xs opacity-70 max-w-md font-mono mx-auto">
234
+ {cameraStatus === 'DENIED'
235
+ ? "Matrix 提示:请允许摄像头访问以接入母体"
236
+ : "Unable to access video device. Check connection and HTTPS."
237
+ }
238
+ </p>
239
+ </div>
240
+
241
+ <div className="flex gap-4">
242
+ <button
243
+ onClick={retryConnection}
244
+ className="px-6 py-2 border border-green-700 bg-green-900/20 text-green-400 rounded hover:bg-green-900/50 text-sm font-mono flex items-center gap-2"
245
+ >
246
+ <Power size={14} /> RECONNECT SENSORS
247
+ </button>
248
+
249
+ <button
250
+ onClick={() => window.location.reload()}
251
+ className="px-6 py-2 border border-red-900 bg-red-900/10 text-red-500 rounded hover:bg-red-900/30 text-sm font-mono"
252
+ >
253
+ SYSTEM REBOOT
254
+ </button>
255
+ </div>
256
+ </div>
257
+ ) : (
258
+ <MatrixCanvas
259
+ stream={stream}
260
+ isActive={appState === AppState.STREAMING || appState === AppState.ANALYZING}
261
+ onFrameCapture={onFrameCaptured}
262
+ captureTrigger={captureTrigger}
263
+ density={density}
264
+ isMirrored={isMirrored}
265
+ />
266
+ )}
267
+ </div>
268
+
269
+ {/* Overlay UI */}
270
+ <div className="absolute inset-0 z-10 pointer-events-none flex flex-col justify-between p-4 sm:p-6">
271
+ {/* Header */}
272
+ <div className="flex flex-col gap-2 pointer-events-auto">
273
+ <div className="flex justify-between items-start">
274
+ <div className="flex flex-col">
275
+ <h1 className="text-2xl sm:text-4xl font-bold tracking-tighter shadow-green-glow font-mono">MATRIX VISION</h1>
276
+ <div className="flex items-center gap-3 text-[10px] sm:text-xs font-mono mt-1">
277
+ <span className={`flex items-center gap-1 ${cameraStatus === 'ACTIVE' ? 'text-green-500' : 'text-red-500'}`}>
278
+ {cameraStatus === 'ACTIVE' ? <ShieldCheck size={12} /> : <ShieldAlert size={12} />}
279
+ CAM: {cameraStatus}
280
+ </span>
281
+ <span className="text-green-900">|</span>
282
+ <span className={`flex items-center gap-1 ${aiConnected ? 'text-green-500' : 'text-yellow-600'}`}>
283
+ {aiConnected ? <Wifi size={12} /> : <WifiOff size={12} />}
284
+ AI: {aiConnected ? 'ONLINE' : 'CONFIG WAIT'}
285
+ </span>
286
+ </div>
287
+ </div>
288
+
289
+ <div className="flex gap-2">
290
+ <button
291
+ onClick={() => setShowTerminal(!showTerminal)}
292
+ className={`p-2 border border-green-800 bg-black/50 backdrop-blur-md rounded hover:bg-green-900/30 transition-colors ${showTerminal ? 'text-green-400' : 'text-green-800'}`}
293
+ title="Toggle Terminal"
294
+ >
295
+ <Monitor size={20} />
296
+ </button>
297
+ </div>
298
+ </div>
299
+ </div>
300
+
301
+ {/* Center Crosshair */}
302
+ <div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-32 h-32 border border-green-500/20 rounded-full flex items-center justify-center pointer-events-none">
303
+ <div className="w-2 h-2 bg-green-500/50 rounded-full"></div>
304
+ <div className="absolute top-0 w-px h-4 bg-green-500/50"></div>
305
+ <div className="absolute bottom-0 w-px h-4 bg-green-500/50"></div>
306
+ <div className="absolute left-0 h-px w-4 bg-green-500/50"></div>
307
+ <div className="absolute right-0 h-px w-4 bg-green-500/50"></div>
308
+ </div>
309
+
310
+ {/* Footer Controls */}
311
+ <div className="flex flex-col gap-4 pointer-events-auto">
312
+ {/* Action Bar */}
313
+ <div className="flex items-center justify-center gap-6 sm:gap-12 pb-4 sm:pb-8">
314
+ <button
315
+ onClick={toggleDensity}
316
+ className="flex flex-col items-center gap-1 group"
317
+ >
318
+ <div className="w-12 h-12 rounded-full border border-green-600 bg-black/80 flex items-center justify-center group-active:scale-95 transition-all shadow-[0_0_15px_rgba(0,255,0,0.2)]">
319
+ <Eye size={20} className="group-hover:text-white transition-colors" />
320
+ </div>
321
+ <span className="text-[10px] uppercase tracking-widest opacity-70 font-mono">Grid</span>
322
+ </button>
323
+
324
+ <button
325
+ onClick={toggleMirror}
326
+ className="flex flex-col items-center gap-1 group"
327
+ >
328
+ <div className={`w-12 h-12 rounded-full border border-green-600 bg-black/80 flex items-center justify-center group-active:scale-95 transition-all shadow-[0_0_15px_rgba(0,255,0,0.2)] ${isMirrored ? 'bg-green-900/40 text-white' : ''}`}>
329
+ <FlipHorizontal size={20} className="group-hover:text-white transition-colors" />
330
+ </div>
331
+ <span className="text-[10px] uppercase tracking-widest opacity-70 font-mono">Flip</span>
332
+ </button>
333
+
334
+ <button
335
+ onClick={handleCapture}
336
+ disabled={appState === AppState.ANALYZING || appState === AppState.ERROR || !aiConnected}
337
+ className={`flex flex-col items-center gap-2 group ${!aiConnected ? 'opacity-50 cursor-not-allowed' : ''}`}
338
+ >
339
+ <div className={`w-20 h-20 rounded-full border-2 ${aiConnected ? 'border-green-400 bg-green-900/20' : 'border-yellow-900 bg-black'} flex items-center justify-center group-active:scale-90 transition-all shadow-[0_0_30px_rgba(0,255,0,0.4)] relative overflow-hidden`}>
340
+ {aiConnected && <div className="absolute inset-0 bg-green-500/10 animate-pulse"></div>}
341
+ <Zap size={32} className={`${aiConnected ? 'text-green-400' : 'text-green-900'} ${appState === AppState.ANALYZING ? 'animate-spin' : ''}`} />
342
+ </div>
343
+ <span className="text-xs font-bold uppercase tracking-widest text-green-400 shadow-black drop-shadow-md font-mono">
344
+ {appState === AppState.ANALYZING ? 'DECODING' : 'DECIPHER'}
345
+ </span>
346
+ </button>
347
+
348
+ <button
349
+ onClick={handleSwitchCamera}
350
+ className="flex flex-col items-center gap-1 group"
351
+ >
352
+ <div className="w-12 h-12 rounded-full border border-green-600 bg-black/80 flex items-center justify-center group-active:scale-95 transition-all shadow-[0_0_15px_rgba(0,255,0,0.2)]">
353
+ <RefreshCw size={20} className="group-hover:text-white transition-colors" />
354
+ </div>
355
+ <span className="text-[10px] uppercase tracking-widest opacity-70 font-mono">Cam</span>
356
+ </button>
357
+ </div>
358
+ </div>
359
+ </div>
360
+
361
+ {showTerminal && (
362
+ <TerminalOutput
363
+ logs={terminalLogs}
364
+ isAnalyzing={appState === AppState.ANALYZING}
365
+ onClose={() => setShowTerminal(false)}
366
+ />
367
+ )}
368
+ </div>
369
+ );
370
+ };
371
+
372
+ export default App;
matrix-vision_0/README.md ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <div align="center">
2
+ <img width="1200" height="475" alt="GHBanner" src="https://github.com/user-attachments/assets/0aa67016-6eaf-458a-adb2-6e31a0763ed6" />
3
+ </div>
4
+
5
+ # Run and deploy your AI Studio app
6
+
7
+ This contains everything you need to run your app locally.
8
+
9
+ View your app in AI Studio: https://ai.studio/apps/drive/1otUwkXlSal39CBn26Q0ZcpKXEnvuaAEu
10
+
11
+ ## Run Locally
12
+
13
+ **Prerequisites:** Node.js
14
+
15
+
16
+ 1. Install dependencies:
17
+ `npm install`
18
+ 2. Set the `GEMINI_API_KEY` in [.env.local](.env.local) to your Gemini API key
19
+ 3. Run the app:
20
+ `npm run dev`
matrix-vision_0/components/MatrixCanvas.tsx ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React, { useRef, useEffect, useCallback } from 'react';
2
+
3
+ interface MatrixCanvasProps {
4
+ stream: MediaStream | null;
5
+ isActive: boolean;
6
+ onFrameCapture?: (dataUrl: string) => void;
7
+ captureTrigger?: number;
8
+ density?: number;
9
+ isMirrored?: boolean;
10
+ }
11
+
12
+ // 5-Tier Bucket System for better depth perception
13
+ const BUCKETS = {
14
+ GLOW: { color: '#EEFFEE', alpha: 1.0, threshold: 240, glow: 15, glowColor: '#00FF00' }, // Highlights
15
+ BRIGHT: { color: '#00FF41', alpha: 0.95, threshold: 160, glow: 0, glowColor: '' }, // Subject
16
+ MID: { color: '#00D200', alpha: 0.75, threshold: 90, glow: 0, glowColor: '' }, // Midtones
17
+ LOW: { color: '#007500', alpha: 0.40, threshold: 40, glow: 0, glowColor: '' }, // Shadows
18
+ DIM: { color: '#003300', alpha: 0.15, threshold: 10, glow: 0, glowColor: '' } // Background
19
+ };
20
+
21
+ const MatrixCanvas: React.FC<MatrixCanvasProps> = ({
22
+ stream,
23
+ isActive,
24
+ onFrameCapture,
25
+ captureTrigger,
26
+ density = 12,
27
+ isMirrored = false
28
+ }) => {
29
+ const videoRef = useRef<HTMLVideoElement>(null);
30
+ const canvasRef = useRef<HTMLCanvasElement>(null);
31
+ const smallCanvasRef = useRef<HTMLCanvasElement | null>(null);
32
+
33
+ const animationRef = useRef<number>(0);
34
+ const lastDrawTimeRef = useRef<number>(0);
35
+
36
+ const chars = "ハミヒーウシナモニサワツオリアホテマケメエカキムユラセネスタヌヘ012345789:・.=\"*+-<>¦|";
37
+ const TARGET_FPS = 30;
38
+ const FRAME_INTERVAL = 1000 / TARGET_FPS;
39
+
40
+ const processFrame = useCallback((timestamp: number) => {
41
+ const video = videoRef.current;
42
+ const canvas = canvasRef.current;
43
+
44
+ if (!video || !canvas || !isActive) return;
45
+
46
+ const elapsed = timestamp - lastDrawTimeRef.current;
47
+ if (elapsed < FRAME_INTERVAL) {
48
+ animationRef.current = requestAnimationFrame(processFrame);
49
+ return;
50
+ }
51
+ lastDrawTimeRef.current = timestamp - (elapsed % FRAME_INTERVAL);
52
+
53
+ const ctx = canvas.getContext('2d', { alpha: false });
54
+ if (!ctx) return;
55
+
56
+ if (video.readyState === video.HAVE_ENOUGH_DATA) {
57
+ const rect = canvas.getBoundingClientRect();
58
+ // Cap DPR at 2.0 to prevent performance issues on high-density mobile screens (iPhone, etc.)
59
+ const dpr = Math.min(window.devicePixelRatio || 1, 2);
60
+
61
+ const displayWidth = Math.floor(rect.width);
62
+ const displayHeight = Math.floor(rect.height);
63
+
64
+ if (canvas.width !== displayWidth * dpr || canvas.height !== displayHeight * dpr) {
65
+ canvas.width = displayWidth * dpr;
66
+ canvas.height = displayHeight * dpr;
67
+ ctx.scale(dpr, dpr);
68
+ }
69
+
70
+ // -- OFFSCREEN PROCESSING --
71
+ const fontSize = density;
72
+ const cols = Math.floor(displayWidth / fontSize);
73
+ const rows = Math.floor(displayHeight / fontSize);
74
+
75
+ if (!smallCanvasRef.current) {
76
+ smallCanvasRef.current = document.createElement('canvas');
77
+ }
78
+ const smallCanvas = smallCanvasRef.current;
79
+
80
+ if (smallCanvas.width !== cols || smallCanvas.height !== rows) {
81
+ smallCanvas.width = cols;
82
+ smallCanvas.height = rows;
83
+ }
84
+
85
+ const smallCtx = smallCanvas.getContext('2d', { willReadFrequently: true });
86
+ if (!smallCtx) return;
87
+
88
+ smallCtx.drawImage(video, 0, 0, cols, rows);
89
+
90
+ const frameData = smallCtx.getImageData(0, 0, cols, rows);
91
+ const pixels = frameData.data;
92
+
93
+ // -- RENDERING --
94
+ ctx.fillStyle = '#000000';
95
+ ctx.fillRect(0, 0, displayWidth, displayHeight);
96
+
97
+ ctx.font = `${fontSize}px 'Share Tech Mono', monospace`;
98
+ ctx.textBaseline = 'top';
99
+
100
+ const batches: Record<keyof typeof BUCKETS, {x: number, y: number, char: string}[]> = {
101
+ GLOW: [], BRIGHT: [], MID: [], LOW: [], DIM: []
102
+ };
103
+
104
+ for (let y = 0; y < rows; y++) {
105
+ for (let x = 0; x < cols; x++) {
106
+ const index = (y * cols + x) * 4;
107
+ const r = pixels[index];
108
+ const g = pixels[index + 1];
109
+ const b = pixels[index + 2];
110
+
111
+ let luma = 0.299 * r + 0.587 * g + 0.114 * b;
112
+
113
+ const normalized = luma / 255;
114
+ const contrast = (normalized * normalized) * 255 * 1.2;
115
+
116
+ if (contrast < BUCKETS.DIM.threshold) continue;
117
+
118
+ const char = chars[Math.floor(Math.random() * chars.length)];
119
+
120
+ const drawX = isMirrored ? (cols - 1 - x) * fontSize : x * fontSize;
121
+ const drawY = y * fontSize;
122
+
123
+ if (contrast > BUCKETS.GLOW.threshold) batches.GLOW.push({ x: drawX, y: drawY, char });
124
+ else if (contrast > BUCKETS.BRIGHT.threshold) batches.BRIGHT.push({ x: drawX, y: drawY, char });
125
+ else if (contrast > BUCKETS.MID.threshold) batches.MID.push({ x: drawX, y: drawY, char });
126
+ else if (contrast > BUCKETS.LOW.threshold) batches.LOW.push({ x: drawX, y: drawY, char });
127
+ else batches.DIM.push({ x: drawX, y: drawY, char });
128
+ }
129
+ }
130
+
131
+ if (batches.DIM.length) {
132
+ ctx.fillStyle = BUCKETS.DIM.color;
133
+ ctx.globalAlpha = BUCKETS.DIM.alpha;
134
+ for (const p of batches.DIM) ctx.fillText(p.char, p.x, p.y);
135
+ }
136
+ if (batches.LOW.length) {
137
+ ctx.fillStyle = BUCKETS.LOW.color;
138
+ ctx.globalAlpha = BUCKETS.LOW.alpha;
139
+ for (const p of batches.LOW) ctx.fillText(p.char, p.x, p.y);
140
+ }
141
+ if (batches.MID.length) {
142
+ ctx.fillStyle = BUCKETS.MID.color;
143
+ ctx.globalAlpha = BUCKETS.MID.alpha;
144
+ for (const p of batches.MID) ctx.fillText(p.char, p.x, p.y);
145
+ }
146
+ if (batches.BRIGHT.length) {
147
+ ctx.fillStyle = BUCKETS.BRIGHT.color;
148
+ ctx.globalAlpha = BUCKETS.BRIGHT.alpha;
149
+ for (const p of batches.BRIGHT) ctx.fillText(p.char, p.x, p.y);
150
+ }
151
+ if (batches.GLOW.length) {
152
+ ctx.fillStyle = BUCKETS.GLOW.color;
153
+ ctx.globalAlpha = BUCKETS.GLOW.alpha;
154
+ ctx.shadowColor = BUCKETS.GLOW.glowColor;
155
+ ctx.shadowBlur = BUCKETS.GLOW.glow;
156
+ for (const p of batches.GLOW) ctx.fillText(p.char, p.x, p.y);
157
+ ctx.shadowBlur = 0;
158
+ }
159
+ ctx.globalAlpha = 1.0;
160
+ }
161
+
162
+ animationRef.current = requestAnimationFrame(processFrame);
163
+ }, [isActive, density, chars, FRAME_INTERVAL, isMirrored]);
164
+
165
+ useEffect(() => {
166
+ if (captureTrigger && captureTrigger > 0 && canvasRef.current && onFrameCapture) {
167
+ const dataUrl = canvasRef.current.toDataURL('image/jpeg', 0.9);
168
+ onFrameCapture(dataUrl);
169
+ }
170
+ }, [captureTrigger, onFrameCapture]);
171
+
172
+ useEffect(() => {
173
+ if (videoRef.current && stream) {
174
+ videoRef.current.srcObject = stream;
175
+ videoRef.current.play().catch(e => console.error("Video play error:", e));
176
+ }
177
+ }, [stream]);
178
+
179
+ useEffect(() => {
180
+ if (isActive) {
181
+ animationRef.current = requestAnimationFrame(processFrame);
182
+ }
183
+ return () => {
184
+ if (animationRef.current) cancelAnimationFrame(animationRef.current);
185
+ };
186
+ }, [isActive, processFrame]);
187
+
188
+ return (
189
+ <div className="relative w-full h-full bg-black overflow-hidden flex items-center justify-center">
190
+ <video
191
+ ref={videoRef}
192
+ playsInline
193
+ muted
194
+ autoPlay
195
+ className="absolute opacity-0 pointer-events-none"
196
+ style={{ width: 1, height: 1 }}
197
+ />
198
+ <canvas
199
+ ref={canvasRef}
200
+ className="w-full h-full object-cover"
201
+ />
202
+ <div className="absolute inset-0 pointer-events-none shadow-[inset_0_0_100px_rgba(0,0,0,0.9)]"></div>
203
+ </div>
204
+ );
205
+ };
206
+
207
+ export default MatrixCanvas;
matrix-vision_0/components/TerminalOutput.tsx ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React, { useEffect, useRef } from 'react';
2
+ import { Terminal } from 'lucide-react';
3
+
4
+ interface TerminalOutputProps {
5
+ logs: string[];
6
+ isAnalyzing: boolean;
7
+ onClose: () => void;
8
+ }
9
+
10
+ const TerminalOutput: React.FC<TerminalOutputProps> = ({ logs, isAnalyzing, onClose }) => {
11
+ const bottomRef = useRef<HTMLDivElement>(null);
12
+
13
+ useEffect(() => {
14
+ bottomRef.current?.scrollIntoView({ behavior: 'smooth' });
15
+ }, [logs]);
16
+
17
+ return (
18
+ <div className="absolute bottom-0 left-0 right-0 bg-black/90 border-t-2 border-green-500 backdrop-blur-sm max-h-[40vh] flex flex-col z-50 transition-all duration-300">
19
+ <div className="flex items-center justify-between px-4 py-2 bg-green-900/20 border-b border-green-500/30">
20
+ <div className="flex items-center gap-2 text-green-500">
21
+ <Terminal size={16} />
22
+ <span className="text-xs font-bold tracking-wider">TERMINAL_OUTPUT // SYSTEM.LOG</span>
23
+ </div>
24
+ <button
25
+ onClick={onClose}
26
+ className="text-green-500 hover:text-white hover:bg-green-900/50 px-2 py-1 rounded text-xs uppercase"
27
+ >
28
+ [Close]
29
+ </button>
30
+ </div>
31
+
32
+ <div className="p-4 overflow-y-auto font-mono text-sm space-y-2 flex-1">
33
+ {logs.map((log, index) => (
34
+ <div key={index} className="break-words">
35
+ <span className="text-green-700 mr-2">[{new Date().toLocaleTimeString()}]</span>
36
+ <span className="text-green-400 typing-effect">{log}</span>
37
+ </div>
38
+ ))}
39
+ {isAnalyzing && (
40
+ <div className="flex items-center gap-2 text-green-500 animate-pulse">
41
+ <span className="w-2 h-4 bg-green-500 block"></span>
42
+ <span>DECODING DATA STREAM...</span>
43
+ </div>
44
+ )}
45
+ <div ref={bottomRef} />
46
+ </div>
47
+ </div>
48
+ );
49
+ };
50
+
51
+ export default TerminalOutput;
matrix-vision_0/gemini.ts ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { GoogleGenAI } from "@google/genai";
2
+
3
+ const getApiKey = (): string | undefined => {
4
+ const key = process.env.API_KEY;
5
+
6
+ if (!key) {
7
+ console.warn("Matrix Vision System Warning: API_KEY is missing. AI features will be disabled.");
8
+ return undefined;
9
+ }
10
+ return key;
11
+ };
12
+
13
+ export const checkAIConnection = (): boolean => {
14
+ return !!process.env.API_KEY;
15
+ };
16
+
17
+ export const decodeMatrixImage = async (base64Image: string): Promise<string> => {
18
+ const apiKey = getApiKey();
19
+
20
+ if (!apiKey) {
21
+ // Return a specific string that the UI can detect to show a friendly configuration prompt
22
+ return "CONFIG_MISSING";
23
+ }
24
+
25
+ try {
26
+ const ai = new GoogleGenAI({ apiKey: process.env.API_KEY });
27
+
28
+ // Clean base64 string if it contains metadata header
29
+ const cleanBase64 = base64Image.replace(/^data:image\/(png|jpeg|jpg);base64,/, '');
30
+
31
+ const response = await ai.models.generateContent({
32
+ model: 'gemini-3-flash-preview',
33
+ contents: {
34
+ parts: [
35
+ {
36
+ inlineData: {
37
+ data: cleanBase64,
38
+ mimeType: 'image/jpeg',
39
+ },
40
+ },
41
+ {
42
+ text: "You are an operator in the Matrix. I am sending you a raw data feed (a visual represented by green code characters). Decipher the visual pattern and tell me exactly what objects or scene is hidden in this code. Be brief and use a 'hacker' persona tone."
43
+ },
44
+ ],
45
+ },
46
+ config: {
47
+ systemInstruction: "You are Tank, the operator from the Matrix. You analyze raw code streams.",
48
+ temperature: 0.7,
49
+ }
50
+ });
51
+
52
+ return response.text || "Connection interrupted. No data received.";
53
+ } catch (error) {
54
+ console.error("Gemini Analysis Error:", error);
55
+ return "Error decoding stream. The signal is too weak.";
56
+ }
57
+ };
matrix-vision_0/index.html ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <link rel="icon" type="image/svg+xml" href="./vite.svg" />
6
+ <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
7
+ <meta name="theme-color" content="#000000" />
8
+ <meta name="apple-mobile-web-app-capable" content="yes">
9
+ <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
10
+ <title>Matrix Vision</title>
11
+ <script src="https://cdn.tailwindcss.com"></script>
12
+ <link rel="preconnect" href="https://fonts.googleapis.com">
13
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
14
+ <link href="https://fonts.googleapis.com/css2?family=Share+Tech+Mono&display=swap" rel="stylesheet">
15
+ <style>
16
+ body {
17
+ background-color: #000;
18
+ font-family: 'Share Tech Mono', monospace;
19
+ overflow: hidden; /* Prevent scrolling for app-like feel */
20
+ }
21
+ /* Custom scrollbar for matrix logs */
22
+ ::-webkit-scrollbar {
23
+ width: 6px;
24
+ }
25
+ ::-webkit-scrollbar-track {
26
+ background: #001100;
27
+ }
28
+ ::-webkit-scrollbar-thumb {
29
+ background: #003300;
30
+ }
31
+ ::-webkit-scrollbar-thumb:hover {
32
+ background: #005500;
33
+ }
34
+ </style>
35
+ <script type="importmap">
36
+ {
37
+ "imports": {
38
+ "react-dom/": "https://esm.sh/react-dom@^19.2.4/",
39
+ "@google/genai": "https://esm.sh/@google/genai@^1.40.0",
40
+ "lucide-react": "https://esm.sh/lucide-react@^0.563.0",
41
+ "react/": "https://esm.sh/react@^19.2.4/",
42
+ "react": "https://esm.sh/react@^19.2.4"
43
+ }
44
+ }
45
+ </script>
46
+ <link rel="stylesheet" href="/index.css">
47
+ </head>
48
+ <body>
49
+ <div id="root"></div>
50
+ <script type="module" src="/index.tsx"></script>
51
+ </body>
52
+ </html>
matrix-vision_0/index.tsx ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React from 'react';
2
+ import ReactDOM from 'react-dom/client';
3
+ import App from './App';
4
+
5
+ const rootElement = document.getElementById('root');
6
+ if (!rootElement) {
7
+ throw new Error("Could not find root element to mount to");
8
+ }
9
+
10
+ const root = ReactDOM.createRoot(rootElement);
11
+ root.render(
12
+ <React.StrictMode>
13
+ <App />
14
+ </React.StrictMode>
15
+ );
matrix-vision_0/metadata.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "Matrix Vision",
3
+ "description": "A real-time camera filter that transforms your world into the Matrix digital rain code.",
4
+ "requestFramePermissions": [
5
+ "camera"
6
+ ]
7
+ }
matrix-vision_0/package.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "matrix-vision",
3
+ "private": true,
4
+ "version": "0.0.0",
5
+ "type": "module",
6
+ "scripts": {
7
+ "dev": "vite",
8
+ "build": "vite build",
9
+ "preview": "vite preview"
10
+ },
11
+ "dependencies": {
12
+ "react-dom": "^19.2.4",
13
+ "@google/genai": "^1.40.0",
14
+ "lucide-react": "^0.563.0",
15
+ "react": "^19.2.4"
16
+ },
17
+ "devDependencies": {
18
+ "@types/node": "^22.14.0",
19
+ "@vitejs/plugin-react": "^5.0.0",
20
+ "typescript": "~5.8.2",
21
+ "vite": "^6.2.0"
22
+ }
23
+ }
matrix-vision_0/tsconfig.json ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "experimentalDecorators": true,
5
+ "useDefineForClassFields": false,
6
+ "module": "ESNext",
7
+ "lib": [
8
+ "ES2022",
9
+ "DOM",
10
+ "DOM.Iterable"
11
+ ],
12
+ "skipLibCheck": true,
13
+ "types": [
14
+ "node"
15
+ ],
16
+ "moduleResolution": "bundler",
17
+ "isolatedModules": true,
18
+ "moduleDetection": "force",
19
+ "allowJs": true,
20
+ "jsx": "react-jsx",
21
+ "paths": {
22
+ "@/*": [
23
+ "./*"
24
+ ]
25
+ },
26
+ "allowImportingTsExtensions": true,
27
+ "noEmit": true
28
+ }
29
+ }
matrix-vision_0/types.ts ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export interface CameraDevice {
2
+ deviceId: string;
3
+ label: string;
4
+ }
5
+
6
+ export enum AppState {
7
+ IDLE = 'IDLE',
8
+ STREAMING = 'STREAMING',
9
+ ANALYZING = 'ANALYZING',
10
+ ERROR = 'ERROR'
11
+ }
12
+
13
+ export interface AnalysisResult {
14
+ text: string;
15
+ timestamp: number;
16
+ }
matrix-vision_0/vite.config.ts ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import path from 'path';
2
+ import { defineConfig, loadEnv } from 'vite';
3
+ import react from '@vitejs/plugin-react';
4
+
5
+ export default defineConfig(({ mode }) => {
6
+ const env = loadEnv(mode, '.', '');
7
+ return {
8
+ server: {
9
+ port: 3000,
10
+ host: '0.0.0.0',
11
+ },
12
+ plugins: [react()],
13
+ define: {
14
+ 'process.env.API_KEY': JSON.stringify(env.GEMINI_API_KEY),
15
+ 'process.env.GEMINI_API_KEY': JSON.stringify(env.GEMINI_API_KEY)
16
+ },
17
+ resolve: {
18
+ alias: {
19
+ '@': path.resolve(__dirname, '.'),
20
+ }
21
+ }
22
+ };
23
+ });