Prompt specification
Build or customize the Three.js 3D scene "Greenhouse climate-rule simulator" inside the active workspace.
Engineering Constraints:
1. Runtime & Orbit: Use Three.js r160 with OrbitControls (damping enabled) and ACESFilmicToneMapping.
2. Frame Timing: Drive all motion strictly with clock.getDelta() so animation speed is FPS-independent.
3. Viewport Hygiene: Handle window resize cleanly, cap DPR at Math.min(window.devicePixelRatio, 2), and dispose geometries/materials/renderer on unmount.
Scene Metadata:
Scene: Greenhouse climate-rule simulator
Category: Biology & Nature · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/greenhouse-climate-rule-simulator-x1072
Scene Description Prompt:
Make a standalone HTML scene with Three.js from cdnjs that depicts greenhouse ventilation. Create a toy enclosure with explicitly fictional heat and ventilation rates; users open vents and shade panels while displayed state variables respond transparently to the stated rules. Low-poly.
Working Three.js Starter (greenhouse-climate-rule-simulator-x1072):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Greenhouse Ventilation — Fictional Toy Model</title>
<style>
:root{
--bg:#0c1116; --panel:#121a22; --line:#243140; --txt:#dde6ef; --dim:#8fa3b8;
--cool:#7fd1ff; --warm:#ffb066; --green:#8ee08a; --accent:#7fd1ff;
}
*{box-sizing:border-box}
html,body{margin:0;height:100%;overflow:hidden;background:var(--bg);color:var(--txt);
font-family:ui-sans-serif,system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;}
#scene{position:fixed;inset:0;display:block;touch-action:none}
#panel{
position:fixed;top:0;left:0;width:352px;height:100%;overflow-y:auto;
background:rgba(13,19,26,.93);border-right:1px solid var(--line);
padding:14px 16px 40px;backdrop-filter:blur(8px);
}
#panel::-webkit-scrollbar{width:8px}#panel::-webkit-scrollbar-thumb{background:#26323f;border-radius:4px}
h1{font-size:17px;margin:0 0 2px;letter-spacing:.2px}
h1 span{color:var(--dim);font-weight:400;font-size:12px;display:block;margin-top:3px}
h2{font-size:11px;text-transform:uppercase;letter-spacing:.13em;color:var(--dim);
margin:18px 0 8px;border-bottom:1px solid var(--line);padding-bottom:5px}
h2 small{text-transform:none;letter-spacing:0;color:#5f7386;font-weight:400;margin-left:6px}
.sub{font-size:11.5px;color:var(--dim);margin:8px 0 12px;line-height:1.45}
.stats{display:grid;grid-template-columns:repeat(3,1fr);gap:8px}
.stat{background:#0f1720;border:1px solid var(--line);border-radius:8px;padding:8px 9px}
.stat .label{font-size:10px;color:var(--dim);text-transform:uppercase;letter-spacing:.08em}
.stat .val{font-size:26px;font-weight:600;font-variant-numeric:tabular-nums;line-height:1.15;margin-top:2px}
.stat .unit{font-size:10px;color:var(--dim)}
#statT{color:var(--warm)} #statRH{color:var(--cool)} #statCO2{color:var(--green)}
.row{display:flex;align-items:center;gap:8px;width:100%;text-align:left;cursor:pointer;
background:#0f1720;border:1px solid var(--line);color:var(--txt);border-radius:7px;
padding:7px 9px;margin-bottom:6px;font-size:12.5px;font-family:inherit;transition:.15s}
.row:hover{border-color:#3a4d61;background:#131e29}
.row .sw{width:22px;height:12px;border-radius:7px;background:#2a3644;position:relative;flex:0 0 auto;transition:.18s}
.row .sw::after{content:"";position:absolute;top:1px;left:1px;width:10px;height:10px;border-radius:50%;
background:#7c8b9b;transition:.18s}
.row.on{background:#10241f;border-color:#2c6a4f}
.row.on .sw{background:#2f7a58}.row.on .sw::after{left:11px;background:#b6f5cf}
.row .name{flex:1}
.row .k{color:#63798d;font-size:11px;font-variant-numeric:tabular-nums}
.row .pct{color:var(--dim);font-size:11px;width:38px;text-align:right;font-variant-numeric:tabular-nums}
.row.on .pct{color:#b6f5cf}
label{display:block;font-size:12px;color:var(--dim);margin:10px 0}
label span{float:right;color:var(--txt);font-variant-numeric:tabular-nums}
input[type=range]{width:100%;margin-top:6px;accent-color:#3f8f6d}
select,button#reset{width:100%;margin-top:6px;background:#0f1720;color:var(--txt);
border:1px solid var(--line);border-radius:7px;padding:7px;font-family:inherit;font-size:12.5px;cursor:pointer}
button#reset:hover{border-color:#3a4d61}
.calc{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:10.8px;
line-height:1.5;color:#9fb6c9;background:#0c131a;border:1px solid var(--line);
border-radius:7px;padding:7px 9px;margin-bottom:6px;white-space:pre-wrap;word-break:break-word}
.calc b{color:var(--accent);font-weight:600}
.flows{display:grid;grid-template-columns:1fr 1fr;gap:5px 10px;font-size:11.5px;color:var(--dim);
font-variant-numeric:tabular-nums}
.flows span{color:var(--txt)}
#chart{width:100%;height:118px;display:block;border:1px solid var(--line);border-radius:7px;background:#0c131a}
.legend{font-size:10.5px;color:var(--dim);display:flex;gap:12px;margin-top:5px}
.legend i{display:inline-block;width:9px;height:9px;border-radius:2px;margin-right:4px}
pre.rules{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:10.4px;
line-height:1.55;color:#93aabc;background:#0c131a;border:1px solid var(--line);
border-radius:7px;padding:9px 10px;white-space:pre-wrap;margin:0}
.hint{position:fixed;left:50%;transform:translateX(-50%);bottom:14px;z-index:5;
background:rgba(12,18,25,.82);border:1px solid var(--line);color:var(--dim);
font-size:11.5px;padding:7px 14px;border-radius:20px;pointer-events:none}
.hint b{color:var(--txt);font-weight:600}
@media (max-width:760px){#panel{width:290px} .hint{display:none}}
</style>
</head>
<body>
<canvas id="scene"></canvas>
<aside id="panel">
<h1>Greenhouse Ventilation<span>Low-poly toy — every rate below is invented</span></h1>
<p class="sub">Open the vents and roll out the shade panels; the readouts move exactly as the
written equations say, and the live computation box shows the substituted numbers.</p>
<div class="stats">
<div class="stat"><div class="label">Air temp</div><div class="val" id="statT">24.0</div><div class="unit">°C</div></div>
<div class="stat"><div class="label">Humidity</div><div class="val" id="statRH">62</div><div class="unit">% RH</div></div>
<div class="stat"><div class="label">CO₂</div><div class="val" id="statCO2">700</div><div class="unit">ppm</div></div>
</div>
<h2>Openings <small>button or click the part in 3D</small></h2>
<div id="openings"></div>
<h2>Shade panels <small>4 panels, roof</small></h2>
<div id="shades"></div>
<h2>Environment</h2>
<label>Outside temperature <span id="outVal">18.0 °C</span>
<input type="range" id="outside" min="8" max="32" step="0.5" value="18"></label>
<label>Toy sun gain <span id="sunVal">1.00 ×</span>
<input type="range" id="sun" min="0" max="1.5" step="0.05" value="1"></label>
<label>Simulation speed
<select id="speed">
<option value="0">Paused</option>
<option value="1">1× — 1 sim-minute / real second</option>
<option value="5" selected>5× — 5 sim-minutes / real second</option>
<option value="20">20× — 20 sim-minutes / real second</option>
</select></label>
<button id="reset">Reset toy state</button>
<h2>Live computation <small>exactly the coded equations</small></h2>
<div class="calc" id="calcT"></div>
<div class="calc" id="calcRH"></div>
<div class="calc" id="calcCO2"></div>
<div class="flows" id="flows"></div>
<h2>History</h2>
<canvas id="chart"></canvas>
<div class="legend"><span><i style="background:#ffb066"></i>Temperature (0–50 °C)</span>
<span><i style="background:#7fd1ff"></i>Humidity (0–100 %)</span></div>
<h2>The fictional rules</h2>
<pre class="rules">MODEL CONSTANTS (all invented for demonstration)
C = 22.0 thermal capacity [toy units / °C]
Q_sun0 = 9.0 toy heat units/min at sun = 1, no shade
shade blocking = 0.70 of the toy sun gain
V_base = 0.10 always-on leakage
k_loss = 0.45 wall-loss coefficient
M_evap = 6.5 toy moisture units/min (watering + evaporation)
RH_scale = 30.0
RH_drain = 0.076 + 0.05·Vn
CO2_out = 420 ppm ; air exchange e = 0.08 + 0.25·Vn
photosynthesis = 55·(1 − 0.70·S) ; respiration = 15 ppm/min
STATE VARIABLES
T = air temperature (°C)
RH = relative humidity (%)
CO2= greenhouse CO2 (ppm)
G = toy growth points (integrates net photosynthesis)
OPENINGS (coefficient k, opening fraction o ∈ [0,1])
ridge vent k=0.60 | side vent L k=0.35 | side vent R k=0.35
end door k=0.25 | exhaust fan k=0.80
Vn = Σ k·o S = (Σ shade deploy)/4
RULES (per simulated minute)
q_sun = 9.0·sun·(1 − 0.70·S)
q_vent = (0.10 + Vn)·(T − T_out)
q_loss = 0.45·(T − T_out)
dT/dt = (q_sun − q_vent − q_loss) / 22.0
dRH/dt = (6.5 − (0.076 + 0.05·Vn)·RH) / 30.0
dCO2/dt = (0.08 + 0.25·Vn)·(420 − CO2)
+ (55·(1 − 0.70·S) − 15)
dG/dt = (55·(1 − 0.70·S) − 15) / 100
Nothing here is real agronomy: the numbers are a made-up
toy so that cause and effect stay obvious.</pre>
</aside>
<div class="hint"><b>Drag</b> orbit · <b>Scroll</b> zoom · <b>Right-drag</b> pan · <b>Click</b> a vent/shade to toggle it · <b>Space</b> pause</div>
<script type="module">
import * as THREE from 'https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js';
/* ============================================================
1. THE FICTIONAL MODEL (constants + rules, see panel)
============================================================ */
const C = 22.0; // thermal capacity, toy units per °C
const Q_SUN0 = 9.0; // toy heat units/min at sun = 1, no shade
const SHADE_EFF = 0.70; // shade blocks 70% of the toy sun gain
const V_BASE = 0.10; // always-on leakage
const LOSS_K = 0.45; // wall loss coefficient
const M_EVAP = 6.5; // toy moisture units/min
const RH_SCALE = 30.0;
const RH_DRAIN0 = 0.076, RH_DRAIN_V = 0.05;
const CO2_OUT = 420; // outdoor CO2 ppm
const E_BASE = 0.08, E_V = 0.25;
const PHOTO0 = 55, RESP = 15;
const openings = [
{id:'ridge', label:'Ridge vent', coeff:0.60, open:0, target:0},
{id:'sideL', label:'Side vent (left)', coeff:0.35, open:0, target:0},
{id:'sideR', label:'Side vent (right)',coeff:0.35, open:0, target:0},
{id:'door', label:'End door', coeff:0.25, open:0, target:0},
{id:'fan', label:'Exhaust fan', coeff:0.80, open:0, target:0},
];
const shades = [
{id:'sh1', label:'Roof shade 1 (front)', deploy:0, target:0},
{id:'sh2', label:'Roof shade 2 (front)', deploy:0, target:0},
{id:'sh3', label:'Roof shade 3 (back)', deploy:0, target:0},
{id:'sh4', label:'Roof shade 4 (back)', deploy:0, target:0},
];
const S0 = {T:24.0, RH:62, CO2:700, G:0, out:18, sun:1.0};
const state = {T:S0.T, RH:S0.RH, CO2:S0.CO2, G:S0.G, out:S0.out, sun:S0.sun};
let simMinutes = 0, speed = 5;
const derived = {Vn:0, S:0, qSun:0, qVent:0, qLoss:0, netCO2:0, e:0, dT:0, dRH:0, dCO2:0};
function computeDerived(){
let Vn = 0; for(const o of openings) Vn += o.coeff * o.open;
let sd = 0; for(const p of shades) sd += p.deploy;
const S = sd / shades.length;
const qSun = Q_SUN0 * state.sun * (1 - SHADE_EFF * S);
const qVent = (V_BASE + Vn) * (state.T - state.out);
const qLoss = LOSS_K * (state.T - state.out);
const netCO2 = PHOTO0 * (1 - SHADE_EFF * S) - RESP;
const e = E_BASE + E_V * Vn;
Object.assign(derived, {
Vn, S, qSun, qVent, qLoss, netCO2, e,
dT: (qSun - qVent - qLoss) / C,
dRH: (M_EVAP - (RH_DRAIN0 + RH_DRAIN_V * Vn) * state.RH) / RH_SCALE,
dCO2: e * (CO2_OUT - state.CO2) + netCO2,
});
return derived;
}
function stepSim(dtMin){
computeDerived();
state.T += derived.dT * dtMin;
state.RH += derived.dRH * dtMin;
state.CO2 += derived.dCO2 * dtMin;
state.G += (derived.netCO2 / 100) * dtMin;
state.T = THREE.MathUtils.clamp(state.T, -20, 70);
state.RH = THREE.MathUtils.clamp(state.RH, 0, 100);
state.CO2 = THREE.MathUtils.clamp(state.CO2, 200, 3000);
simMinutes += dtMin;
}
/* ============================================================
2. RENDERER / SCENE / CUSTOM CAMERA RIG
============================================================ */
const canvas = document.getElementById('scene');
const renderer = new THREE.WebGLRenderer({canvas, antialias:true});
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.05;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x8fc6e6);
scene.fog = new THREE.Fog(0x8fc6e6, 40, 130);
const camera = new THREE.PerspectiveCamera(48, 1, 0.1, 300);
/* hand-rolled orbit controls (no addons) */
const cam = {theta:0.62, phi:1.03, radius:23, target:new THREE.Vector3(0,2.0,0)};
const camHome = {theta:0.62, phi:1.03, radius:23, target:new THREE.Vector3(0,2.0,0)};
function applyCamera(){
const sp = Math.sin(cam.phi), cp = Math.cos(cam.phi);
camera.position.set(
cam.target.x + cam.radius*sp*Math.sin(cam.theta),
cam.target.y + cam.radius*cp,
cam.target.z + cam.radius*sp*Math.cos(cam.theta));
camera.lookAt(cam.target);
}
applyCamera();
const hemi = new THREE.HemisphereLight(0xbfe4ff, 0x4a5a3c, 0.55); scene.add(hemi);
const sunLight = new THREE.DirectionalLight(0xfff2d8, 1.2);
sunLight.position.set(14, 18, 10);
sunLight.castShadow = true;
sunLight.shadow.mapSize.set(1024,1024);
sunLight.shadow.camera.left=-16; sunLight.shadow.camera.right=16;
sunLight.shadow.camera.top=16; sunLight.shadow.camera.bottom=-16;
sunLight.shadow.camera.far=60; sunLight.shadow.bias=-0.0012;
scene.add(sunLight);
const fill = new THREE.DirectionalLight(0x9fc7ff, 0.35); fill.position.set(-12,8,-10); scene.add(fill);
const insideGlow = new THREE.PointLight(0xffb066, 0.0, 12, 2); insideGlow.position.set(0,2.4,0); scene.add(insideGlow);
/* ============================================================
3. LOW-POLY GREENHOUSE
============================================================ */
const M = {
frame : new THREE.MeshStandardMaterial({color:0xeef3f6, roughness:.55, metalness:.05, flatShading:true}),
glass : new THREE.MeshStandardMaterial({color:0xbfe4f5, roughness:.06, metalness:0, transparent:true,
opacity:.22, side:THREE.DoubleSide, depthWrite:false}),
wood : new THREE.MeshStandardMaterial({color:0xb07a4a, roughness:.85, flatShading:true}),
shade : new THREE.MeshStandardMaterial({color:0xf1e6c9, roughness:.95, side:THREE.DoubleSide, flatShading:true}),
bench : new THREE.MeshStandardMaterial({color:0x9a7b52, roughness:.9, flatShading:true}),
pot : new THREE.MeshStandardMaterial({color:0xc0663f, roughness:.9, flatShading:true}),
leaf : new THREE.MeshStandardMaterial({color:0x4f9b46, roughness:.9, flatShading:true}),
leaf2 : new THREE.MeshStandardMaterial({color:0x66b04f, roughness:.9, flatShading:true}),
soil : new THREE.MeshStandardMaterial({color:0x5a4433, roughness:1, flatShading:true}),
ground: new THREE.MeshStandardMaterial({color:0x3d6b45, roughness:1, flatShading:true}),
path : new THREE.MeshStandardMaterial({color:0x9d917a, roughness:1, flatShading:true}),
trunk : new THREE.MeshStandardMaterial({color:0x6b4a32, roughness:1, flatShading:true}),
dark : new THREE.MeshStandardMaterial({color:0x39424c, roughness:.6, metalness:.3, flatShading:true}),
};
function box(w,h,d,mat,x=0,y=0,z=0){
const m = new THREE.Mesh(new THREE.BoxGeometry(w,h,d), mat);
m.position.set(x,y,z); m.castShadow = true; m.receiveShadow = true; scene.add(m); return m;
}
const GH = {w:8, d:6, h:3.0, ridge:4.6};
const slopeLen = Math.hypot(GH.d/2, GH.ridge-GH.h); // 3.4
const theta = Math.atan2(GH.ridge-GH.h, GH.d/2); // ~28°
/* ground + path */
const ground = new THREE.Mesh(new THREE.PlaneGeometry(160,160), M.ground);
ground.rotation.x = -Math.PI/2; ground.position.y=-0.02; ground.receiveShadow = true; scene.add(ground);
box(4.2,0.03,26, M.path, 0,0.005,0).receiveShadow = true;
/* frame: posts, sills, beams */
const postXs=[-4,-2,0,2,4], postZs=[-3,-1.5,0,1.5,3];
postZs.forEach(z=>postXs.forEach(x=>box(0.13,GH.h,0.13,M.frame,x,GH.h/2,z)));
postXs.forEach(x=>postZs.forEach(z=>{ if(z!==-3&&z!==3) box(0.13,GH.h,0.13,M.frame,x,GH.h/2,z); }));
box(GH.w+0.14,0.14,0.14,M.frame,0,0.07,-GH.d/2); box(GH.w+0.14,0.14,0.14,M.frame,0,0.07,GH.d/2);
box(0.14,0.14,GH.d+0.14,M.frame,-GH.w/2,0.07,0); box(0.14,0.14,GH.d+0.14,M.frame,GH.w/2,0.07,0);
box(GH.w+0.14,0.13,0.13,M.frame,0,GH.h,-GH.d/2); box(GH.w+0.14,0.13,0.13,M.frame,0,GH.h,GH.d/2);
box(0.13,0.13,GH.d+0.14,M.frame,-GH.w/2,GH.h,0); box(0.13,0.13,GH.d+0.14,M.frame,GH.w/2,GH.h,0);
box(GH.w+0.16,0.15,0.15,M.frame,0,GH.ridge,0);
/* roof slopes (groups rotated about X) + rafters + glass */
const slopeGroups = {};
function makeSlope(sign){
const g = new THREE.Group(); g.position.set(0,GH.ridge,0); g.rotation.x = sign*theta; scene.add(g);
const glass = new THREE.Mesh(new THREE.BoxGeometry(GH.w,0.04,slopeLen), M.glass);
glass.position.set(0,0,sign*slopeLen/2); g.add(glass);
postXs.forEach(x=>{
const r = new THREE.Mesh(new THREE.BoxGeometry(0.11,0.11,slopeLen), M.frame);
r.position.set(x,0.06,sign*slopeLen/2); r.castShadow=true; g.add(r);
});
return g;
}
slopeGroups.front = makeSlope(+1);
slopeGroups.back = makeSlope(-1);
/* walls: glass slabs + gable triangles */
box(0.04,GH.h,GH.d,M.glass,-GH.w/2,GH.h/2,0);
box(0.04,GH.h,GH.d,M.glass, GH.w/2,GH.h/2,0);
box(GH.w,GH.h,0.04,M.glass,0,GH.h/2,-GH.d/2);
box(GH.w,GH.h,0.04,M.glass,0,GH.h/2, GH.d/2);
function gable(z){
const s = new THREE.Shape(); s.moveTo(-GH.w/2,GH.h); s.lineTo(GH.w/2,GH.h); s.lineTo(0,GH.ridge); s.closePath();
const g = new THREE.Mesh(new THREE.ShapeGeometry(s), M.glass);
g.position.z=z; scene.add(g);
}
gable(-GH.d/2); gable(GH.d/2);
/* ---------------- controllable parts ---------------- */
const pickables = [];
function pickable(mesh, kind, id){
mesh.userData.kind = kind; mesh.userData.id = id; pickables.push(mesh); return mesh;
}
/* ridge vent: hinges at the ridge, lifts over the back slope */
const ridgeVent = new THREE.Group(); ridgeVent.position.set(0,GH.ridge+0.06,0); scene.add(ridgeVent);
const ridgePanel = new THREE.Mesh(new THREE.BoxGeometry(3.0,0.06,1.4), M.frame.clone());
ridgePanel.material.color.set(0xdde7ec); ridgePanel.position.set(0,0.02,-0.7);
ridgePanel.castShadow=true; ridgeVent.add(ridgePanel);
pickable(ridgePanel,'opening','ridge');
/* side vents: hinge at top of side wall, swing outward */
function sideVent(id, x, z, dir){
const g = new THREE.Group(); g.position.set(x,GH.h,z); scene.add(g);
const p = new THREE.Mesh(new THREE.BoxGeometry(0.07,1.25,2.3), M.frame.clone());
p.material.color.set(0xdde7ec); p.position.set(0,-0.63,0); p.castShadow=true; g.add(p);
const bar = new THREE.Mesh(new THREE.BoxGeometry(0.10,1.25,0.10), M.frame);
bar.position.set(0,-0.63,-1.15); g.add(bar);
pickable(p,'opening',id);
return {group:g, dir};
}
const svL = sideVent('sideL',-GH.w/2,-1.1,-1);
const svR = sideVent('sideR', GH.w/2, 1.1, 1);
/* end door on the front gable, swings outward */
const door = new THREE.Group(); door.position.set(1.4,0,GH.d/2+0.06); scene.add(door);
const doorPanel = new THREE.Mesh(new THREE.BoxGeometry(1.2,2.25,0.08), M.wood.clone());
doorPanel.position.set(0.6,1.12,0); doorPanel.castShadow=true; door.add(doorPanel);
const doorGlass = new THREE.Mesh(new THREE.BoxGeometry(0.85,0.9,0.04), M.glass);
doorGlass.position.set(0.6,1.62,0.05); door.add(doorGlass);
const knob = new THREE.Mesh(new THREE.BoxGeometry(0.08,0.08,0.08), M.dark);
knob.position.set(1.08,1.12,0.07); door.add(knob);
pickable(doorPanel,'opening','door');
/* exhaust fan on the back wall */
const fanGroup = new THREE.Group(); fanGroup.position.set(-2.2,1.8,-GH.d/2-0.1); scene.add(fanGroup);
const housing = new THREE.Mesh(new THREE.CylinderGeometry(0.38,0.38,0.22,12), M.dark);
housing.rotation.x = Math.PI/2; housing.castShadow=true; fanGroup.add(housing);
const fanBlades = new THREE.Group(); fanBlades.position.z=-0.16; fanGroup.add(fanBlades);
for(let i=0;i<4;i++){
const b = new THREE.Mesh(new THREE.BoxGeometry(0.62,0.10,0.04), M.frame);
b.rotation.z = i*Math.PI/2; b.position.set(Math.cos(i*Math.PI/2)*0.16, Math.sin(i*Math.PI/2)*0.16, 0);
fanBlades.add(b);
}
const fanRing = new THREE.Mesh(new THREE.TorusGeometry(0.40,0.05,4,14), M.dark);
fanGroup.add(fanRing);
pickable(housing,'opening','fan');
/* shade panels: fabric rolls out over the roof slope */
const shadeMeshes = [];
function makeShade(id, sign, xCenter){
const g = new THREE.Group(); g.position.set(xCenter,GH.ridge+0.10,0); g.rotation.x = sign*theta; scene.add(g);
const m = new THREE.Mesh(new THREE.BoxGeometry(3.0,0.05,1), M.shade.clone());
m.castShadow=true; g.add(m); pickable(m,'shade',id);
shadeMeshes.push({group:g, mesh:m, sign, len:slopeLen*0.92});
return m;
}
makeShade('sh1',+1,-2.1); makeShade('sh2',+1, 2.1);
makeShade('sh3',-1,-2.1); makeShade('sh4',-1, 2.1);
/* benches, pots, plants */
const plantGroups = [];
let seed = 7; const rnd = ()=> (seed = (seed*16807)%2147483647)/2147483647;
for(const bz of [-1.5, 1.5]){
box(6.4,0.10,0.85,M.bench,0,0.92,bz);
for(const bx of [-2.7,-0.9,0.9,2.7]) for(const bz2 of [bz-0.3,bz+0.3])
box(0.10,0.90,0.10,M.bench,bx,0.45,bz2);
for(let i=0;i<6;i++){
const px = -2.75 + i*1.1;
const pot = new THREE.Mesh(new THREE.CylinderGeometry(0.20,0.15,0.30,8), M.pot);
pot.position.set(px,1.12,bz); pot.castShadow=true; scene.add(pot);
const grp = new THREE.Group(); grp.position.set(px,1.26,bz); scene.add(grp);
const stem = new THREE.Mesh(new THREE.CylinderGeometry(0.035,0.045,0.34,6), M.leaf2);
stem.position.y=0.17; grp.add(stem);
const f1 = new THREE.Mesh(new THREE.IcosahedronGeometry(0.26,0), i%2?M.leaf:M.leaf2);
f1.position.set(0,0.46,0); f1.scale.set(1,1.25,1); f1.castShadow=true; grp.add(f1);
const f2 = new THREE.Mesh(new THREE.IcosahedronGeometry(0.18,0), M.leaf);
f2.position.set(0.12,0.62,0.06); f2.castShadow=true; grp.add(f2);
plantGroups.push(grp);
}
}
/* outside scenery: low-poly trees + rocks */
for(const [tx,tz,s] of [[-12,-9,1.4],[13,-11,1.1],[-13,7,1.0],[14,8,1.5],[0,-16,1.2]]){
const t = new THREE.Group(); t.position.set(tx,0,tz); t.scale.setScalar(s); scene.add(t);
const trunk = new THREE.Mesh(new THREE.CylinderGeometry(0.22,0.3,1.6,6), M.trunk);
trunk.position.y=0.8; trunk.castShadow=true; t.add(trunk);
for(let k=0;k<2;k++){
const c = new THREE.Mesh(new THREE.ConeGeometry(1.1-k*0.3,1.8,6), k?M.leaf2:M.leaf);
c.position.y=1.9+k*1.0; c.castShadow=true; t.add(c);
}
}
for(let i=0;i<14;i++){
const r = new THREE.Mesh(new THREE.DodecahedronGeometry(0.25+rnd()*0.3,0), M.path);
r.position.set((rnd()-0.5)*40,0.1,(rnd()-0.5)*40); r.rotation.set(rnd()*3,rnd()*3,rnd()*3);
r.castShadow=true; scene.add(r);
}
/* interior "air" tint box, driven by temperature */
const airBox = new THREE.Mesh(new THREE.BoxGeometry(GH.w-0.3,GH.h-0.15,GH.d-0.3),
new THREE.MeshBasicMaterial({color:0x9fd0ff, transparent:true, opacity:.07, depthWrite:false}));
airBox.position.set(0,(GH.h-0.15)/2,0); scene.add(airBox);
/* ============================================================
4. PARTICLES: warm air leaving open vents + rising heat motes
============================================================ */
const pGeo = new THREE.TetrahedronGeometry(0.09);
const pMat = new THREE.MeshBasicMaterial({color:0xffc27a, transparent:true, opacity:.9});
const particles = [];
for(let i=0;i<90;i++){
const m = new THREE.Mesh(pGeo,pMat); m.visible=false; scene.add(m);
particles.push({mesh:m, active:false, life:0, vel:new THREE.Vector3()});
}
const ventAnchors = {
ridge:{pos:new THREE.Vector3(0,GH.ridge+0.6,-0.5), dir:new THREE.Vector3(0,0.75,-0.65)},
sideL:{pos:new THREE.Vector3(-GH.w/2-0.2,GH.h-0.6,-1.1), dir:new THREE.Vector3(-1,0.15,0)},
sideR:{pos:new THREE.Vector3( GH.w/2+0.2,GH.h-0.6, 1.1), dir:new THREE.Vector3( 1,0.15,0)},
door :{pos:new THREE.Vector3(2.0,1.1,GH.d/2+0.3), dir:new THREE.Vector3(0,0.1,1)},
fan :{pos:new THREE.Vector3(-2.2,1.8,-GH.d/2-0.35), dir:new THREE.Vector3(0,0,-1)},
};
let spawnAcc = 0;
function updateParticles(dt, Vn){
spawnAcc += dt * (6 + 46*Vn);
while(spawnAcc >= 1){
spawnAcc -= 1;
const openOnes = openings.filter(o=>o.open>0.05);
if(!openOnes.length) break;
const o = openOnes[Math.floor(Math.random()*openOnes.length)];
const p = particles.find(p=>!p.active);
if(!p) break;
const a = ventAnchors[o.id];
p.active=true; p.life=2.2+Math.random()*1.4;
p.mesh.position.copy(a.pos).add(new THREE.Vector3((Math.random()-0.5)*1.4,(Math.random()-0.5)*0.7,(Math.random()-0.5)*1.4));
p.vel.copy(a.dir).multiplyScalar(1.2+Math.random()*1.4);
}
for(const p of particles){
if(!p.active) continue;
p.life -= dt;
if(p.life<=0){ p.active=false; p.mesh.visible=false; continue; }
p.vel.y += 0.35*dt; p.vel.multiplyScalar(1-0.35*dt);
p.mesh.position.addScaledVector(p.vel, dt);
p.mesh.rotation.x += dt*4; p.mesh.rotation.y += dt*3;
p.mesh.scale.setScalar(Math.min(1, p.life*1.4));
p.mesh.visible = true;
}
}
/* rising heat motes inside */
const moteN = 90, motePos = new Float32Array(moteN*3);
for(let i=0;i<moteN;i++){ motePos[i*3]=(Math.random()-0.5)*7; motePos[i*3+1]=Math.random()*2.6+0.4; motePos[i*3+2]=(Math.random()-0.5)*5; }
const moteGeo = new THREE.BufferGeometry(); moteGeo.setAttribute('position', new THREE.BufferAttribute(motePos,3));
const motes = new THREE.Points(moteGeo, new THREE.PointsMaterial({color:0xffb46b,size:0.09,transparent:true,opacity:.6,depthWrite:false}));
scene.add(motes);
/* ============================================================
5. UI
============================================================ */
const $ = id => document.getElementById(id);
const openList=$('openings'), shadeList=$('shades');
openings.forEach(o=>{
const b=document.createElement('button'); b.className='row'; b.dataset.id=o.id;
b.innerHTML=`<span class="sw"></span><span class="name">${o.label}</span><span class="k">k=${o.coeff.toFixed(2)}</span><span class="pct">0%</span>`;
b.addEventListener('click',()=>toggleOpening(o.id)); openList.appendChild(b); o.btn=b;
});
shades.forEach(p=>{
const b=document.createElement('button'); b.className='row'; b.dataset.id=p.id;
b.innerHTML=`<span class="sw"></span><span class="name">${p.label}</span><span class="k">deploy</span><span class="pct">0%</span>`;
b.addEventListener('click',()=>toggleShade(p.id)); shadeList.appendChild(b); p.btn=b;
});
function toggleOpening(id){ const o=openings.find(x=>x.id===id); if(o) o.target = o.target>0.5?0:1; }
function toggleShade(id){ const p=shades.find(x=>x.id===id); if(p) p.target = p.target>0.5?0:1; }
$('outside').addEventListener('input',e=>{ state.out=parseFloat(e.target.value); $('outVal').textContent=state.out.toFixed(1)+' °C'; });
$('sun').addEventListener('input',e=>{ state.sun=parseFloat(e.target.value); $('sunVal').textContent=state.sun.toFixed(2)+' ×'; });
$('speed').addEventListener('change',e=>{ speed=parseFloat(e.target.value); });
$('reset').addEventListener('click',resetAll);
function resetAll(){
state.T=S0.T; state.RH=S0.RH; state.CO2=S0.CO2; state.G=S0.G;
state.out=S0.out; state.sun=S0.sun; simMinutes=0; history.length=0;
openings.forEach(o=>{o.open=0;o.target=0;}); shades.forEach(p=>{p.deploy=0;p.target=0;});
$('outside').value=state.out; $('outVal').textContent=state.out.toFixed(1)+' °C';
$('sun').value=state.sun; $('sunVal').textContent=state.sun.toFixed(2)+' ×';
}
addEventListener('keydown',e=>{
if(e.code==='Space'){ e.preventDefault(); const sel=$('speed'); sel.value = sel.value==='0'? String(speed||5) : '0'; speed=parseFloat(sel.value); }
if(e.key==='r'||e.key==='R') resetAll();
});
/* history + chart */
const history = [];
const chart = $('chart'), cctx = chart.getContext('2d');
function sizeChart(){
const r = chart.getBoundingClientRect(), dpr = Math.min(devicePixelRatio,2);
chart.width = Math.max(1,Math.round(r.width*dpr)); chart.height = Math.max(1,Math.round(r.height*dpr));
}
addEventListener('resize',sizeChart);
function drawChart(){
const W=chart.width, H=chart.height, dpr=Math.min(devicePixelRatio,2);
cctx.clearRect(0,0,W,H);
cctx.fillStyle='#0c131a'; cctx.fillRect(0,0,W,H);
cctx.strokeStyle='#1d2833'; cctx.lineWidth=1*dpr;
for(let i=0;i<=4;i++){
const y = (H-16*dpr) * i/4 + 6*dpr;
cctx.beginPath(); cctx.moveTo(30*dpr,y); cctx.lineTo(W-4*dpr,y); cctx.stroke();
}
const n=history.length; if(n<2) return;
const x0=30*dpr, x1=W-4*dpr, y0=6*dpr, y1=H-16*dpr;
const t0=history[0].t, t1=history[n-1].t, span=Math.max(1e-6,t1-t0);
const px = t => x0 + (t-t0)/span*(x1-x0);
const pyT = v => y1 - Math.max(0,Math.min(1,v/50))*(y1-y0);
const pyR = v => y1 - Math.max(0,Math.min(1,v/100))*(y1-y0);
const line=(get,color)=>{ cctx.strokeStyle=color; cctx.lineWidth=1.8*dpr; cctx.beginPath();
for(let i=0;i<n;i++){ const x=px(history[i].t), y=get(history[i]); i?cctx.lineTo(x,y):cctx.moveTo(x,y);} cctx.stroke(); };
line(h=>pyT(h.T),'#ffb066'); line(h=>pyR(h.RH),'#7fd1ff');
cctx.fillStyle='#6f8698'; cctx.font=(9*dpr)+'px ui-sans-serif,system-ui';
cctx.fillText('T max '+Math.max(...history.map(h=>h.T)).toFixed(1)+'°C', x0+4*dpr, y0+9*dpr);
cctx.fillText('RH max '+Math.max(...history.map(h=>h.RH)).toFixed(0)+'%', x0+4*dpr, y0+20*dpr);
cctx.fillText(t0.toFixed(0)+' min', x0, H-3*dpr);
cctx.fillText(t1.toFixed(0)+' min', x1-34*dpr, H-3*dpr);
}
/* live numbers */
function fmt(v,n=2){ return (v>=0?'+':'')+v.toFixed(n); }
function updateUI(){
const d=computeDerived();
$('statT').textContent=state.T.toFixed(1);
$('statRH').textContent=state.RH.toFixed(0);
$('statCO2').textContent=state.CO2.toFixed(0);
for(const o of openings){
o.btn.classList.toggle('on', o.target>0.5);
o.btn.querySelector('.pct').textContent=Math.round(o.open*100)+'%';
}
for(const p of shades){
p.btn.classList.toggle('on', p.target>0.5);
p.btn.querySelector('.pct').textContent=Math.round(p.deploy*100)+'%';
}
$('calcT').innerHTML =
`<b>dT/dt</b> = (${Q_SUN0.toFixed(2)}·${state.sun.toFixed(2)}·(1−0.70·${d.S.toFixed(2)})`
+ ` − (0.10+${d.Vn.toFixed(2)})·(${state.T.toFixed(1)}−${state.out.toFixed(1)})`
+ ` − 0.45·(${state.T.toFixed(1)}−${state.out.toFixed(1)})) / 22.0\n`
+ `= ${fmt(d.dT,3)} °C/min (q_sun ${d.qSun.toFixed(2)}, q_vent ${d.qVent.toFixed(2)}, q_loss ${d.qLoss.toFixed(2)})`;
$('calcRH').innerHTML =
`<b>dRH/dt</b> = (6.50 − (0.076+0.05·${d.Vn.toFixed(2)})·${state.RH.toFixed(1)}) / 30.0\n`
+ `= ${fmt(d.dRH,3)} %/min`;
$('calcCO2').innerHTML =
`<b>dCO2/dt</b> = (0.08+0.25·${d.Vn.toFixed(2)})·(420−${state.CO2.toFixed(0)})`
+ ` + (55·(1−0.70·${d.S.toFixed(2)})−15)\n= ${fmt(d.dCO2,2)} ppm/min (net plant ${d.netCO2.toFixed(1)})`;
$('flows').innerHTML =
`Vn total <span>${d.Vn.toFixed(2)}</span><br>shade S <span>${d.S.toFixed(2)}</span><br>`
+ `growth G <span>${state.G.toFixed(0)} pts</span><br>sim time <span>${simMinutes.toFixed(1)} min</span>`;
drawChart();
}
/* ============================================================
6. POINTER: orbit / pan / zoom / pick
============================================================ */
const raycaster = new THREE.Raycaster(), ndc = new THREE.Vector2();
let dragging=false, panning=false, downX=0, downY=0, moved=0, lastX=0, lastY=0;
canvas.addEventListener('contextmenu',e=>e.preventDefault());
canvas.addEventListener('pointerdown',e=>{
dragging=true; panning = e.button===2 || e.shiftKey; moved=0;
downX=lastX=e.clientX; downY=lastY=e.clientY; canvas.setPointerCapture(e.pointerId);
});
canvas.addEventListener('pointermove',e=>{
if(dragging){
const dx=e.clientX-lastX, dy=e.clientY-lastY; moved += Math.abs(dx)+Math.abs(dy);
lastX=e.clientX; lastY=e.clientY;
if(panning){
const right = new THREE.Vector3().setFromMatrixColumn(camera.matrix,0);
const up = new THREE.Vector3().setFromMatrixColumn(camera.matrix,1);
const k = cam.radius*0.0016;
cam.target.addScaledVector(right,-dx*k).addScaledVector(up, dy*k);
}else{
cam.theta -= dx*0.006;
cam.phi = THREE.MathUtils.clamp(cam.phi - dy*0.005, 0.16, 1.46);
}
applyCamera();
}else{ hoverCheck(e); }
});
canvas.addEventListener('pointerup',e=>{
if(dragging && moved<6){ const hit=pick(e); if(hit) toggle(hit); }
dragging=false; panning=false;
});
canvas.addEventListener('wheel',e=>{
e.preventDefault();
cam.radius = THREE.MathUtils.clamp(cam.radius * Math.exp(e.deltaY*0.0012), 9, 55);
applyCamera();
},{passive:false});
canvas.addEventListener('dblclick',()=>{ Object.assign(cam,{theta:camHome.theta,phi:camHome.phi,radius:camHome.radius});
cam.target.copy(camHome.target); applyCamera(); });
function pick(e){
const r=canvas.getBoundingClientRect();
ndc.x=((e.clientX-r.left)/r.width)*2-1; ndc.y=-((e.clientY-r.top)/r.height)*2+1;
raycaster.setFromCamera(ndc,camera);
const hits=raycaster.intersectObjects(pickables,false);
return hits.length?hits[0].object:null;
}
let hovered=null;
function hoverCheck(e){
const o=pick(e);
if(hovered===o) return;
if(hovered){ hovered.material.emissive.set(0x000000); hovered.material.emissiveIntensity=1; }
hovered=o;
if(hovered){ hovered.material.emissive.set(0x2f7fa8); hovered.material.emissiveIntensity=0.55; canvas.style.cursor='pointer'; }
else canvas.style.cursor='grab';
}
function toggle(o){
if(o.userData.kind==='opening') toggleOpening(o.userData.id);
else toggleShade(o.userData.id);
}
/* ============================================================
7. ANIMATION LOOP
============================================================ */
const coldC=new THREE.Color(0x9fd0ff), hotC=new THREE.Color(0xffb066);
let last=performance.now(), uiAcc=0, histAcc=0;
function animate(now){
requestAnimationFrame(animate);
const dt=Math.min((now-last)/1000,0.08); last=now;
/* animate the physical parts toward their targets */
openings.forEach(o=>o.open += (o.target-o.open)*Math.min(1,dt*5));
shades.forEach(p=>p.deploy += (p.target-p.deploy)*Math.min(1,dt*3.2));
const ridge=openings.find(o=>o.id==='ridge');
ridgeVent.rotation.x = -theta + ridge.open*1.9*theta;
const sideL=openings.find(o=>o.id==='sideL'), sideR=openings.find(o=>o.id==='sideR');
svL.group.rotation.z = -sideL.open*1.4;
svR.group.rotation.z = sideR.open*1.4;
const dr=openings.find(o=>o.id==='door');
door.rotation.y = -dr.open*1.5;
const fan=openings.find(o=>o.id==='fan');
fanBlades.rotation.z += dt*(fan.open>0.05 ? 16*fan.open : 0);
/* shade fabric rolls out over the roof slope */
shades.forEach((p,i)=>{
const sm=shadeMeshes[i], d=p.deploy;
const len=Math.max(0.05, sm.len*d);
sm.mesh.scale.z = len;
sm.mesh.position.z = sm.sign*(len/2 + 0.10);
sm.mesh.position.y = 0.05 + 0.02*d;
});
/* simulation */
if(speed>0){ stepSim(dt*speed); }
/* lighting + interior look follow the same rules */
const d=computeDerived();
sunLight.intensity = 0.25 + 1.35*state.sun*(1-0.55*d.S);
hemi.intensity = 0.35 + 0.25*state.sun;
insideGlow.intensity = Math.max(0,(state.T-state.out))*0.16;
insideGlow.color.setHSL(0.08, 0.8, 0.5);
airBox.material.color.lerpColors(coldC, hotC, THREE.MathUtils.clamp((state.T-16)/22,0,1));
airBox.material.opacity = 0.05 + Math.min(0.10, Math.abs(state.T-22)*0.006);
/* plants grow with the toy growth index G */
const gs = 1 + state.G/150;
plantGroups.forEach(g=>g.scale.set(gs,gs,gs));
/* particles */
updateParticles(dt, d.Vn);
motes.visible = d.qSun>0.4;
if(motes.visible){
for(let i=0;i<moteN;i++){
motePos[i*3+1] += dt*(0.18+0.5*(d.qSun/9));
if(motePos[i*3+1]>2.9){ motePos[i*3+1]=0.4; motePos[i*3]=(Math.random()-0.5)*7; motePos[i*3+2]=(Math.random()-0.5)*5; }
}
moteGeo.attributes.position.needsUpdate=true;
}
/* history sampling */
histAcc += dt*speed;
if(histAcc>0.25){ histAcc=0; history.push({t:simMinutes,T:state.T,RH:state.RH}); if(history.length>400) history.shift(); }
uiAcc += dt;
if(uiAcc>0.1){ uiAcc=0; updateUI(); }
renderer.render(scene,camera);
}
function resize(){
const w=innerWidth, h=innerHeight;
renderer.setSize(w,h,false);
camera.aspect=w/h; camera.updateProjectionMatrix();
sizeChart();
}
addEventListener('resize',resize);
resize(); sizeChart(); updateUI();
requestAnimationFrame(animate);
</script>
</body>
</html>
```