Weather system, day/night cycle, agent behaviors, city expansion
Browse files- Sun movement east→zenith→west with dynamic shadows
- Weather effects: rain (4000 particles), snow (2000 particles), thunderstorms (lightning flashes), fog, cloudy skies
- Sun brightness/size adjusts per weather (bright sunny → dim stormy)
- Storm clouds layer (18 dark clouds) for bad weather
- Night: residential buildings become transparent, agents sleep in beds
- Furniture inside buildings: tables at restaurants/bars, desks in offices/schools, seats in cinema/church
- Agent poses: walking, sitting (at tables/desks), sleeping (in beds)
- Bad weather: 70% agents stay indoors; night: all go home to sleep
- Demo mode cycles through full day/night + weather types automatically
- Moon enlarged (10), stars visible from 19:00, brighter after 21:00
- Trees halved in size for better proportion with buildings
- City expanded: WORLD_SIZE 100→130, shadow camera enlarged
- 10 new public buildings (bank, court, gallery, daycare, vet, yoga, pub, etc.)
- 4 new streets for expanded area
- Ollama default model: llama3.3:latest
- Snow/snowy weather icon added to both 3d.html and index.html
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Files changed (3)
- src/soci/engine/llm.py+3-3
- web/3d.html+444-39
- web/index.html+35-5
26 unmodified lines2728293031323334967 unmodified lines100210031004100510061007100826 unmodified linesMODEL_HAIKU = "claude-haiku-4-5-20251001"# Ollama model IDs (popular open-source models)MODEL_LLAMA = "llama3.1:8b"MODEL_LLAMA_SMALL = "llama3.1:8b"MODEL_MISTRAL = "mistral"MODEL_QWEN = "qwen2.5"MODEL_GEMMA = "gemma2"967 unmodified linesdefault_model = model or os.environ.get("GEMINI_MODEL", MODEL_GEMINI_FLASH)return GeminiClient(default_model=default_model)elif provider == PROVIDER_OLLAMA:default_model = model or os.environ.get("OLLAMA_MODEL", MODEL_OLLAMA_SOCI)return OllamaClient(base_url=ollama_url, default_model=default_model)else:raise ValueError(f"Unknown LLM provider: {provider}. Use 'nn', 'claude', 'groq', 'gemini', or 'ollama'.")26 unmodified lines2728293031323334967 unmodified lines100210031004100510061007100826 unmodified linesMODEL_HAIKU = "claude-haiku-4-5-20251001"# Ollama model IDs (popular open-source models)MODEL_LLAMA = "llama3.3:latest"MODEL_LLAMA_SMALL = "llama3.3:latest"MODEL_MISTRAL = "mistral"MODEL_QWEN = "qwen2.5"MODEL_GEMMA = "gemma2"967 unmodified linesdefault_model = model or os.environ.get("GEMINI_MODEL", MODEL_GEMINI_FLASH)return GeminiClient(default_model=default_model)elif provider == PROVIDER_OLLAMA:default_model = model or os.environ.get("OLLAMA_MODEL", MODEL_LLAMA)return OllamaClient(base_url=ollama_url, default_model=default_model)else:raise ValueError(f"Unknown LLM provider: {provider}. Use 'nn', 'claude', 'groq', 'gemini', or 'ollama'.")
170 unmodified lines171172173174175176177146 unmodified lines32432532632732832959 unmodified lines38939039139239339439539639739839940068 unmodified lines469470471472473474144 unmodified lines6196206216226236247 unmodified lines63263363463563663734 unmodified lines672673674675676677328 unmodified lines1006100710081009101010111012258 unmodified lines1271127212731274127512761 unmodified line12781279128012811282128326 unmodified lines1310131113121313131413151316109 unmodified lines142614271428142914301431143233 unmodified lines14661467146814691470147115 unmodified lines148714881489149014911492149349 unmodified lines15431544154515461547154815497 unmodified lines15571558155915601561156237 unmodified lines1600160116021603160416051 unmodified line1607160816091610161116121613142 unmodified lines17561757175817591760176131 unmodified lines17931794179517961797179817991800180118022 unmodified lines180518061807180818091810181118121813399 unmodified lines221322142215221622172218221922202221222222232224222522262227222822292230223122325 unmodified lines2238223922402241224222432244224522462247224840 unmodified lines2289229022912292229322942295104 unmodified lines240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429170 unmodified lines// ============================================================// CONSTANTS// ============================================================const WORLD_SIZE = 100;const HALF = WORLD_SIZE / 2;const PALETTE = {146 unmodified linespark_east: { x: 0.86, y: 0.58, type: 'park', label: 'Rose Garden' },park_south: { x: 0.40, y: 0.88, type: 'park', label: 'Lakeside Park' },playground: { x: 0.15, y: 0.58, type: 'park', label: 'Kids Playground' },};function toWorld(nx, ny) {59 unmodified linessunLight.castShadow = true;sunLight.shadow.mapSize.width = 2048;sunLight.shadow.mapSize.height = 2048;sunLight.shadow.camera.left = -60;sunLight.shadow.camera.right = 60;sunLight.shadow.camera.top = 60;sunLight.shadow.camera.bottom = -60;sunLight.shadow.camera.near = 1;sunLight.shadow.camera.far = 150;sunLight.shadow.bias = -0.001;scene.add(sunLight);68 unmodified linescreateRoad(35, -HALF * 1.1, 35, HALF * 1.1, 2.5);createRoad(42, -HALF * 1.1, 42, HALF * 1.1, 2.5);// ============================================================// MATERIAL HELPERS// ============================================================144 unmodified linesmat(BLDG_COLORS.door));door.position.set(0, 0.6, d / 2 + 0.05);group.add(door);// Windows7 unmodified linesgroup.add(win);}const label = createLabel(locData.label, group, wallH + roofH + 1);const badge = createOccupantBadge(group, wallH + roofH);group.userData = { id, type: 'house', label, badge, locData };34 unmodified lines}}const label = createLabel(locData.label, group, wallH + 2);const badge = createOccupantBadge(group, wallH + 1);group.userData = { id, type: 'apartment', label, badge, locData };328 unmodified linesconst tx = (Math.random() - 0.5) * 6;const tz = (Math.random() - 0.5) * 4;if (Math.abs(tx) > 1) {const t = createTree(0, 0, 0.7 + Math.random() * 0.5);t.position.set(tx, 0, tz);scene.remove(t);group.add(t);258 unmodified linescase 'market': bldg = createMarket(id, locData); break;default: bldg = createShop(id, locData); break;}const pos = toWorld(locData.x, locData.y);bldg.position.set(pos.x, 0, pos.z);scene.add(bldg);1 unmodified linereturn bldg;}// ============================================================// PLACE ALL BUILDINGS// ============================================================26 unmodified lines}if (Math.abs(tx) < 2.5 || Math.abs(tz + 7) < 2.5) tooClose = true; // avoid main roadsif (!tooClose) {createTree(tx, tz, 0.6 + Math.random() * 0.8);treePositions.push({ x: tx, z: tz });}}109 unmodified linesconst moonSprite = new THREE.Sprite(new THREE.SpriteMaterial({ map: celestialTex(0xccddff), transparent: true, depthTest: false }));moonSprite.scale.set(7, 7, 1);moonSprite.renderOrder = -1;moonSprite.visible = false;scene.add(moonSprite);33 unmodified linesclouds.push(cg);}// Position sun/moon based on hourfunction updateCelestials(hour) {// Sun: rises 6, peaks 12, sets 1815 unmodified lines} else {moonSprite.visible = false;}starPoints.visible = hour >= 20 || hour <= 5;}updateCelestials(10);49 unmodified linesscene.fog = new THREE.FogExp2(PALETTE.fog, 0.004);}// Window glowscene.traverse(o => {if (o.userData?.isWindow && o.material) {if (isNight) {7 unmodified lines}}});}// Parse simulation time string → { hour, phase }37 unmodified linesreturn g;}function createAgentMesh(agentId, agentData) {const group = new THREE.Group();const idx = getAgentIdx(agentId);1 unmodified lineconst shirtColor = AGENT_COLORS[idx % AGENT_COLORS.length];const skinColor = SKIN_COLORS[h % SKIN_COLORS.length];const hairColor = HAIR_COLORS[(h >> 3) % HAIR_COLORS.length];const wearsSkirt = (h >> 6) % 3 === 0;const bottomColor = wearsSkirt? SKIRT_COLORS[(h >> 8) % SKIRT_COLORS.length]: PANTS_COLORS[(h >> 8) % PANTS_COLORS.length];142 unmodified lineslet simState = {};let wsConnected = false;let ws = null;function connectWebSocket() {const protocol = location.protocol === 'https:' ? 'wss:' : 'ws:';31 unmodified linesconst agents = simState.agents || {};const locations = simState.locations || {};// Update time displaydocument.getElementById('sim-time').textContent = msg.time || '';const weather = simState.weather || simState.clock?.weather || '';const weatherIcons = { sunny: '☀️', clear: '☀️', cloudy: '☁️', rainy: '🌧️', stormy: '⛈️', foggy: '🌫️' };document.getElementById('sim-weather').textContent = weatherIcons[weather] || '';document.getElementById('sim-agents').textContent = `${Object.keys(agents).length} agents`;2 unmodified linesdocument.getElementById('sim-cost').textContent = `$${parseFloat(cost).toFixed(4)}`;}// Update sky / lighting from simulation timeconst { hour, phase } = parseSimTime(msg.time || '');updateTimeOfDay(phase, hour);// Register dynamic locationsfor (const [locId, locData] of Object.entries(locations)) {399 unmodified lines}}// Walking animation — swing limbs when moving, gentle bob when idleconst dx2 = target ? target.x - mesh.position.x : 0;const dz2 = target ? target.z - mesh.position.z : 0;const dist = Math.sqrt(dx2 * dx2 + dz2 * dz2);const moving = dist > 0.15;const walkPhase = frameCount * 0.12 + hash(agentId) * 0.5;const swing = moving ? Math.sin(walkPhase) * 0.7 : 0;if (mesh.userData.leftLeg) mesh.userData.leftLeg.rotation.x = swing;if (mesh.userData.rightLeg) mesh.userData.rightLeg.rotation.x = -swing;if (mesh.userData.leftArm) mesh.userData.leftArm.rotation.x = -swing * 0.5;if (mesh.userData.rightArm) mesh.userData.rightArm.rotation.x = swing * 0.5;mesh.position.y = moving? Math.abs(Math.sin(walkPhase * 2)) * 0.04: Math.sin(frameCount * 0.02 + hash(agentId) * 0.1) * 0.015;}// Subtle tree sway5 unmodified lines});}// Cloud driftfor (const cloud of clouds) {cloud.position.x += cloud.userData.speed;if (cloud.position.x > 70) cloud.position.x = -70;}renderer.render(scene, camera);}40 unmodified lines// ============================================================// BOOT// ============================================================const isEmbedded = window.parent !== window;if (isEmbedded) {document.getElementById('status-bar').style.display = 'none';document.getElementById('controls-bar').style.display = 'none';104 unmodified linesfor (const d of demoNames) {demoAgents[d.id] = { name: d.name, location: d.location, state: 'idle', needs: {} };}handleStateUpdate({type: 'tick', time: 'Day 1, 10:30 (morning)',state: { agents: demoAgents, locations: {}, weather: 'sunny' }});document.getElementById('sim-time').textContent = 'Day 1, 10:30 (morning)';document.getElementById('sim-weather').textContent = '☀️';document.getElementById('sim-agents').textContent = `${demoNames.length} agents (demo)`;// Animate demo agents moving between locationsconst locIds = Object.keys(LOCATION_POSITIONS).filter(k => !k.startsWith('street'));setInterval(() => {if (wsConnected) return;const agents = Object.keys(demoAgents);const moveCount = 3 + Math.floor(Math.random() * 5);for (let i = 0; i < moveCount; i++) {const who = agents[Math.floor(Math.random() * agents.length)];const dest = locIds[Math.floor(Math.random() * locIds.length)];demoAgents[who].location = dest;}handleStateUpdate({type: 'tick', time: 'Day 1, 10:30 (morning)',state: { agents: demoAgents, locations: {}, weather: 'sunny' }});}, 2000);}// Hide zoom hint after a few seconds170 unmodified lines171172173174175176177146 unmodified lines32432532632732832933033133233333433533633733833934034134234334434559 unmodified lines40540640740840941041141241341441541668 unmodified lines485486487488489490491492493494495496144 unmodified lines6416426436446456466477 unmodified lines65565665765865966066166266366466566666766866967067167267367467567667767867968034 unmodified lines715716717718719720721722723724725726727728729730328 unmodified lines1059106010611062106310641065258 unmodified lines13241325132613271328132913301 unmodified line1332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138426 unmodified lines1411141214131414141514161417109 unmodified lines152715281529153015311532153333 unmodified lines156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169315 unmodified lines1709171017111712171317141715171649 unmodified lines17661767176817691770177117727 unmodified lines1780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180537 unmodified lines18431844184518461847184818491850185118521853185418551 unmodified line185718581859186018611862186318641865142 unmodified lines200820092010201120122013201431 unmodified lines20462047204820492050205120522053205420552056205720582 unmodified lines2061206220632064206520662067206820692070399 unmodified lines247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225135 unmodified lines2519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258340 unmodified lines262426252626262726282629104 unmodified lines27342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834170 unmodified lines// ============================================================// CONSTANTS// ============================================================const WORLD_SIZE = 130;const HALF = WORLD_SIZE / 2;const PALETTE = {146 unmodified linespark_east: { x: 0.86, y: 0.58, type: 'park', label: 'Rose Garden' },park_south: { x: 0.40, y: 0.88, type: 'park', label: 'Lakeside Park' },playground: { x: 0.15, y: 0.58, type: 'park', label: 'Kids Playground' },// ── Additional public buildings ───────────────────────────post_office: { x: 0.30, y: 0.58, type: 'office', label: 'Post Office' },bank: { x: 0.60, y: 0.58, type: 'office', label: 'City Bank' },court: { x: 0.44, y: 0.58, type: 'townhall', label: 'Courthouse' },gallery: { x: 0.15, y: 0.34, type: 'museum', label: 'Art Gallery' },daycare: { x: 0.15, y: 0.42, type: 'school', label: 'Sunny Daycare' },vet_clinic: { x: 0.65, y: 0.58, type: 'hospital', label: 'Vet Clinic' },yoga_studio: { x: 0.56, y: 0.58, type: 'shop', label: 'Zen Yoga' },pub: { x: 0.70, y: 0.42, type: 'shop', label: "The Oak Pub" },ice_cream: { x: 0.30, y: 0.42, type: 'shop', label: 'Scoop & Joy' },taxi_stand: { x: 0.50, y: 0.42, type: 'shop', label: 'Taxi Stand' },// ── Streets ───────────────────────────────────────────────street_main: { x: 0.50, y: 0.28, type: 'square', label: 'Main Street' },street_west: { x: 0.15, y: 0.50, type: 'square', label: 'West Avenue' },};function toWorld(nx, ny) {59 unmodified linessunLight.castShadow = true;sunLight.shadow.mapSize.width = 2048;sunLight.shadow.mapSize.height = 2048;sunLight.shadow.camera.left = -80;sunLight.shadow.camera.right = 80;sunLight.shadow.camera.top = 80;sunLight.shadow.camera.bottom = -80;sunLight.shadow.camera.near = 1;sunLight.shadow.camera.far = 200;sunLight.shadow.bias = -0.001;scene.add(sunLight);68 unmodified linescreateRoad(35, -HALF * 1.1, 35, HALF * 1.1, 2.5);createRoad(42, -HALF * 1.1, 42, HALF * 1.1, 2.5);// Extra streets for expanded citycreateRoad(-HALF * 1.1, -48, HALF * 1.1, -48, 2); // far far northcreateRoad(-HALF * 1.1, 48, HALF * 1.1, 48, 2); // far far southcreateRoad(-52, -HALF * 1.1, -52, HALF * 1.1, 2); // far westcreateRoad(52, -HALF * 1.1, 52, HALF * 1.1, 2); // far east// ============================================================// MATERIAL HELPERS// ============================================================144 unmodified linesmat(BLDG_COLORS.door));door.position.set(0, 0.6, d / 2 + 0.05);door.userData.isDoor = true;group.add(door);// Windows7 unmodified linesgroup.add(win);}// Bed (visible when house is transparent at night)const bed = new THREE.Mesh(new THREE.BoxGeometry(1.2, 0.15, 0.7),mat(0x8b6040));bed.position.set(0.6, 0.08, 0);group.add(bed);const mattress = new THREE.Mesh(new THREE.BoxGeometry(1.1, 0.1, 0.6),mat(0xe8e0d0));mattress.position.set(0.6, 0.18, 0);group.add(mattress);const pillow = new THREE.Mesh(new THREE.BoxGeometry(0.25, 0.08, 0.35),mat(0xf0f0f0));pillow.position.set(1.1, 0.24, 0);group.add(pillow);const label = createLabel(locData.label, group, wallH + roofH + 1);const badge = createOccupantBadge(group, wallH + roofH);group.userData = { id, type: 'house', label, badge, locData };34 unmodified lines}}// Beds inside (visible at night through transparent walls)for (let bx = -1; bx <= 1; bx += 2) {const bed = new THREE.Mesh(new THREE.BoxGeometry(1.0, 0.12, 0.5), mat(0x8b6040));bed.position.set(bx * 1.2, 0.06, 0);group.add(bed);const matt = new THREE.Mesh(new THREE.BoxGeometry(0.9, 0.08, 0.45), mat(0xe0d8c8));matt.position.set(bx * 1.2, 0.14, 0);group.add(matt);}const label = createLabel(locData.label, group, wallH + 2);const badge = createOccupantBadge(group, wallH + 1);group.userData = { id, type: 'apartment', label, badge, locData };328 unmodified linesconst tx = (Math.random() - 0.5) * 6;const tz = (Math.random() - 0.5) * 4;if (Math.abs(tx) > 1) {const t = createTree(0, 0, 0.35 + Math.random() * 0.25);t.position.set(tx, 0, tz);scene.remove(t);group.add(t);258 unmodified linescase 'market': bldg = createMarket(id, locData); break;default: bldg = createShop(id, locData); break;}addFurniture(id, bldg, locData);const pos = toWorld(locData.x, locData.y);bldg.position.set(pos.x, 0, pos.z);scene.add(bldg);1 unmodified linereturn bldg;}const FOOD_LOCS = new Set(['restaurant','bar','cafe','diner','bakery','sushi_bar','pizzeria','coffeehouse','pub','ice_cream']);const DESK_LOCS = new Set(['office','office_tech','office_media','school','library','townhall','post_office','bank','court','daycare']);const SEAT_LOCS = new Set(['cinema','church','museum']);const SITTING_LOCS = new Set([...FOOD_LOCS, ...DESK_LOCS, ...SEAT_LOCS]);function addFurniture(id, group, locData) {const tableMat = mat(0x8b6040);const chairMat = mat(0x6a5030);const deskMat = mat(0xa09080);if (FOOD_LOCS.has(id)) {for (let i = -1; i <= 1; i++) {const table = new THREE.Mesh(new THREE.BoxGeometry(0.7, 0.4, 0.7), tableMat);table.position.set(i * 1.6, 0.2, 3.0);group.add(table);for (let s of [-0.5, 0.5]) {const chair = new THREE.Mesh(new THREE.BoxGeometry(0.3, 0.25, 0.3), chairMat);chair.position.set(i * 1.6 + s, 0.125, 3.6);group.add(chair);const back = new THREE.Mesh(new THREE.BoxGeometry(0.3, 0.3, 0.05), chairMat);back.position.set(i * 1.6 + s, 0.35, 3.75);group.add(back);}}} else if (DESK_LOCS.has(id)) {for (let i = -1; i <= 1; i += 2) {const desk = new THREE.Mesh(new THREE.BoxGeometry(1.2, 0.45, 0.6), deskMat);desk.position.set(i * 1.3, 0.225, 3.0);group.add(desk);const ch = new THREE.Mesh(new THREE.BoxGeometry(0.3, 0.25, 0.3), chairMat);ch.position.set(i * 1.3, 0.125, 3.5);group.add(ch);}} else if (SEAT_LOCS.has(id)) {for (let row = 0; row < 2; row++) {for (let col = -1; col <= 1; col++) {const seat = new THREE.Mesh(new THREE.BoxGeometry(0.4, 0.25, 0.35), chairMat);seat.position.set(col * 0.7, 0.125, 2.5 + row * 0.8);group.add(seat);const sb = new THREE.Mesh(new THREE.BoxGeometry(0.4, 0.35, 0.05), chairMat);sb.position.set(col * 0.7, 0.35, 2.5 + row * 0.8 + 0.18);group.add(sb);}}}}// ============================================================// PLACE ALL BUILDINGS// ============================================================26 unmodified lines}if (Math.abs(tx) < 2.5 || Math.abs(tz + 7) < 2.5) tooClose = true; // avoid main roadsif (!tooClose) {createTree(tx, tz, 0.3 + Math.random() * 0.4);treePositions.push({ x: tx, z: tz });}}109 unmodified linesconst moonSprite = new THREE.Sprite(new THREE.SpriteMaterial({ map: celestialTex(0xccddff), transparent: true, depthTest: false }));moonSprite.scale.set(10, 10, 1);moonSprite.renderOrder = -1;moonSprite.visible = false;scene.add(moonSprite);33 unmodified linesclouds.push(cg);}// ============================================================// WEATHER EFFECTS — rain, snow, lightning, storm clouds// ============================================================let currentWeather = 'sunny';const stormClouds = [];for (let ci = 0; ci < 18; ci++) {const cg = new THREE.Group();const nPuffs = 4 + Math.floor(Math.random() * 5);for (let j = 0; j < nPuffs; j++) {const pf = new THREE.Mesh(new THREE.SphereGeometry(2.0 + Math.random() * 2.8, 7, 5),new THREE.MeshStandardMaterial({ color: 0x556070, roughness: 1, metalness: 0, transparent: true, opacity: 0.85, flatShading: true }));pf.scale.y = 0.25;pf.position.set((Math.random() - 0.5) * 10, (Math.random() - 0.5) * 0.6, (Math.random() - 0.5) * 6);cg.add(pf);}cg.position.set((Math.random() - 0.5) * 140, 17 + Math.random() * 8, (Math.random() - 0.5) * 140);cg.userData.speed = 0.007 + Math.random() * 0.012;cg.visible = false;scene.add(cg);stormClouds.push(cg);}const RAIN_COUNT = 4000;const rainGeo = new THREE.BufferGeometry();const rainPositions = new Float32Array(RAIN_COUNT * 3);const rainVelocities = new Float32Array(RAIN_COUNT);for (let i = 0; i < RAIN_COUNT; i++) {rainPositions[i*3] = (Math.random() - 0.5) * 120;rainPositions[i*3+1] = Math.random() * 40;rainPositions[i*3+2] = (Math.random() - 0.5) * 120;rainVelocities[i] = 0.45 + Math.random() * 0.35;}rainGeo.setAttribute('position', new THREE.BufferAttribute(rainPositions, 3));const rainMat = new THREE.PointsMaterial({ color: 0x8899cc, size: 0.1, transparent: true, opacity: 0.45 });const rainSystem = new THREE.Points(rainGeo, rainMat);rainSystem.visible = false;scene.add(rainSystem);const SNOW_COUNT = 2000;const snowGeo = new THREE.BufferGeometry();const snowPositions = new Float32Array(SNOW_COUNT * 3);const snowDriftX = new Float32Array(SNOW_COUNT);const snowDriftZ = new Float32Array(SNOW_COUNT);for (let i = 0; i < SNOW_COUNT; i++) {snowPositions[i*3] = (Math.random() - 0.5) * 120;snowPositions[i*3+1] = Math.random() * 35;snowPositions[i*3+2] = (Math.random() - 0.5) * 120;snowDriftX[i] = (Math.random() - 0.5) * 0.012;snowDriftZ[i] = (Math.random() - 0.5) * 0.012;}snowGeo.setAttribute('position', new THREE.BufferAttribute(snowPositions, 3));const snowMat = new THREE.PointsMaterial({ color: 0xffffff, size: 0.2, transparent: true, opacity: 0.85 });const snowSystem = new THREE.Points(snowGeo, snowMat);snowSystem.visible = false;scene.add(snowSystem);const lightningLight = new THREE.PointLight(0xccddff, 0, 200);lightningLight.position.set(0, 50, 0);scene.add(lightningLight);let lightningTimer = 0;let nextLightningAt = 0;function updateWeather(weather) {currentWeather = (weather || 'sunny').toLowerCase();const isSunny = currentWeather === 'sunny' || currentWeather === 'clear';const isCloudy = currentWeather === 'cloudy';const isRainy = currentWeather === 'rainy';const isStormy = currentWeather === 'stormy';const isSnowy = currentWeather === 'snowy' || currentWeather === 'snow';const isFoggy = currentWeather === 'foggy';const precipitating = isRainy || isStormy || isSnowy;if (sunSprite.visible) {sunSprite.material.opacity = isSunny ? 1.0 : isCloudy ? 0.3 : precipitating ? 0.05 : isFoggy ? 0.35 : 0.8;const ss = isSunny ? 16 : isCloudy ? 10 : precipitating ? 6 : 14;sunSprite.scale.set(ss, ss, 1);}if (!isNight) {const wm = isSunny ? 1.0 : isCloudy ? 0.55 : isRainy ? 0.3 : isStormy ? 0.2 : isSnowy ? 0.4 : isFoggy ? 0.35 : 1.0;sunLight.intensity *= wm;ambientLight.intensity = Math.max(ambientLight.intensity * (0.5 + wm * 0.5), 0.08);hemiLight.intensity *= (0.6 + wm * 0.4);}const fairVis = !(precipitating);const fairOp = isSunny ? 0.7 : isCloudy ? 0.95 : 0.5;clouds.forEach(c => {c.visible = fairVis || isCloudy;if (!isNight) c.children.forEach(p => { p.material.opacity = fairOp; });});const showStorm = isCloudy || precipitating;const sc = isStormy ? 0x3a3a50 : isRainy ? 0x4a5560 : isSnowy ? 0x8890a0 : 0x6a7580;const so = isStormy ? 0.95 : isRainy ? 0.88 : isSnowy ? 0.8 : 0.7;stormClouds.forEach(c => {c.visible = showStorm;c.children.forEach(p => { p.material.color.set(sc); p.material.opacity = so; });});rainSystem.visible = isRainy || isStormy;rainMat.opacity = isStormy ? 0.65 : 0.4;snowSystem.visible = isSnowy;if (isFoggy && !isNight) {scene.fog = new THREE.FogExp2(0xaaaaaa, 0.018);} else if (isStormy && !isNight) {scene.fog = new THREE.FogExp2(0x333340, 0.009);} else if (isRainy && !isNight) {scene.fog = new THREE.FogExp2(0x556678, 0.007);} else if (isSnowy && !isNight) {scene.fog = new THREE.FogExp2(0x99a0a8, 0.006);}if (isSnowy && !isNight) ground.material.color.set(0xd8dce0);}// Position sun/moon based on hourfunction updateCelestials(hour) {// Sun: rises 6, peaks 12, sets 1815 unmodified lines} else {moonSprite.visible = false;}starPoints.visible = hour >= 19 || hour <= 5;starPoints.material.opacity = (hour >= 21 || hour <= 4) ? 0.9 : 0.5;}updateCelestials(10);49 unmodified linesscene.fog = new THREE.FogExp2(PALETTE.fog, 0.004);}// Window glow + building transparency at nightscene.traverse(o => {if (o.userData?.isWindow && o.material) {if (isNight) {7 unmodified lines}}});const deepNight = phase === 'night';for (const [, bldg] of buildingMeshes) {const btype = bldg.userData?.type;const isResidential = btype === 'house' || btype === 'apartment';if (!isResidential) continue;bldg.traverse(child => {if (child.isMesh && !child.userData?.isWindow && !child.userData?.isDoor) {if (deepNight) {child.material.transparent = true;child.material.opacity = 0.3;child.material.depthWrite = false;} else {child.material.transparent = false;child.material.opacity = 1.0;child.material.depthWrite = true;}}});}}// Parse simulation time string → { hour, phase }37 unmodified linesreturn g;}const FEMALE_NAMES = new Set(['elena','lila','helen','diana','priya','rosa','yuki','nina','zoe','alice','ada','mia','dara','hana','vera','nadia','petra','ling','maya','sophie','anya','clara','elsa','greta','irene','kira','marta','olga','rita','tanya','viola','xena','zara','bianca','dina','fiona','hazel','jenna',]);function createAgentMesh(agentId, agentData) {const group = new THREE.Group();const idx = getAgentIdx(agentId);1 unmodified lineconst shirtColor = AGENT_COLORS[idx % AGENT_COLORS.length];const skinColor = SKIN_COLORS[h % SKIN_COLORS.length];const hairColor = HAIR_COLORS[(h >> 3) % HAIR_COLORS.length];const genderStr = (agentData?.gender || '').toLowerCase();const isFemale = genderStr === 'female' || (!genderStr && FEMALE_NAMES.has(agentId.toLowerCase()));const wearsSkirt = isFemale;const bottomColor = wearsSkirt? SKIRT_COLORS[(h >> 8) % SKIRT_COLORS.length]: PANTS_COLORS[(h >> 8) % PANTS_COLORS.length];142 unmodified lineslet simState = {};let wsConnected = false;let ws = null;const isEmbedded = window.parent !== window;function connectWebSocket() {const protocol = location.protocol === 'https:' ? 'wss:' : 'ws:';31 unmodified linesconst agents = simState.agents || {};const locations = simState.locations || {};// Forward state to parent when embeddedif (isEmbedded) window.parent.postMessage({ type: 'state-update', state: simState, time: msg.time }, '*');// Update time displaydocument.getElementById('sim-time').textContent = msg.time || '';const weather = simState.weather || simState.clock?.weather || '';const weatherIcons = { sunny: '☀️', clear: '☀️', cloudy: '☁️', rainy: '🌧️', stormy: '⛈️', foggy: '🌫️', snowy: '🌨️', snow: '🌨️' };document.getElementById('sim-weather').textContent = weatherIcons[weather] || '';document.getElementById('sim-agents').textContent = `${Object.keys(agents).length} agents`;2 unmodified linesdocument.getElementById('sim-cost').textContent = `$${parseFloat(cost).toFixed(4)}`;}// Update sky / lighting from simulation time + weatherconst { hour, phase } = parseSimTime(msg.time || '');updateTimeOfDay(phase, hour);updateWeather(weather);// Register dynamic locationsfor (const [locId, locData] of Object.entries(locations)) {399 unmodified lines}}// Sleeping, sitting, walking, or idle animationconst agentState = mesh.userData.data?.state || '';const agentLoc = mesh.userData.data?.location || '';const isSleeping = agentState === 'sleeping';const dx2 = target ? target.x - mesh.position.x : 0;const dz2 = target ? target.z - mesh.position.z : 0;const dist = Math.sqrt(dx2 * dx2 + dz2 * dz2);const moving = dist > 0.15;const atLocation = dist < 0.3;const isSitting = !moving && atLocation && SITTING_LOCS.has(agentLoc);if (isSleeping) {mesh.rotation.x = Math.PI / 2;mesh.rotation.z = 0;mesh.position.y = 0.35;if (mesh.userData.leftLeg) mesh.userData.leftLeg.rotation.x = 0.15;if (mesh.userData.rightLeg) mesh.userData.rightLeg.rotation.x = -0.08;if (mesh.userData.leftArm) mesh.userData.leftArm.rotation.x = 0.6;if (mesh.userData.rightArm) mesh.userData.rightArm.rotation.x = 0.4;} else if (isSitting) {mesh.rotation.x = 0;mesh.position.y = 0.0;if (mesh.userData.leftLeg) mesh.userData.leftLeg.rotation.x = -Math.PI / 2;if (mesh.userData.rightLeg) mesh.userData.rightLeg.rotation.x = -Math.PI / 2;if (mesh.userData.leftArm) mesh.userData.leftArm.rotation.x = -0.3;if (mesh.userData.rightArm) mesh.userData.rightArm.rotation.x = -0.3;} else {mesh.rotation.x = 0;const walkPhase = frameCount * 0.12 + hash(agentId) * 0.5;const swing = moving ? Math.sin(walkPhase) * 0.7 : 0;if (mesh.userData.leftLeg) mesh.userData.leftLeg.rotation.x = swing;if (mesh.userData.rightLeg) mesh.userData.rightLeg.rotation.x = -swing;if (mesh.userData.leftArm) mesh.userData.leftArm.rotation.x = -swing * 0.5;if (mesh.userData.rightArm) mesh.userData.rightArm.rotation.x = swing * 0.5;mesh.position.y = moving? Math.abs(Math.sin(walkPhase * 2)) * 0.04: Math.sin(frameCount * 0.02 + hash(agentId) * 0.1) * 0.015;}}// Subtle tree sway5 unmodified lines});}// Rain animationif (rainSystem.visible) {const rp = rainGeo.attributes.position.array;const windX = currentWeather === 'stormy' ? 0.06 : 0.012;for (let i = 0; i < RAIN_COUNT; i++) {rp[i*3+1] -= rainVelocities[i];rp[i*3] += windX;if (rp[i*3+1] < 0) {rp[i*3] = (Math.random() - 0.5) * 120;rp[i*3+1] = 35 + Math.random() * 10;rp[i*3+2] = (Math.random() - 0.5) * 120;}}rainGeo.attributes.position.needsUpdate = true;}// Snow animationif (snowSystem.visible) {const sp = snowGeo.attributes.position.array;for (let i = 0; i < SNOW_COUNT; i++) {sp[i*3] += snowDriftX[i] + Math.sin(frameCount * 0.008 + i) * 0.004;sp[i*3+1] -= 0.025 + Math.random() * 0.008;sp[i*3+2] += snowDriftZ[i];if (sp[i*3+1] < 0) {sp[i*3] = (Math.random() - 0.5) * 120;sp[i*3+1] = 28 + Math.random() * 10;sp[i*3+2] = (Math.random() - 0.5) * 120;}}snowGeo.attributes.position.needsUpdate = true;}// Lightning flashesif (currentWeather === 'stormy') {if (frameCount >= nextLightningAt) {lightningLight.intensity = 10 + Math.random() * 15;lightningLight.position.set((Math.random() - 0.5) * 60, 45, (Math.random() - 0.5) * 60);lightningTimer = 2 + Math.floor(Math.random() * 5);nextLightningAt = frameCount + 90 + Math.floor(Math.random() * 250);}if (lightningTimer > 0) {lightningTimer--;lightningLight.intensity *= 0.45;if (lightningTimer <= 0) lightningLight.intensity = 0;}} else {lightningLight.intensity = 0;}// Cloud driftfor (const cloud of clouds) {cloud.position.x += cloud.userData.speed;if (cloud.position.x > 70) cloud.position.x = -70;}for (const cloud of stormClouds) {if (!cloud.visible) continue;cloud.position.x += cloud.userData.speed;if (cloud.position.x > 70) cloud.position.x = -70;}renderer.render(scene, camera);}40 unmodified lines// ============================================================// BOOT// ============================================================if (isEmbedded) {document.getElementById('status-bar').style.display = 'none';document.getElementById('controls-bar').style.display = 'none';104 unmodified linesfor (const d of demoNames) {demoAgents[d.id] = { name: d.name, location: d.location, state: 'idle', needs: {} };}let demoDay = 1;let demoMinute = 630; // 10:30const DEMO_WEATHER_CYCLE = ['sunny','sunny','sunny','cloudy','cloudy','rainy','stormy','rainy','cloudy','sunny','sunny','snowy','cloudy','sunny','foggy','sunny'];let demoWIdx = 0;function demoTimeStr() {const hh = Math.floor(demoMinute / 60);const mm = demoMinute % 60;const phase = hh >= 5 && hh < 7 ? 'dawn' : hh >= 7 && hh < 12 ? 'morning' : hh >= 12 && hh < 17 ? 'afternoon' : hh >= 17 && hh < 20 ? 'evening' : 'night';return `Day ${demoDay}, ${String(hh).padStart(2,'0')}:${String(mm).padStart(2,'0')} (${phase})`;}const agentHome = {};for (const d of demoNames) {agentHome[d.id] = d.location;}const residentialLocs = Object.entries(LOCATION_POSITIONS).filter(([, v]) => v.type === 'house' || v.type === 'apartment').map(([k]) => k);const publicLocs = Object.keys(LOCATION_POSITIONS).filter(k => !k.startsWith('street'));handleStateUpdate({type: 'tick', time: demoTimeStr(),state: { agents: demoAgents, locations: {}, weather: DEMO_WEATHER_CYCLE[0] }});document.getElementById('sim-agents').textContent = `${demoNames.length} agents (demo)`;setInterval(() => {if (wsConnected) return;demoMinute += 20;if (demoMinute >= 1440) { demoMinute -= 1440; demoDay++; }const hh = Math.floor(demoMinute / 60);if (demoMinute % 60 === 0 && hh % 3 === 0) {demoWIdx = (demoWIdx + 1) % DEMO_WEATHER_CYCLE.length;}const w = DEMO_WEATHER_CYCLE[demoWIdx];const badW = w === 'rainy' || w === 'stormy' || w === 'snowy';const isNightTime = hh >= 22 || hh < 6;const isLateEvening = hh >= 20 && hh < 22;const agents = Object.keys(demoAgents);if (isNightTime) {for (const who of agents) {const home = agentHome[who] || residentialLocs[hash(who) % residentialLocs.length];demoAgents[who].location = home;demoAgents[who].state = 'sleeping';}} else if (isLateEvening) {const goHomeCount = Math.floor(agents.length * 0.6);for (let i = 0; i < goHomeCount; i++) {const who = agents[Math.floor(Math.random() * agents.length)];const home = agentHome[who] || residentialLocs[hash(who) % residentialLocs.length];demoAgents[who].location = home;demoAgents[who].state = 'resting';}const moveCount = 2 + Math.floor(Math.random() * 3);for (let i = 0; i < moveCount; i++) {const who = agents[Math.floor(Math.random() * agents.length)];if (demoAgents[who].state !== 'resting') {demoAgents[who].location = publicLocs[Math.floor(Math.random() * publicLocs.length)];demoAgents[who].state = 'idle';}}} else if (badW) {const stayInCount = Math.floor(agents.length * 0.7);for (let i = 0; i < stayInCount; i++) {const who = agents[Math.floor(Math.random() * agents.length)];const home = agentHome[who] || residentialLocs[hash(who) % residentialLocs.length];demoAgents[who].location = home;demoAgents[who].state = 'sheltering';}const moveCount = 1 + Math.floor(Math.random() * 2);for (let i = 0; i < moveCount; i++) {const who = agents[Math.floor(Math.random() * agents.length)];demoAgents[who].location = publicLocs[Math.floor(Math.random() * publicLocs.length)];demoAgents[who].state = 'idle';}} else {const moveCount = 3 + Math.floor(Math.random() * 5);for (let i = 0; i < moveCount; i++) {const who = agents[Math.floor(Math.random() * agents.length)];demoAgents[who].location = publicLocs[Math.floor(Math.random() * publicLocs.length)];demoAgents[who].state = 'idle';}}handleStateUpdate({type: 'tick', time: demoTimeStr(),state: { agents: demoAgents, locations: {}, weather: w }});}, 2500);}// Hide zoom hint after a few seconds
40 unmodified lines41424344454647526 unmodified lines5745755765775785792153 unmodified lines27332734273527362737273827394 unmodified lines2744274527462747274827492750275127522753275427551148 unmodified lines390439053906390739083909391040 unmodified lines.dot { width: 8px; height: 8px; border-radius: 50%; display: inline-block; }.dot.green { background: #4ecca3; } .dot.yellow { background: #f0c040; } .dot.red { background: #e94560; }#main { display: flex; flex-direction: row; height: calc(100vh - 50px); }#viewport-3d { flex: 7; position: relative; min-width: 0; }#viewport-3d iframe { width: 100%; height: 100%; border: none; display: block; }#canvas-container { display: none; }#cityCanvas { display: none; }526 unmodified linesconst WEATHER_ICONS = {sunny:'\u2600\uFE0F', clear:'\u2600\uFE0F', cloudy:'\u2601\uFE0F',rainy:'\uD83C\uDF27\uFE0F', stormy:'\u26C8\uFE0F', foggy:'\uD83C\uDF2B\uFE0F',};const SKY = {2153 unmodified linesconst mayorBadge = a.is_mayor ? ' \uD83C\uDFDB\uFE0F' : '';const ageStr = a.age != null ? ` (${a.age})` : '';return `<div class="agent-list-item" onclick="selectedAgentId='${aid}';fetchAgentDetail('${aid}');" style="${isDead ? 'opacity:0.5' : ''}"><span class="agent-dot" style="background:${color}"></span><span style="font-size:13px">${gi}</span><div class="agent-info">4 unmodified lines}).join('')}`;}async function fetchAgentDetail(agentId) {try {const res=await fetch(`${API_BASE}/agents/${agentId}`);if(!res.ok) return;renderAgentDetail(await res.json());} catch(e){}}function renderAgentDetail(data) {1148 unmodified linesif (e.data?.type === 'agent-select' && e.data.agentId) {selectedAgentId = e.data.agentId;switchTab('agents');fetchAgentDetail(e.data.agentId);}});40 unmodified lines41424344454647526 unmodified lines5745755765775785795802153 unmodified lines27342735273627372738273927404 unmodified lines274527462747274827492750275127522753275427552756275727582759276027612762276327641148 unmodified lines391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394040 unmodified lines.dot { width: 8px; height: 8px; border-radius: 50%; display: inline-block; }.dot.green { background: #4ecca3; } .dot.yellow { background: #f0c040; } .dot.red { background: #e94560; }#main { display: flex; flex-direction: row; height: calc(100vh - 50px); }#viewport-3d { flex: 6; position: relative; min-width: 0; }#viewport-3d iframe { width: 100%; height: 100%; border: none; display: block; }#canvas-container { display: none; }#cityCanvas { display: none; }526 unmodified linesconst WEATHER_ICONS = {sunny:'\u2600\uFE0F', clear:'\u2600\uFE0F', cloudy:'\u2601\uFE0F',rainy:'\uD83C\uDF27\uFE0F', stormy:'\u26C8\uFE0F', foggy:'\uD83C\uDF2B\uFE0F',snowy:'🌨️', snow:'🌨️',};const SKY = {2153 unmodified linesconst mayorBadge = a.is_mayor ? ' \uD83C\uDFDB\uFE0F' : '';const ageStr = a.age != null ? ` (${a.age})` : '';return `<div class="agent-list-item" onclick="selectedAgentId='${aid}';selectAgentFromList('${aid}');" style="${isDead ? 'opacity:0.5' : ''}"><span class="agent-dot" style="background:${color}"></span><span style="font-size:13px">${gi}</span><div class="agent-info">4 unmodified lines}).join('')}`;}function selectAgentFromList(agentId) {fetchAgentDetail(agentId);send3d('select-agent');}async function fetchAgentDetail(agentId) {try {const res=await fetch(`${API_BASE}/agents/${agentId}`);if(!res.ok) throw 0;renderAgentDetail(await res.json());} catch(e){const ag = agents[agentId];if (ag) renderAgentDetail({ ...ag, id: agentId, memories: [], relationships: [], recent_memories: [] });}}function renderAgentDetail(data) {1148 unmodified linesif (e.data?.type === 'agent-select' && e.data.agentId) {selectedAgentId = e.data.agentId;switchTab('agents');// In demo mode (no server), show inline detail from iframe stateconst ag = agents[e.data.agentId];if (ag) {renderAgentDetail({ ...ag, id: e.data.agentId, memories: [], relationships: [] });} else {fetchAgentDetail(e.data.agentId);}}if (e.data?.type === 'state-update' && e.data.state) {const s = e.data.state;// Parse time string from iframeconst timeMatch = (e.data.time || '').match(/Day\s+(\d+),\s*(\d+:\d+)\s*\((\w+)\)/i);const dayNum = timeMatch ? parseInt(timeMatch[1]) : 1;const timeStr = timeMatch ? timeMatch[2] : '10:30';const tod = timeMatch ? timeMatch[3] : 'morning';processStateData({clock: { day: dayNum, time_str: timeStr, time_of_day: tod, total_ticks: Date.now() },agents: s.agents || {},weather: s.weather || 'sunny',active_conversations: 0,llm_usage: '',});}});