Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat(city): add immersive audio, enhanced postprocessing, and settings system
Adam Eivyad81363fb50b
diff --git a/.changelog/v0.12.x.md b/.changelog/v0.12.x.mdindex d116161f12..1a78774afa 100644--- a/.changelog/v0.12.x.md+++ b/.changelog/v0.12.x.md@@ -444,6 +444,43 @@ This release adds branch management and automated release workflow capabilities- **Negative example routing** ✅: Anti-pattern recording in task learning — every task completion now records a `routingAccuracy` cross-reference (taskType × modelTier) with success/failure counts. `suggestModelTier()` enhanced to avoid tiers with <40% success and prefer proven-successful tiers. New "Routing Accuracy" section in Learning tab shows misroutes, tier overview cards, and a full task-type × tier matrix table. New `GET /api/cos/learning/routing` endpoint. Reset also cleans up routing data.- **Deterministic workflow skills** ✅: Recurring autonomous jobs (daily briefing, git maintenance, brain processing, project review) converted from inline prompt strings to versioned skill templates in `data/prompts/skills/jobs/`. Each template defines structured sections (Steps, Expected Outputs, Success Criteria) that `generateTaskFromJob()` assembles into effective prompts. New API routes (`GET/PUT /api/prompts/skills/jobs/:name`, preview endpoint) and a "Job Skills" tab in the Prompt Manager UI for editing templates without touching code.+### CyberCity — Immersive Audio & Visual Overhaul+- **Procedural synthwave music**: Web Audio API synthesizer generating ambient cyberpunk music with bass drone, arpeggiated lead, detuned pad layer, LFO filter sweeps, reverb, and delay — chord progression (Am → Em → F → C) at 100BPM, all procedurally generated with zero audio files+- **Spatial sound effects**: 5 synthesized SFX types — building hover (sine sweep), building click (noise burst + ping), lightning thunder (distorted noise), shooting star whoosh (panned noise sweep), and data pulse chirp — all generated in real-time from Web Audio oscillators+- **Enhanced post-processing**: 3 new GPU shader passes on top of existing bloom — chromatic aberration (R/B channel offset at screen edges), animated film grain (noise overlay), and cinematic color grading (shadows → deep blue, midtones → cyan, highlights → warm white)+- **Reflective wet-street ground**: Dark metallic ground plane (metalness 0.9, roughness 0.15) beneath the grid for natural light reflections, doubled puddle count (20 → 40), rolling fog layer at street level with animated opacity+- **Settings system**: localStorage-persisted settings with quality presets (Low/Medium/High/Ultra) controlling DPR, bloom, chromatic aberration, film grain, color grading, particle density, and scanline overlay — all toggleable individually via HUD panel at `/city/settings`+- **Animated lighting**: Magenta and blue accent lights now slowly oscillate in intensity, plus a sweeping cyan searchlight that rotates around the city perimeter+- **Enhanced buildings**: Online buildings get reflective glass roof caps (MeshPhysicalMaterial), glow halo wireframes pulse on hover, buildings emit SFX on pointer interaction+- **FogExp2 depth**: Switched from linear fog to exponential fog for more natural depth falloff+- **Configurable particles**: Particle counts scale with the `particleDensity` setting (0.25x to 2x multiplier)+- **Scanline toggle**: CRT scanline overlay can be independently toggled while preserving vignette and edge glow effects++**New files**:+- `client/src/hooks/useCitySettings.js` — localStorage-persisted settings hook with quality presets+- `client/src/hooks/useCityAudio.js` — React lifecycle bridge for Web Audio engine+- `client/src/components/city/CitySettingsContext.jsx` — React context provider for settings+- `client/src/components/city/CitySettingsPanel.jsx` — HUD-style settings panel with toggles and sliders+- `client/src/components/city/audio/cityAudioEngine.js` — Singleton Web Audio API manager with master/music/sfx gain buses+- `client/src/components/city/audio/citySynthMusic.js` — Procedural synthwave generator (bass, arp, pad, reverb, delay)+- `client/src/components/city/audio/citySoundEffects.js` — 5 procedural SFX functions++**Modified files**:+- `client/src/pages/CyberCity.jsx` — Settings provider, audio hook, settings panel integration+- `client/src/App.jsx` — Added `/city/settings` route+- `client/src/components/city/CityScene.jsx` — FogExp2, DPR from settings, playSfx prop threading+- `client/src/components/city/CityEffects.jsx` — 3 new ShaderPass effects (chromatic aberration, film grain, color grading)+- `client/src/components/city/CityGround.jsx` — Reflective ground plane, more puddles, rolling fog+- `client/src/components/city/CityLights.jsx` — Animated lights, sweeping searchlight, removed duplicate fog+- `client/src/components/city/CityHud.jsx` — Settings gear icon button+- `client/src/components/city/Building.jsx` — Glass roof, glow halo, SFX on hover/click+- `client/src/components/city/CityWeather.jsx` — Lightning SFX trigger+- `client/src/components/city/CityShootingStars.jsx` — Star spawn SFX trigger+- `client/src/components/city/CityParticles.jsx` — Density multiplier from settings+- `client/src/components/city/CityScanlines.jsx` — Settings toggle+- `client/src/components/city/BuildingCluster.jsx` — playSfx prop threading+- `client/src/components/city/Borough.jsx` — playSfx prop threading+### CyberCity — Borough Layout Redesign- **Borough neighborhoods**: Each app is now its own borough — a main skyscraper surrounded by smaller process buildings in a ring, creating distinct neighborhoods with organic spacing- **Process buildings**: Lightweight neon-lit buildings representing each PM2 process an app runs, with status-colored wireframe edges (cyan=online, amber=stopped, indigo=not found), process name labels, blinking tip lights, and base glow circlesdiff --git a/client/src/App.jsx b/client/src/App.jsxindex 39b927c11b..8477c53f52 100644--- a/client/src/App.jsx+++ b/client/src/App.jsx@@ -64,6 +64,7 @@ export default function App() {<Route path="shell" element={<Shell />} /><Route path="browser" element={<BrowserPage />} /><Route path="city" element={<CyberCity />} />+ <Route path="city/settings" element={<CyberCity />} /><Route path="agents" element={<Agents />} /><Route path="agents/:agentId" element={<Agents />} /><Route path="agents/:agentId/:tab" element={<Agents />} />diff --git a/client/src/components/city/Borough.jsx b/client/src/components/city/Borough.jsxindex 7f59d4b971..e0fefb2826 100644--- a/client/src/components/city/Borough.jsx+++ b/client/src/components/city/Borough.jsx@@ -13,7 +13,7 @@ const hashString = (str) => {return Math.abs(hash);};-export default function Borough({ app, position, agentMap, onBuildingClick }) {+export default function Borough({ app, position, agentMap, onBuildingClick, playSfx }) {const agentData = agentMap.get(app.id);const agents = agentData?.agents || [];const height = getBuildingHeight(app);@@ -52,6 +52,7 @@ export default function Borough({ app, position, agentMap, onBuildingClick }) {position={position}agentCount={agents.length}onClick={() => onBuildingClick?.(app)}+ playSfx={playSfx}/>{/* Process buildings in ring around main building */}diff --git a/client/src/components/city/Building.jsx b/client/src/components/city/Building.jsxindex 5e61c04e09..faa81b3387 100644--- a/client/src/components/city/Building.jsx+++ b/client/src/components/city/Building.jsx@@ -267,9 +267,10 @@ function NeonEdgeStrip({ position, height, color, delay }) {);}-export default function Building({ app, position, agentCount, onClick }) {+export default function Building({ app, position, agentCount, onClick, playSfx }) {const meshRef = useRef();const glowRef = useRef();+ const haloRef = useRef();const [hovered, setHovered] = useState(false);const height = getBuildingHeight(app);@@ -312,6 +313,13 @@ export default function Building({ app, position, agentCount, onClick }) {if (glowRef.current) {glowRef.current.material.opacity = 0.25 + (isOnline ? Math.sin(t * 1.5) * 0.1 : 0) + (hovered ? 0.2 : 0);}++ // Glow halo wireframe pulse+ if (haloRef.current) {+ haloRef.current.material.opacity = hovered+ ? 0.15 + Math.sin(t * 8) * 0.1+ : 0.05 + Math.sin(t * 1.5 + seed) * 0.03;+ }});return (@@ -320,8 +328,8 @@ export default function Building({ app, position, agentCount, onClick }) {<meshref={meshRef}position={[0, height / 2, 0]}- onClick={onClick}- onPointerEnter={() => setHovered(true)}+ onClick={() => { playSfx?.('buildingClick'); onClick?.(); }}+ onPointerEnter={() => { setHovered(true); playSfx?.('buildingHover'); }}onPointerLeave={() => setHovered(false)}><boxGeometry args={[width, height, depth]} />@@ -344,16 +352,38 @@ export default function Building({ app, position, agentCount, onClick }) {/></lineSegments>- {/* Neon accent strip at building top */}+ {/* Reflective glass roof cap on online buildings */}<mesh position={[0, height + 0.02, 0]} rotation={[-Math.PI / 2, 0, 0]}><planeGeometry args={[width + 0.1, depth + 0.1]} />- <meshBasicMaterial- color={edgeColor}- transparent- opacity={app.archived ? 0.2 : 0.5}- />+ {isOnline ? (+ <meshPhysicalMaterial+ color={edgeColor}+ roughness={0.1}+ metalness={0.8}+ transparent+ opacity={0.7}+ />+ ) : (+ <meshBasicMaterial+ color={edgeColor}+ transparent+ opacity={app.archived ? 0.2 : 0.5}+ />+ )}</mesh>+ {/* Glow halo wireframe - slightly larger than building */}+ {!app.archived && (+ <lineSegments ref={haloRef} position={[0, height / 2, 0]}>+ <edgesGeometry args={[new THREE.BoxGeometry(width + 0.15, height + 0.15, depth + 0.15)]} />+ <lineBasicMaterial+ color={accentColor}+ transparent+ opacity={0.05}+ />+ </lineSegments>+ )}+{/* Vertical neon edge strips on corners */}{!app.archived && (<>diff --git a/client/src/components/city/BuildingCluster.jsx b/client/src/components/city/BuildingCluster.jsxindex 17135529c4..80dfbb64b5 100644--- a/client/src/components/city/BuildingCluster.jsx+++ b/client/src/components/city/BuildingCluster.jsx@@ -4,7 +4,7 @@ import { computeCityLayout } from './cityLayout';import { DISTRICT_PARAMS, PIXEL_FONT_URL } from './cityConstants';import Borough from './Borough';-export default function BuildingCluster({ apps, agentMap, onBuildingClick, onPositionsReady }) {+export default function BuildingCluster({ apps, agentMap, onBuildingClick, onPositionsReady, playSfx }) {const positions = useMemo(() => computeCityLayout(apps), [apps]);// Notify parent when positions change (for data streams, roads, traffic)@@ -35,6 +35,7 @@ export default function BuildingCluster({ apps, agentMap, onBuildingClick, onPosposition={pos}agentMap={agentMap}onBuildingClick={onBuildingClick}+ playSfx={playSfx}/>);})}diff --git a/client/src/components/city/CityEffects.jsx b/client/src/components/city/CityEffects.jsxindex 7ec3d7f30d..e07fa37a2e 100644--- a/client/src/components/city/CityEffects.jsx+++ b/client/src/components/city/CityEffects.jsx@@ -3,14 +3,120 @@ import { useThree, useFrame, extend } from '@react-three/fiber';import { EffectComposer } from 'three/examples/jsm/postprocessing/EffectComposer.js';import { RenderPass } from 'three/examples/jsm/postprocessing/RenderPass.js';import { UnrealBloomPass } from 'three/examples/jsm/postprocessing/UnrealBloomPass.js';+import { ShaderPass } from 'three/examples/jsm/postprocessing/ShaderPass.js';import * as THREE from 'three';-extend({ EffectComposer, RenderPass, UnrealBloomPass });+extend({ EffectComposer, RenderPass, UnrealBloomPass, ShaderPass });-export default function CityEffects() {+// Chromatic Aberration shader -- offset R/B channels at screen edges+const ChromaticAberrationShader = {+ uniforms: {+ tDiffuse: { value: null },+ uStrength: { value: 0.003 },+ },+ vertexShader: `+ varying vec2 vUv;+ void main() {+ vUv = uv;+ gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);+ }+ `,+ fragmentShader: `+ uniform sampler2D tDiffuse;+ uniform float uStrength;+ varying vec2 vUv;+ void main() {+ vec2 center = vec2(0.5);+ vec2 dir = vUv - center;+ float dist = length(dir);+ float offset = dist * uStrength;+ float r = texture2D(tDiffuse, vUv + dir * offset).r;+ float g = texture2D(tDiffuse, vUv).g;+ float b = texture2D(tDiffuse, vUv - dir * offset).b;+ gl_FragColor = vec4(r, g, b, 1.0);+ }+ `,+};++// Film Grain shader -- animated noise overlay+const FilmGrainShader = {+ uniforms: {+ tDiffuse: { value: null },+ uTime: { value: 0 },+ uIntensity: { value: 0.04 },+ },+ vertexShader: `+ varying vec2 vUv;+ void main() {+ vUv = uv;+ gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);+ }+ `,+ fragmentShader: `+ uniform sampler2D tDiffuse;+ uniform float uTime;+ uniform float uIntensity;+ varying vec2 vUv;+ float rand(vec2 co) {+ return fract(sin(dot(co, vec2(12.9898, 78.233))) * 43758.5453);+ }+ void main() {+ vec4 color = texture2D(tDiffuse, vUv);+ float noise = rand(vUv * uTime) * uIntensity;+ color.rgb += noise - uIntensity * 0.5;+ gl_FragColor = color;+ }+ `,+};++// Color Grading shader -- push shadows blue, midtones cyan, highlights warm+const ColorGradingShader = {+ uniforms: {+ tDiffuse: { value: null },+ },+ vertexShader: `+ varying vec2 vUv;+ void main() {+ vUv = uv;+ gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);+ }+ `,+ fragmentShader: `+ uniform sampler2D tDiffuse;+ varying vec2 vUv;+ void main() {+ vec4 color = texture2D(tDiffuse, vUv);+ float lum = dot(color.rgb, vec3(0.299, 0.587, 0.114));+ // Shadows -> deep blue (#0d0d2b)+ vec3 shadowTint = vec3(0.051, 0.051, 0.169);+ // Midtones -> cyan+ vec3 midTint = vec3(0.024, 0.714, 0.831);+ // Highlights -> warm white+ vec3 highTint = vec3(1.0, 0.95, 0.9);+ float shadowWeight = smoothstep(0.0, 0.3, lum) * (1.0 - smoothstep(0.0, 0.4, lum));+ float midWeight = smoothstep(0.2, 0.5, lum) * (1.0 - smoothstep(0.5, 0.8, lum));+ float highWeight = smoothstep(0.6, 1.0, lum);+ color.rgb = mix(color.rgb, color.rgb * shadowTint * 3.0, shadowWeight * 0.25);+ color.rgb = mix(color.rgb, color.rgb * midTint * 1.4, midWeight * 0.15);+ color.rgb = mix(color.rgb, color.rgb * highTint, highWeight * 0.1);+ // Slight contrast boost+ color.rgb = (color.rgb - 0.5) * 1.08 + 0.5;+ gl_FragColor = color;+ }+ `,+};++export default function CityEffects({ settings }) {const composerRef = useRef();+ const grainPassRef = useRef();const { gl, scene, camera, size } = useThree();+ const bloomEnabled = settings?.bloomEnabled ?? true;+ const bloomStrength = settings?.bloomStrength ?? 0.5;+ const chromaticAberration = settings?.chromaticAberration ?? true;+ const filmGrain = settings?.filmGrain ?? true;+ const colorGrading = settings?.colorGrading ?? true;+useEffect(() => {const composer = new EffectComposer(gl);composer.setSize(size.width, size.height);@@ -19,26 +125,50 @@ export default function CityEffects() {const renderPass = new RenderPass(scene, camera);composer.addPass(renderPass);- const bloomPass = new UnrealBloomPass(- new THREE.Vector2(size.width, size.height),- 0.5, // strength- 0.8, // radius- 0.35 // threshold- );- composer.addPass(bloomPass);+ if (bloomEnabled) {+ const bloomPass = new UnrealBloomPass(+ new THREE.Vector2(size.width, size.height),+ bloomStrength,+ 0.8,+ 0.25+ );+ composer.addPass(bloomPass);+ }++ if (colorGrading) {+ const cgPass = new ShaderPass(ColorGradingShader);+ composer.addPass(cgPass);+ }++ if (chromaticAberration) {+ const caPass = new ShaderPass(ChromaticAberrationShader);+ caPass.uniforms.uStrength.value = bloomStrength >= 0.6 ? 0.005 : 0.003;+ composer.addPass(caPass);+ }++ if (filmGrain) {+ const fgPass = new ShaderPass(FilmGrainShader);+ grainPassRef.current = fgPass;+ composer.addPass(fgPass);+ } else {+ grainPassRef.current = null;+ }composerRef.current = composer;return () => {composer.dispose();};- }, [gl, scene, camera, size.width, size.height]);+ }, [gl, scene, camera, size.width, size.height, bloomEnabled, bloomStrength, chromaticAberration, filmGrain, colorGrading]);- useFrame(() => {+ useFrame(({ clock }) => {+ if (grainPassRef.current) {+ grainPassRef.current.uniforms.uTime.value = clock.getElapsedTime();+ }if (composerRef.current) {composerRef.current.render();}- }, 1); // priority 1 = runs after default render+ }, 1);return null;}diff --git a/client/src/components/city/CityGround.jsx b/client/src/components/city/CityGround.jsxindex 5ccc22bad1..e97b6ac9d5 100644--- a/client/src/components/city/CityGround.jsx+++ b/client/src/components/city/CityGround.jsx@@ -11,7 +11,7 @@ function WetPatch({ position, size, color }) {useFrame(({ clock }) => {if (!ref.current) return;const t = clock.getElapsedTime();- ref.current.material.opacity = 0.08 + Math.sin(t * 0.8 + position[0] * 3) * 0.03;+ ref.current.material.opacity = 0.1 + Math.sin(t * 0.8 + position[0] * 3) * 0.04;});return (@@ -20,7 +20,7 @@ function WetPatch({ position, size, color }) {<meshBasicMaterialcolor={color}transparent- opacity={0.08}+ opacity={0.1}blending={THREE.AdditiveBlending}side={THREE.DoubleSide}/>@@ -28,26 +28,67 @@ function WetPatch({ position, size, color }) {);}-export default function CityGround() {+// Rolling fog layer with animated opacity+function RollingFog() {+ const ref = useRef();++ useFrame(({ clock }) => {+ if (!ref.current) return;+ const t = clock.getElapsedTime();+ ref.current.material.opacity = 0.012 + Math.sin(t * 0.15) * 0.008;+ ref.current.position.z = Math.sin(t * 0.05) * 3;+ });++ return (+ <mesh ref={ref} rotation={[-Math.PI / 2, 0, 0]} position={[0, 0.5, 0]}>+ <planeGeometry args={[100, 100]} />+ <meshBasicMaterial+ color="#06b6d4"+ transparent+ opacity={0.012}+ blending={THREE.AdditiveBlending}+ side={THREE.DoubleSide}+ />+ </mesh>+ );+}++export default function CityGround({ settings }) {+ const reflectionsEnabled = settings?.reflectionsEnabled ?? true;+const puddles = useMemo(() => {const result = [];let s = 137;const rand = () => { s = (s * 16807 + 0) % 2147483647; return (s & 0x7fffffff) / 2147483647; };const colors = CITY_COLORS.neonAccents;+ const count = reflectionsEnabled ? 40 : 20;- for (let i = 0; i < 20; i++) {+ for (let i = 0; i < count; i++) {result.push({id: `puddle-${i}`,- position: [(rand() - 0.5) * 40, 0.005, (rand() - 0.5) * 40],- size: 0.5 + rand() * 2,+ position: [(rand() - 0.5) * 50, 0.005, (rand() - 0.5) * 50],+ size: 0.5 + rand() * 2.5,color: colors[Math.floor(rand() * colors.length)],});}return result;- }, []);+ }, [reflectionsEnabled]);return (<group>+ {/* Reflective dark ground plane */}+ {reflectionsEnabled && (+ <mesh rotation={[-Math.PI / 2, 0, 0]} position={[0, -0.02, 0]}>+ <planeGeometry args={[120, 120]} />+ <meshStandardMaterial+ color="#050510"+ metalness={0.9}+ roughness={0.15}+ side={THREE.DoubleSide}+ />+ </mesh>+ )}+<GridinfiniteGridcellSize={1}@@ -77,6 +118,9 @@ export default function CityGround() {side={THREE.DoubleSide}/></mesh>++ {/* Rolling fog layer at street level */}+ {reflectionsEnabled && <RollingFog />}</group>);}diff --git a/client/src/components/city/CityHud.jsx b/client/src/components/city/CityHud.jsxindex e6fd8e579c..658b0ba4da 100644--- a/client/src/components/city/CityHud.jsx+++ b/client/src/components/city/CityHud.jsx@@ -1,4 +1,5 @@import { useState, useEffect, useMemo, useRef } from 'react';+import { useNavigate, useLocation } from 'react-router-dom';import CityActivityLog from './CityActivityLog';import CityAgentBar from './CityAgentBar';@@ -94,6 +95,8 @@ function HealthBar({ value, max, color }) {}export default function CityHud({ cosStatus, cosAgents, agentMap, eventLogs, connected, apps, productivityData }) {+ const navigate = useNavigate();+ const location = useLocation();const [time, setTime] = useState(new Date());const [uptimeSeconds, setUptimeSeconds] = useState(0);const [scanLine, setScanLine] = useState(0);@@ -282,12 +285,25 @@ export default function CityHud({ cosStatus, cosAgents, agentMap, eventLogs, con{/* Bottom: Agent status bar */}<CityAgentBar cosAgents={cosAgents} agentMap={agentMap} />- {/* Bottom-left corner decoration */}- <div className="absolute bottom-16 left-3 pointer-events-none">- <div className="font-pixel text-[8px] text-cyan-500/15 tracking-widest leading-tight">- {'>'} SYS.INIT<br/>- {'>'} NET.LINK<br/>- {'>'} HUD.READY+ {/* Bottom-left: Settings gear + corner decoration */}+ <div className="absolute bottom-16 left-3">+ <button+ onClick={() => navigate(location.pathname === '/city/settings' ? '/city' : '/city/settings')}+ className="pointer-events-auto mb-2 relative bg-black/80 backdrop-blur-sm border border-cyan-500/30 rounded-lg px-2.5 py-1.5 hover:border-cyan-400/60 transition-all group"+ >+ <HudCorner position="tl" />+ <HudCorner position="br" />+ <svg className="w-3.5 h-3.5 text-cyan-500/60 group-hover:text-cyan-400 transition-colors" style={{ filter: 'drop-shadow(0 0 4px rgba(6,182,212,0.3))' }} fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>+ <path strokeLinecap="round" strokeLinejoin="round" d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.066 2.573c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.573 1.066c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.066-2.573c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />+ <path strokeLinecap="round" strokeLinejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />+ </svg>+ </button>+ <div className="pointer-events-none">+ <div className="font-pixel text-[8px] text-cyan-500/15 tracking-widest leading-tight">+ {'>'} SYS.INIT<br/>+ {'>'} NET.LINK<br/>+ {'>'} HUD.READY+ </div></div></div></div>diff --git a/client/src/components/city/CityLights.jsx b/client/src/components/city/CityLights.jsxindex 25a486b8b2..2bbe71e4e4 100644--- a/client/src/components/city/CityLights.jsx+++ b/client/src/components/city/CityLights.jsx@@ -1,15 +1,69 @@+import { useRef } from 'react';+import { useFrame } from '@react-three/fiber';import { CITY_COLORS } from './cityConstants';+// Animated accent light that slowly shifts color+function AnimatedLight({ position, baseColor, intensity, distance, shiftRange = 0.1, speed = 0.5 }) {+ const ref = useRef();++ useFrame(({ clock }) => {+ if (!ref.current) return;+ const t = clock.getElapsedTime();+ ref.current.intensity = intensity + Math.sin(t * speed) * intensity * shiftRange;+ });++ return (+ <pointLight+ ref={ref}+ position={position}+ intensity={intensity}+ color={baseColor}+ distance={distance}+ />+ );+}++// Sweeping searchlight effect+function Searchlight() {+ const ref = useRef();++ useFrame(({ clock }) => {+ if (!ref.current) return;+ const t = clock.getElapsedTime();+ const angle = t * 0.2;+ const radius = 25;+ ref.current.position.x = Math.cos(angle) * radius;+ ref.current.position.z = Math.sin(angle) * radius;+ // Point toward center+ ref.current.target.position.set(0, 0, 0);+ ref.current.target.updateMatrixWorld();+ });++ return (+ <spotLight+ ref={ref}+ position={[25, 30, 0]}+ intensity={0.3}+ color="#06b6d4"+ angle={0.15}+ penumbra={0.8}+ distance={80}+ decay={1.5}+ castShadow={false}+ />+ );+}+export default function CityLights() {return (<><ambientLight intensity={0.06} color={CITY_COLORS.ambient} />{/* Main overhead cyan - brighter */}<pointLight position={[0, 25, 0]} intensity={0.6} color="#06b6d4" distance={80} />- {/* Magenta accent from left - stronger */}- <pointLight position={[-20, 10, -15]} intensity={0.45} color="#ec4899" distance={55} />- {/* Blue accent from right - stronger */}- <pointLight position={[20, 10, 15]} intensity={0.45} color="#3b82f6" distance={55} />+ {/* Magenta accent from left - animated color shift */}+ <AnimatedLight position={[-20, 10, -15]} baseColor="#ec4899" intensity={0.45} distance={55} speed={0.3} shiftRange={0.15} />+ {/* Blue accent from right - animated shift */}+ <AnimatedLight position={[20, 10, 15]} baseColor="#3b82f6" intensity={0.45} distance={55} speed={0.4} shiftRange={0.12} />{/* Purple from behind - more presence */}<pointLight position={[0, 15, -25]} intensity={0.3} color="#8b5cf6" distance={50} />{/* Warm orange ground level accent */}@@ -18,8 +72,8 @@ export default function CityLights() {<pointLight position={[-12, 2, 8]} intensity={0.12} color="#22c55e" distance={20} />{/* Red warning accent from below-right */}<pointLight position={[15, 1, -10]} intensity={0.08} color="#f43f5e" distance={18} />- {/* Deep fog for depth fade - pushes out further */}- <fog attach="fog" args={[CITY_COLORS.fog, 30, 80]} />+ {/* Sweeping searchlight */}+ <Searchlight /></>);}diff --git a/client/src/components/city/CityParticles.jsx b/client/src/components/city/CityParticles.jsxindex e2a787c15f..5b3987b74b 100644--- a/client/src/components/city/CityParticles.jsx+++ b/client/src/components/city/CityParticles.jsx@@ -1,11 +1,14 @@import { Sparkles } from '@react-three/drei';-export default function CityParticles() {+export default function CityParticles({ settings }) {+ const density = settings?.particleDensity ?? 1.0;+ const scale = (base) => Math.max(1, Math.round(base * density));+return (<>{/* Cyan ambient sparkles - main atmosphere */}<Sparkles- count={120}+ count={scale(120)}scale={[50, 20, 50]}size={1.8}speed={0.3}@@ -14,7 +17,7 @@ export default function CityParticles() {/>{/* Pink/magenta secondary sparkles */}<Sparkles- count={50}+ count={scale(50)}scale={[40, 15, 40]}size={1.2}speed={0.25}@@ -23,7 +26,7 @@ export default function CityParticles() {/>{/* Purple deep sparkles */}<Sparkles- count={35}+ count={scale(35)}scale={[45, 15, 45]}size={1}speed={0.2}@@ -32,7 +35,7 @@ export default function CityParticles() {/>{/* Orange warm dust near ground */}<Sparkles- count={25}+ count={scale(25)}scale={[35, 5, 35]}size={0.8}speed={0.15}@@ -42,7 +45,7 @@ export default function CityParticles() {/>{/* Blue high-altitude sparkles */}<Sparkles- count={30}+ count={scale(30)}scale={[50, 8, 50]}size={0.6}speed={0.1}diff --git a/client/src/components/city/CityScanlines.jsx b/client/src/components/city/CityScanlines.jsxindex 5eaa74bef2..7c31b1decc 100644--- a/client/src/components/city/CityScanlines.jsx+++ b/client/src/components/city/CityScanlines.jsx@@ -1,16 +1,44 @@import { useState, useEffect } from 'react';// CSS-based CRT scanline + vignette overlay for cyberpunk atmosphere-export default function CityScanlines() {+export default function CityScanlines({ settings }) {const [flicker, setFlicker] = useState(1);+ const enabled = settings?.scanlineOverlay ?? true;// Random subtle brightness flicker like a CRT monitoruseEffect(() => {+ if (!enabled) return;const interval = setInterval(() => {setFlicker(0.97 + Math.random() * 0.03);}, 150);return () => clearInterval(interval);- }, []);+ }, [enabled]);++ if (!enabled) {+ // Still render vignette and edge glow even when scanlines are off+ return (+ <>+ <div+ className="absolute inset-0 pointer-events-none z-10"+ style={{+ background: 'radial-gradient(ellipse at center, transparent 40%, rgba(0,0,0,0.5) 100%)',+ }}+ />+ <div+ className="absolute top-0 left-0 right-0 h-px pointer-events-none z-10"+ style={{+ background: 'linear-gradient(90deg, transparent, rgba(6,182,212,0.15) 30%, rgba(6,182,212,0.3) 50%, rgba(6,182,212,0.15) 70%, transparent)',+ }}+ />+ <div+ className="absolute bottom-0 left-0 right-0 h-px pointer-events-none z-10"+ style={{+ background: 'linear-gradient(90deg, transparent, rgba(139,92,246,0.15) 30%, rgba(139,92,246,0.3) 50%, rgba(139,92,246,0.15) 70%, transparent)',+ }}+ />+ </>+ );+ }return (<>diff --git a/client/src/components/city/CityScene.jsx b/client/src/components/city/CityScene.jsxindex 1a84a92700..0a00aa4b20 100644--- a/client/src/components/city/CityScene.jsx+++ b/client/src/components/city/CityScene.jsx@@ -20,7 +20,7 @@ import CityNeonSigns from './CityNeonSigns';import CityEmbers from './CityEmbers';import CityEffects from './CityEffects';-export default function CityScene({ apps, agentMap, onBuildingClick, cosStatus, productivityData }) {+export default function CityScene({ apps, agentMap, onBuildingClick, cosStatus, productivityData, settings, playSfx }) {const [positions, setPositions] = useState(null);const handlePositionsReady = useCallback((pos) => {@@ -30,27 +30,30 @@ export default function CityScene({ apps, agentMap, onBuildingClick, cosStatus,const stoppedCount = apps.filter(a => !a.archived && a.overallStatus !== 'online').length;const totalCount = apps.filter(a => !a.archived).length;+ const dpr = settings?.dpr || [1, 1.5];+return (<Canvascamera={{ position: [0, 25, 45], fov: 50 }}- dpr={[1, 1.5]}+ dpr={dpr}shadows={false}style={{ background: '#030308' }}gl={{ antialias: true }}>- <fog attach="fog" args={['#030308', 30, 130]} />+ <fogExp2 attach="fog" args={['#030308', 0.018]} /><CityLights /><CityStarfield />- <CityShootingStars />+ <CityShootingStars playSfx={playSfx} /><CityCelestial /><CitySkyline />- <CityGround />+ <CityGround settings={settings} /><CityRoads positions={positions} /><BuildingClusterapps={apps}agentMap={agentMap}onBuildingClick={onBuildingClick}onPositionsReady={handlePositionsReady}+ playSfx={playSfx}/><CityDataStreams positions={positions} /><CityTraffic positions={positions} />@@ -62,11 +65,11 @@ export default function CityScene({ apps, agentMap, onBuildingClick, cosStatus,/><CityVolumetricLights positions={positions} /><CityNeonSigns positions={positions} />- <CityWeather stoppedCount={stoppedCount} totalCount={totalCount} />+ <CityWeather stoppedCount={stoppedCount} totalCount={totalCount} playSfx={playSfx} /><CityDataRain /><CityEmbers />- <CityParticles />- <CityEffects />+ <CityParticles settings={settings} />+ <CityEffects settings={settings} /><OrbitControlsmaxPolarAngle={Math.PI / 2.2}minDistance={5}diff --git a/client/src/components/city/CitySettingsContext.jsx b/client/src/components/city/CitySettingsContext.jsxnew file mode 100644index 0000000000..5e7b95acdd--- /dev/null+++ b/client/src/components/city/CitySettingsContext.jsx@@ -0,0 +1,20 @@+import { createContext, useContext } from 'react';+import useCitySettings from '../../hooks/useCitySettings';++const CitySettingsContext = createContext(null);++export function CitySettingsProvider({ children }) {+ const [settings, updateSetting, resetSettings] = useCitySettings();++ return (+ <CitySettingsContext.Provider value={{ settings, updateSetting, resetSettings }}>+ {children}+ </CitySettingsContext.Provider>+ );+}++export function useCitySettingsContext() {+ const ctx = useContext(CitySettingsContext);+ if (!ctx) return { settings: null, updateSetting: () => {}, resetSettings: () => {} };+ return ctx;+}diff --git a/client/src/components/city/CitySettingsPanel.jsx b/client/src/components/city/CitySettingsPanel.jsxnew file mode 100644index 0000000000..b24aaceea8--- /dev/null+++ b/client/src/components/city/CitySettingsPanel.jsx@@ -0,0 +1,202 @@+import { useNavigate } from 'react-router-dom';+import { useCitySettingsContext } from './CitySettingsContext';+import { QUALITY_PRESETS } from '../../hooks/useCitySettings';++function HudCorner({ position = 'tl', color = 'cyan' }) {+ const corners = {+ tl: 'top-0 left-0 border-t border-l',+ tr: 'top-0 right-0 border-t border-r',+ bl: 'bottom-0 left-0 border-b border-l',+ br: 'bottom-0 right-0 border-b border-r',+ };+ return (+ <div+ className={`absolute w-2 h-2 ${corners[position]} border-${color}-400/60`}+ style={{ borderWidth: '1px' }}+ />+ );+}++function SettingToggle({ label, value, onChange }) {+ return (+ <div className="flex items-center justify-between py-1">+ <span className="font-pixel text-[10px] text-gray-400 tracking-wide">{label}</span>+ <button+ onClick={() => onChange(!value)}+ className={`w-8 h-4 rounded-full relative transition-colors ${value ? 'bg-cyan-500/40 border-cyan-500/60' : 'bg-gray-700/40 border-gray-600/40'} border`}+ >+ <div+ className={`absolute top-0.5 w-2.5 h-2.5 rounded-full transition-all ${value ? 'left-[14px] bg-cyan-400 shadow-[0_0_6px_rgba(6,182,212,0.5)]' : 'left-[2px] bg-gray-500'}`}+ />+ </button>+ </div>+ );+}++function SettingSlider({ label, value, onChange, min = 0, max = 1, step = 0.05 }) {+ return (+ <div className="py-1">+ <div className="flex items-center justify-between mb-1">+ <span className="font-pixel text-[10px] text-gray-400 tracking-wide">{label}</span>+ <span className="font-pixel text-[9px] text-cyan-400/60">{Math.round(value * 100)}%</span>+ </div>+ <input+ type="range"+ min={min}+ max={max}+ step={step}+ value={value}+ onChange={(e) => onChange(parseFloat(e.target.value))}+ className="w-full h-1 bg-gray-700 rounded-full appearance-none cursor-pointer accent-cyan-500"+ style={{+ background: `linear-gradient(to right, #06b6d4 0%, #06b6d4 ${value / max * 100}%, #374151 ${value / max * 100}%, #374151 100%)`,+ }}+ />+ </div>+ );+}++export default function CitySettingsPanel() {+ const navigate = useNavigate();+ const { settings, updateSetting, resetSettings } = useCitySettingsContext();++ if (!settings) return null;++ return (+ <div className="absolute bottom-4 right-4 z-50 pointer-events-auto animate-in slide-in-from-bottom-4 duration-300">+ <div className="relative bg-black/90 backdrop-blur-md border border-cyan-500/30 rounded-lg w-72 max-h-[80vh] overflow-y-auto">+ <HudCorner position="tl" />+ <HudCorner position="tr" />+ <HudCorner position="bl" />+ <HudCorner position="br" />++ {/* Header */}+ <div className="flex items-center justify-between px-4 py-2.5 border-b border-cyan-500/20">+ <span className="font-pixel text-[11px] text-cyan-400 tracking-widest" style={{ textShadow: '0 0 8px rgba(6,182,212,0.4)' }}>+ SETTINGS+ </span>+ <button+ onClick={() => navigate('/city')}+ className="font-pixel text-[10px] text-gray-500 hover:text-cyan-400 transition-colors tracking-wide"+ >+ [X]+ </button>+ </div>++ <div className="px-4 py-3 space-y-4">+ {/* Quality Preset */}+ <div>+ <div className="font-pixel text-[9px] text-cyan-500/60 tracking-wider mb-2">QUALITY PRESET</div>+ <div className="grid grid-cols-4 gap-1">+ {Object.keys(QUALITY_PRESETS).map(preset => (+ <button+ key={preset}+ onClick={() => updateSetting('qualityPreset', preset)}+ className={`font-pixel text-[9px] py-1.5 rounded border transition-all tracking-wide ${+ settings.qualityPreset === preset+ ? 'bg-cyan-500/20 border-cyan-500/50 text-cyan-400 shadow-[0_0_8px_rgba(6,182,212,0.2)]'+ : 'bg-gray-800/40 border-gray-700/40 text-gray-500 hover:border-gray-600'+ }`}+ >+ {preset.toUpperCase()}+ </button>+ ))}+ </div>+ </div>++ {/* Music */}+ <div>+ <div className="font-pixel text-[9px] text-cyan-500/60 tracking-wider mb-1">MUSIC</div>+ <SettingToggle+ label="SYNTHWAVE"+ value={settings.musicEnabled}+ onChange={(v) => updateSetting('musicEnabled', v)}+ />+ {settings.musicEnabled && (+ <SettingSlider+ label="VOLUME"+ value={settings.musicVolume}+ onChange={(v) => updateSetting('musicVolume', v)}+ />+ )}+ </div>++ {/* Sound Effects */}+ <div>+ <div className="font-pixel text-[9px] text-cyan-500/60 tracking-wider mb-1">SOUND FX</div>+ <SettingToggle+ label="ENABLED"+ value={settings.sfxEnabled}+ onChange={(v) => updateSetting('sfxEnabled', v)}+ />+ {settings.sfxEnabled && (+ <SettingSlider+ label="VOLUME"+ value={settings.sfxVolume}+ onChange={(v) => updateSetting('sfxVolume', v)}+ />+ )}+ </div>++ {/* Visual Effects */}+ <div>+ <div className="font-pixel text-[9px] text-cyan-500/60 tracking-wider mb-1">VISUAL FX</div>+ <SettingToggle+ label="BLOOM"+ value={settings.bloomEnabled}+ onChange={(v) => updateSetting('bloomEnabled', v)}+ />+ {settings.bloomEnabled && (+ <SettingSlider+ label="STRENGTH"+ value={settings.bloomStrength}+ onChange={(v) => updateSetting('bloomStrength', v)}+ />+ )}+ <SettingToggle+ label="REFLECTIONS"+ value={settings.reflectionsEnabled}+ onChange={(v) => updateSetting('reflectionsEnabled', v)}+ />+ <SettingToggle+ label="CHROMATIC ABERRATION"+ value={settings.chromaticAberration}+ onChange={(v) => updateSetting('chromaticAberration', v)}+ />+ <SettingToggle+ label="FILM GRAIN"+ value={settings.filmGrain}+ onChange={(v) => updateSetting('filmGrain', v)}+ />+ <SettingToggle+ label="COLOR GRADING"+ value={settings.colorGrading}+ onChange={(v) => updateSetting('colorGrading', v)}+ />+ <SettingToggle+ label="SCANLINES"+ value={settings.scanlineOverlay}+ onChange={(v) => updateSetting('scanlineOverlay', v)}+ />+ <SettingSlider+ label="PARTICLE DENSITY"+ value={settings.particleDensity}+ onChange={(v) => updateSetting('particleDensity', v)}+ min={0.25}+ max={2}+ step={0.25}+ />+ </div>++ {/* Reset */}+ <button+ onClick={resetSettings}+ className="w-full font-pixel text-[9px] py-1.5 rounded border border-red-500/30 text-red-400/60 hover:bg-red-500/10 hover:text-red-400 transition-all tracking-wider"+ >+ RESET DEFAULTS+ </button>+ </div>+ </div>+ </div>+ );+}diff --git a/client/src/components/city/CityShootingStars.jsx b/client/src/components/city/CityShootingStars.jsxindex 0622b5de5e..2a2ecf2f94 100644--- a/client/src/components/city/CityShootingStars.jsx+++ b/client/src/components/city/CityShootingStars.jsx@@ -25,7 +25,7 @@ const TRAIL_FRAG = ``;// A single shooting star with glowing head and fading trail-function ShootingStar({ index }) {+function ShootingStar({ index, playSfx }) {const groupRef = useRef();const headRef = useRef();const trailRef = useRef();@@ -69,6 +69,7 @@ function ShootingStar({ index }) {s.active = true;s.progress = 0;s.speed = 0.6 + Math.random() * 0.8;+ playSfx?.('shootingStar');s.length = 6 + Math.random() * 6;// Random start position in upper sky hemisphere@@ -184,13 +185,13 @@ function ShootingStar({ index }) {);}-export default function CityShootingStars() {+export default function CityShootingStars({ playSfx }) {return (<group>{/* 3 potential shooting stars, staggered spawn times */}- <ShootingStar index={0} />- <ShootingStar index={1} />- <ShootingStar index={2} />+ <ShootingStar index={0} playSfx={playSfx} />+ <ShootingStar index={1} playSfx={playSfx} />+ <ShootingStar index={2} playSfx={playSfx} /></group>);}diff --git a/client/src/components/city/CityWeather.jsx b/client/src/components/city/CityWeather.jsxindex 8360ced18a..374b145082 100644--- a/client/src/components/city/CityWeather.jsx+++ b/client/src/components/city/CityWeather.jsx@@ -34,7 +34,7 @@ const RAIN_FRAG = ``;// Lightning flash - brief bright flash across the scene-function LightningFlash({ active }) {+function LightningFlash({ active, playSfx }) {const lightRef = useRef();const flashState = useRef({ nextFlash: 0, intensity: 0, flickerCount: 0 });@@ -51,6 +51,7 @@ function LightningFlash({ active }) {state.intensity = 2.0 + Math.random() * 3.0;state.flickerCount = 2 + Math.floor(Math.random() * 3);state.nextFlash = t + 8 + Math.random() * 12;+ playSfx?.('lightning');}if (state.intensity > 0) {@@ -78,7 +79,7 @@ function LightningFlash({ active }) {);}-export default function CityWeather({ stoppedCount = 0, totalCount = 1 }) {+export default function CityWeather({ stoppedCount = 0, totalCount = 1, playSfx }) {const pointsRef = useRef();const matRef = useRef();@@ -132,7 +133,7 @@ export default function CityWeather({ stoppedCount = 0, totalCount = 1 }) {depthWrite={false}/></points>- {showLightning && <LightningFlash active={showLightning} />}+ {showLightning && <LightningFlash active={showLightning} playSfx={playSfx} />}</group>);}diff --git a/client/src/components/city/audio/cityAudioEngine.js b/client/src/components/city/audio/cityAudioEngine.jsnew file mode 100644index 0000000000..cf99fdf9ca--- /dev/null+++ b/client/src/components/city/audio/cityAudioEngine.js@@ -0,0 +1,46 @@+// Singleton audio engine -- Web Audio API only, no external dependencies+let audioCtx = null;+let masterGain = null;+let musicGain = null;+let sfxGain = null;++export const getAudioContext = () => audioCtx;+export const getMusicGain = () => musicGain;+export const getSfxGain = () => sfxGain;++export const initAudio = () => {+ if (audioCtx) return audioCtx;+ audioCtx = new (window.AudioContext || window.webkitAudioContext)();++ masterGain = audioCtx.createGain();+ masterGain.gain.value = 1.0;+ masterGain.connect(audioCtx.destination);++ musicGain = audioCtx.createGain();+ musicGain.gain.value = 0.3;+ musicGain.connect(masterGain);++ sfxGain = audioCtx.createGain();+ sfxGain.gain.value = 0.5;+ sfxGain.connect(masterGain);++ return audioCtx;+};++export const setMusicVolume = (v) => {+ if (musicGain) musicGain.gain.value = Math.max(0, Math.min(1, v));+};++export const setSfxVolume = (v) => {+ if (sfxGain) sfxGain.gain.value = Math.max(0, Math.min(1, v));+};++export const cleanup = () => {+ if (audioCtx && audioCtx.state !== 'closed') {+ audioCtx.close();+ }+ audioCtx = null;+ masterGain = null;+ musicGain = null;+ sfxGain = null;+};diff --git a/client/src/components/city/audio/citySoundEffects.js b/client/src/components/city/audio/citySoundEffects.jsnew file mode 100644index 0000000000..6415ccc55a--- /dev/null+++ b/client/src/components/city/audio/citySoundEffects.js@@ -0,0 +1,138 @@+// Procedural sound effects using Web Audio API -- each SFX is a pure function+import { getAudioContext, getSfxGain } from './cityAudioEngine';++// Helper: create white noise buffer+const createNoiseBuffer = (ctx, duration) => {+ const sampleRate = ctx.sampleRate;+ const length = sampleRate * duration;+ const buffer = ctx.createBuffer(1, length, sampleRate);+ const data = buffer.getChannelData(0);+ for (let i = 0; i < length; i++) {+ data[i] = Math.random() * 2 - 1;+ }+ return buffer;+};++// Building hover: soft scan tone (sine sweep 200->800Hz, 100ms)+const playBuildingHover = (ctx, output) => {+ const now = ctx.currentTime;+ const osc = ctx.createOscillator();+ osc.type = 'sine';+ osc.frequency.setValueAtTime(200, now);+ osc.frequency.exponentialRampToValueAtTime(800, now + 0.1);+ const filter = ctx.createBiquadFilter();+ filter.type = 'bandpass';+ filter.frequency.value = 500;+ filter.Q.value = 2;+ const gain = ctx.createGain();+ gain.gain.setValueAtTime(0.15, now);+ gain.gain.exponentialRampToValueAtTime(0.001, now + 0.12);+ osc.connect(filter);+ filter.connect(gain);+ gain.connect(output);+ osc.start(now);+ osc.stop(now + 0.15);+};++// Building click: percussive ping (noise burst + sine)+const playBuildingClick = (ctx, output) => {+ const now = ctx.currentTime;+ // Noise burst+ const noise = ctx.createBufferSource();+ noise.buffer = createNoiseBuffer(ctx, 0.03);+ const noiseGain = ctx.createGain();+ noiseGain.gain.setValueAtTime(0.2, now);+ noiseGain.gain.exponentialRampToValueAtTime(0.001, now + 0.03);+ noise.connect(noiseGain);+ noiseGain.connect(output);+ noise.start(now);+ // Sine ping+ const osc = ctx.createOscillator();+ osc.type = 'sine';+ osc.frequency.value = 1200;+ const gain = ctx.createGain();+ gain.gain.setValueAtTime(0.15, now);+ gain.gain.exponentialRampToValueAtTime(0.001, now + 0.15);+ osc.connect(gain);+ gain.connect(output);+ osc.start(now);+ osc.stop(now + 0.2);+};++// Lightning: thunder crack (noise, high-pass, distortion, decay)+const playLightning = (ctx, output) => {+ const now = ctx.currentTime;+ const noise = ctx.createBufferSource();+ noise.buffer = createNoiseBuffer(ctx, 0.5);+ const filter = ctx.createBiquadFilter();+ filter.type = 'highpass';+ filter.frequency.value = 400;+ const distortion = ctx.createWaveShaperNode();+ const curve = new Float32Array(256);+ for (let i = 0; i < 256; i++) {+ const x = (i / 128) - 1;+ curve[i] = (Math.PI + 50) * x / (Math.PI + 50 * Math.abs(x));+ }+ distortion.curve = curve;+ const gain = ctx.createGain();+ gain.gain.setValueAtTime(0.3, now);+ gain.gain.exponentialRampToValueAtTime(0.001, now + 0.35);+ noise.connect(filter);+ filter.connect(distortion);+ distortion.connect(gain);+ gain.connect(output);+ noise.start(now);+};++// Shooting star: whoosh (high-pass noise sweep 2kHz->200Hz, panned)+const playShootingStar = (ctx, output) => {+ const now = ctx.currentTime;+ const noise = ctx.createBufferSource();+ noise.buffer = createNoiseBuffer(ctx, 0.6);+ const filter = ctx.createBiquadFilter();+ filter.type = 'highpass';+ filter.frequency.setValueAtTime(2000, now);+ filter.frequency.exponentialRampToValueAtTime(200, now + 0.5);+ const panner = ctx.createStereoPanner();+ panner.pan.value = Math.random() * 2 - 1;+ const gain = ctx.createGain();+ gain.gain.setValueAtTime(0.12, now);+ gain.gain.exponentialRampToValueAtTime(0.001, now + 0.55);+ noise.connect(filter);+ filter.connect(panner);+ panner.connect(gain);+ gain.connect(output);+ noise.start(now);+};++// Data pulse: chirp (sine 400->600Hz, 80ms)+const playDataPulse = (ctx, output) => {+ const now = ctx.currentTime;+ const osc = ctx.createOscillator();+ osc.type = 'sine';+ osc.frequency.setValueAtTime(400, now);+ osc.frequency.exponentialRampToValueAtTime(600, now + 0.08);+ const gain = ctx.createGain();+ gain.gain.setValueAtTime(0.1, now);+ gain.gain.exponentialRampToValueAtTime(0.001, now + 0.1);+ osc.connect(gain);+ gain.connect(output);+ osc.start(now);+ osc.stop(now + 0.12);+};++const SFX_MAP = {+ buildingHover: playBuildingHover,+ buildingClick: playBuildingClick,+ lightning: playLightning,+ shootingStar: playShootingStar,+ dataPulse: playDataPulse,+};++export const playSfx = (name) => {+ const ctx = getAudioContext();+ const output = getSfxGain();+ if (!ctx || !output || ctx.state === 'closed') return;+ const fn = SFX_MAP[name];+ if (fn) fn(ctx, output);+};diff --git a/client/src/components/city/audio/citySynthMusic.js b/client/src/components/city/audio/citySynthMusic.jsnew file mode 100644index 0000000000..da4e32abca--- /dev/null+++ b/client/src/components/city/audio/citySynthMusic.js@@ -0,0 +1,169 @@+// Procedural ambient synthwave using Web Audio oscillators+import { getAudioContext, getMusicGain } from './cityAudioEngine';++let isPlaying = false;+let oscillators = [];+let intervals = [];+let nodesCleanup = [];++// Chord progressions (Am -> Em -> F -> C) as frequency arrays+const CHORDS = [+ [110, 130.81, 164.81], // Am (A2, C3, E3)+ [82.41, 123.47, 164.81], // Em (E2, B2, E3)+ [87.31, 110, 130.81], // F (F2, A2, C3)+ [65.41, 98.0, 130.81], // C (C2, G2, C3)+];++// Arp note patterns (scale degrees relative to chord root)+const ARP_PATTERN = [0, 2, 4, 7, 12, 7, 4, 2];++const createReverb = (ctx) => {+ const convolver = ctx.createConvolver();+ const rate = ctx.sampleRate;+ const length = rate * 2.5;+ const impulse = ctx.createBuffer(2, length, rate);+ for (let ch = 0; ch < 2; ch++) {+ const data = impulse.getChannelData(ch);+ for (let i = 0; i < length; i++) {+ data[i] = (Math.random() * 2 - 1) * Math.pow(1 - i / length, 2.5);+ }+ }+ convolver.buffer = impulse;+ return convolver;+};++export const startMusic = () => {+ const ctx = getAudioContext();+ const output = getMusicGain();+ if (!ctx || !output || isPlaying) return;+ isPlaying = true;++ const reverb = createReverb(ctx);+ const reverbGain = ctx.createGain();+ reverbGain.gain.value = 0.3;+ reverb.connect(reverbGain);+ reverbGain.connect(output);++ const delay = ctx.createDelay(1.0);+ delay.delayTime.value = 0.375; // dotted eighth at ~100BPM+ const delayFeedback = ctx.createGain();+ delayFeedback.gain.value = 0.35;+ delay.connect(delayFeedback);+ delayFeedback.connect(delay);+ delayFeedback.connect(output);++ // --- Bass drone layer ---+ const bassFilter = ctx.createBiquadFilter();+ bassFilter.type = 'lowpass';+ bassFilter.frequency.value = 200;+ bassFilter.Q.value = 2;+ bassFilter.connect(output);+ bassFilter.connect(reverb);++ let currentChordIdx = 0;+ const bassOsc = ctx.createOscillator();+ bassOsc.type = 'sawtooth';+ bassOsc.frequency.value = CHORDS[0][0];+ const bassGain = ctx.createGain();+ bassGain.gain.value = 0.12;+ bassOsc.connect(bassGain);+ bassGain.connect(bassFilter);+ bassOsc.start();+ oscillators.push(bassOsc);++ // LFO for filter sweep+ const lfo = ctx.createOscillator();+ lfo.type = 'sine';+ lfo.frequency.value = 0.08;+ const lfoGain = ctx.createGain();+ lfoGain.gain.value = 120;+ lfo.connect(lfoGain);+ lfoGain.connect(bassFilter.frequency);+ lfo.start();+ oscillators.push(lfo);++ // --- Pad layer (wide stereo detuned sines) ---+ const padGain = ctx.createGain();+ padGain.gain.value = 0.04;+ padGain.connect(output);+ padGain.connect(reverb);++ const padOscs = [];+ for (let i = 0; i < 3; i++) {+ const osc = ctx.createOscillator();+ osc.type = 'sine';+ osc.frequency.value = CHORDS[0][i];+ osc.detune.value = (i - 1) * 8; // slight spread+ osc.connect(padGain);+ osc.start();+ padOscs.push(osc);+ oscillators.push(osc);+ }++ // --- Arp lead layer ---+ const arpFilter = ctx.createBiquadFilter();+ arpFilter.type = 'bandpass';+ arpFilter.frequency.value = 1200;+ arpFilter.Q.value = 1.5;+ const arpGain = ctx.createGain();+ arpGain.gain.value = 0;+ arpFilter.connect(arpGain);+ arpGain.connect(output);+ arpGain.connect(delay);+ arpGain.connect(reverb);++ const arpOsc = ctx.createOscillator();+ arpOsc.type = 'triangle';+ arpOsc.frequency.value = 440;+ arpOsc.detune.value = 5;+ arpOsc.connect(arpFilter);+ arpOsc.start();+ oscillators.push(arpOsc);++ let arpStep = 0;+ // Chord change every 2.4s (4 beats at 100BPM)+ const chordInterval = setInterval(() => {+ if (!isPlaying) return;+ currentChordIdx = (currentChordIdx + 1) % CHORDS.length;+ const chord = CHORDS[currentChordIdx];+ const now = ctx.currentTime;+ bassOsc.frequency.setTargetAtTime(chord[0], now, 0.3);+ padOscs.forEach((osc, i) => {+ osc.frequency.setTargetAtTime(chord[i] * 2, now, 0.3);+ });+ }, 2400);+ intervals.push(chordInterval);++ // Arp sixteenth notes at 100BPM = 150ms per step+ const arpInterval = setInterval(() => {+ if (!isPlaying) return;+ const chord = CHORDS[currentChordIdx];+ const rootFreq = chord[0] * 4; // two octaves up+ const semitone = ARP_PATTERN[arpStep % ARP_PATTERN.length];+ const freq = rootFreq * Math.pow(2, semitone / 12);+ const now = ctx.currentTime;++ arpOsc.frequency.setTargetAtTime(freq, now, 0.01);+ // Short percussive envelope+ arpGain.gain.setTargetAtTime(0.06, now, 0.005);+ arpGain.gain.setTargetAtTime(0.0, now + 0.06, 0.04);++ arpStep++;+ }, 150);+ intervals.push(arpInterval);++ nodesCleanup.push(reverb, reverbGain, delay, delayFeedback, bassFilter, bassGain, padGain, arpFilter, arpGain);+};++export const stopMusic = () => {+ isPlaying = false;+ oscillators.forEach(osc => {+ osc.stop();+ osc.disconnect();+ });+ oscillators = [];+ intervals.forEach(clearInterval);+ intervals = [];+ nodesCleanup.forEach(node => node.disconnect());+ nodesCleanup = [];+};diff --git a/client/src/hooks/useCityAudio.js b/client/src/hooks/useCityAudio.jsnew file mode 100644index 0000000000..5141d4306f--- /dev/null+++ b/client/src/hooks/useCityAudio.js@@ -0,0 +1,74 @@+import { useState, useEffect, useCallback, useRef } from 'react';+import { initAudio, setMusicVolume, setSfxVolume, cleanup as cleanupAudio } from '../components/city/audio/cityAudioEngine';+import { startMusic, stopMusic } from '../components/city/audio/citySynthMusic';+import { playSfx as playSfxFn } from '../components/city/audio/citySoundEffects';++export default function useCityAudio(settings) {+ const [isAudioReady, setIsAudioReady] = useState(false);+ const initedRef = useRef(false);+ const settingsRef = useRef(settings);+ settingsRef.current = settings;++ // Init AudioContext on first user gesture+ useEffect(() => {+ const handleGesture = () => {+ if (initedRef.current) return;+ initedRef.current = true;+ const ctx = initAudio();+ if (ctx) {+ setIsAudioReady(true);+ // Start music if enabled at init time+ if (settingsRef.current?.musicEnabled) {+ startMusic();+ setMusicVolume(settingsRef.current.musicVolume);+ }+ }+ window.removeEventListener('click', handleGesture);+ window.removeEventListener('keydown', handleGesture);+ };+ window.addEventListener('click', handleGesture);+ window.addEventListener('keydown', handleGesture);+ return () => {+ window.removeEventListener('click', handleGesture);+ window.removeEventListener('keydown', handleGesture);+ };+ }, []);++ // Toggle music on/off based on settings+ useEffect(() => {+ if (!isAudioReady || !settings) return;+ if (settings.musicEnabled) {+ startMusic();+ setMusicVolume(settings.musicVolume);+ } else {+ stopMusic();+ }+ }, [isAudioReady, settings?.musicEnabled]);++ // Update music volume+ useEffect(() => {+ if (!isAudioReady || !settings?.musicEnabled) return;+ setMusicVolume(settings.musicVolume);+ }, [isAudioReady, settings?.musicVolume]);++ // Update SFX volume+ useEffect(() => {+ if (!isAudioReady || !settings) return;+ setSfxVolume(settings.sfxVolume);+ }, [isAudioReady, settings?.sfxVolume]);++ // Cleanup on unmount+ useEffect(() => {+ return () => {+ stopMusic();+ cleanupAudio();+ };+ }, []);++ const playSfx = useCallback((name) => {+ if (!isAudioReady || !settingsRef.current?.sfxEnabled) return;+ playSfxFn(name);+ }, [isAudioReady]);++ return { playSfx, isAudioReady };+}diff --git a/client/src/hooks/useCitySettings.js b/client/src/hooks/useCitySettings.jsnew file mode 100644index 0000000000..a69fec610b--- /dev/null+++ b/client/src/hooks/useCitySettings.js@@ -0,0 +1,76 @@+import { useState, useCallback } from 'react';++const STORAGE_KEY = 'portos-city-settings';++const QUALITY_PRESETS = {+ low: {+ bloomEnabled: false, bloomStrength: 0,+ reflectionsEnabled: false, chromaticAberration: false,+ filmGrain: false, colorGrading: false,+ particleDensity: 0.5, scanlineOverlay: false,+ dpr: [1, 1],+ },+ medium: {+ bloomEnabled: true, bloomStrength: 0.3,+ reflectionsEnabled: true, chromaticAberration: false,+ filmGrain: false, colorGrading: true,+ particleDensity: 0.75, scanlineOverlay: true,+ dpr: [1, 1.25],+ },+ high: {+ bloomEnabled: true, bloomStrength: 0.5,+ reflectionsEnabled: true, chromaticAberration: true,+ filmGrain: true, colorGrading: true,+ particleDensity: 1.0, scanlineOverlay: true,+ dpr: [1, 1.5],+ },+ ultra: {+ bloomEnabled: true, bloomStrength: 0.7,+ reflectionsEnabled: true, chromaticAberration: true,+ filmGrain: true, colorGrading: true,+ particleDensity: 1.5, scanlineOverlay: true,+ dpr: [1, 2],+ },+};++const DEFAULT_SETTINGS = {+ musicEnabled: false,+ musicVolume: 0.3,+ sfxEnabled: true,+ sfxVolume: 0.5,+ qualityPreset: 'high',+ ...QUALITY_PRESETS.high,+};++const loadSettings = () => {+ const saved = localStorage.getItem(STORAGE_KEY);+ if (!saved) return DEFAULT_SETTINGS;+ return { ...DEFAULT_SETTINGS, ...JSON.parse(saved) };+};++export { QUALITY_PRESETS };++export default function useCitySettings() {+ const [settings, setSettings] = useState(loadSettings);++ const updateSetting = useCallback((key, value) => {+ setSettings(prev => {+ // If changing quality preset, apply bulk changes+ if (key === 'qualityPreset' && QUALITY_PRESETS[value]) {+ const next = { ...prev, qualityPreset: value, ...QUALITY_PRESETS[value] };+ localStorage.setItem(STORAGE_KEY, JSON.stringify(next));+ return next;+ }+ const next = { ...prev, [key]: value };+ localStorage.setItem(STORAGE_KEY, JSON.stringify(next));+ return next;+ });+ }, []);++ const resetSettings = useCallback(() => {+ localStorage.removeItem(STORAGE_KEY);+ setSettings(DEFAULT_SETTINGS);+ }, []);++ return [settings, updateSetting, resetSettings];+}diff --git a/client/src/pages/CyberCity.jsx b/client/src/pages/CyberCity.jsxindex 6f1e2f95c3..1683942960 100644--- a/client/src/pages/CyberCity.jsx+++ b/client/src/pages/CyberCity.jsx@@ -1,16 +1,24 @@import { useCallback, useState, useEffect } from 'react';-import { useNavigate } from 'react-router-dom';+import { useNavigate, useLocation } from 'react-router-dom';import { useCityData } from '../hooks/useCityData';+import useCityAudio from '../hooks/useCityAudio';import * as api from '../services/api';import CityScene from '../components/city/CityScene';import CityHud from '../components/city/CityHud';import CityScanlines from '../components/city/CityScanlines';+import { CitySettingsProvider, useCitySettingsContext } from '../components/city/CitySettingsContext';+import CitySettingsPanel from '../components/city/CitySettingsPanel';-export default function CyberCity() {+function CyberCityInner() {const { apps, cosAgents, cosStatus, eventLogs, agentMap, loading, connected } = useCityData();+ const { settings } = useCitySettingsContext();+ const { playSfx } = useCityAudio(settings);const navigate = useNavigate();+ const location = useLocation();const [productivityData, setProductivityData] = useState(null);+ const showSettings = location.pathname === '/city/settings';+// Fetch productivity data for HUD vitals and billboardsuseEffect(() => {const fetchProductivity = async () => {@@ -44,6 +52,8 @@ export default function CyberCity() {onBuildingClick={handleBuildingClick}cosStatus={cosStatus}productivityData={productivityData}+ settings={settings}+ playSfx={playSfx}/><CityHudcosStatus={cosStatus}@@ -54,7 +64,16 @@ export default function CyberCity() {apps={apps}productivityData={productivityData}/>- <CityScanlines />+ <CityScanlines settings={settings} />+ {showSettings && <CitySettingsPanel />}</div>);}++export default function CyberCity() {+ return (+ <CitySettingsProvider>+ <CyberCityInner />+ </CitySettingsProvider>+ );+}